repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
Atikur10/snake_water_gun_game
project2.c
#include<stdio.h> #include<stdlib.h> #include<time.h> int Compgame(char you, char comp){ // for draw condition if (you == comp) { return 0; } // Non Draw conditions if(you == 's' && comp == 'w'){ return 1; } else if(you == 'w' && comp == 's') { return -1; } if (you == 'g' && comp == 'w') { return -1; } else if (you == 'w' && comp == 'g') { return 1; } if (you == 'g' && comp == 's') { return 1; } else if (you == 'g' && comp == 's') { return -1; } } int main() { char you , comp; srand(time(0)); int number = rand()%100 + 1; //printf("The number is %d\n",number); if (number < 33) { comp = 's'; } else if (number > 33 && number < 66) { comp = 'w'; } else { comp = 'g'; } printf("Enter s for snake , w for water and g for gun\n"); scanf("%c",&you); int result = Compgame(you,comp); printf("Computer chooses %c and you chose %c\n",comp,you); if (result == 0) { printf("Game Draws!"); } else if (result == 1) { printf("You Won!"); } else { printf("You Lose!"); } return 0; }
hwxue/xhwXNIMDemo
Example/xhwXNIMDemo/xhwwbViewController.h
// // xhwwbViewController.h // xhwXNIMDemo // // Created by hwxue on 07/01/2019. // Copyright (c) 2019 hwxue. All rights reserved. // @import UIKit; @interface xhwwbViewController : UIViewController @end
hwxue/xhwXNIMDemo
Example/xhwXNIMDemo/xhwwbAppDelegate.h
// // xhwwbAppDelegate.h // xhwXNIMDemo // // Created by hwxue on 07/01/2019. // Copyright (c) 2019 hwxue. All rights reserved. // @import UIKit; @interface xhwwbAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
ccarr66/SHA-256
src/sha256.h
<gh_stars>0 #include <algorithm> #include <cstdint> #include <climits> class SHA256 { public: using word_ty = uint32_t; using bitLen_ty = size_t; static constexpr bitLen_ty byteLen = CHAR_BIT; static constexpr bitLen_ty blockLen = 512; static constexpr size_t wordLenInByte = sizeof(word_ty); static constexpr bitLen_ty wordLen = byteLen * wordLenInByte; static constexpr size_t blockLenInWord = blockLen / wordLen; static constexpr bitLen_ty endMarkerLen = 64; static constexpr size_t endMarkerLenInWord = endMarkerLen / wordLen; using block_ty = word_ty[blockLenInWord]; word_ty resultHashValues[8]; static_assert(blockLen % wordLen == 0); static_assert(endMarkerLen % wordLen == 0); private: constexpr word_ty rotL(word_ty x, bitLen_ty n) { return (x << n) | (x >> (wordLen - n)); } constexpr word_ty rotR(word_ty x, bitLen_ty n) { return (x >> n) | (x << (wordLen - n)); } constexpr word_ty shR(word_ty x, bitLen_ty n) { return (x >> n); } constexpr word_ty CH(word_ty x, word_ty y, word_ty z) { return (x & y) ^ (~x & z); } constexpr word_ty MAJ(word_ty x, word_ty y, word_ty z) { return (x & y) ^ (x & z) ^ (y & z); } constexpr word_ty BSIG0(word_ty x) { return rotR(x, 2) ^ rotR(x, 13) ^ rotR(x, 22); } constexpr word_ty BSIG1(word_ty x) { return rotR(x, 6) ^ rotR(x, 11) ^ rotR(x, 25); } constexpr word_ty SSIG0(word_ty x) { return rotR(x, 7) ^ rotR(x, 18) ^ shR(x, 3); } constexpr word_ty SSIG1(word_ty x) { return rotR(x, 17) ^ rotR(x, 19) ^ shR(x, 10); } void copyDataToBlock(const char* data, size_t dataLen, block_ty& block, size_t blockIdx) { auto wordIdx = size_t{0}; auto byteInWordIdx = size_t{0}; constexpr auto blockLenInByte = blockLenInWord * wordLenInByte; const auto beginPtr = data + blockLenInByte * blockIdx; const auto endPtr = data + std::min(blockLenInByte * (blockIdx + 1), dataLen); for(auto c = beginPtr; c < endPtr; c++) { const auto shiftAmt = CHAR_BIT * (wordLenInByte - 1 - byteInWordIdx); block[wordIdx] |= static_cast<word_ty>(*c) << shiftAmt; byteInWordIdx = (byteInWordIdx + 1) % wordLenInByte; if(byteInWordIdx == 0) wordIdx++; } } void setEndMarker(block_ty& block, bitLen_ty dataBitLen) { constexpr auto maskWord = (static_cast<uint64_t>(1ul) << wordLen) - 1; //results in 64'h0000000100000000 => 64'h00000000ffffffff auto& endMarkerHighWord = block[blockLenInWord - endMarkerLenInWord + 0]; auto& endMarkerLowWord = block[blockLenInWord - endMarkerLenInWord + 1]; const auto endMarkerRaw = uint64_t{ dataBitLen }; endMarkerLowWord = endMarkerRaw & maskWord; endMarkerHighWord = (endMarkerRaw >> wordLen) & maskWord; return; } void setMessageEndBit(block_ty& block, bitLen_ty dataBitLen) { const auto lastWordIdx = size_t{(dataBitLen % blockLen) / wordLen}; const auto lastBitIdx = size_t{dataBitLen % wordLen}; block[lastWordIdx] |= static_cast<word_ty>(0x80000000 >> lastBitIdx); } struct workingVariables { word_ty a,b,c,d,e,f,g,h; workingVariables(const word_ty initVal[8]) : a(initVal[0]),b(initVal[1]),c(initVal[2]),d(initVal[3]), e(initVal[4]),f(initVal[5]),g(initVal[6]),h(initVal[7]) {} }; void prepareMessageSchedule(const block_ty& block, word_ty* messageSchedule) { for(size_t i = 0; i < 64; i++) { auto newWord = word_ty{0}; if(i < 16) newWord = block[i]; else newWord = SSIG1(messageSchedule[i - 2]) + messageSchedule[i - 7] + SSIG0(messageSchedule[i - 15]) + messageSchedule[i - 16]; messageSchedule[i] = newWord; } } void processWorkingVars(workingVariables& wv, word_ty wt, word_ty K) { auto T1 = wv.h + BSIG1(wv.e) + CH(wv.e, wv.f, wv.g) + K + wt; auto T2 = BSIG0(wv.a) + MAJ(wv.a,wv.b,wv.c); wv.h = wv.g; wv.g = wv.f; wv.f = wv.e; wv.e = wv.d + T1; wv.d = wv.c; wv.c = wv.b; wv.b = wv.a; wv.a = T1 + T2; } void performHash(const block_ty& block) { constexpr word_ty K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; word_ty messageSchedule[64]; prepareMessageSchedule(block, messageSchedule); workingVariables currVar(resultHashValues); auto i = size_t{0}; for(const auto& w : messageSchedule) processWorkingVars(currVar, w, K[i++]); resultHashValues[0] += currVar.a; resultHashValues[1] += currVar.b; resultHashValues[2] += currVar.c; resultHashValues[3] += currVar.d; resultHashValues[4] += currVar.e; resultHashValues[5] += currVar.f; resultHashValues[6] += currVar.g; resultHashValues[7] += currVar.h; } public: //requires strData to point to an char array with len elements SHA256(const char* data, size_t dataLen) { constexpr auto maxLastBlockLen = bitLen_ty {blockLen - endMarkerLen}; static_assert(maxLastBlockLen < blockLen); const auto dataBitLen = bitLen_ty{dataLen * CHAR_BIT}; const auto lastBlockLen = (dataBitLen + 1) % blockLen; constexpr auto endMarkerLen = bitLen_ty {64}; auto numZeros = bitLen_ty {0}; if(lastBlockLen > maxLastBlockLen) numZeros = blockLen - (lastBlockLen - maxLastBlockLen); else numZeros = maxLastBlockLen - lastBlockLen; const auto totalLen = bitLen_ty {dataBitLen + 1 + numZeros + endMarkerLen}; const auto numBlocks = size_t {totalLen / blockLen}; constexpr word_ty initialHash[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; for(auto i = 0u; i < 8u; i++) resultHashValues[i] = initialHash[i]; block_ty currentblock = {0}; for(auto b = 0u; b < numBlocks; b++) { copyDataToBlock(data, dataLen, currentblock, b); if(b == numBlocks - 1) { setEndMarker(currentblock, dataBitLen); setMessageEndBit(currentblock, dataBitLen); } performHash(currentblock); } } }; /*#define DEBUG_MACHINE #ifdef DEBUG_MACHINE #include <iostream> #include <iomanip> #endif #include <algorithm> #include <memory> #include <climits> #include <cstring> class SHA256 { public: using word_ty = uint32_t; using bitLen_ty = size_t; static constexpr bitLen_ty byteLen = CHAR_BIT; static constexpr bitLen_ty blockLen = 512; static constexpr size_t wordLenInByte = sizeof(word_ty); static constexpr bitLen_ty wordLen = byteLen * wordLenInByte; static constexpr size_t blockLenInWord = blockLen / wordLen; static constexpr bitLen_ty endMarkerLen = 64; static constexpr size_t endMarkerLenInWord = endMarkerLen / wordLen; using block_ty = word_ty[blockLenInWord]; word_ty resultHashValues[8]; static_assert(blockLen % wordLen == 0); static_assert(endMarkerLen % wordLen == 0); static constexpr bool isBigEndian() { const auto testVal = uint32_t{0x89ABCDEF}; const auto mostSigByte = uint8_t {(testVal & 0xff000000) >> 24}; const auto leastSigByte = uint8_t {testVal & 0xff}; const auto byteRef = (const uint8_t&)testVal; if(byteRef == mostSigByte) return true; else if (byteRef == leastSigByte) return false; else throw; //this causes compilation to fail bc it's in constexpr context } #ifdef DEBUG_MACHINE void printOutputHex(void) { std::cout << "\n"; for(const auto& word : resultHashValues) std::cout << std::setfill('0') << std::setw(wordLenInByte * 2) << std::hex << word; } void printOutputBits(void) { std::cout << "\n"; for(const auto& word : resultHashValues) { for(size_t i = 0; i < wordLen; i++) { if(word & (1 << (wordLen - 1 - i))) std::cout << "1"; else std::cout << "0"; } } } #else std::unique_ptr<char[]> printOutputHex(void) { const auto retStrLen = 16 * wordLenInByte + 1; // chars needed = 2 char/byte[each nibble] * .. // ..* 8 words * #bytes/word auto retStr = std::make_unique<char[]>(retStrLen); auto retStrRef = retStr.get(); auto endianIdxCorrector = [](size_t byteIdx) { auto correctIdx = size_t{byteIdx}; if constexpr(isBigEndian() == false) correctIdx = wordLenInByte - 1 - byteIdx; return correctIdx; }; for(const auto& word : resultHashValues) { auto charPtrToWord = reinterpret_cast<const char*>(&word); for(size_t byteIdx = 0; byteIdx < wordLenInByte; byteIdx++) { const auto byte = *(charPtrToWord + endianIdxCorrector(byteIdx)); const auto upperNibble = static_cast<char>((byte & 0xf0) >> 4); const auto lowerNibble = static_cast<char>(byte & 0x0f); auto nibbleToASCII = [](char n) { auto retVal = n; if(n >= 0x0 && n <= 0x9) retVal += 0x30; else if(n >= 0xA && n <= 0xF) retVal += 0x41 - 0xA; else retVal = 0xFF; return retVal; }; *retStrRef++ = nibbleToASCII(upperNibble); *retStrRef++ = nibbleToASCII(lowerNibble); } } retStrRef[retStrLen - 1] = '\0'; return retStr; } std::unique_ptr<char[]> printOutputBits(void) { const auto retStrLen = 8 * wordLenInByte * byteLen + 1; auto retStr = std::make_unique<char[]>(retStrLen); auto retStrRef = retStr.get(); auto wordToBits = [](word_ty c, char* &retStrPos) { for(size_t i = 0; i < wordLen; i++) { if(c & (1 << (wordLen - 1 - i))) *retStrPos++ = '1'; else *retStrPos++ = '0'; } }; for(const auto& word : resultHashValues) wordToBits(word, retStrRef); retStrRef[retStrLen - 1] = '\0'; return retStr; } #endif private: class blockCont { public: size_t len{0}; std::unique_ptr<block_ty[]> blockArr; block_ty& operator[](size_t i) { return blockArr[i];} block_ty& last() {return blockArr[len - 1];} block_ty * begin() { return &(blockArr[0]);}; block_ty const* begin() const { return &(blockArr[0]);}; block_ty * end() { return &(blockArr[len]);}; block_ty const* end() const { return &(blockArr[len]);}; blockCont(size_t len) : len(len), blockArr(std::make_unique<block_ty[]>(len)) {} #ifdef DEBUG_MACHINE void printBlocksHex(void) { std::cout << "\n"; for(const auto& block : *this) { std::cout << "\n0x"; for(const auto& word : block) std::cout << std::setfill('0') << std::setw(wordLenInByte * 2) << std::hex << word; } } void printBlocksBits(void) { std::cout << "\n"; for(const auto& block : *this) { std::cout << '\n'; auto printWord = [](word_ty c) { std::cout << ' '; for(size_t i = 0; i < wordLen; i++) { if(c & (1 << (wordLen - 1 - i))) std::cout << "1"; else std::cout << "0"; } }; std::for_each(std::begin(block), std::end(block), printWord); } } #else std::unique_ptr<char[]> printBlocksHex(void) { const auto retStrLen = this->len * wordLenInByte + 1; auto retStr = std::make_unique<char[]>(retStrLen); auto retStrRef = retStr.get(); for(const auto& block : *this) { for(const auto& word : block) { auto charPtrToWord = reinterpret_cast<const char*>(&word); for(size_t byteIdx = 0; byteIdx < wordLenInByte; byteIdx++) *retStrRef++ = *(charPtrToWord + byteIdx); } } retStrRef[retStrLen - 1] = '\0'; return retStr; } std::unique_ptr<char[]> printBlocksBits(void) { const auto retStrLen = this->len * wordLenInByte * byteLen + 1; auto retStr = std::make_unique<char[]>(retStrLen); auto retStrRef = retStr.get(); auto wordToBits = [](word_ty c, char* &retStrPos) { for(size_t i = 0; i < wordLen; i++) { if(c & (1 << (wordLen - 1 - i))) *retStrPos++ = '1'; else *retStrPos++ = '0'; } }; for(const auto& block : *this) for(const auto& word : block) wordToBits(word, retStrRef); retStrRef[retStrLen - 1] = '\0'; return retStr; } #endif }; constexpr word_ty rotL(word_ty x, bitLen_ty n) { return (x << n) | (x >> (wordLen - n)); } constexpr word_ty rotR(word_ty x, bitLen_ty n) { return (x >> n) | (x << (wordLen - n)); } constexpr word_ty shR(word_ty x, bitLen_ty n) { return (x >> n); } constexpr word_ty CH(word_ty x, word_ty y, word_ty z) { return (x & y) ^ (~x & z); } constexpr word_ty MAJ(word_ty x, word_ty y, word_ty z) { return (x & y) ^ (x & z) ^ (y & z); } constexpr word_ty BSIG0(word_ty x) { return rotR(x, 2) ^ rotR(x, 13) ^ rotR(x, 22); } constexpr word_ty BSIG1(word_ty x) { return rotR(x, 6) ^ rotR(x, 11) ^ rotR(x, 25); } constexpr word_ty SSIG0(word_ty x) { return rotR(x, 7) ^ rotR(x, 18) ^ shR(x, 3); } constexpr word_ty SSIG1(word_ty x) { return rotR(x, 17) ^ rotR(x, 19) ^ shR(x, 10); } static constexpr word_ty K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; static constexpr word_ty initialHash[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; void copyDataToBlocks(const char* data, size_t dataLen, blockCont& blocks) { auto blockIdx = size_t{0}; auto wordIdx = size_t{0}; auto byteInWordIdx = size_t{0}; auto setByteInWord = [&](char c) -> word_ty { auto shiftAmt = size_t{0}; if constexpr(isBigEndian()) shiftAmt = CHAR_BIT * byteInWordIdx; else shiftAmt = CHAR_BIT * (wordLenInByte - 1 - byteInWordIdx); return word_ty{ static_cast<word_ty>(c) << shiftAmt}; }; std::for_each( data, data + dataLen, [&](char c) { blocks[blockIdx][wordIdx] |= setByteInWord(c); byteInWordIdx = (byteInWordIdx + 1) % wordLenInByte; if(byteInWordIdx == 0) { wordIdx = (wordIdx + 1) % blockLenInWord; if(wordIdx == blockLenInWord) blockIdx++; } } ); } void setEndMarker(blockCont& blocks, bitLen_ty dataBitLen) { constexpr auto maskWord = uint64_t{ (1ul << wordLen) - 1 }; //results in 64'h0000000100000000 => 64'h00000000ffffffff auto& lastBlock = blocks.last(); auto& endMarkerHighWord = lastBlock[blockLenInWord - endMarkerLenInWord + 0]; auto& endMarkerLowWord = lastBlock[blockLenInWord - endMarkerLenInWord + 1]; constexpr auto assignEndMarkerRaw = [](const bitLen_ty& dataBitLen) -> uint64_t{ if constexpr (isBigEndian()) { return uint64_t{ ((dataBitLen >> 56) & 0x00000000000000FF) | ((dataBitLen >> 40) & 0x000000000000FF00) | ((dataBitLen >> 24) & 0x0000000000FF0000) | ((dataBitLen >> 8) & 0x00000000FF000000) | ((dataBitLen << 8) & 0x000000FF00000000) | ((dataBitLen << 24) & 0x0000FF0000000000) | ((dataBitLen << 40) & 0x00FF000000000000) | ((dataBitLen << 56) & 0xFF00000000000000)}; } else return uint64_t{ dataBitLen }; }; const auto endMarkerRaw = assignEndMarkerRaw(dataBitLen); endMarkerLowWord = endMarkerRaw & maskWord; endMarkerHighWord = (endMarkerRaw >> wordLen) & maskWord; return; } void setMessageEndBit(blockCont& blocks, bitLen_ty dataBitLen) { const auto lastBlockIdx = size_t{dataBitLen / blockLen}; const auto lastWordIdx = size_t{(dataBitLen % blockLen) / wordLen}; const auto lastBitIdx = size_t{dataBitLen % wordLen}; auto endBitMask = word_ty{0}; if constexpr(isBigEndian()) endBitMask = static_cast<word_ty>(0x00000001 << lastBitIdx); else endBitMask = static_cast<word_ty>(0x80000000 >> lastBitIdx); blocks[lastBlockIdx][lastWordIdx] |= endBitMask; } struct workingVariables { word_ty a,b,c,d,e,f,g,h; workingVariables(const word_ty initVal[8]) : a(initVal[0]),b(initVal[1]),c(initVal[2]),d(initVal[3]), e(initVal[4]),f(initVal[5]),g(initVal[6]),h(initVal[7]) {} }; void prepareMessageSchedule(const block_ty& block, word_ty* messageSchedule) { for(size_t i = 0; i < 64; i++) { auto newWord = word_ty{0}; if(i < 16) newWord = block[i]; else newWord = SSIG1(messageSchedule[i - 2]) + messageSchedule[i - 7] + SSIG0(messageSchedule[i - 15]) + messageSchedule[i - 16]; messageSchedule[i] = newWord; } } void processWorkingVars(workingVariables& wv, word_ty wt, word_ty K) { auto T1 = wv.h + BSIG1(wv.e) + CH(wv.e, wv.f, wv.g) + K + wt; auto T2 = BSIG0(wv.a) + MAJ(wv.a,wv.b,wv.c); wv.h = wv.g; wv.g = wv.f; wv.f = wv.e; wv.e = wv.d + T1; wv.d = wv.c; wv.c = wv.b; wv.b = wv.a; wv.a = T1 + T2; } void performHash(const blockCont& blocks) { std::copy(std::begin(initialHash), std::end(initialHash), std::begin(resultHashValues)); auto hashBlock = [&](const block_ty& block) -> void { word_ty messageSchedule[64]; prepareMessageSchedule(block, messageSchedule); workingVariables currVar(resultHashValues); auto i = size_t{0}; for(const auto& w : messageSchedule) processWorkingVars(currVar, w, K[i++]); resultHashValues[0] += currVar.a; resultHashValues[1] += currVar.b; resultHashValues[2] += currVar.c; resultHashValues[3] += currVar.d; resultHashValues[4] += currVar.e; resultHashValues[5] += currVar.f; resultHashValues[6] += currVar.g; resultHashValues[7] += currVar.h; }; std::for_each(blocks.begin(), blocks.end(), hashBlock); } public: //requires strData to point to an char array with len elements SHA256(const char* data, size_t dataLen) { constexpr auto maxLastBlockLen = bitLen_ty {blockLen - endMarkerLen}; static_assert(maxLastBlockLen < blockLen); const auto dataBitLen = bitLen_ty{dataLen * CHAR_BIT}; const auto lastBlockLen = (dataBitLen + 1) % blockLen; constexpr auto endMarkerLen = bitLen_ty {64}; auto numZeros = bitLen_ty {0}; if(lastBlockLen > maxLastBlockLen) numZeros = blockLen - (lastBlockLen - maxLastBlockLen); else numZeros = maxLastBlockLen - lastBlockLen; const auto totalLen = bitLen_ty {dataBitLen + 1 + numZeros + endMarkerLen}; const auto numBlocks = size_t {totalLen / blockLen}; auto blocks = blockCont(numBlocks); copyDataToBlocks(data, dataLen, blocks); setEndMarker(blocks, dataBitLen); setMessageEndBit(blocks, dataBitLen); performHash(blocks); } }; */
mun4w4r/gibran
include/rpigpio.h
<gh_stars>1000+ #define GPIO_LED_DELAY 100000000 #define GPIO_PERI_BASE_OLD 0x20000000 #define GPIO_PERI_BASE_NEW 0x3F000000 #define GPIO_BASE 0x200000 #define PAGE_SIZE (4*1024) #define BLOCK_SIZE (4*1024) #define INP_GPIO(g) *(gpio +((g) /10)) &= ~(7 << (((g) %10) *3)) #define OUT_GPIO(g) *(gpio +((g) /10)) |= (1 << (((g) %10) *3)) #define GPIO_SET *(gpio +7) #define GPIO_CLR *(gpio +10) #define GET_GPIO(g) (*(gpio +13) & (1 << g)) static int rpirevision; static void *gpio_map; static volatile unsigned *gpio;
huasali/oc-developer-protocol
oc-developer-protocol/Protocol/CryptUtil.h
<reponame>huasali/oc-developer-protocol // // CryptUtil.h // oc-developer-protocol // // Created by Huasali on 2021/11/25. // #import <Foundation/Foundation.h> #import "CryptHelper.h" NS_ASSUME_NONNULL_BEGIN @interface CryptUtil : NSObject + (NSMutableDictionary *)inputData; + (NSMutableDictionary *)outputData; /// 测试数据 /// @param callback log回调 + (void)cryptTest:(void(^)(NSString *log))callback; @end NS_ASSUME_NONNULL_END
huasali/oc-developer-protocol
oc-developer-protocol/ViewController/ProtocolViewController.h
<filename>oc-developer-protocol/ViewController/ProtocolViewController.h // // ProtocolViewController.h // oc-developer-protocol // // Created by Huasali on 2021/11/25. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ProtocolViewController : UIViewController @property (nonatomic, copy) NSString *className; @end NS_ASSUME_NONNULL_END
huasali/oc-developer-protocol
oc-developer-protocol/Protocol/AESCryptUtil.h
<reponame>huasali/oc-developer-protocol // // AESCryptUtil.h // oc-developer-protocol // // Created by Huasali on 2021/11/25. // #import <Foundation/Foundation.h> #import "CryptUtil.h" NS_ASSUME_NONNULL_BEGIN @interface AESCryptUtil : CryptUtil /// AES128 CBC 加密 countPadding + (NSData *)aescbcEncryptData:(NSData *)data key:(NSData *)keyData iv:(NSData *)ivData; /// AES128 CBC 解密 countPadding + (NSData *)aescbcDecryptData:(NSData *)encryptData key:(NSData *)keyData iv:(NSData *)ivData; /// AES128 CBC 加密 PKCS7padding iv 0 + (NSData *)aes128cbcEncryptData:(NSData *)data key:(NSData *)keyData; /// AES128 CBC 解密PKCS7padding iv 0 + (NSData *)aes128cbcDecryptData:(NSData *)data key:(NSData *)keyData; /// AES128 CFB 加密 NOPadding iv 16字节0 + (NSData *)aes128cfbEncryptData:(NSData *)data key:(NSData *)keyData; /// AES128 CFB 解密 NOPadding iv 16字节0 + (NSData *)aes128cfbDecryptData:(NSData *)data key:(NSData *)keyData; @end NS_ASSUME_NONNULL_END
huasali/oc-developer-protocol
oc-developer-protocol/Protocol/OTPCryptUtil.h
<filename>oc-developer-protocol/Protocol/OTPCryptUtil.h<gh_stars>0 // // OTPCryptUtil.h // oc-developer-protocol // // Created by Huasali on 2021/11/25. // #import <Foundation/Foundation.h> #import "CryptUtil.h" NS_ASSUME_NONNULL_BEGIN @interface OTPCryptUtil : CryptUtil /// One-Time Password /// @param pwdData 密码 /// @param time 时间 /// @param key key + (NSData *)otpHashWithPWD:(NSData *)pwdData time:(uint32_t)time key:(uint32_t)key; @end NS_ASSUME_NONNULL_END
huasali/oc-developer-protocol
oc-developer-protocol/ViewController/ViewController.h
// // ViewController.h // oc-developer-protocol // // Created by Huasali on 2021/11/22. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
huasali/oc-developer-protocol
oc-developer-protocol/Protocol/DHCryptUtil.h
// // DHCryptUtil.h // oc-developer-protocol // // Created by Huasali on 2021/12/3. // #import "CryptUtil.h" NS_ASSUME_NONNULL_BEGIN @interface DHCryptUtil : CryptUtil @end NS_ASSUME_NONNULL_END
huasali/oc-developer-protocol
oc-developer-protocol/Protocol/CryptHelper.h
// // CryptHelper.h // oc-developer-protocol // // Created by Huasali on 2021/11/25. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN #define StringFrom(fmt, ...) [NSString stringWithFormat:fmt,##__VA_ARGS__] #define LogRed(frmt,...) NSLog((XCODE_COLORS_ESCAPE @"fg249,73,72;" frmt XCODE_COLORS_RESET),##__VA_ARGS__) @interface CryptHelper : NSObject + (NSData *)appendCountPadding:(NSData *)data; + (NSData *)subCountPaddingData:(NSData *)data; + (NSData *)randPaddingData:(int)count; /// 字典转字符串 /// @param dic 字典 + (NSString *)jsonStringFromDictionary:(NSDictionary *)dic; /// 字符串转字典 /// @param string 字符串 + (NSDictionary *)dictionaryFromJsonString:(NSString *)string; /// 字节字符串转data /// @param string 字节字符串 + (NSData *)dataFromBytesString:(NSString *)string; /// data转字节字符串 /// @param data data + (NSString *)bytesStringFromData:(NSData *)data; + (NSString *)bytesStringFromByte:(Byte *)byte; /// data按utf-8转字符串 /// @param data data + (NSString *)stringFromData:(NSData *)data; /// 字符传按utf-8转data /// @param string 字符串 + (NSData *)dataFromString:(NSString *)string; /// Description 任意类型转字符串 /// @param data 任意数据 + (NSString *)logStringFromObject:(id)data; + (NSArray <Class> *)classesInfo; @end NS_ASSUME_NONNULL_END
YichengZhong/CodeQL_C-C-
Test_Cl/sort.c
#include"sort.h" void bub_sort(){ int *in; int i , j; in = malloc(N*sizeof(int)); srand((unsigned)time(NULL)); ins(i,0,N){ in[i] = rand()%100; } ins(i,0,N){ printf("%d%s",in[i],i == N-1 ? "\n" : "->"); } ins(i,0,N-1){ ins(j,i,N){ if(in[i] > in[j]){ swap(in[i] , in[j]); } } } ins(i,0,N){ printf("%d%s" , in[i] , i == N-1 ? "\n" : "->"); } free(in); in = NULL; }
YichengZhong/CodeQL_C-C-
Test_Cl/main.c
<gh_stars>0 #include"sort.h" int main(){ bub_sort(); int x = x; // BAD: undefined behavior occurs here x = 0; return 0; }
YichengZhong/CodeQL_C-C-
Test_Cl/sort.h
#ifndef SORT_H #define SORT_H #include<stdio.h> #include<time.h> #include<stdlib.h> #define N 10 #define swap(a,b) {a^=b;b^=a;a^=b;} #define ins(a,b,c) for( a = b ; a < c ; ++a) void bub_sort(); #endif
ZpFate/AnalyticSDWebImage
AnalyticSDWebImage/SecondViewController.h
<reponame>ZpFate/AnalyticSDWebImage // // SecondViewController.h // AnalyticSDWebImage // // Created by <NAME> on 2019/9/10. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface SecondViewController : UIViewController @end NS_ASSUME_NONNULL_END
ZpFate/AnalyticSDWebImage
AnalyticSDWebImage/Person.h
<gh_stars>1-10 // // Person.h // AnalyticSDWebImage // // Created by <NAME> on 2019/8/9. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface Person : NSObject @property (nonatomic, copy) void(^runBlock)(NSString *name); @end NS_ASSUME_NONNULL_END
ZpFate/AnalyticSDWebImage
AnalyticSDWebImage/SDWebImage/SDWebImageDefine.h
<filename>AnalyticSDWebImage/SDWebImage/SDWebImageDefine.h /* * This file is part of the SDWebImage package. * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" typedef void(^SDWebImageNoParamsBlock)(void); typedef NSString * SDWebImageContextOption NS_EXTENSIBLE_STRING_ENUM; typedef NSDictionary<SDWebImageContextOption, id> SDWebImageContext; typedef NSMutableDictionary<SDWebImageContextOption, id> SDWebImageMutableContext; #pragma mark - Image scale /** Return the image scale factor for the specify key, supports file name and url key. This is the built-in way to check the scale factor when we have no context about it. Because scale factor is not stored in image data (It's typically from filename). However, you can also provide custom scale factor as well, see `SDWebImageContextImageScaleFactor`. @param key The image cache key @return The scale factor for image */ FOUNDATION_EXPORT CGFloat SDImageScaleFactorForKey(NSString * _Nullable key); /** Scale the image with the scale factor for the specify key. If no need to scale, return the original image. This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. @note This is actually a convenience function, which firstlly call `SDImageScaleFactorForKey` and then call `SDScaledImageForScaleFactor`, kept for backward compatibility. @param key The image cache key @param image The image @return The scaled image */ FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image); /** Scale the image with the scale factor. If no need to scale, return the original image. This works for `UIImage`(UIKit) or `NSImage`(AppKit). And this function also preserve the associated value in `UIImage+Metadata.h`. @param scale The image scale factor @param image The image @return The scaled image */ FOUNDATION_EXPORT UIImage * _Nullable SDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image); #pragma mark - WebCache Options /// WebCache options typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { /** * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. * This flag disable this blacklisting. * 如果一个url加载图片失败会加入黑名单 不在重试, 设置该选项取消黑名单限制 */ SDWebImageRetryFailed = 1 << 0, /** * By default, image downloads are started during UI interactions, this flags disable this feature, * leading to delayed download on UIScrollView deceleration for instance. * 默认情况是在UI交互的时候下载图片 * 低优先级, 设置该选项在UIScrollView滑动减速时才开始下载图片 */ SDWebImageLowPriority = 1 << 1, /** * This flag enables progressive download, the image is displayed progressively during download as a browser would do. * By default, the image is only displayed once completely downloaded. * 设置该选项 图片会逐渐展示,像浏览器一样 * 默认是图片下载完成展示 */ SDWebImageProgressiveLoad = 1 << 2, /** * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. * * Use this flag only if you can't make your URLs static with embedded cache busting parameter. * 一个图片缓存了,还是会重新请求.并且缓存侧略依据NSURLCache而不是SDWebImage.URL不变,图片会更新时使用 * 需要服务端支持cache control */ SDWebImageRefreshCached = 1 << 3, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. * 启动后台下载 */ SDWebImageContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; * 可以控制存在NSHTTPCookieStore的cookies */ SDWebImageHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL certificates. * Useful for testing purposes. Use with caution in production. * 允许不安全的SSL证书,在正式环境中慎用 */ SDWebImageAllowInvalidSSLCertificates = 1 << 6, /** * By default, images are loaded in the order in which they were queued. This flag moves them to * the front of the queue. * 高优先级下载 会把该任务放置到队列前面 */ SDWebImageHighPriority = 1 << 7, /** * By default, placeholder images are loaded while the image is loading. This flag will delay the loading * of the placeholder image until after the image has finished loading. * 默认情况下,占位图会在图片下载的时候显示.这个flag开启会延迟占位图显示的时间,等到图片下载完成之后才会显示占位图 */ SDWebImageDelayPlaceholder = 1 << 8, /** * We usually don't apply transform on animated images as most transformers could not manage animated images. * Use this flag to transform them anyway. * 我们通常不会对变换动图,因为大多数变缓都无法管理动图。 ?? */ SDWebImageTransformAnimatedImage = 1 << 9, /** * By default, image is added to the imageView after download. But in some cases, we want to * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) * Use this flag if you want to manually set the image in the completion when success * (默认情况下,图像在下载后添加到imageView。 * 但在某些情况下,我们希望在设置图像之前可以手动修改动画 */ SDWebImageAvoidAutoSetImage = 1 << 10, /** * By default, images are decoded respecting their original size. On iOS, this flag will scale down the * images to a size compatible with the constrained memory of devices. * This flag take no effect if `SDWebImageAvoidDecodeImage` is set. And it will be ignored if `SDWebImageProgressiveLoad` is set. * 默认情况下,图像将根据其原始大小进行解码。此标志将图像缩小到与设备的受限内存兼容的大小; * 主要用于加载大图片时避免高内存导致闪退 */ SDWebImageScaleDownLargeImages = 1 << 11, /** * By default, we do not query image data when the image is already cached in memory. This mask can force to query image data at the same time. However, this query is asynchronously unless you specify `SDWebImageQueryMemoryDataSync` * 默认情况下,当图像已经缓存在内存中时,我们不查询图像数据。 * 此掩码可以强制同时查询图像数据。除非指定“SDWebImageQueryMemoryDataSync”,否则此查询是异步的` */ SDWebImageQueryMemoryData = 1 << 12, /** * By default, when you only specify `SDWebImageQueryMemoryData`, we query the memory image data asynchronously. Combined this mask as well to query the memory image data synchronously. * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. * (默认情况下,当您仅指定“SDWebImageQueryMemoryData”时,我们将异步查询内存映像数据。结合该掩模,实现了对内存图像数据的同步查询。) */ SDWebImageQueryMemoryDataSync = 1 << 13, /** * By default, when the memory cache miss, we query the disk cache asynchronously. This mask can force to query disk cache (when memory cache miss) synchronously. * @note These 3 query options can be combined together. For the full list about these masks combination, see wiki page. * @note Query data synchronously is not recommend, unless you want to ensure the image is loaded in the same runloop to avoid flashing during cell reusing. * (默认情况下,当内存缓存丢失时,我们异步查询磁盘缓存。此掩码可以强制同步查询磁盘缓存(当内存缓存丢失时)。 */ SDWebImageQueryDiskDataSync = 1 << 14, /** * By default, when the cache missed, the image is load from the loader. This flag can prevent this to load from cache only. * (默认情况下,当缓存丢失时,从加载程序加载图像。 * 此标志可设置为仅从缓存加载此文件 */ SDWebImageFromCacheOnly = 1 << 15, /** * By default, we query the cache before the image is load from the loader. This flag can prevent this to load from loader only. * 默认情况下,我们在从加载程序加载图像之前查询缓存。此标志可防止仅从加载程序加载此文件。 */ SDWebImageFromLoaderOnly = 1 << 16, /** * By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image download from the network. This mask can force to apply view transition for memory and disk cache as well. * 默认情况下,当使用“SDWebImageTransition”在映像加载完成后执行某些视图转换时,此转换仅在管理器的回调是异步的(从网络或磁盘缓存查询)时应用于映像.此掩码可以强制对任何情况应用视图转换,如内存缓存查询或同步磁盘缓存查询 */ SDWebImageForceTransition = 1 << 17, /** * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation. * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image. * 默认情况下,我们将在缓存查询和从网络下载期间在后台解码图像。这有助于提高性能,因为在屏幕上渲染图像时,需要首先对其进行解码。但是,这个过程也会增加内存的使用。如果由于内存消耗过多而遇到问题,此标志可能会阻止对图像进行解码。 */ SDWebImageAvoidDecodeImage = 1 << 18, /** * By default, we decode the animated image. This flag can force decode the first frame only and produece the static image. * 默认情况下,我们解码动画图像。此标志只能强制解码第一帧并生成静态图像 */ SDWebImageDecodeFirstFrameOnly = 1 << 19, /** * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. However, you can specify to preload all frames into memory to reduce CPU usage when the animated image is shared by lots of imageViews. * This will actually trigger `preloadAllAnimatedImageFrames` in the background queue(Disk Cache & Download only). * 默认情况下,对于“SDAnimatedImage”,我们在渲染期间解码动画图像帧以减少内存使用。但是,您可以指定将所有帧预加载到内存中,以在大量ImageView共享动画图像时减少CPU使用量。这实际上会触发后台队列中的“prelodallanimatedImageFrames”(仅限于磁盘缓存和下载) */ SDWebImagePreloadAllFrames = 1 << 20 }; #pragma mark - Context Options /** A String to be used as the operation key for view category to store the image load operation. This is used for view instance which supports different image loading process. If nil, will use the class name as operation key. (NSString *) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextSetImageOperationKey; /** A SDWebImageManager instance to control the image download and cache process using in UIImageView+WebCache category and likes. If not provided, use the shared manager (SDWebImageManager *) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCustomManager; /** A id<SDImageTransformer> instance which conforms `SDImageTransformer` protocol. It's used for image transform after the image load finished and store the transformed image to cache. If you provide one, it will ignore the `transformer` in manager and use provided one instead. (id<SDImageTransformer>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageTransformer; /** A CGFloat raw value which specify the image scale factor. The number should be greater than or equal to 1.0. If not provide or the number is invalid, we will use the cache key to specify the scale factor. (NSNumber) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextImageScaleFactor; /** A SDImageCacheType raw value which specify the cache type when the image has just been downloaded and will be stored to the cache. Specify `SDImageCacheTypeNone` to disable cache storage; `SDImageCacheTypeDisk` to store in disk cache only; `SDImageCacheTypeMemory` to store in memory only. And `SDImageCacheTypeAll` to store in both memory cache and disk cache. If not provide or the value is invalid, we will use `SDImageCacheTypeAll`. (NSNumber) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextStoreCacheType; /** A Class object which the instance is a `UIImage/NSImage` subclass and adopt `SDAnimatedImage` protocol. We will call `initWithData:scale:options:` to create the instance (or `initWithAnimatedCoder:scale:` when using progressive download) . If the instance create failed, fallback to normal `UIImage/NSImage`. This can be used to improve animated images rendering performance (especially memory usage on big animated images) with `SDAnimatedImageView` (Class). */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextAnimatedImageClass; /** A id<SDWebImageDownloaderRequestModifier> instance to modify the image download request. It's used for downloader to modify the original request from URL and options. If you provide one, it will ignore the `requestModifier` in downloader and use provided one instead. (id<SDWebImageDownloaderRequestModifier>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextDownloadRequestModifier; /** A id<SDWebImageCacheKeyFilter> instance to convert an URL into a cache key. It's used when manager need cache key to use image cache. If you provide one, it will ignore the `cacheKeyFilter` in manager and use provided one instead. (id<SDWebImageCacheKeyFilter>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheKeyFilter; /** A id<SDWebImageCacheSerializer> instance to convert the decoded image, the source downloaded data, to the actual data. It's used for manager to store image to the disk cache. If you provide one, it will ignore the `cacheSerializer` in manager and use provided one instead. (id<SDWebImageCacheSerializer>) */ FOUNDATION_EXPORT SDWebImageContextOption _Nonnull const SDWebImageContextCacheSerializer;
LeoMarin/OpenGL
CollisionDetection/src/CollisionDetection.h
#pragma once #include "Point.h" #include "QuadTree.h" #include "SpatialHash.h" #include <GLCore.h> #include <GLCoreUtils.h> class CollisionDetection : public GLCore::Layer { public: enum class CollisionSystem { BruteForce = 0, QuadTree, SpatialHashing }; CollisionDetection(); virtual ~CollisionDetection(); virtual void OnAttach() override; virtual void OnDetach() override; virtual void OnEvent(GLCore::Event& event) override; virtual void OnUpdate(GLCore::Timestep ts) override; virtual void OnImGuiRender() override; void PointRenderingSetup(); void GridRenderingSetup(); void DrawPoints(); void DrawGrid(int collisionSystem); void MovePoints(); void GeneratePoints(); void GenerateVerices(std::vector<Vertex>& vertices); void GenerateIndices(std::vector<uint32_t>& indices); void BruteForceCollisionDetection(); void QuadTreeCollisionDetection(); void SpatialHashingCollisionDetection(); private: GLCore::Utils::Shader* m_Shader; GLCore::Utils::OrthographicCameraController m_CameraController; GLuint m_QuadVA, m_QuadVB, m_QuadIB, m_AccelerationVA, m_AccelerationVB, m_AccelerationIB; glm::vec4 m_SquareColor = { 1.f, 1.f, 1.f, 1.0f }; const float m_BoundaryX = 1.5f; const float m_BoundaryY = 1.f; float m_Speed = 0.05f; float m_PointSize = 0.005f; int m_NumberOfPoints = 10000; int m_PreviousNumberOfPoints = m_NumberOfPoints; const int m_MaxPoints = 10000; int collisionSystem = 2; std::vector<Point> m_Points; QuadTree quadTree{}; SpatialHash spatialHash{ m_BoundaryX, m_BoundaryY, 100, 100 }; bool isBruteforce = false, isQuadTree = false, isSpatialHash = true; };
LeoMarin/OpenGL
CollisionDetection/src/SpatialHash.h
#pragma once #include <vector> #include <cmath> #include "Point.h" #include <iostream> class SpatialHash { public: SpatialHash(float boundaryX, float boundaryY, int numberOfCellsPerRow, int numberOfCellsPerColumn); ~SpatialHash(); // Hash function int GetCellIndex(Point& point); void FillSpatialHashTable(std::vector<Point>& points, int numberOfPoints); void Redistribute(); void AddPoint(Point* p); void CollisionDetection(); void CheckAdjecentCells(Point& point, int cellIndex); void GenerateSpatialHashVertices(std::vector<Vertex>& vertices); void ClearPoints(); private: float m_BoundaryX, m_BoundaryY; int m_NumberOfCellsPerColumn, m_NumberofCellsPerRow; std::vector<std::vector<Point*>> m_HashedPoints; };
LeoMarin/OpenGL
CollisionDetection/src/QuadTree.h
<reponame>LeoMarin/OpenGL #pragma once #include "Point.h" #include <vector> class QuadTree { public: enum class ChildPosition { UpRight = 0, UpLeft, DownLeft, DownRight, Root }; QuadTree(); // creating parent node QuadTree(QuadTree& parent, ChildPosition childPosition); // creating child node ~QuadTree(); void GenerateQuadTree(std::vector<Point>& points, int numberOfPoints); void CreateChildNodes(); void AddPoint(Point& point); bool PointIsInsideQuad(const Point& point); void CreateQuadTreeVertices(std::vector<Vertex>& vertices); void Redistribute(); void DeleteChildNodes(); void CollisionDetection(); static const int maxPoints = 4; private: QuadTree* parentNode; QuadTree* childNodes[4] = { nullptr }; // order: up-right, up-left, down-left, down-right std::vector<Point*> points; float xMax, xMin, yMax, yMin; };
LeoMarin/OpenGL
CollisionDetection/src/Point.h
#pragma once #include <cmath> struct Vector2 { float x; float y; }; struct Point { Vector2 position; Vector2 speed; float size; Point(float posX, float posY, float speedX, float speedY, float size); void CollisionDetection(Point& other); void Move(float speed, float boundaryX, float boundaryY); }; struct Vertex { float Position[3]; Vertex(float x, float y, float z) { Position[0] = x; Position[1] = y; Position[2] = z; } };
georgelam6/SLECS
src/ComponentManager.h
#pragma once #include <unordered_map> #include <memory> #include "ECSCommon.h" #include "ComponentArray.h" class ComponentManager { private: std::unordered_map<const char*, ComponentType> m_componentTypes; std::unordered_map<const char*, std::shared_ptr<IComponentArray>> m_componentArrays; ComponentType m_nextComponentType; template <typename T> std::shared_ptr<ComponentArray<T>> GetComponentArray() { const char* typeName = typeid(T).name(); assert(m_componentTypes.find(typeName) != m_componentTypes.end() && "Component used before registration."); return std::static_pointer_cast<ComponentArray<T>>(m_componentArrays[typeName]); } public: template <typename T> void RegisterComponent() { const char* typeName = typeid(T).name(); assert(m_componentTypes.find(typeName) == m_componentTypes.end() && "Registering component type more than once."); m_componentTypes.insert({typeName, m_nextComponentType}); m_componentArrays.insert({typeName, std::make_shared<ComponentArray<T>>()}); ++m_nextComponentType; } template <typename T> ComponentType GetComponentType() { const char* typeName = typeid(T).name(); assert(m_componentTypes.find(typeName) != m_componentTypes.end() && "Component used before registration."); return m_componentTypes[typeName]; } template <typename T> void AddComponent(EntityHandle ent, T component) { GetComponentArray<T>()->InsertData(ent, component); } template <typename T> void RemoveComponent(EntityHandle ent) { GetComponentArray<T>()->RemoveData(ent); } template <typename T> T& GetComponent(EntityHandle ent) { return GetComponentArray<T>()->GetData(ent); } inline void EntityDestroyed(EntityHandle ent) { for (const auto& pair : m_componentArrays) { const auto& component = pair.second; component->EntityDestroyed(ent); } } };
georgelam6/SLECS
src/ComponentArray.h
<reponame>georgelam6/SLECS<gh_stars>0 #pragma once #include <unordered_map> #include <array> #include <cassert> #include "ECSCommon.h" class IComponentArray { public: virtual ~IComponentArray() = default; virtual void EntityDestroyed(EntityHandle ent) = 0; }; template <typename T> class ComponentArray : public IComponentArray { private: std::array<T, MAX_COMPONENTS> m_componentArray; std::unordered_map<EntityHandle, size_t> m_entityToIndexMap; std::unordered_map<size_t, EntityHandle> m_indexToEntityMap; size_t m_size; public: inline void InsertData(EntityHandle ent, T component) { assert(m_entityToIndexMap.find(ent) == m_entityToIndexMap.end() && "Component added to same entity more than once."); size_t newIndex = m_size; m_entityToIndexMap[ent] = newIndex; m_indexToEntityMap[newIndex] = ent; m_componentArray[newIndex] = component; ++m_size; } inline void RemoveData(EntityHandle ent) { assert(m_entityToIndexMap.find(ent) != m_entityToIndexMap.end() && "Removing non-existent component."); size_t indexOfRemovedEntity = m_entityToIndexMap[ent]; size_t indexOfLastElement = m_size - 1; m_componentArray[indexOfRemovedEntity] = m_componentArray[indexOfLastElement]; EntityHandle entityOfLastElement = m_indexToEntityMap[indexOfLastElement]; m_entityToIndexMap[entityOfLastElement] = indexOfRemovedEntity; m_indexToEntityMap[indexOfRemovedEntity] = entityOfLastElement; m_entityToIndexMap.erase(ent); m_indexToEntityMap.erase(indexOfLastElement); --m_size; } inline T& GetData(EntityHandle ent) { assert(m_entityToIndexMap.find(ent) != m_entityToIndexMap.end() && "Retrieving non-existent component."); return m_componentArray[m_entityToIndexMap[ent]]; } inline void EntityDestroyed(EntityHandle ent) override { if (m_entityToIndexMap.find(ent) != m_entityToIndexMap.end()) { RemoveData(ent); } } };
georgelam6/SLECS
src/EntityManager.h
#pragma once #include "ECSCommon.h" #include <queue> #include <array> class EntityManager { private: std::queue<EntityHandle> m_availableEntities; std::array<Signature, MAX_ENTITIES> m_signatures; uint32_t m_livingEntityCount{0}; public: EntityManager(); EntityHandle CreateEntity(); void DestroyEntity(EntityHandle ent); void SetSignature(EntityHandle ent, Signature signature); Signature GetSignature(EntityHandle ent); };
georgelam6/SLECS
include/SLECS.h
#pragma once #include <memory> #include "../src/ECSCommon.h" #include "../src/ComponentManager.h" #include "../src/EntityManager.h" #include "../src/SystemManager.h" #include "../src/ComponentArray.h" #include "../src/System.h" class ECS { private: std::unique_ptr<ComponentManager> m_componentManager; std::unique_ptr<EntityManager> m_entityManager; std::unique_ptr<SystemManager> m_systemManager; public: ECS() { m_componentManager = std::make_unique<ComponentManager>(); m_entityManager = std::make_unique<EntityManager>(); m_systemManager = std::make_unique<SystemManager>(); } /* Entities */ EntityHandle CreateEntity() { return m_entityManager->CreateEntity(); } void DestroyEntity(EntityHandle ent) { m_entityManager->DestroyEntity(ent); m_componentManager->EntityDestroyed(ent); m_systemManager->EntityDestroyed(ent); } /* Components */ template <typename T> void RegisterComponent() { m_componentManager->RegisterComponent<T>(); } template <typename T> T& AddComponent(EntityHandle ent, T component) { m_componentManager->AddComponent<T>(ent, component); auto signature = m_entityManager->GetSignature(ent); signature.set(m_componentManager->GetComponentType<T>(), true); m_entityManager->SetSignature(ent, signature); m_systemManager->EntitySignatureChanged(ent, signature); return m_componentManager->GetComponent<T>(ent); } template <typename T> void RemoveComponent(EntityHandle ent) { m_componentManager->RemoveComponent<T>(ent); auto signature = m_entityManager->GetSignature(ent); signature.set(m_componentManager->GetComponentType<T>(), false); m_entityManager->SetSignature(ent, signature); m_systemManager->EntitySignatureChanged(ent, signature); } template <typename T> T& GetComponent(EntityHandle ent) { return m_componentManager->GetComponent<T>(ent); } template <typename T> bool HasComponent(EntityHandle ent) { return m_entityManager->GetSignature(ent).test(m_componentManager->GetComponentType<T>()); } template <typename T> ComponentType GetComponentType() { return m_componentManager->GetComponentType<T>(); } /* Systems */ template <typename T, typename... Args> std::shared_ptr<T> RegisterSystem(Args... constructorArgs) { return m_systemManager->RegisterSystem<T>(constructorArgs...); } template <typename T> void SetSystemSignature(Signature signature) { m_systemManager->SetSignature<T>(signature); } };
georgelam6/SLECS
src/ECSCommon.h
#pragma once #include <cstdint> #include <bitset> using EntityHandle = std::uint32_t; using ComponentType = std::uint8_t; static const std::uint32_t MAX_ENTITIES = 5000; static const std::uint8_t MAX_COMPONENTS = 32; using Signature = std::bitset<MAX_COMPONENTS>;
georgelam6/SLECS
src/SystemManager.h
<gh_stars>0 #pragma once #include <unordered_map> #include <memory> #include <cassert> #include "System.h" class SystemManager { private: std::unordered_map<const char*, Signature> m_signatures; std::unordered_map<const char*, std::shared_ptr<System>> m_systems; public: void EntityDestroyed(EntityHandle ent); void EntitySignatureChanged(EntityHandle ent, Signature entitySignature); template<typename T, typename... Args> std::shared_ptr<T> RegisterSystem(Args... constructorArgs) { const char* typeName = typeid(T).name(); assert(m_systems.find(typeName) == m_systems.end() && "Registering a system more than once."); auto system = std::make_shared<T>(constructorArgs...); m_systems.insert({typeName, system}); return system; } template<typename T> void SetSignature(Signature signature) { const char* typeName = typeid(T).name(); assert(m_systems.find(typeName) != m_systems.end() && "System used before registration."); m_signatures.insert({typeName, signature}); } };
georgelam6/SLECS
src/System.h
<reponame>georgelam6/SLECS #pragma once #include <set> #include "ECSCommon.h" class System { public: std::set<EntityHandle> m_entities; };
zyvv/BBUpdate
BBUpdate/BBUpdate.h
// // BBUpdate.h // BBUpdate // // Created by 张洋威 on 2016/10/20. // Copyright © 2016年 yhyvr.<EMAIL>. All rights reserved. // #import <Foundation/Foundation.h> @interface BBUpdate : NSObject /** 配置应用商店appID @param appID 应用商店appID */ + (void)updateWithAppID:(nonnull NSString *)appID; /** 配置更新弹框提示 @param alertTitle 提示的标题 默认:“应用名+有新版本了”,比如“奇幻斑斑有新版本了” @param updateTitle 马上更新按钮的标题 默认:“马上更新” @param cancelTitle 取消更新按钮的标题 默认:“我知道了” */ + (void)setupAlertTitle:(nullable NSString *)alertTitle updateTitle:(nullable NSString *)updateTitle cancelTitle:(nullable NSString *)cancelTitle; @end
iambhavikmistry/banksystem
BankSystem.c
#include<stdio.h> main() { int i,j,k,l,co,n; float balance=0,add,wid,temp; char us[6],ps[6],yn; login: printf("Enter Username : \n"); fflush(stdin); scanf("%[^\n]",us); printf("Enter Password : \n"); fflush(stdin); scanf("%[^\n]",ps); // printf("%s",us); // printf("%s",ps); for(l=0; l<5; l++) { switch(l) { case 0: if(us[0] != 'a' || ps[0] != 'a') { goto login; } break; case 1: if(us[1] != 'd' || ps[1] != 'd') { goto login; } break; case 2: if(us[2] != 'm' || ps[2] != 'm') { goto login; } break; case 3: if(us[3] != 'i' || ps[3] != 'i') { goto login; } break; case 4: if(us[4] != 'n' || ps[4] != 'n') { goto login; } break; default: printf("Invalid"); break; } } options: printf("\n\n\n\t\t\tWelcome to Kangal Bank\n\n\n"); printf("\t\tSelect Options\n\n"); printf("\t\t1.Deposit\n"); printf("\t\t2.Withdraw\n"); printf("\t\t3.Check available balance\n"); printf("\t\t4.LogOut\n\n\n"); printf("Choose Option : "); scanf("%d",&co); switch(co) { case 1: printf("\t\t\nHow much amount do you want to DEPOSIT : "); scanf("%f",&add); balance+=add; printf("\t\t\nAvailable Balance is %f",balance); goto options; break; case 2: printf("\t\t\nHow much amount do you want to WITHDRAW : "); scanf("%f",&wid); if(wid>balance) { printf("\n\t\tYou don't have enough money\n\t\tPlease choose correct option"); goto options; } balance-=wid; printf("\t\t\nAvailable Balance is %f",balance); goto options; break; case 3: printf("\t\t\n\nAvailable Balance is %f",balance); goto options; break; case 4: printf("\n\t\tyou are logged out\n\n\ndo you want to login again? yes or no :"); fflush(stdin); scanf("%c",&yn); if(yn=='y'||yn=='Y') { goto login; } else { printf("\t\tBYE SEE YOU SOON"); } } }
pepstack/pytools
templates/%clib%/src/common/misc.h
/*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename misc.h * miscellaneous tools for application. * * @author <NAME> <<EMAIL>> * @version 0.0.10 * @create 2017-08-28 11:12:10 * @update 2021-07-20 11:55:37 */ #ifndef _MISC_H_ #define _MISC_H_ #if defined(__cplusplus) extern "C" { #endif #include "cstrbuf.h" #define ERROR_STRING_LEN_MAX 1024 #if defined(__WINDOWS__) # include <Windows.h> typedef HANDLE filehandle_t; # define filehandle_invalid INVALID_HANDLE_VALUE # define fseek_pos_set ((int)FILE_BEGIN) # define fseek_pos_cur ((int)FILE_CURRENT) # define fseek_pos_end ((int)FILE_END) # define getprocessid() ((int)GetCurrentProcessId()) # define getthreadid() ((int) GetCurrentThreadId()) #else /* non-windows: Linux or Cygwin */ /* See feature_test_macros(7) */ #ifndef _LARGEFILE64_SOURCE # define _LARGEFILE64_SOURCE #endif # include <sys/types.h> # include <sys/stat.h> # include <sys/time.h> # include <fcntl.h> # include <unistd.h> /* usleep() */ # if defined(__CYGWIN__) # include <Windows.h> # include <pthread.h> /* pthread_self() */ NOWARNING_UNUSED(static) pid_t getthreadid(void) { pthread_t tid = pthread_self(); return (int)ptr_cast_to_int(tid); } # else /* non-cygwin */ # include <sys/syscall.h> /* syscall(SYS_gettid) */ NOWARNING_UNUSED(static) pid_t getthreadid(void) { return syscall(SYS_gettid); } # endif # define getprocessid() ((int)getpid()) typedef int filehandle_t; # define filehandle_invalid ((filehandle_t)(-1)) # define fseek_pos_set ((int)SEEK_SET) # define fseek_pos_cur ((int)SEEK_CUR) # define fseek_pos_end ((int)SEEK_END) #endif /** * error message api */ #if defined(__WINDOWS__) || defined(__CYGWIN__) NOWARNING_UNUSED(static) const char *format_win32_syserror (int werrnum, char *errmsgbuf, size_t bufsize) { int len; *errmsgbuf = '\0'; len = (int) FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, (DWORD)werrnum, 0, errmsgbuf, (DWORD)bufsize, NULL); if (! len) { snprintf(errmsgbuf, bufsize, "Failed to FormatMessageA for Windows Error(%d): LastError=%d", werrnum, (int) GetLastError()); } else if (len < (int) bufsize) { errmsgbuf[len] = '\0'; } errmsgbuf[bufsize - 1] = '\0'; return errmsgbuf; } #else NOWARNING_UNUSED(static) const char *format_posix_syserror (int errnum, char *errmsgbuf, size_t bufsize) { char *str = errmsgbuf; *errmsgbuf = '\0'; /* GNU-specific */ str = strerror_r(errnum, errmsgbuf, bufsize); errmsgbuf[bufsize - 1] = '\0'; return str; } #endif /** * file api */ #if defined(__WINDOWS__) NOWARNING_UNUSED(static) filehandle_t file_create(const char *pathname, int flags, int mode) { filehandle_t hf = CreateFileA(pathname, (DWORD)(flags), FILE_SHARE_READ, NULL, CREATE_NEW, (DWORD)(mode), NULL); return hf; } NOWARNING_UNUSED(static) filehandle_t file_open_read(const char *pathname) { filehandle_t hf = CreateFileA(pathname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); return hf; } NOWARNING_UNUSED(static) filehandle_t file_write_new(const char *pathname) { return file_create(pathname, GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL); } NOWARNING_UNUSED(static) int file_close(filehandle_t *phf) { if (phf) { filehandle_t hf = *phf; if (hf != filehandle_invalid) { *phf = filehandle_invalid; if (CloseHandle(hf)) { return 0; } } } return (-1); } NOWARNING_UNUSED(static) sb8 file_seek(filehandle_t hf, sb8 distance, int fseekpos) { LARGE_INTEGER li; li.QuadPart = distance; if (SetFilePointerEx(hf, li, &li, fseekpos)) { return (sb8)li.QuadPart; } /* error */ return (sb8)(-1); } NOWARNING_UNUSED(static) sb8 file_size(filehandle_t hf) { LARGE_INTEGER li; if (GetFileSizeEx(hf, &li)) { /* success */ return (sb8)li.QuadPart; } /* error */ return (sb8)(-1); } NOWARNING_UNUSED(static) int file_readbytes(filehandle_t hf, char *bytesbuf, ub4 sizebuf) { BOOL ret; DWORD cbread, cboffset = 0; while (cboffset != (DWORD)sizebuf) { ret = ReadFile(hf, (void *)(bytesbuf + cboffset), (DWORD)(sizebuf - cboffset), &cbread, NULL); if (!ret) { /* read on error: uses GetLastError() for more */ return (-1); } if (cbread == 0) { /* reach to end of file */ break; } cboffset += cbread; } /* success: actual read bytes */ return (int)cboffset; } NOWARNING_UNUSED(static) int file_writebytes(filehandle_t hf, const char *bytesbuf, ub4 bytestowrite) { BOOL ret; DWORD cbwritten, cboffset = 0; while (cboffset != (DWORD)bytestowrite) { ret = WriteFile(hf, (const void *)(bytesbuf + cboffset), (DWORD)(bytestowrite - cboffset), &cbwritten, NULL); if (!ret) { /* write on error */ return (-1); } cboffset += cbwritten; } /* success */ return 0; } NOWARNING_UNUSED(static) int pathfile_exists(const char *pathname) { if (pathname) { WIN32_FIND_DATAA FindFileData; HANDLE handle = FindFirstFileA(pathname, &FindFileData); if (handle != INVALID_HANDLE_VALUE) { FindClose(handle); /* found */ return 1; } } /* not found */ return 0; } NOWARNING_UNUSED(static) int pathfile_remove(const char *pathname) { if (DeleteFileA(pathname)) { return 0; } return (-1); } NOWARNING_UNUSED(static) int pathfile_move(const char *pathnameOld, const char *pathnameNew) { return MoveFileA(pathnameOld, pathnameNew); } #else /* Linux? */ NOWARNING_UNUSED(static) filehandle_t file_create(const char *pathname, int flags, int mode) { int fd = open(pathname, flags | O_CREAT | O_EXCL, (mode_t)(mode)); return fd; } NOWARNING_UNUSED(static) filehandle_t file_open_read(const char *pathname) { int fd = open(pathname, O_RDONLY | O_EXCL, S_IRUSR | S_IRGRP | S_IROTH); return fd; } NOWARNING_UNUSED(static) filehandle_t file_write_new(const char *pathname) { return file_create(pathname, O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); } NOWARNING_UNUSED(static) int file_close(filehandle_t *phf) { if (phf) { filehandle_t hf = *phf; if (hf != filehandle_invalid) { *phf = filehandle_invalid; return close(hf); } } return (-1); } NOWARNING_UNUSED(static) sb8 file_seek(filehandle_t hf, sb8 distance, int fseekpos) { #ifdef WIN32 /* warning: cygwin */ return (sb8) lseek(hf, distance, fseekpos); #else return (sb8) lseek64(hf, (off64_t)distance, fseekpos); #endif } NOWARNING_UNUSED(static) int file_readbytes(filehandle_t hf, char *bytesbuf, ub4 sizebuf) { size_t cbread, cboffset = 0; while (cboffset != (size_t)sizebuf) { cbread = read(hf, (void *)(bytesbuf + cboffset), (size_t)(sizebuf - cboffset)); if (cbread == -1) { /* read on error: uses strerror(errno) for more */ return (-1); } if (cbread == 0) { /* reach to end of file */ break; } cboffset += cbread; } /* success: actual read bytes */ return (int)cboffset; } /* https://linux.die.net/man/2/write */ NOWARNING_UNUSED(static) int file_writebytes(filehandle_t hf, const char *bytesbuf, ub4 bytestowrite) { ssize_t cbret; off_t woffset = 0; while (woffset != (off_t)bytestowrite) { cbret = write(hf, (const void *)(bytesbuf + woffset), bytestowrite - woffset); if (cbret == -1) { /* error */ return (-1); } if (cbret > 0) { woffset += cbret; } } /* success */ return 0; } NOWARNING_UNUSED(static) int pathfile_exists(const char *pathname) { if (pathname && access(pathname, F_OK) != -1) { /* file exists */ return 1; } /* file doesn't exist */ return 0; } NOWARNING_UNUSED(static) int pathfile_remove(const char *pathname) { return remove(pathname); } NOWARNING_UNUSED(static) int pathfile_move(const char *pathnameOld, const char *pathnameNew) { return rename(pathnameOld, pathnameNew); } #endif NOWARNING_UNUSED(static) int getenv_with_prefix(const char *varName, const char *prefix, char *valBuf, size_t valBufSize) { const char *env = getenv(varName); if (env) { int prelen = cstr_length(prefix, valBufSize); int envlen = cstr_length(env, valBufSize); if (prelen + envlen < (int)valBufSize) { return snprintf_chkd_V1(valBuf, valBufSize, "%.*s%.*s", prelen, prefix, envlen, env); } else { /* buffer is not enough */ return -1; } } /* env not found */ return 0; } NOWARNING_UNUSED(static) cstrbuf get_proc_pathfile(void) { int r, bufsize = 128; char *pathbuf = (char*) alloca(bufsize); #if defined(__WINDOWS__) while ((r = (int)GetModuleFileNameA(0, pathbuf, (DWORD)bufsize)) >= bufsize) { bufsize += 128; pathbuf = (char*) alloca(bufsize); } if (r <= 0) { printf("GetModuleFileNameA failed.\n"); exit(EXIT_FAILURE); } #else while ((r = readlink("/proc/self/exe", pathbuf, bufsize)) >= (int)bufsize) { bufsize += 128; pathbuf = alloca(bufsize); } if (r <= 0) { printf("readlink failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); } #endif pathbuf[r] = '\0'; return cstrbufNew(0, pathbuf, r); } /** * get_proc_abspath * get absolute path for current process. */ NOWARNING_UNUSED(static) cstrbuf get_proc_abspath(void) { cstrbuf pathfile = get_proc_pathfile(); char *p = strrchr(pathfile->str, '\\'); char *q = strrchr(pathfile->str, '/'); if (p && q) { (p > q)? (*p = 0) : (*q = 0); } else if (p) { *p = 0; } else if (q) { *q = 0; } pathfile->len = (ub4)strnlen(pathfile->str, pathfile->len); return pathfile; } NOWARNING_UNUSED(static) cstrbuf find_config_pathfile(const char *cfgpath, const char *cfgname, const char *envvarname, const char *etcconfpath) { cstrbuf config = 0; cstrbuf dname = 0; cstrbuf tname = 0; cstrbuf pname = 0; tname = cstrbufCat(0, "/%s", cfgname); pname = cstrbufCat(0, "%c%s", PATH_SEPARATOR_CHAR, cfgname); if (cfgpath) { int pathlen = cstr_length(cfgpath, -1); if (cstr_endwith(cfgpath, pathlen, pname->str, (int)pname->len) || cstr_endwith(cfgpath, pathlen, tname->str, (int)tname->len)) { config = cstrbufNew(0, cfgpath, pathlen); } else { char endchr = cfgpath[pathlen - 1]; if (endchr == PATH_SEPARATOR_CHAR || endchr == '/') { config = cstrbufCat(0, "%.*s%.*s", pathlen, cfgpath, (int)pname->len - 1, cfgname); } else { config = cstrbufCat(0, "%.*s%c%.*s", pathlen, cfgpath, PATH_SEPARATOR_CHAR, (int)pname->len - 1, cfgname); } } printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); goto finish_up; } else { char *p; dname = get_proc_abspath(); // 1: "$(appbin_dir)/clogger.cfg" config = cstrbufConcat(dname, pname, 0); if (config) { printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); } else { printf("(misc.h:%d) [%d] null config\n", __LINE__, getprocessid()); } if (pathfile_exists(config->str)) { goto finish_up; } cstrbufFree(&config); // 2: "$(appbin_dir)/conf/clogger.cfg" config = cstrbufCat(0, "%.*s%cconf%.*s", cstrbufGetLen(dname), cstrbufGetStr(dname), PATH_SEPARATOR_CHAR, cstrbufGetLen(pname), cstrbufGetStr(pname)); printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); if (pathfile_exists(config->str)) { goto finish_up; } // 3: "$appbindir/../conf/clogger.cfg" cstrbufTrunc(config, dname->len); p = strrchr(config->str, PATH_SEPARATOR_CHAR); if (p) { cstrbufTrunc(config, (ub4)(p - config->str)); config = cstrbufCat(config, "%cconf%.*s", PATH_SEPARATOR_CHAR, cstrbufGetLen(pname), cstrbufGetStr(pname)); if (config) { printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); } else { printf("(misc.h:%d) [%d] null config\n", __LINE__, getprocessid()); } if (pathfile_exists(config->str)) { goto finish_up; } } cstrbufFree(&config); if (envvarname) { // 4: $CLOGGER_CONF=/path/to/clogger.cfg printf("(misc.h:%d) [%d] check environment: %s\n", __LINE__, getprocessid(), envvarname); p = getenv(envvarname); if (p) { char endchr; config = cstrbufNew(cstr_length(p, -1) + pname->len + 1, p, -1); if (cstr_endwith(config->str, config->len, pname->str, (int)pname->len) || cstr_endwith(config->str, config->len, tname->str, (int)tname->len)) { printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); goto finish_up; } endchr = config->str[config->len - 1]; if (endchr == PATH_SEPARATOR_CHAR || endchr == '/') { config = cstrbufCat(config, "%.*s", (int)pname->len - 1, cfgname); } else { config = cstrbufCat(config, "%.*s", cstrbufGetLen(pname), cstrbufGetStr(pname)); } printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); goto finish_up; } } if (etcconfpath) { printf("(misc.h:%d) [%d] check os path: %s\n", __LINE__, getprocessid(), etcconfpath); config = cstrbufCat(0, "%s%.*s", etcconfpath, cstrbufGetLen(pname), cstrbufGetStr(pname)); printf("(misc.h:%d) [%d] check config: %.*s\n", __LINE__, getprocessid(), cstrbufGetLen(config), cstrbufGetStr(config)); goto finish_up; } } finish_up: cstrbufFree(&tname); cstrbufFree(&pname); cstrbufFree(&dname); /* dont need to know whether config exists or not at all */ return config; } #ifdef __cplusplus } #endif #endif /* _MISC_H_ */
pepstack/pytools
templates/%clib%/src/common/shmipc.h
<filename>templates/%clib%/src/common/shmipc.h /*********************************************************************** * Copyright (c) 2008-2080, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename shmipc.h * shared memory ipc for Windows and Linux * * @author <NAME> <<EMAIL>> * @version 1.0.0 * @create 2020-12-05 12:46:50 * @update 2021-05-18 18:25:08 * */ #ifndef SHMIPC_H__ #define SHMIPC_H__ #if defined(__cplusplus) extern "C" { #endif #include "cstrbuf.h" #if defined(__WINDOWS__) || defined(__CYGWIN__) # include <Windows.h> # else /* LINUX */ # include <sys/ipc.h> # include <sys/shm.h> #endif #ifndef __STDC_FORMAT_MACROS # define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #ifndef NOWARNING_UNUSED # if defined(__GNUC__) || defined(__CYGWIN__) # define NOWARNING_UNUSED(x) __attribute__((unused)) x # else # define NOWARNING_UNUSED(x) x # endif #endif #if defined(__WINDOWS__) || defined(__CYGWIN__) typedef HANDLE shmhandle_t; typedef char * shmkey_t; #else typedef int shmhandle_t; typedef key_t shmkey_t; #endif #define shmipc_invalid_handle ((shmhandle_t)(-1)) #if defined(__WINDOWS__) || defined(__CYGWIN__) NOWARNING_UNUSED(static) shmkey_t shmipc_keygen (const char *filename, int pid, char *keybuf, size_t bufsz) { snprintf(keybuf, bufsz, "Local\\%s.%d", filename, pid); keybuf[bufsz - 1] = 0; return keybuf; } NOWARNING_UNUSED(static) shmhandle_t shmipc_create (const char *key, const void *copydata, size_t copysize, size_t maxsize, size_t offset) { HANDLE hMapFile; PVOID pvBuf; int err; if (maxsize < copysize) { maxsize = copysize; } hMapFile = CreateFileMappingA( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access (DWORD) 0, // maximum object size (high-order DWORD) (DWORD) maxsize, // maximum object size (low-order DWORD) key); // name of mapping object: "Local\\yourname" if (! hMapFile) { errno = GetLastError(); return shmipc_invalid_handle; } pvBuf = MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission (DWORD) 0, (DWORD) offset, (SIZE_T) copysize); if (! pvBuf) { err = GetLastError(); CloseHandle(hMapFile); errno = err; return shmipc_invalid_handle; } memcpy(pvBuf, copydata, copysize); if (! UnmapViewOfFile(pvBuf)) { err = GetLastError(); CloseHandle(hMapFile); errno = err; return shmipc_invalid_handle; } return hMapFile; } NOWARNING_UNUSED(static) int shmipc_read (const char *key, void *readbuf, size_t readbytes, size_t offset) { HANDLE hMapFile; PVOID pvBuf; int err; hMapFile = OpenFileMappingA( FILE_MAP_READ, // read access FALSE, // do not inherit the name key); // name of mapping object if (! hMapFile) { errno = GetLastError(); return -1; } pvBuf = MapViewOfFile(hMapFile, // handle to map object FILE_MAP_READ, // read permission (DWORD) 0, (DWORD) offset, (SIZE_T) readbytes); if (! pvBuf) { err = GetLastError(); CloseHandle(hMapFile); errno = err; return -1; } memcpy(readbuf, pvBuf, readbytes); UnmapViewOfFile(pvBuf); CloseHandle(hMapFile); return 0; } NOWARNING_UNUSED(static) void shmipc_destroy (shmhandle_t *hp) { HANDLE h = *hp; if (h != shmipc_invalid_handle) { *hp = shmipc_invalid_handle; CloseHandle(h); } } #else /* LINUX */ NOWARNING_UNUSED(static) shmkey_t shmipc_keygen (const char *filename, int pid) { int pidint = pid; char pidstr[20]; int idx = snprintf(pidstr, sizeof(pidstr), "%x", pid) - 1; if (pidstr[idx] == '0') { pidstr[idx] = pidstr[0]; } errno = 0; pidint = (int) strtol(pidstr, NULL, 16); if (errno) { perror("strtol"); } /* https://man7.org/linux/man-pages/man3/ftok.3.html */ return (shmkey_t) ftok(filename, pidint); } NOWARNING_UNUSED(static) shmhandle_t shmipc_create (shmkey_t key, const void *copydata, size_t copysize, size_t maxsize, size_t offset) { int shmid, err; void *addr; int flags = 0600 | IPC_CREAT | IPC_EXCL; if (maxsize < copysize) { maxsize = copysize; } shm_create_always: shmid = shmget(key, maxsize, flags); if (shmid == shmipc_invalid_handle) { if (errno != EEXIST) { return (-1); } shmid = shmget(key, 0, 0); if (shmid == shmipc_invalid_handle) { return (-1); } if (shmctl(shmid, IPC_RMID, 0) == -1) { return (-1); } goto shm_create_always; } addr = shmat(shmid, NULL, 0); if (!addr) { err = errno; shmctl(shmid, IPC_RMID, 0); errno = err; return (-1); } memcpy(addr, copydata, copysize); shmdt(addr); return shmid; } NOWARNING_UNUSED(static) int shmipc_read (shmkey_t key, void *readbuf, size_t readbytes, size_t offset) { int shmid; void *addr; shmid = shmget(key, 0, 0); if (shmid == shmipc_invalid_handle) { return (-1); } addr = shmat(shmid, 0, 0); if (!addr) { return (-1); } memcpy(readbuf, addr + offset, readbytes); shmdt(addr); return 0; } NOWARNING_UNUSED(static) void shmipc_destroy (shmhandle_t *hp) { int shmid = *hp; if (shmid != shmipc_invalid_handle) { *hp = shmipc_invalid_handle; shmctl(shmid, IPC_RMID, 0); } } #endif #ifdef __cplusplus } #endif #endif /* SHMIPC_H__ */
pepstack/pytools
templates/%clib%/src/common/timeut.h
<gh_stars>0 /*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename timeut.h * date time utility api. * * @author <NAME> <<EMAIL>> * @version 0.0.10 * @create 2017-08-28 11:12:10 * @update 2021-03-12 22:55:37 */ #ifndef _TIMEUT_H_ #define _TIMEUT_H_ #if defined(__cplusplus) extern "C" { #endif #include "mscrtdbg.h" #include "unitypes.h" #if defined(__WINDOWS__) static void sleep_msec(int milliseconds) { Sleep(milliseconds); } static void sleep_usec(int microseconds) { int ms = microseconds / 1000; int us = microseconds % 1000; if (ms > 0) { Sleep(ms); } if (us > 0) { LARGE_INTEGER lval = { 0 }; LONGLONG startTime; double cpuFreq, delayTimeUs = 0; // get cpuFreq if (!QueryPerformanceFrequency(&lval)) { return; } cpuFreq = (double)lval.QuadPart; if (cpuFreq < 1000) { return; } // get startTime if (!QueryPerformanceCounter(&lval)) { return; } startTime = lval.QuadPart; do { Sleep(0); if (!QueryPerformanceCounter(&lval)) { return; } delayTimeUs = (((double)(lval.QuadPart - startTime)) / cpuFreq) * 1000000; } while (delayTimeUs < us); } } #else /* non-windows: Linux or Cygwin */ #ifndef _TIMESPEC_DEFINED # define _TIMESPEC_DEFINED #endif /* sleep in milliseconds */ NOWARNING_UNUSED(static) void sleep_msec(int milliseconds) { if (milliseconds > 0) { struct timespec ts; ts.tv_sec = milliseconds / 1000; ts.tv_nsec = (milliseconds % 1000) * 1000000; nanosleep(&ts, 0); } } /* sleep in micro seconds, do not use usleep */ NOWARNING_UNUSED(static) void sleep_usec(int us) { if (us > 0) { /** * 1 sec = 1000 ms (millisec) * 1 ms = 1000 us (microsec) * 1 us = 1000 ns (nanosec) * 1 sec = 1000 000 000 ns (nanosec) */ struct timespec ts; ts.tv_sec = us / 1000000; ts.tv_nsec = (us % 1000000) * 1000; nanosleep(&ts, 0); } } #endif NOWARNING_UNUSED(static) const char *timezone_format(long tz, char *tzfmt) { if (tz < 0) { snprintf_chkd_V1(tzfmt, 5 + 1, "+%02d%02d", -(int)(tz / 3600), -(int)((tz % 3600) / 60)); } else if (tz > 0) { snprintf_chkd_V1(tzfmt, 5 + 1, "-%02d%02d", (int)(tz / 3600), (int)((tz % 3600) / 60)); } else { /* UTC */ memcpy(tzfmt, "+0000", 5); } tzfmt[5] = 0; return tzfmt; } NOWARNING_UNUSED(static) long timezone_compute(time_t ts, char *tzfmt) { long tz; time_t ut; struct tm t; #if defined(__WINDOWS__) if (gmtime_s(&t, &ts) != (errno_t)0) { /* error */ perror("gmtime_s\n"); return (-1); } ut = mktime(&t); #else if (!gmtime_r(&ts, &t)) { /* error */ perror("gmtime\n"); return (-1); } ut = mktime(&t); #endif tz = (long)difftime(ut, ts); if (tzfmt) { timezone_format(tz, tzfmt); } return tz; } NOWARNING_UNUSED(static) int daylight_compute(time_t ts) { struct tm tm; tm.tm_isdst = 0; #if defined(__WINDOWS__) localtime_s(&tm, &ts); #else localtime_r(&ts, &tm); #endif return tm.tm_isdst; } NOWARNING_UNUSED(static) void getnowtimeofday(struct timespec *now) { #if defined(_WIN32) FILETIME tmfile; ULARGE_INTEGER _100nanos; GetSystemTimeAsFileTime(&tmfile); _100nanos.LowPart = tmfile.dwLowDateTime; _100nanos.HighPart = tmfile.dwHighDateTime; _100nanos.QuadPart -= 0x19DB1DED53E8000; /* Convert 100ns units to seconds */ now->tv_sec = (time_t)(_100nanos.QuadPart / (10000 * 1000)); /* Convert remainder to nanoseconds */ now->tv_nsec = (long) ((_100nanos.QuadPart % (10000 * 1000)) * 100); #else if (clock_gettime(CLOCK_REALTIME, now) == -1) { /* must be successful */ perror("clock_gettime"); exit(EXIT_FAILURE); } #endif } /** * taken from: redis/src/localtime.c * although localtime_s on windows is a bit faster than getlocaltime_safe, * here we use getlocaltime_safe due to it cross-platforms. */ NOWARNING_UNUSED(static) void getlocaltime_safe(struct tm *loc, int64_t t, int tz, int dst) { /** * A year not divisible by 4 is not leap. * If div by 4 and not 100 is surely leap. * If div by 100 *and* 400 is not leap. * If div by 100 and not by 400 is leap. */ #define YEAR_IS_LEAPYEAR(year) ((year) % 4 ? 0 : ((year) % 100 ? 1 : ((year) % 400 ? 0 : 1))) #define SECONDS_PER_MINUTE ((time_t)60) #define SECONDS_PER_HOUR ((time_t)3600) #define SECONDS_PER_DAY ((time_t)86400) /* We need to calculate in which month and day of the month we are. To do * so we need to skip days according to how many days there are in each * month, and adjust for the leap year that has one more day in February. */ static const int mean_mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; static const int leap_mdays[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /* Adjust for timezone. 0 for UTC */ t -= tz; /* Adjust for daylight time. 0 default */ t += 3600 * dst; /* Days passed since epoch. */ int64_t days = t / SECONDS_PER_DAY; /* Remaining seconds. */ int64_t seconds = t % SECONDS_PER_DAY; loc->tm_isdst = dst; loc->tm_hour = (int)(seconds / SECONDS_PER_HOUR); loc->tm_min = (int)((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE); loc->tm_sec = (int)((seconds % SECONDS_PER_HOUR) % SECONDS_PER_MINUTE); /* 1/1/1970 was a Thursday, that is, day 4 from the POV of the tm structure * where sunday = 0, so to calculate the day of the week we have to add 4 * and take the modulo by 7. */ loc->tm_wday = (int)((days + 4) % 7); /* Calculate the current year. */ loc->tm_year = 1970; while (1) { /* Leap years have one day more. */ int64_t days_this_year = 365 + YEAR_IS_LEAPYEAR(loc->tm_year); if (days_this_year > days) break; days -= days_this_year; loc->tm_year++; } /* Number of day of the current year. */ loc->tm_yday = (int)days; loc->tm_mon = 0; if (YEAR_IS_LEAPYEAR(loc->tm_year)) { while (days >= leap_mdays[loc->tm_mon]) { days -= leap_mdays[loc->tm_mon]; loc->tm_mon++; } } else { while (days >= mean_mdays[loc->tm_mon]) { days -= mean_mdays[loc->tm_mon]; loc->tm_mon++; } } /* Add 1 since our 'days' is zero-based. */ loc->tm_mday = (int)(days + 1); /* Surprisingly tm_year is year-1900. */ loc->tm_year -= 1900; #undef SECONDS_PER_MINUTE #undef SECONDS_PER_HOUR #undef SECONDS_PER_DAY #undef YEAR_IS_LEAPYEAR } NOWARNING_UNUSED(static) sb8 difftime_msec(const struct timespec *oldtms, const struct timespec *newtms) { sb8 sec = 0; sb8 nsec = 0; if (!oldtms && !newtms) { /* get current timestamp in ms */ struct timespec now; getnowtimeofday(&now); sec = now.tv_sec; nsec = now.tv_nsec; } else if (oldtms && newtms) { sec = (sb8)(newtms->tv_sec - oldtms->tv_sec); nsec = (sb8)(newtms->tv_nsec - oldtms->tv_nsec); } else if (newtms) { sec = (sb8)(newtms->tv_sec); nsec = (sb8)(newtms->tv_nsec); } else if (oldtms) { sec = (sb8)(oldtms->tv_sec); nsec = (sb8)(oldtms->tv_nsec); } if (sec > 0) { if (nsec >= 0) { return ((sec * 1000UL) + nsec / 1000000UL); } else { /* nsec < 0 */ return (sec - 1) * 1000UL + (nsec + 1000000000UL) / 1000000UL; } } else if (sec < 0) { if (nsec <= 0) { return ((sec * 1000UL) + nsec / 1000000UL); } else{ /* nsec > 0 */ return (sec + 1) * 1000UL + (nsec - 1000000000UL) / 1000000UL; } } else { /* sec = 0 */ return nsec / 1000000UL; } } NOWARNING_UNUSED(static) const char * format_nowtimeofday (char *datefmt) { struct timespec now; struct tm loc; getnowtimeofday(&now); getlocaltime_safe(&loc, now.tv_sec, 0, 0); snprintf_chkd_V1(datefmt, 24, "%04d-%02d-%02d %02d:%02d:%02d UTC", loc.tm_year + 1900, loc.tm_mon + 1, loc.tm_mday, loc.tm_hour, loc.tm_min, loc.tm_sec); datefmt[23] = 0; return datefmt; } #ifdef __cplusplus } #endif #endif /* _TIMEUT_H_ */
pepstack/pytools
templates/%clib%/src/common/unsema.h
/*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename unsema.h * Unnamed Semaphore API for both Windows and Linux * * @author <NAME> <<EMAIL>> * @version 0.0.1 * @create 2019-12-12 11:32:50 * @update 2019-12-12 12:32:50 */ #ifndef _UN_SEMA_H_ #define _UN_SEMA_H_ #if defined(__cplusplus) extern "C" { #endif #include "unitypes.h" #ifdef __WINDOWS__ # include <Winsock2.h> # include <Windows.h> typedef HANDLE unsema_t; #else # include <semaphore.h> typedef sem_t unsema_t; #endif #define UNSEMA_VALUE_MAX SB2MAXVAL #ifdef SEM_VALUE_MAX # undef UNSEMA_VALUE_MAX # define UNSEMA_VALUE_MAX SEM_VALUE_MAX #endif #ifdef _POSIX_SEM_VALUE_MAX # undef UNSEMA_VALUE_MAX # define UNSEMA_VALUE_MAX _POSIX_SEM_VALUE_MAX #endif #if UNSEMA_VALUE_MAX > SB2MAXVAL # undef UNSEMA_VALUE_MAX # define UNSEMA_VALUE_MAX SB2MAXVAL #endif NOWARNING_UNUSED(static) int unsema_init (unsema_t *sema, int initval) { int err = -1; #ifdef __WINDOWS__ unsema_t h = CreateSemaphoreA(NULL, initval, SB4MAXVAL, NULL); if (h) { *sema = h; err = 0; } #else err = sem_init(sema, 0, initval); #endif return err; } NOWARNING_UNUSED(static) int unsema_uninit (unsema_t *sema) { int err = -1; #ifdef __WINDOWS__ if (CloseHandle(*sema)) { *sema = NULL; err = 0; } #else err = sem_destroy(sema); #endif return err; } NOWARNING_UNUSED(static) int unsema_wait (unsema_t *sema) { int err = -1; #ifdef __WINDOWS__ if (WAIT_OBJECT_0 == WaitForSingleObject(*sema, INFINITE)) { // success err = 0; } else { err = 1; } #else err = sem_wait(sema); #endif return err; } NOWARNING_UNUSED(static) int unsema_timedwait (unsema_t *sema, ub4 milliseconds) { int err = -1; #ifdef __WINDOWS__ if (WAIT_OBJECT_0 == WaitForSingleObject(*sema, (DWORD) milliseconds)) { // success err = 0; } else { // other errors err = 1; } #else // Linux struct timespec ts; #ifdef UNSEMA_USES_GETTIMEOFDAY struct timeval tv; gettimeofday(&tv, 0); ts.tv_sec = tv.tv_sec + milliseconds/1000; ts.tv_nsec = tv.tv_usec * 1000 + (milliseconds % 1000) * 1000000; #else clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += (milliseconds/1000); ts.tv_nsec += ((milliseconds % 1000) * 1000000); #endif err = sem_timedwait(sema, &ts); #endif return err; } NOWARNING_UNUSED(static) int unsema_post (unsema_t *sema) { int err = -1; #ifdef __WINDOWS__ if (ReleaseSemaphore(*sema, 1, NULL)) { // success err = 0; } #else err = sem_post(sema); #endif return err; } /** * get previous value and post */ NOWARNING_UNUSED(static) int unsema_postget (unsema_t *sema) { #ifdef __WINDOWS__ LONG lCount; if (ReleaseSemaphore(*sema, 1, &lCount)) { // success return (int) lCount; } #else int value; if (sem_getvalue(sema, &value) == 0 && sem_post(sema) == 0) { // success return value; } #endif // error return (-1); } #ifdef __cplusplus } #endif #endif /* _UN_SEMA_H_ */
pepstack/pytools
templates/%clib%/deps/libshttpd/include/shttpd/shttpd.h
<reponame>pepstack/pytools /** * Copyright (c) 2004-2008 <NAME> <<EMAIL>> * All rights reserved * * "THE BEER-WARE LICENSE" (Revision 42): * Sergey Lyubka wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. * * $Id: shttpd.h,v 1.18 2008/08/23 08:34:50 drozd Exp $ */ #ifndef SHTTPD_H_INCLUDED #define SHTTPD_H_INCLUDED #ifdef __cplusplus extern "C" { #endif typedef struct shttpd_ctx_t * shttpd_ctx; typedef struct shttpd_arg_t * shttpd_arg; #define SHTTPD_END_OF_OUTPUT 1 /* No more data do send */ #define SHTTPD_CONNECTION_ERROR 2 /* Server closed the connection */ #define SHTTPD_MORE_POST_DATA 4 /* arg->in has incomplete data */ #define SHTTPD_POST_BUFFER_FULL 8 /* arg->in has max data */ #define SHTTPD_SSI_EVAL_TRUE 16 /* SSI eval callback must set it */ #define SHTTPD_SUSPEND 32 /* User wants to suspend output */ typedef enum { SHOPT_ROOT, SHOPT_INDEX_FILES, SHOPT_PORTS, SHOPT_DIR_LIST, SHOPT_CGI_EXTS, SHOPT_CGI_INTERP, SHOPT_CGI_ENV, SHOPT_SSI_EXTS, SHOPT_AUTH_REALM, SHOPT_AUTH_GPASSWD, SHOPT_AUTH_PUT, SHOPT_ACCESS_LOG, SHOPT_ERROR_LOG, SHOPT_MIME_TYPES, SHOPT_SSL_CERT, SHOPT_ALIASES, SHOPT_ACL, SHOPT_INETD, SHOPT_UID, SHOPT_CFG_URI, SHOPT_PROTECT, SHOPT_SERVICE, SHOPT_HIDE, SHOPT_THREADS, SHOPTIONS_NUM } shttpd_opt_t; /** * shttpd_arg_t * structure is passed to the user callback function */ struct shttpd_arg_t { void *priv; /* Private! Do not touch! */ void *state; /* User state */ void *user_data; /* Data from register_uri() */ struct { char *buf; /* Buffer pointer */ int len; /* Size of a buffer */ int num_bytes; /* Bytes processed by callback */ } in; /* Input is here, POST data */ struct { char *buf; /* Buffer pointer */ int len; /* Size of a buffer */ int num_bytes; /* Bytes processed by callback */ } out; /* Output goes here */ unsigned int flags; }; /* * User callback function * Called when certain registered URLs have been requested. * These are the requirements to the callback function: * * 1. It must copy data into 'out.buf' buffer, not more than 'out.len' bytes, * and record how many bytes are copied, into 'out.num_bytes' * 2. It must not call any blocking functions * 3. It must set SHTTPD_END_OF_OUTPUT flag when there is no more data to send * 4. For POST requests, it must process the incoming data (in.buf) of length * 'in.len', and set 'in.num_bytes', which is how many bytes of POST * data was processed and can be discarded by SHTTPD. * 5. If callback allocates arg->state, to keep state, it must deallocate it * at the end of coonection SHTTPD_CONNECTION_ERROR or SHTTPD_END_OF_OUTPUT * 6. If callback function wants to suspend until some event, it must store * arg->priv pointer elsewhere, set SHTTPD_SUSPEND flag and return. When * the event happens, user code should call shttpd_wakeup(priv). * It is safe to call shttpd_wakeup() from any thread. User code must * not call shttpd_wakeup once the connection is closed. */ typedef void (*shttpd_callback_t)(shttpd_arg); /** * shttpd_init * Initialize shttpd context */ extern shttpd_ctx shttpd_init (int argc, char *argv[]); /** * shttpd_set_option * Set new value for option */ extern int shttpd_set_option (shttpd_ctx ctx, const char *optname, const char *optval); /** * shttpd_get_option * Get value of option */ extern const char * shttpd_get_option (shttpd_ctx ctx, shttpd_opt_t opt); /** * shttpd_fini * Dealocate the context, close all connections */ extern void shttpd_fini (shttpd_ctx ctx); /** * shttpd_register_uri * Setup the callback function for specified URL */ extern void shttpd_register_uri (shttpd_ctx ctx, const char *uri, shttpd_callback_t callback, void *const user_data); /** * shttpd_poll * Do connections processing */ extern void shttpd_poll (shttpd_ctx ctx, int milliseconds); /** * shttpd_version * return string with SHTTPD version */ extern const char *shttpd_version (void); /** * shttpd_get_var * Fetch POST/GET variable value by name. Return value len */ extern int shttpd_get_var (const char *var, const char *buf, int buf_len, char *value, int value_len); /** * shttpd_get_header * return value of the specified HTTP header */ extern const char *shttpd_get_header (shttpd_arg arg, const char *header_name); /** * shttpd_get_env * return values for the following pseudo-variables: * REQUEST_METHOD * REQUEST_URI * REMOTE_USER * REMOTE_ADDR */ extern const char *shttpd_get_env (shttpd_arg arg, const char *name); extern void shttpd_get_http_version (shttpd_arg arg, unsigned long *major, unsigned long *minor); /** * shttpd_printf * helper function to output data */ extern size_t shttpd_printf (shttpd_arg arg, const char *fmt, ...); /** * shttpd_handle_error * Register custom HTTP error handler */ extern void shttpd_handle_error (shttpd_ctx ctx, int status, shttpd_callback_t func, void *const data); extern void shttpd_register_ssi_func (shttpd_ctx ctx, const char *name, shttpd_callback_t func, void *const user_data); /** * shttpd_wakeup * Clear SHTTPD_SUSPEND state for the connection */ extern void shttpd_wakeup (const void *priv); extern int shttpd_join (shttpd_ctx ctx, fd_set *, fd_set *, int *max_fd); extern int shttpd_socketpair (int sp[2]); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* SHTTPD_H_INCLUDED */
pepstack/pytools
templates/%clib%/src/common/ringbuf.h
/*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename ringbuf.h * Multi-threads Safety Ring Buffer. * * This code has been tested OK on 20 threads! * * @author <NAME> <<EMAIL>> * @version 1.0.0 * @create 2019-12-14 12:46:50 * @update 2020-06-30 11:32:10 */ /************************************************************** * Length(L) = 10, Read(R), Write(W), wrap factor=0,1 * Space(S) * * + R W + + * |--+--+--+--+--+--+--+--+--+--|--+--+--+--+--+--+--+--+--+--|--+--+--+-- * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 * * S = L - (fL + W - R), W - R < L * D = fL + W - R * * S > 0: writable * D > 0: readable *************************************************************/ /************************************************************** * * RW * wrap=0 |----------|----------|--- * L L * R W * wrap=1 |----------|----------|--- * * RW * wrap=0 |----------|----------|--- * * W R * wrap=1 |----------|----------|--- * * RW * wrap=0 |----------|----------|--- * * wrap(R, W, L) => ((R/L == W/L)? 0 : 1) * * A = W + 1 (or A = R + 1) * * W1 = (( A/L ) %2 ) * L + A % L *************************************************************/ #ifndef _RINGBUF_H_ #define _RINGBUF_H_ #if defined(__cplusplus) extern "C" { #endif #include "uatomic.h" #include "memapi.h" #define RINGBUF_LENGTH_MAX 0x01FFFF /* must > 1 */ #define RINGBUF_LENGTH_MIN 2 #define RINGBUF_RESTORE_STATE(Ro, Wo, L) \ int wrap = ((int)((Ro)/(L) == (Wo)/(L) ? 0 : 1)); \ int R = (Ro) % (L); \ int W = (Wo) % (L) #define RINGBUF_NORMALIZE_OFFSET(Ao, L) \ ((((Ao)/(L))%2)*L + (Ao)%(L)) #define ringbuf_elt_free(elt) free(elt) typedef void (*ringbuf_elt_free_cb)(void *); typedef struct { ringbuf_elt_free_cb free_cb; size_t size; char data[1]; } ringbuf_elt_t, *ringbuf_eltp; static char * ringbuf_elt_new (size_t datasize, ringbuf_elt_free_cb free_cb, ringbuf_elt_t **eltp) { ringbuf_elt_t *elt = (ringbuf_elt_t *) mem_alloc_zero(1, sizeof(*elt) + datasize); if (! elt) { /* out memory */ exit(EXIT_FAILURE); } elt->free_cb = free_cb; elt->size = datasize; *eltp = elt; return (char *) elt->data; } typedef struct { /* MT-safety Read Lock */ uatomic_int RLock; /* MT-safety Write Lock */ uatomic_int WLock; /* Write (push) index: 0, L-1 */ uatomic_int W; /* Read (pop) index: 0, L-1 */ uatomic_int R; /* Length of ring buffer */ int L; /* Buffer */ ringbuf_elt_t *B[0]; } ringbuf_t; /** * public interface */ static ringbuf_t * ringbuf_init(int length) { ringbuf_t *rb; if (length < RINGBUF_LENGTH_MIN) { length = RINGBUF_LENGTH_MIN; } if (length > RINGBUF_LENGTH_MAX) { length = RINGBUF_LENGTH_MAX; } /* new and initialize read and write index by 0 */ rb = (ringbuf_t *) mem_alloc_zero(1, sizeof(*rb) + sizeof(ringbuf_elt_t*) * length); rb->L = length; return rb; } static void ringbuf_uninit(ringbuf_t *rb) { uatomic_int_set(&rb->RLock, 1); uatomic_int_set(&rb->WLock, 1); ringbuf_elt_free_cb elt_free; int i = rb->L; while (i-- > 0) { ringbuf_elt_t *elt = rb->B[i]; if (elt) { rb->B[i] = NULL; elt_free = elt->free_cb; if (elt_free) { elt_free(elt); } } } mem_free(rb); } static int ringbuf_push (ringbuf_t *rb, ringbuf_elt_t *elt) { if (! uatomic_int_comp_exch(&rb->WLock, 0, 1)) { /* copy constant of length */ int L = rb->L; /* original values of R, W */ int Ro = uatomic_int_get(&rb->R); /* MUST get W after R */ int Wo = rb->W; RINGBUF_RESTORE_STATE(Ro, Wo, L); /* Sw = L - (f*L+W - R) */ if (L + R - wrap*L - W > 0) { /* writable: Sw > 0 */ rb->B[W] = elt; /* to next Write offset */ ++Wo; /* W = [0, 2L) */ W = RINGBUF_NORMALIZE_OFFSET(Wo, L); uatomic_int_set(&rb->W, W); /* push success */ uatomic_int_zero(&rb->WLock); return 1; } uatomic_int_zero(&rb->WLock); } /* push failed */ return 0; } static int ringbuf_pop (ringbuf_t *rb, ringbuf_elt_t **eltp) { if (! uatomic_int_comp_exch(&rb->RLock, 0, 1)) { int L = rb->L; /* original values of W, R */ int Wo = uatomic_int_get(&rb->W); /* MUST get R after W */ int Ro = rb->R; RINGBUF_RESTORE_STATE(Ro, Wo, L); /* Sr = f*L + W - R */ if (wrap*L + W - R > 0) { /* readable: Sr > 0 */ *eltp = rb->B[R]; /* must clear elt */ rb->B[R] = NULL; ++Ro; /* R = [0, 2L) */ R = RINGBUF_NORMALIZE_OFFSET(Ro, L); uatomic_int_set(&rb->R, R); /* pop success */ uatomic_int_zero(&rb->RLock); return 1; } uatomic_int_zero(&rb->RLock); } /* pop failed */ return 0; } #define ringbuf_pop_always(rb, elt) \ while (ringbuf_pop((rb), &(elt)) != 1) #define ringbuf_push_always(rb, elt) \ while (ringbuf_push((rb), (elt)) != 1) #ifdef __cplusplus } #endif #endif /* _RINGBUF_H_ */
pepstack/pytools
templates/%clib%/src/common/threadpool.h
/*********************************************************************** * 2014-06-18: last modified by cheungmine * * Copyright (c) 2011, <NAME> <<EMAIL>>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ /** * threadpool.h * both for windows (required pthreads-w32) and linux * @update: 2021-06-22 */ #ifndef _THREADPOOL_H_ #define _THREADPOOL_H_ #if defined(__cplusplus) extern "C" { #endif #ifndef __USE_GNU # define __USE_GNU #endif // both for Linux and Windows #include "unitypes.h" #include "uatomic.h" #include <sched.h> #include <pthread.h> #ifndef POOL_MAX_THREADS # define POOL_MAX_THREADS 16384 #endif #ifndef POOL_MAX_QUEUES # define POOL_MAX_QUEUES 131072 #endif #ifndef POOL_DEFAULT_THREADS # define POOL_DEFAULT_THREADS 16 #endif #ifndef POOL_DEFAULT_QUEUES # define POOL_DEFAULT_QUEUES 256 #endif #ifndef POOL_TASK_ARG_SIZE_MAX # define POOL_TASK_ARG_SIZE_MAX 16384 #endif #if !defined(__WINDOWS__) && !defined(__CYGWIN__) /* 0-based cpu id */ # ifndef POOL_CPU_ID_MAX # define POOL_CPU_ID_MAX 255 # endif #endif /** * @file threadpool.h * @brief Threadpool Header file */ typedef struct threadpool_t threadpool_t; /** * @file threadpool.h * @brief thread_context_t * thread can take itself argument * added by cheungmine. * 2014-06-17 * 2018-11-20: task_arg for threadpool_task_t */ typedef struct thread_context_t { int id; void *pool; pthread_t thread; void *thread_arg; struct threadpool_task_t *task; } thread_context_t; /** * @struct threadpool_task * @brief the work struct * * @var function Pointer to the function that will perform the task. * @var argument Argument to be passed to the function. */ typedef struct threadpool_task_t { void (*function)(thread_context_t *); ub8 flags; /* user defined 64 bits value */ void *argument; /* reference to user-specified argument */ size_t arg_size; /* actual size in bytes stored in task_arg */ unsigned char task_arg[0]; } threadpool_task_t; typedef enum { threadpool_success = 0, threadpool_invalid = -1, threadpool_lock_failure = -2, threadpool_queue_full = -3, threadpool_shutdown = -4, threadpool_run_failure = -5, threadpool_out_memory = -6, threadpool_task_arg_overflow = -7 } threadpool_error_t; static const char* threadpool_error_messages[] = { "threadpool_success", "threadpool_invalid", "threadpool_lock_failure", "threadpool_queue_full", "threadpool_shutdown", "threadpool_run_failure", "threadpool_out_memory", "threadpool_task_arg_overflow", 0 }; /** * @function threadpool_create * @brief Creates a threadpool_t object. * @param thread_count Number of worker threads. * @param queue_size Size of the queue for tasks. * @param thread_args array of arguments with count of thread_count, NULL if ignored. * @param task_arg_size pre-allocated buffer for per-task if it > 0. * @return a newly created thread pool or NULL */ extern threadpool_t *threadpool_create (int thread_count, int queue_size, int stack_size, int affinity_cpus, void **thread_args, size_t task_arg_size); /** * @function threadpool_add * @brief add a new task in the queue of a thread pool * @param pool Thread pool to which add the task. * @param function Pointer to the function that will perform the task. * @param argument Argument to be passed to the function. * @param flags Caller-specified parameter. * @return 0 if all goes well, negative values in case of error (@see * threadpool_error_t for codes). */ extern int threadpool_add (threadpool_t *pool, void (*routine)(thread_context_t *), void *argument, void *task_arg, int arg_size, ub8 flags); /** * @function threadpool_unused_queues * @brief get unused size of queues in thread pool * @param pool Thread pool to which get size of queues * @return 0 if queues are full, positive values for unused queues. * negative values in case of error (@see threadpool_error_t for codes). */ extern int threadpool_unused_queues (threadpool_t *pool); /** * @function threadpool_get_threads_count * @brief get size of pool (number of threads) * @param pool Thread pool to which get number of threads * @return number of threads. */ extern int threadpool_get_threads_count (threadpool_t *pool); /** * @function threadpool_get_context * @brief get thread_context_t by id * @param pool Thread pool * @param id thread index 1 based * @return 0 if queues are full, positive values for unused queues. * negative values in case of error (@see threadpool_error_t for codes). */ extern thread_context_t * threadpool_get_context (threadpool_t *pool, int id); /** * @function threadpool_destroy * @brief Stops and destroys a thread pool. * @param pool Thread pool to destroy. * @param flags Unused parameter. */ extern int threadpool_destroy (threadpool_t *pool); /** * pthread_attr_init_config * pthread_attr_init and config */ extern int pthread_attr_init_config (pthread_attr_t *pattr, int stack_size, int scope, int joinable); #if !defined(__WINDOWS__) && !defined(__CYGWIN__) /** * pthread_set_affinity_cpus * 计算线程亲和的 cpu id * * thrid: 线程编号, 0,1,2,3,... * affinity_cpus: 亲和度, 表示每个线程可运行在几个 cpu 上. 亲和度=4: 表示每个线程可运行在 4 个 cpu 上 * * set cpu affinity for thread * https://blog.csdn.net/guotianqing/article/details/80958281 * * 命令查看进程的 cpu 亲和力列表: # taskset -cp pid */ extern int thread_set_affinity_cpus (int thrid, int affinity_cpus, cpu_set_t *cpuset); /** * thread_check_affinity_cpus * Check the actual affinity mask assigned to the thread */ extern int thread_check_affinity_cpus (pthread_t thread, int *cpuid_list, int cnt); #endif #if defined(__cplusplus) } #endif #endif /* _THREADPOOL_H_ */
pepstack/pytools
templates/%clib%/src/common/emerglog.h
/*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename emerglog.h * syslog for EMERG event message. * * see syslog as below: * $ cat /var/log/messages | grep $ident * * @author <NAME> <<EMAIL>> * @version 0.0.10 * @create 2017-05-02 12:02:50 * @update 2021-06-22 18:29:50 */ #ifndef EMERG_LOG_H_INCLUDED #define EMERG_LOG_H_INCLUDED /** * close "Message from syslogd@code ..." to terminals on el6: * * 1) Comment out the line "*.emerg ... *" in file '/etc/rsyslog.conf' like below: * * # Everybody gets emergency messages * #!-- *.emerg * * * 2) Then restart rsyslog service: * $ /etc/init.d/rsyslog restart */ #if defined(__cplusplus) extern "C" { #endif #if defined (__WINDOWS__) #ifndef _INC_WINDOWS # include <WinSock2.h> #endif # include "win32/syslog.h" #else # include <sys/time.h> # include <syslog.h> #endif #ifndef EMERGLOG_MSGLEN # define EMERGLOG_MSGLEN 1023 #endif #ifndef EMERGLOG_IDENT # define EMERGLOG_IDENT "emerglog.h" #endif #ifndef EMERGLOG_OPTION # define EMERGLOG_OPTION (LOG_PID | LOG_NDELAY | LOG_NOWAIT | LOG_PERROR) #endif NOWARNING_UNUSED(static) void emerg_syslog_message(int exitcode, const char *ident, const char *filename, int lineno, const char *format, ...) { char msgbuf[EMERGLOG_MSGLEN + 1]; int chlen = 0; va_list args; va_start(args, format); chlen = vsnprintf(msgbuf, sizeof(msgbuf), format, args); va_end(args); if (chlen > EMERGLOG_MSGLEN) { chlen = EMERGLOG_MSGLEN; } else if (chlen < 0) { chlen = 0; } msgbuf[chlen] = '\0'; if (ident) { openlog(ident, EMERGLOG_OPTION, 0); } else { openlog(EMERGLOG_IDENT, EMERGLOG_OPTION, 0); } if (filename && lineno) { syslog(LOG_USER | LOG_EMERG, "(%s:%d) %.*s\n", filename, lineno, chlen, msgbuf); } else { syslog(LOG_USER | LOG_EMERG, "%.*s\n", chlen, msgbuf); } closelog(); if (exitcode) { exit(exitcode); } } #define emerglog_oom_exit(ptr, ident) do { \ if (! (ptr)) { \ emerg_syslog_message(EXIT_FAILURE, ident, __FILE__, __LINE__, "FATAL: no memory allocated"); \ } \ } while(0) #if defined(_MSC_VER) # define emerglog_err_exit(err, ident, message, ...) do { \ if ((err)) { \ emerg_syslog_message(EXIT_FAILURE, ident, __FILE__, __LINE__, message, __VA_ARGS__); \ } \ } while(0) # define emerglog_exit(ident, message, ...) \ emerg_syslog_message(EXIT_FAILURE, ident, __FILE__, __LINE__, message, __VA_ARGS__) # define emerglog_msg(ident, message, ...) \ emerg_syslog_message(0, ident, __FILE__, __LINE__, message, __VA_ARGS__) #else # define emerglog_err_exit(err, ident, message, args...) do { \ if ((err)) { \ emerg_syslog_message(EXIT_FAILURE, ident, __FILE__, __LINE__, message, ##args); \ } \ } while(0) # define emerglog_exit(ident, message, args...) \ emerg_syslog_message(EXIT_FAILURE, ident, __FILE__, __LINE__, message, ##args) # define emerglog_msg(ident, message, args...) \ emerg_syslog_message(0, ident, __FILE__, __LINE__, message, ##args) #endif #if defined(__cplusplus) } #endif #endif /* EMERG_LOG_H_INCLUDED */
pepstack/pytools
templates/%clib%/src/common/threadpool.c
<reponame>pepstack/pytools<gh_stars>0 /********************************************************************** * 2018-11-20: last modified by cheungmine * * Copyright (c) 2011, <NAME> <<EMAIL>>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * cpu affinity: * http://man7.org/linux/man-pages/man3/pthread_create.3.html * http://man7.org/linux/man-pages/man3/pthread_setaffinity_np.3.html *********************************************************************/ /** * @file threadpool.c * @brief Threadpool implementation file * * @update: 2021-06-22 */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* memcpy */ #include "threadpool.h" #if !defined(__WINDOWS__) # include <unistd.h> # include <sys/sysinfo.h> #endif #if defined(__WINDOWS__) && !defined(__CYGWIN__) # if defined (_MSC_VER) # pragma warning(disable:4996) // link to pthread-w32 lib only for MS Windows # pragma comment(lib, "pthreadVC2.lib") # endif #endif /** * @struct threadpool * @brief The threadpool struct * * @var notify Condition variable to notify worker threads. * @var threads Array containing worker threads ID. * @var thread_count Number of threads * @var queue Array containing the task queue. * @var queue_size Size of the task queue. * @var head Index of the first element. * @var tail Index of the next element. * @var shutdown Flag indicating if the pool is shutting down */ struct threadpool_t { pthread_mutex_t lock; pthread_cond_t notify; int head; int tail; uatomic_int count; int shutdown; int started; int thread_count; int queue_size; int task_arg_size; int task_size; /* total sizeof task */ threadpool_task_t *queues; thread_context_t thread_ctxs[0]; }; #if defined(__WINDOWS__) # define pool_count_get(pool) InterlockedCompareExchange(&pool->count, 0, 0) # define pool_count_add(pool) InterlockedIncrement(&pool->count) # define pool_count_sub(pool) InterlockedDecrement(&pool->count) #else # define pool_count_get(pool) __sync_add_and_fetch(&pool->count, 0) # define pool_count_add(pool) __sync_add_and_fetch(&pool->count, 1) # define pool_count_sub(pool) __sync_sub_and_fetch(&pool->count, 1) #endif #define threadpool_get_task_at(pool, offset) \ ((threadpool_task_t *) ((unsigned char *) pool->queues + offset * pool->task_size)) thread_context_t * threadpool_get_context (threadpool_t *pool, int id) { return &(pool->thread_ctxs[id - 1]); } /** * @function void *threadpool_run(void *threadpool) * @brief the worker thread * @param threadpool the pool which own the thread */ static void *threadpool_run (void *threadpool); int threadpool_free(threadpool_t *pool); threadpool_t *threadpool_create(int thread_count, int queue_size, int stack_size, int affinity_cpus, void **thread_args, size_t task_arg_size) { int i; threadpool_t *pool = NULL; pthread_attr_t attr; #if !defined(__WINDOWS__) && !defined(__CYGWIN__) cpu_set_t cpuset; #endif /* Check thread_count for negative or otherwise very big input parameters */ if (thread_count < 0 || thread_count > POOL_MAX_THREADS) { goto err; } if (thread_count == 0) { thread_count = POOL_DEFAULT_THREADS; } /* Check queue_size for negative or otherwise very big input parameters */ if (queue_size < 0 || queue_size > POOL_MAX_QUEUES) { goto err; } if (queue_size == 0) { queue_size = POOL_DEFAULT_QUEUES; } /* Check task_arg_size for negative or otherwise very big input parameters */ if (task_arg_size == (size_t)(-1) || task_arg_size > POOL_TASK_ARG_SIZE_MAX) { goto err; } /* create threadpool */ if ( (pool = (threadpool_t *) malloc (sizeof(threadpool_t) + sizeof(thread_context_t) * thread_count + (sizeof(threadpool_task_t) + task_arg_size) * queue_size) ) == NULL ) { goto err; } /* Initialize */ pool->thread_count = thread_count; pool->queue_size = queue_size; pool->task_arg_size = (int) task_arg_size; pool->task_size = (int) (sizeof(threadpool_task_t) + task_arg_size); pool->head = pool->tail = pool->count = 0; pool->shutdown = pool->started = 0; pool->queues = (threadpool_task_t *) (& pool->thread_ctxs[thread_count]); /* Initialize mutex and conditional variable first */ if ((pthread_mutex_init (&(pool->lock), NULL) != 0) || (pthread_cond_init (&(pool->notify), NULL) != 0)) { goto err; } /* http://man7.org/linux/man-pages/man3/pthread_create.3.html */ if (pthread_attr_init_config(&attr, 0, PTHREAD_SCOPE_SYSTEM, PTHREAD_CREATE_JOINABLE) != 0) { goto err; } /* Start worker threads */ for (i = 0; i < thread_count; i++) { thread_context_t * pctx = & pool->thread_ctxs[i]; /* set thread id: 1 based */ pctx->id = i + 1; /* set pool to each thread context */ pctx->pool = (void*) pool; /* assign thread argument if valid */ if (thread_args) { pctx->thread_arg = thread_args[i]; } else { pctx->thread_arg = 0; } /* Set affinity mask to include CPUs 0 to 7 */ # if !defined(__WINDOWS__) && !defined(__CYGWIN__) if (affinity_cpus > 0) { thread_set_affinity_cpus(pctx->id, affinity_cpus, &cpuset); if (pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset) != 0) { printf("pthread_attr_setaffinity_np error: %s\n", strerror(errno)); threadpool_destroy(pool); pthread_attr_destroy(&attr); return NULL; } } # endif if ( pthread_create (& pctx->thread, &attr, threadpool_run, (void*) pctx) != 0) { threadpool_destroy(pool); pthread_attr_destroy(&attr); return NULL; } else { # if !defined(__WINDOWS__) && !defined(__CYGWIN__) CPU_ZERO(&cpuset); if (pthread_getaffinity_np (pctx->thread, sizeof(cpu_set_t), &cpuset) != 0) { printf("pthread_attr_setaffinity_np error: %s\n", strerror(errno)); threadpool_destroy(pool); pthread_attr_destroy(&attr); return NULL; } # endif pool->started++; } } /* Destroy the thread attributes object, since it is no longer needed */ if (pthread_attr_destroy(&attr) != 0) { printf("pthread_attr_destroy error: %s\n", strerror(errno)); threadpool_destroy(pool); return NULL; } return pool; err: if(pool) { threadpool_free(pool); } return NULL; } int threadpool_add (threadpool_t *pool, void (*function)(thread_context_t *), void *argument, void *task_arg, int arg_size, ub8 flags) { int err = 0; int next; if ( pool == NULL || function == NULL ) { return threadpool_invalid; } if (arg_size > pool->task_arg_size) { return threadpool_task_arg_overflow; } if (pthread_mutex_lock (&(pool->lock)) != 0) { return threadpool_lock_failure; } next = pool->tail + 1; next = (next == pool->queue_size) ? 0 : next; do { /* Are we shutting down ? */ if (pool->shutdown) { err = threadpool_shutdown; break; } /* Are we full ? */ if (pool_count_get(pool) == pool->queue_size) { err = threadpool_queue_full; break; } /* Add task to queues */ do { threadpool_task_t *ptask = threadpool_get_task_at(pool, pool->tail); ptask->function = function; ptask->argument = argument; if (arg_size > 0) { /* task_arg is enabled */ ptask->arg_size = arg_size; memcpy((void*) ptask->task_arg, task_arg, arg_size); } else { /* task_arg not enabled */ ptask->arg_size = 0; } /* Use flags to determine whether argument or task_arg is enabled */ ptask->flags = flags; } while(0); pool->tail = next; /* pool->count += 1; */ pool_count_add(pool); /* pthread_cond_broadcast */ if (pthread_cond_signal (&(pool->notify)) != 0) { err = threadpool_lock_failure; break; } } while(0); if (pthread_mutex_unlock (&pool->lock) != 0) { err = threadpool_lock_failure; } return err; } int threadpool_unused_queues (threadpool_t *pool) { if ( !pool || pool->shutdown ) { return threadpool_invalid; } else { return (pool->queue_size - pool_count_get(pool)); } } int threadpool_get_threads_count (threadpool_t *pool) { return pool ? pool->thread_count : 0; } int threadpool_destroy (threadpool_t *pool) { int i, err = 0; if (pool == NULL) { return threadpool_invalid; } if (pthread_mutex_lock (&(pool->lock)) != 0) { return threadpool_lock_failure; } do { /* Already shutting down */ if (pool->shutdown) { err = threadpool_shutdown; break; } pool->shutdown = 1; /* Wake up all worker threads */ if ((pthread_cond_broadcast(&(pool->notify)) != 0) || (pthread_mutex_unlock(&(pool->lock)) != 0)) { err = threadpool_lock_failure; break; } /* Join all worker thread */ for (i = 0; i < pool->thread_count; i++) { if (pthread_join (pool->thread_ctxs[i].thread, NULL) != 0) { err = threadpool_run_failure; } } } while(0); if (pthread_mutex_unlock (&pool->lock) != 0) { err = threadpool_lock_failure; } /* Only if everything went well do we deallocate the pool */ if (!err) { threadpool_free (pool); } return err; } int threadpool_free (threadpool_t *pool) { if (pool == NULL || pool->started > 0) { return -1; } pthread_mutex_lock (&(pool->lock)); pthread_mutex_destroy (&(pool->lock)); pthread_cond_destroy (&(pool->notify)); free(pool); return 0; } /** * each thread run function */ static void *threadpool_run (void * param) { thread_context_t *thread_ctx = (thread_context_t *) param; threadpool_t *pool = thread_ctx->pool; threadpool_task_t *taskcpy = (threadpool_task_t *) malloc(pool->task_size); for (;;) { /* Lock must be taken to wait on conditional variable */ pthread_mutex_lock(&(pool->lock)); /* Wait on condition variable, check for spurious wakeups. When returning from pthread_cond_wait(), we own the lock. */ while ((pool_count_get(pool) == 0) && (!pool->shutdown)) { pthread_cond_wait (&(pool->notify), &(pool->lock)); } if (pool->shutdown) { break; } /* Grab our task */ memcpy(taskcpy, threadpool_get_task_at(pool, pool->head), pool->task_size); thread_ctx->task = (threadpool_task_t *) taskcpy; pool->head += 1; pool->head = (pool->head == pool->queue_size) ? 0 : pool->head; /* pool->count -= 1; */ pool_count_sub(pool); /* Unlock */ pthread_mutex_unlock (&(pool->lock)); /* Get to work */ (*(taskcpy->function)) (thread_ctx); } pool->started--; free(taskcpy); pthread_mutex_unlock (&(pool->lock)); pthread_exit(0); return 0; } int pthread_attr_init_config (pthread_attr_t *pattr, int stack_size, int scope, int joinable) { if (pthread_attr_init(pattr) != 0) { printf("pthread_attr_init error: %s\n", strerror(errno)); return -1; } if (stack_size > 0) { if (pthread_attr_setstacksize(pattr, stack_size) != 0) { printf("pthread_attr_setstacksize error: %s\n", strerror(errno)); pthread_attr_destroy(pattr); return -1; } } /** * scope specified the value PTHREAD_SCOPE_PROCESS, which is not supported on Linux. * Linux ONLY supports PTHREAD_SCOPE_SYSTEM, not the PTHREAD_SCOPE_PROCESS. */ if (pthread_attr_setscope(pattr, scope) != 0 && scope != PTHREAD_SCOPE_PROCESS) { if (errno) { printf("pthread_attr_setscope error: %s\n", strerror(errno)); pthread_attr_destroy(pattr); return -1; } } if (pthread_attr_setdetachstate(pattr, joinable) != 0) { printf("pthread_attr_setdetachstate error: %s\n", strerror(errno)); pthread_attr_destroy(pattr); return -1; } return 0; } #if !defined(__WINDOWS__) && !defined(__CYGWIN__) /** * thread_set_affinity_cpus * 计算线程亲和的 cpu id * * thrid: 线程编号, 0,1,2,3,... * affinity_cpus: 亲和度, 表示每个线程可运行在几个 cpu 上. 亲和度=4: 表示每个线程可运行在 4 个 cpu 上 * * set cpu affinity for thread * https://blog.csdn.net/guotianqing/article/details/80958281 */ int thread_set_affinity_cpus (int thrid, int affinity_cpus, cpu_set_t *cpuset) { int cpu_id; CPU_ZERO(cpuset); /* 可用的 cpu 数 */ int onln_cpus = get_nprocs(); /* 把可用的 cpu 按照亲和度分为组: cpu_grps = 2 [0,1] */ int cpu_grps = 1; if (affinity_cpus == -1) { affinity_cpus = POOL_CPU_ID_MAX + 1; } else if (affinity_cpus > POOL_CPU_ID_MAX) { affinity_cpus = POOL_CPU_ID_MAX + 1; } if (affinity_cpus > 0) { cpu_grps = onln_cpus / affinity_cpus; } if (cpu_grps < 1) { cpu_grps = 1; } /* 计算任意一个线程在亲和在哪组 cpu 上 */ int grp_id = thrid % cpu_grps; /* 给定 grp_id, 计算其所有的 cpu_id */ for (cpu_id = affinity_cpus * grp_id; cpu_id < affinity_cpus * (grp_id + 1); cpu_id++) { CPU_SET(cpu_id, cpuset); } return onln_cpus; } int thread_check_affinity_cpus (pthread_t thread, int *cpuid_list, int cnt) { int j, cid = 0; cpu_set_t cpuset; CPU_ZERO(&cpuset); if (pthread_getaffinity_np (thread, sizeof(cpu_set_t), &cpuset) != 0) { return -1; } else { for (j = 0; j < CPU_SETSIZE; j++) { if (CPU_ISSET(j, &cpuset)) { if (cid < cnt) { cpuid_list[cid++] = j; } } } } return cid; } #endif
pepstack/pytools
templates/%clib%/src/common/cstrbuf.h
/*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename cstrbuf.h * C String Buffer Functions. * * @author <NAME> <<EMAIL>> * @version 0.0.10 * @create 2017-08-28 11:12:10 * @update 2021-07-12 21:59:46 */ #ifndef _CSTRBUF_H_ #define _CSTRBUF_H_ #if defined(__cplusplus) extern "C" { #endif #include "memapi.h" #include "unitypes.h" #ifndef cstr_allocate_blocksize # define cstr_allocate_blocksize 16 #endif #ifndef cstr_length_maximum # define cstr_length_maximum 536870911 #endif #define cstr_bool_true 1 #define cstr_bool_false 0 #define cstr_length(str, maxlen) ((int)((str)==NULL? 0: ((int)(maxlen)==(-1)? strlen(str) : strnlen(str, (int)(maxlen))))) #define cstr_copybuf(dstbuf, src) \ snprintf_chkd_V1(dstbuf, sizeof(dstbuf), "%.*s", (int)strnlen(src, sizeof(dstbuf) - 1), (const char *)(src)) #define cstr_copybuf_len(dstbuf, src, srclen) \ snprintf_chkd_V1(dstbuf, sizeof(dstbuf), "%.*s", (int)(((int)(srclen)) < ((int)sizeof(dstbuf))? (srclen) : (sizeof(dstbuf) - 1)), (const char *)(src)) NOWARNING_UNUSED(static) void cstr_varray_free (char ** varr, int maxnum) { while (varr && maxnum-- > 0) { char *p = varr[maxnum]; if (p) { varr[maxnum] = NULL; mem_free(p); } } } NOWARNING_UNUSED(static) char * cstr_toupper (char * s, int num) { char *p = s; while (num-- > 0 && *p) { *p = toupper(*p); p++; } return s; } NOWARNING_UNUSED(static) char * cstr_tolower (char * s, int num) { char *p = s; while (num-- > 0 && *p) { *p = tolower(*p); p++; } return s; } /** * trim specified character in given string */ NOWARNING_UNUSED(static) char * cstr_trim_chr(char* s, char c) { char *f = s, *p = s; while (*p) { if (*p != c) { *f++ = *p; } ++p; } *f = 0; return s; } NOWARNING_UNUSED(static) char * cstr_trim_chrs (char * str, const char * chrs, int num) { while (num-- > 0) { cstr_trim_chr(str, chrs[num]); } return str; } NOWARNING_UNUSED(static) char * cstr_Ltrim_chr (char * str, char ch) { char *p = str; while (*p && *p++ == ch) { str = p; } return str; } NOWARNING_UNUSED(static) char* cstr_Rtrim_chr (char * str, char ch, int *outlen) { char *p = str; char *q = p; while (*p) { if (*p != ch) { q = p; } p++; } if (++q <= p) { *q = 0; if (outlen) { *outlen = (int)(q - str); } } else { if (outlen) { *outlen = 0; } } return str; } #define cstr_LRtrim_chr(str, c, outlen) cstr_Rtrim_chr(cstr_Ltrim_chr((str), (c)), (c), (outlen)) NOWARNING_UNUSED(static) char * cstr_Lfind_chr (char * str, int len, char c) { if (! str || len <= 0) { return NULL; } else { char *p = str; while ((int)(p - str) < len && *p) { if (*p == c) { return p; } p++; } return NULL; } } NOWARNING_UNUSED(static) char * cstr_Rfind_chr (char * str, int len, char c) { if (! str || len <= 0) { return NULL; } else { char *p = &str[len-1]; while (len-- > 0) { if (*p == c) { return p; } p--; } return NULL; } } NOWARNING_UNUSED(static) char * cstr_find_chrs (char * str, int len, const char *chrs, int nch) { if (! str || len <= 0) { return NULL; } else { int i; char *p = str; while ((int)(p - str) < len && *p) { for (i = 0; i < nch; i++) { if (chrs[i] == *p) { return p; } } p++; } return NULL; } } /** * int isspace(char c); * Standard white-space characters are: * ' ' (0x20) space (SPC) arcii=32 * '\t' (0x09) horizontal tab (TAB) * '\n' (0x0a) newline (LF) * '\v' (0x0b) vertical tab (VT) * '\f' (0x0c) feed (FF) * '\r' (0x0d) carriage return (CR) */ NOWARNING_UNUSED(static) char * cstr_Ltrim_whitespace (char *str) { char *p = str; while (p && isspace((int)*p)) { p++; } return p; } NOWARNING_UNUSED(static) int cstr_Rtrim_whitespace (char *str, int len) { while (len-- > 0) { if (isspace((int)str[len])) { str[len] = 0; } else { break; } } return len + 1; } NOWARNING_UNUSED(static) char * cstr_LRtrim_whitespace (char *str) { char *p = cstr_Ltrim_whitespace(str); cstr_Rtrim_whitespace(p, cstr_length(p, -1)); return p; } NOWARNING_UNUSED(static) int cstr_shrink_whitespace (const char *str, int *start, int *end) { int s = *start; int e = *end; for (; s < *end; s++) { if (! isspace((int)str[s])) { break; } } *start = s; for (; e >= *start; e--) { if (! isspace((int)str[e])) { break; } } *end = e; return (*end - *start + 1); } NOWARNING_UNUSED(static) char * cstr_trim_whitespace (char * s) { return (*s==0)?s:((( ! isspace((int)*s) )?(((cstr_trim_whitespace(s+1)-1)==s)? s : (*(cstr_trim_whitespace(s+1)-1)=*s, *s=32 ,cstr_trim_whitespace(s+1))):cstr_trim_whitespace(s+1))); } NOWARNING_UNUSED(static) char * cstr_replace_chr (char * str, char ch, char rpl) { char *p = str; while (p && *p) { if (*p == ch) { *p = rpl; } p++; } return str; } NOWARNING_UNUSED(static) int cstr_slpit_chr (const char * str, int len, char delim, char **outstrs, int outstrslen[], int maxoutnum) { char *p; const char *s = str; int outlen; int i = 0; int n = 1; while (s && (p = (char *)strchr(s, delim)) && (p < str +len)) { s = p+1; n++; } if (! outstrs) { // only to get count return n; } if (n > 0) { char *sb; char *s0 = (char*) mem_alloc_unset(len + 1); memcpy(s0, str, len); s0[len] = 0; sb = s0; while (sb && (p = strchr(sb, delim))) { *p++ = 0; if (i < maxoutnum) { // remove whitespaces outlen = 0; outstrs[i] = mem_strdup( cstr_LRtrim_chr(sb, 32, &outlen) ); if (outstrslen) { outstrslen[i] = outlen; } i++; } else { // overflow than maxoutnum break; } sb = (char *) p; } if (i < maxoutnum) { outlen = 0; outstrs[i] = mem_strdup( cstr_LRtrim_chr(sb, 32, &outlen) ); if (outstrslen) { outstrslen[i] = outlen; } i++; } mem_free(s0); } return i; } NOWARNING_UNUSED(static) int cstr_replace_new (const char *original, const char *pattern, const char *replacement, char **outresult) { size_t const replen = strlen(replacement); size_t const patlen = strlen(pattern); size_t const orilen = strlen(original); size_t patcnt = 0; const char * oriptr; const char * patloc; *outresult = 0; // find how many times the pattern occurs in the original string for ((oriptr = original); (patloc = strstr(oriptr, pattern)); (oriptr = patloc + patlen)) { patcnt++; } if (patcnt) { // allocate memory for the new string size_t len = orilen + patcnt * (replen - patlen); char * result = (char *) mem_alloc_unset( sizeof(char) * (len + 1) ); // copy the original string, // replacing all the instances of the pattern char * retptr = result; for ((oriptr = original); (patloc = strstr(oriptr, pattern)); (oriptr = patloc + patlen)) { size_t const skplen = patloc - oriptr; // copy the section until the occurence of the pattern strncpy(retptr, oriptr, skplen); retptr += skplen; // copy the replacement strncpy(retptr, replacement, replen); retptr += replen; } // copy the rest of the string. strcpy(retptr, oriptr); *outresult = result; return (int) len; } return 0; } /** * true: * "8897391" * " 123.456" * "+123456.123" * "-100 " * false: * "" * " " * "189 0931" * "12.56.89" * "+ 1234.556" */ NOWARNING_UNUSED(static) int cstr_isnumeric (char *numeric, int len) { int i = 0; int dots = 0; char *str = cstr_LRtrim_whitespace(numeric); len = cstr_length(str, len); if (len < 1 || len > 40) { return cstr_bool_false; } if (str[0] == '+' || str[0] == '-') { i = 1; } for (; i < len; i++) { if (! isdigit((int)str[i])) { if (str[i] == '.') { dots++; if (dots > 1) { return cstr_bool_false; } } else { return cstr_bool_false; } } } return cstr_bool_true; } NOWARNING_UNUSED(static) int cstr_to_sb8 (int base, const char *str, size_t slen, sb8 *outval) { if (!str || slen == 0) { // null string as 0 *outval = 0; return 0; } else { sb8 val; char *endptr; /* To distinguish success/failure after call */ errno = 0; if (slen == -1 || str[slen] == '\0') { val = strtoll(str, &endptr, base); if (val == 0 && endptr == str) { // error: no qualified digits were found *outval = val; return (-1); } } else { char* sbuf = (char *) alloca(slen + 1); memcpy(sbuf, str, slen); sbuf[slen] = '\0'; val = strtoll(sbuf, &endptr, base); if (val == 0 && endptr == sbuf) { // error: no qualified digits were found *outval = val; return (-1); } } /* Check for various possible errors */ if (errno) { // error occurred *outval = val; return (-1); } /* success return */ *outval = val; return 1; } } NOWARNING_UNUSED(static) int cstr_to_ub8 (int base, const char *str, size_t slen, ub8 *outval) { if (!str || slen == 0) { // null string as 0 *outval = 0; return 0; } else { ub8 val; char *endptr; /* To distinguish success/failure after call */ errno = 0; if (slen == -1 || str[slen] == '\0') { val = strtoull(str, &endptr, base); if (val == 0 && endptr == str) { // error: no qualified digits were found *outval = val; return (-1); } } else { char* sbuf = (char *) alloca(slen + 1); memcpy(sbuf, str, slen); sbuf[slen] = '\0'; val = strtoull(sbuf, &endptr, base); if (val == 0 && endptr == sbuf) { // error: no qualified digits were found *outval = val; return (-1); } } /* Check for various possible errors */ if (errno) { // error occurred *outval = val; return (-1); } /* success return */ *outval = val; return 1; } } NOWARNING_UNUSED(static) int cstr_to_dbl (const char *str, size_t slen, double *outval) { if (!str || slen == 0) { // null string as 0 *outval = 0; return 0; } else { double val; char *endptr; /* To distinguish success/failure after call */ errno = 0; if (slen == -1 || str[slen] == '\0') { val = strtod(str, &endptr); if (val == 0 && endptr == str) { // error: no qualified digits were found *outval = val; return (-1); } } else { char* sbuf = (char *) alloca(slen + 1); memcpy(sbuf, str, slen); sbuf[slen] = '\0'; val = strtod(sbuf, &endptr); if (val == 0 && endptr == sbuf) { // error: no qualified digits were found *outval = val; return (-1); } } /* Check for various possible errors */ if (errno) { // error occurred *outval = val; return (-1); } /* success return */ *outval = val; return 1; } } /** * cstr_split_substr * split string by separator string (sep) into sub strings */ NOWARNING_UNUSED(static) int cstr_split_substr (char *str, const char *sepstr, int seplen, char **subs, int maxsubs) { int i = 0; char *s = str; while (s && i < maxsubs) { char *p = strstr(s, sepstr); if (p) { *p = 0; p += seplen; } subs[i++] = s; s = p; } return i; } NOWARNING_UNUSED(static) int cstr_split_multi_chrs (char *str, int slen, const char *sepchrs, int count, char **outsubs, int outsubslen[], int maxsubs) { char *sub; int substart, subend, sublen; int k; int i = 0; int len = 0; int start = i; int end = start; for (; i < slen; i++) { for (k = 0; k < count; k++) { if (str[i] == sepchrs[k]) { end = i; break; } } if (k < count && end > start && len < maxsubs) { substart = start; subend = end - 1; sublen = cstr_shrink_whitespace(str, &substart, &subend); if (sublen > 0) { sub = (char *) mem_alloc_unset(sublen + 1); memcpy(sub, str + substart, sublen); sub[sublen] = 0; outsubs[len] = sub; outsubslen[len] = sublen; if (++len == maxsubs) { return len; } } start = end; } } end = slen; if (len < maxsubs && end > start) { substart = start; subend = end - 1; sublen = cstr_shrink_whitespace(str, &substart, &subend); if (sublen > 0) { sub = (char *) mem_alloc_unset(sublen + 1); memcpy(sub, str + substart, sublen); sub[sublen] = 0; outsubs[len] = sub; outsubslen[len] = sublen; len++; } } return len; } NOWARNING_UNUSED(static) int cstr_notequal (const char *str1, const char *str2) { if (str1 == str2) { return cstr_bool_false; } if (str1 && str2) { // str1 != str2 return strcmp(str1, str2)? cstr_bool_true : cstr_bool_false; } // str1 != str2 return cstr_bool_true; } NOWARNING_UNUSED(static) int cstr_notequal_len (const char *Astr, int Alen, const char *Bstr, int Blen) { if (Alen != Blen) { // Astr != Bstr return cstr_bool_true; } if (Astr == Bstr) { return cstr_bool_false; } if (Astr && Bstr) { return strncmp(Astr, Bstr, Alen)? cstr_bool_true : cstr_bool_false; } // not eauql return cstr_bool_true; } /** * cstr_compare_len * Safely compare two strings as strncmp(A, B) do * * returns: * 1: A > B * 0: A = B * -1: A < B * * notes: * 1) null string is less than any non-null or empty one. * 2) shorter string is less than longer one. * 3) two null strings is equal (0 returned). */ NOWARNING_UNUSED(static) int cstr_compare_len (const char *Astr, int Alen, const char *Bstr, int Blen, int caseignore) { if (Astr == Bstr) { return 0; } if (! Astr) { // A < B (B is non-null) return (-1); } if (! Bstr) { // A > B (B is null) return 1; } if (! Alen && ! Blen) { // A and B are all empty return 0; } if (Alen < 0 && Blen < 0) { // same as strcmp if (caseignore) { #ifdef _MSC_VER return stricmp(Astr, Bstr); #else return strcasecmp(Astr, Bstr); #endif } else { return strcmp(Astr, Bstr); } } if (Alen < 0) { // get length of Astr Alen = cstr_length(Astr, -1); } if (Blen < 0) { // get length of Astr Blen = cstr_length(Bstr, -1); } if (Alen > Blen) { return 1; } if (Alen < Blen) { return -1; } // Alen == Blen if (caseignore) { #ifdef _MSC_VER return strnicmp(Astr, Bstr, Alen); #else return strncasecmp(Astr, Bstr, Alen); #endif } else { return strncmp(Astr, Bstr, Alen); } } /** * cstr_startwith("HelloWorld", 10, "Hello", 5) == cstr_bool_true * cstr_startwith("HelloWorld", 10, "World", 5) == cstr_bool_false * cstr_startwith("HelloWorld", 10, "hello", 5) == cstr_bool_false */ NOWARNING_UNUSED(static) int cstr_startwith (const char *str, int count, const char *start, int startlen) { if (str == start) { return cstr_bool_true; } if (str && start && startlen <= count) { if (! memcmp(str, start, startlen)) { return cstr_bool_true; } } return cstr_bool_false; } NOWARNING_UNUSED(static) int cstr_endwith (const char *str, int count, const char *end, int endlen) { if (str == end) { return cstr_bool_true; } if (str && end && endlen <= count) { // str="aaaaBBBB" // end="aBBBB" return ! cstr_notequal_len(&str[count - endlen], endlen, end, endlen); } return cstr_bool_false; } NOWARNING_UNUSED(static) int cstr_containwith (const char *str, int count, const char *sub, int sublen) { if (str == sub) { return 0; } if (str && sub && sublen <= count) { int i = 0; for (; i <= count - sublen; i++) { if (! memcmp(&str[i], sub, sublen)) { return i; } } } return -1; } NOWARNING_UNUSED(static) int cstr_startwith_mul (const char *str, int count, const char *starts[], const int *startslen, int startsnum) { while (startsnum-- > 0) { const char *s = starts[startsnum]; if (s) { int len = (startslen? startslen[startsnum] : (int) strlen(s)); if (cstr_startwith(str, count, s, len)) { return startsnum; } } } return (-1); } NOWARNING_UNUSED(static) int cstr_endwith_mul (const char *str, int count, const char *ends[], const int *endslen, int endsnum) { while (endsnum-- > 0) { const char *s = ends[endsnum]; if (s) { int len = (endslen? endslen[endsnum] : (int) strlen(s)); if (cstr_endwith(str, count, s, len)) { return endsnum; } } } return (-1); } NOWARNING_UNUSED(static) int cstr_findstr_in (const char *str, int count, const char *dests[], int destsnum, int caseignore) { int i = 0; /** * FIX warning:‘strncasecmp’ specified bound 18446744073709551614 exceeds maximum object size 9223372036854775807 */ size_t szcnt = (count < 0 ? cstr_length(str, -1) : count); for (; i < destsnum; i++) { const char *dest = dests[i]; if (str == dest) { // found return i; } if (dest && str) { int len = cstr_length(dest, szcnt + 1); if (len == szcnt) { if (caseignore) { #ifdef _MSC_VER if (! strnicmp(str, dest, szcnt)) { // found return i; } #else if (! strncasecmp(str, dest, szcnt)) { // found return i; } #endif } else { if (! strncmp(str, dest, szcnt)) { // found return i; } } } } } // not found return (-1); } NOWARNING_UNUSED(static) int cstr_isdigit (const char *str, int len) { while(len-- > 0) { if (! isdigit((int)str[len])) { return cstr_bool_false; } } return cstr_bool_true; } NOWARNING_UNUSED(static) int cstr_safecopy (char *dstbuf, size_t dstbufsize, size_t dstoffset, const char *source, size_t sourcelen) { if (dstoffset + sourcelen < dstbufsize) { memcpy(dstbuf + dstoffset, source, sourcelen); dstbuf[dstoffset + sourcelen] = '\0'; /* success full copied */ return 1; } if (dstoffset < dstbufsize) { size_t cplen = dstbufsize - dstoffset; memcpy(dstbuf + dstoffset, source, cplen); if (dstbufsize > 3) { dstbuf[dstbufsize - 4] = '.'; dstbuf[dstbufsize - 3] = '.'; dstbuf[dstbufsize - 2] = '.'; } } dstbuf[dstbufsize - 1] = '\0'; /* error with part copied */ return 0; } NOWARNING_UNUSED(static) int cstr_readline (FILE *fp, char line[], size_t maxlen, int ignore_whitespace) { int ch, len = 0; if (ftell(fp) == 0) { int bomhead[3] = {fgetc(fp), fgetc(fp), fgetc(fp)}; if (bomhead[0] == 0xEF && bomhead[1] == 0xBB && bomhead[2] == 0xBF) { fseek(fp, 3, SEEK_SET); } else { fseek(fp, 0, SEEK_SET); } } while ((ch = fgetc(fp)) != EOF) { if ((size_t) len < maxlen) { if (ch != '\r' && ch != '\n' && ch != '\\') { if (! ignore_whitespace || ! isspace((int)ch)) { line[len++] = ch; } } } if (ch == '\n') { break; } } if (ch == EOF && len == 0) { // end of file return -1; } line[len] = 0; return len; } #define TM_YEAR_IS_LEAP(year) ((year) % 4? 0 : ((year) % 100? 1 : ((year) % 400? 0 : 1))) #define CSTR_DATETIME_SIZE_MAX 30 typedef struct { /* date fields: if year = -1, date is invalid */ int year; int month; int day; /* time fields: if hour = -1, time is invalid */ int hour; int minute; int second; /* millisecond: if millisecond = -1, millisecond is invalid */ int millisecond; /** * -1 : timezone is invalid * * 800 = +08:00, -800 = W08:00 */ int timezone; } cstr_datetime_t; NOWARNING_UNUSED(static) const char * cstr_datetime_print (const cstr_datetime_t *dt, char outfmt[CSTR_DATETIME_SIZE_MAX]) { int dlen = 0, tlen = 0, mlen = 0; *outfmt = 0; if (dt->year != -1) { dlen = snprintf_chkd_V1(outfmt, CSTR_DATETIME_SIZE_MAX, "%04d-%02d-%02d", dt->year, dt->month, dt->day); } if (dt->hour != -1) { if (dlen) { outfmt[dlen++] = 32; } tlen = snprintf_chkd_V1(outfmt + dlen, CSTR_DATETIME_SIZE_MAX - dlen, "%02d:%02d:%02d", dt->hour, dt->minute, dt->second); } if (dt->millisecond != -1) { mlen = snprintf_chkd_V1(outfmt + dlen + tlen, CSTR_DATETIME_SIZE_MAX - dlen - tlen, ".%03d", dt->millisecond); } if (dt->timezone != -1) { if (dt->timezone < 0) { snprintf_chkd_V1(outfmt + dlen + tlen + mlen, CSTR_DATETIME_SIZE_MAX - dlen - tlen - mlen, "W%02d:%02d", -dt->timezone / 100, -dt->timezone % 100); } else { snprintf_chkd_V1(outfmt + dlen + tlen + mlen, CSTR_DATETIME_SIZE_MAX - dlen - tlen - mlen, "+%02d:%02d", dt->timezone / 100, dt->timezone % 100); } } return outfmt; } /** * time_is_valid() * * test time is valid. * * remark: * * The number of seconds(sec) after the minute, normally in the range 0 to 59, * but can be up to 60 to allow for leap. * Deciding when to introduce a leap second is the responsibility of the * international earth rotation and reference systems service. * * returns: * 0: error * 1: ok */ NOWARNING_UNUSED(static) int time_is_valid (int year, int mon, int day, int hour, int min, int sec) { if (year < 1900 || year > 9999 || mon <= 0 || mon > 12 || day <= 0 || day > 31 || hour < 0 || hour > 24 || min < 0 || min > 59 || sec < 0 || sec > 60) { return 0; } if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) { // 31 days ok return 1; } else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) { if (day < 31) { return 1; } } else { // mon=2 return (day > 29? 0 : (day < 29? 1: (TM_YEAR_IS_LEAP(year)? 1 : 0))); } return 0; } NOWARNING_UNUSED(static) int cstr_parse_timezone (char *tz) { int sign = 0; /* +08:00/E0800; W08:00 */ if (*tz == '+' || *tz == 'E') { sign = 1; } else if (*tz == '-' || *tz == 'W') { sign = -1; } if (!sign) { return -1; } if (isdigit((int)tz[1]) && isdigit((int)tz[2]) && (tz[3]==':' || tz[3]=='.') && isdigit((int)tz[4]) && isdigit((int)tz[5]) && tz[6]=='\0') { char szhour[3] = {tz[1], tz[2], '\0'}; char szmin[3] = {tz[4], tz[5], '\0'}; int h = atoi(szhour); int m = atoi(szmin); if (h > 23) { return -1; } if (m > 59) { return -1; } return (h * 100 + m) * sign; } return -1; } NOWARNING_UNUSED(static) ub8 cstr_parse_timestamp (char *timestr, cstr_datetime_t *outdt) { int len = 0; int YMD = 0, HMS = 0, MMM = 0; /** * UTC+08:00 = +0800 or E0800 * UTC-11:00 = W0800 * * '2019-12-22 12:36:59.065+08:00' or '2019-12-22 12:36:59.065E08:00' * '2019-12-22 12:36:59.065' * '2019-12-22 12:36:59W08:00' or '2019-12-22 12:36:59-08:00' * '2019-12-22 12:36:59' * '2019-12-22E08:00' or '2019-12-22+08:00' * '2019-12-22' */ char Year[5] = {'0', '0', '0', '0', '\0'}; char Mon[3] = {'0', '0', '\0'}; char Day[3] = {'0', '0', '\0'}; char hour[3] = {'0', '0', '\0'}; char min[3] = {'0', '0', '\0'}; char sec[3] = {'0', '0', '\0'}; char msec[4] = {'0', '0', '0', '\0'}; int timezone = -1; char *str, *a, *b, *hms, *tz; tz = strchr(timestr, '+'); if (!tz) { tz = strchr(timestr, 'E'); if (!tz) { tz = strchr(timestr, 'W'); if (!tz) { // -08:00 or -08.00 tz = strrchr(timestr, '-'); if (tz) { if (tz[1] && tz[2] && (tz[3] == ':' || tz[3] == '.')) { // has timezone // tz; } else { // no timezone tz = 0; } } } } } if (tz) { timezone = cstr_parse_timezone(tz); if (timezone == -1) { // error timezone return (-1); } *tz = 0; } str = cstr_LRtrim_whitespace(timestr); a = strchr(str, 39); b = strrchr(str, 39); if (a && b) { *a++ = 0; *b-- = 0; str = a; len = (int)(b - a) + 1; } else if (a || b) { // error char return (-1); } else { len = cstr_length(str, 30); } if (len == 10) { /* 2019-12-22 */ YMD = 1; a = strchr(str, '-'); b = strrchr(str, '-'); if (a && b && a - str == 4 && b-a == 3) { *a++ = 0; *b++ = 0; snprintf_chkd_V1(Year, sizeof(Year), "%.*s", 4, str); snprintf_chkd_V1(Mon, sizeof(Mon), "%.*s", 2, a); snprintf_chkd_V1(Day, sizeof(Day), "%.*s", 2, b); } else { // error date format return (-1); } } else if (len == 19) { /* 2019-12-22 12:36:59 */ YMD = 1; HMS = 1; a = strchr(str, 32); if (a && a - str == 10) { *a++ = 0; hms = a; a = strchr(str, '-'); b = strrchr(str, '-'); if (a && b && a - str == 4 && b-a == 3) { *a++ = 0; *b++ = 0; snprintf_chkd_V1(Year, sizeof(Year), "%.*s", 4, str); snprintf_chkd_V1(Mon, sizeof(Mon), "%.*s", 2, a); snprintf_chkd_V1(Day, sizeof(Day), "%.*s", 2, b); } else { // error date format return (-1); } a = strchr(hms, ':'); b = strrchr(hms, ':'); if (a && b && a - hms == 2 && b-a == 3) { *a++ = 0; *b++ = 0; snprintf_chkd_V1(hour, sizeof(hour), "%.*s", 2, hms); snprintf_chkd_V1(min, sizeof(min), "%.*s", 2, a); snprintf_chkd_V1(sec, sizeof(sec), "%.*s", 2, b); } else { // error date format return (-1); } } else { // error datetime format return (-1); } } else if (len == 23) { /* 2019-12-22 12:36:59.065 */ YMD = 1; HMS = 1; MMM = 1; a = strchr(str, 32); if (a && a - str == 10) { *a++ = 0; hms = a; a = strchr(str, '-'); b = strrchr(str, '-'); if (a && b && a - str == 4 && b-a == 3) { *a++ = 0; *b++ = 0; snprintf_chkd_V1(Year, sizeof(Year), "%.*s", 4, str); snprintf_chkd_V1(Mon, sizeof(Mon), "%.*s", 2, a); snprintf_chkd_V1(Day, sizeof(Day), "%.*s", 2, b); } else { // error date format return (-1); } a = strchr(hms, ':'); b = strrchr(hms, ':'); if (a && b && a - hms == 2 && b-a == 3) { char *dot = strchr(b, '.'); if (!dot || dot - b != 3) { // error stamp format return (-1); } *a++ = 0; *b++ = 0; *dot++ = 0; snprintf_chkd_V1(hour, sizeof(hour), "%.*s", 2, hms); snprintf_chkd_V1(min, sizeof(min), "%.*s", 2, a); snprintf_chkd_V1(sec, sizeof(sec), "%.*s", 2, b); if (*dot) { msec[0] = *dot++; if (*dot) { msec[1] = *dot++; if (*dot) { msec[2] = *dot++; } } } } else { // error date format return (-1); } } else { // error datetime format return (-1); } } else { // error format return (-1); } if (! YMD) { // no year return (-1); } if (cstr_isdigit(Year, 4) && cstr_isdigit(Mon, 2) && cstr_isdigit(Day, 2) && cstr_isdigit(hour, 2) && cstr_isdigit(min, 2) && cstr_isdigit(sec, 2) && cstr_isdigit(msec, 3)) { ub8 tsec; struct tm t = {0}; t.tm_year = atoi(Year); t.tm_mon = atoi(Mon); t.tm_mday = atoi(Day); t.tm_hour = atoi(hour); t.tm_min = atoi(min); t.tm_sec = atoi(sec); if (! time_is_valid(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)) { // invalid time return (-1); } t.tm_year -= 1900; t.tm_mon -= 1; // since 1970-01-01 UTChh:00:00 (china: hh=8) tsec = (ub8) mktime(&t); if (tsec == (ub8)(-1)) { return (-1); } if (outdt) { outdt->year = atoi(Year); outdt->month = atoi(Mon); outdt->day = atoi(Day); outdt->hour = atoi(hour); outdt->minute = atoi(min); outdt->second = atoi(sec); outdt->millisecond = atoi(msec); outdt->timezone = timezone; } if (! HMS) { outdt->hour = -1; outdt->minute = 0; outdt->second = 0; } if (! MMM) { outdt->millisecond = -1; } tsec *= 1000; return (ub8)(tsec + atoi(msec)); } // error no digit return (-1); } NOWARNING_UNUSED(static) const char * cstr_timestamp_to_datetime (char *stampms, int mslen, char timestr[24]) { ub8 stamp = 0; time_t tsec; int msec; struct tm t; if (mslen == -1) { mslen = cstr_length(stampms, 20); } if (! cstr_to_ub8(10, stampms, mslen, &stamp)) { // error stamp return NULL; } tsec = (time_t)(stamp / 1000); msec = (int)(stamp % 1000); #ifdef _WIN32 if (!localtime_s(&t, (const time_t*) &tsec)) { // error localtime return NULL; } #else if (!localtime_r((const time_t*)&tsec, &t)) { // error localtime return NULL; } #endif t.tm_year += 1900; t.tm_mon += 1; if (! time_is_valid(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)) { // invalid time return NULL; } if (msec) { /* 2012-12-22 17:45:59.875 */ snprintf_chkd_V1(timestr, 24, "%04d-%02d-%02d %02d:%02d:%02d.%03d", t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, msec); } else { snprintf_chkd_V1(timestr, 20, "%04d-%02d-%02d %02d:%02d:%02d", t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); } return timestr; } /********************************************************************** * cstrbuf * C String Buffer Api *********************************************************************/ #define cstrbuf_error_size_len ((ub4)(-1)) #define cstrbuf_len_max 134217727 /* max size is 128 MB */ #define cstrbuf_size_max (cstrbuf_len_max + 1) #define cstrbuf_alignsize(len) ((ub4) (((len + cstr_allocate_blocksize) / cstr_allocate_blocksize) * cstr_allocate_blocksize)) #define cstrbufGetLen(s) ((s)? (int)(s)->len : 0) #define cstrbufGetMaxsz(s) ((s)? (int)(s)->maxsz : 0) #define cstrbufGetStr(s) ((s)? (s)->str : 0) #define cstrbufPrint(s) printf("%.*s", cstrbufGetLen(s), cstrbufGetStr(s)) #define cstrbufCharAt(s, i) ((char *)(s->str+(i))) typedef struct _cstrbuf_t { union { ub8 __maxszlen; struct { ub4 maxsz; ub4 len; }; }; char str[0]; } cstrbuf_t, *cstrbuf; NOWARNING_UNUSED(static) char * cstrbufCharAtSafe(cstrbuf csb, int at) { int len = cstrbufGetLen(csb); if (at >= 0 && at < len) { return cstrbufCharAt(csb, at); } /* invalid cstrbuf or index */ return NULL; } NOWARNING_UNUSED(static) cstrbuf cstrbufNew (ub4 maxsz, const char *str, ub4 len) { cstrbuf_t *csb; if (len == cstrbuf_error_size_len) { len = (ub4) cstr_length(str, cstr_length_maximum); } if (! maxsz) { maxsz = len + 1; } else if (maxsz == cstrbuf_error_size_len || maxsz <= len) { maxsz = cstrbuf_alignsize(len + 1); } else { /* maxsz > len */ maxsz = cstrbuf_alignsize(maxsz); } csb = (cstrbuf_t *) mem_alloc_unset(sizeof(*csb) + maxsz); csb->__maxszlen = 0; *csb->str = 0; if (str) { memcpy(csb->str, str, len); memset(csb->str + len, 0, maxsz - len); csb->len = len; } else { memset(csb->str, 0, maxsz); csb->len = 0; } csb->maxsz = maxsz; return csb; } NOWARNING_UNUSED(static) void cstrbufFree (cstrbuf *csb) { if (csb) { cstrbuf s = *csb; if (s) { *csb = 0; mem_free(s); } } } /* NOTE: dstbuf must have enough space for copy to */ NOWARNING_UNUSED(static) ub4 cstrbufCopyTo (const cstrbuf src, void *dstbuf, ub4 offcb) { if (src && src->len) { memcpy((char*)dstbuf + offcb, src->str, src->len); return (ub4)(offcb + src->len); } return (ub4)offcb; } NOWARNING_UNUSED(static) cstrbuf cstrbufCat (cstrbuf dst, const char *fmt, ...) { int vlen, len; if (! dst) { do { va_list args; va_start(args, fmt); vlen = vsnprintf(0, 0, fmt, args); va_end(args); } while(0); if (vlen < 0) { printf("(%s:%d) vsnprintf error: %s\n", __FILE__, __LINE__, strerror(errno)); return 0; } dst = cstrbufNew(vlen + 1, 0, 0); do { va_list args; va_start(args, fmt); len = vsnprintf(dst->str, dst->maxsz, fmt, args); va_end(args); } while(0); if (len == vlen) { dst->len = len; dst->str[dst->len] = 0; return dst; } printf("(%s:%d) vsnprintf error: %s\n", __FILE__, __LINE__, strerror(errno)); cstrbufFree(&dst); return 0; } else { do { va_list args; va_start(args, fmt); vlen = vsnprintf(&dst->str[dst->len], dst->maxsz - dst->len, fmt, args); va_end(args); } while(0); if (vlen < 0) { printf("(%s:%d) vsnprintf error: %s\n", __FILE__, __LINE__, strerror(errno)); dst->str[dst->len] = 0; return dst; } if (dst->len + vlen < dst->maxsz) { dst->len += vlen; dst->str[dst->len] = 0; return dst; } else { ub4 maxsz = cstrbuf_alignsize(dst->len + vlen + 1); cstrbuf_t *newdst = (cstrbuf_t *) mem_realloc(dst, sizeof(*newdst) + maxsz); if (! newdst) { printf("(%s:%d) Cannot allocate memory.\n", __FILE__, __LINE__); exit(EXIT_FAILURE); } newdst->maxsz = maxsz; do { va_list args; va_start(args, fmt); len = vsnprintf(&newdst->str[newdst->len], newdst->maxsz - newdst->len, fmt, args); va_end(args); } while(0); if (len == vlen) { newdst->len += len; } newdst->str[newdst->len] = 0; return newdst; } } } NOWARNING_UNUSED(static) cstrbuf cstrbufTrunc (cstrbuf s, ub4 len) { if (s->len > len) { s->len = len; s->str[s->len] = 0; } return s; } NOWARNING_UNUSED(static) cstrbuf cstrbufConcat (const cstrbuf start, ...) { va_list argp; cstrbuf src = start; va_start(argp, start); cstrbuf result = 0; do { result = cstrbufCat(result, "%.*s", cstrbufGetLen(src), cstrbufGetStr(src)); src = va_arg(argp, cstrbuf); } while(src); va_end(argp); return result; } NOWARNING_UNUSED(static) cstrbuf cstrbufDup (cstrbuf dst, const char *source, ub4 sourcelen) { if (! dst) { return cstrbufNew(0, source, sourcelen); } if (sourcelen == cstrbuf_error_size_len) { sourcelen = (ub4) cstr_length(source, -1); } if (! sourcelen) { dst->len = 0; dst->str[dst->len] = 0; return dst; } if (dst->maxsz > sourcelen) { memcpy(dst->str, source, sourcelen); dst->len = sourcelen; dst->str[dst->len] = 0; return dst; } mem_free(dst); return cstrbufNew(0, source, sourcelen); } NOWARNING_UNUSED(static) cstrbuf cstrbufSub (const char *source, int startindex, int length, const char *substr, int sublen) { int sourlen = cstr_length(source, -1); cstrbuf endstr = cstrbufNew(0, source + startindex + length, sourlen - startindex - length); cstrbuf result = cstrbufNew(sourlen - length + sublen + 1, source, startindex); memcpy(result->str + startindex, substr, sublen); memcpy(result->str + startindex + sublen, endstr->str, endstr->len); cstrbufFree(&endstr); result->len = sourlen - length + sublen; result->str[result->len] = 0; return result; } NOWARNING_UNUSED(static) cstrbuf cstrbufPushBack (cstrbuf dst, char ch) { if (dst) { if (dst->len + 1 < dst->maxsz) { dst->str[dst->len++] = ch; } else { dst = cstrbufCat(dst, "%c", ch); } } else { dst = cstrbufCat(NULL, "%c", ch); } return dst; } #ifdef __cplusplus } #endif #endif /* _CSTRBUF_H_ */
pepstack/pytools
templates/%clib%/src/common/readconf.c
<gh_stars>0 /*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename readconf.c * read ini file api for Linux and Windows. * * @author <NAME> <<EMAIL>> * @version 0.0.9 * @create 2012-05-21 10:14:00 * @update 2020-05-19 18:34:50 */ #include "readconf.h" #include <math.h> # if defined (_MSC_VER) # pragma warning(disable:4996) #endif #ifndef NOWARNING_UNUSED # if defined(__GNUC__) || defined(__CYGWIN__) # define NOWARNING_UNUSED(x) __attribute__((unused)) x # else # define NOWARNING_UNUSED(x) x # endif #endif typedef struct _conf_position_t { FILE *_fp; char _secname[READCONF_MAX_SECNAME + 4]; char _linebuf[READCONF_MAX_LINESIZE + 4]; } conf_position_t; NOWARNING_UNUSED(static) char * trim(char *s, char c) { return (*s==0)?s:(((*s!=c)?(((trim(s+1,c)-1)==s)?s:(*(trim(s+1,c)-1)=*s,*s=c,trim(s+1,c))):trim(s+1,c))); } NOWARNING_UNUSED(static) char * trim_whitespace (char * s) { return (*s==0)?s:((( ! isspace((int)*s) )?(((trim_whitespace(s+1)-1)==s)? s : (*(trim_whitespace(s+1)-1)=*s, *s=32 ,trim_whitespace(s+1))):trim_whitespace(s+1))); } NOWARNING_UNUSED(static) char * ltrim (char *s, char c) { while(*s!=0&&*s==c){s++;}return s; } NOWARNING_UNUSED(static) char * rtrim (char *s, char c) { char *p=s,*q=s;while(*p!=0){if(*p!=c){q=p;q++;}p++;}if(q!=s)*q=0;return s; } NOWARNING_UNUSED(static) char * dtrim (char *s, char c) { return rtrim(ltrim(s, c), c); } NOWARNING_UNUSED(static) int readln (FILE *fp, char *strbuf, int bufsize) { int i, j; char ch; for (i=0, j=0; i<bufsize; j++) { if (fread(&ch, sizeof(char), 1, fp) != 1) { /* read error */ if (feof(fp) != 0) { if (j==0) { return -1; /* end file */ } else { break; } } return -2; } else { /* read a char */ if (ch==10 || ch==0) { /* 10='\n' */ /* read a line ok */ break; } if (ch==12 || ch==0x1A) { /* 12='\f' */ strbuf[i++]=ch; break; } if (ch != 13) { /* '\r' */ strbuf[i++]=ch; } } if (i==bufsize) { return -3; /* exceed max chars */ } } strbuf[i] = 0; return i; } NOWARNING_UNUSED(static) int splitpair (char *strbuf, char sep, char **key, char **val) { char *at = strchr(strbuf, sep); if (at) { *at++ = 0; } *key = strbuf; *key = dtrim(dtrim(*key, 32), 9); *val = at; if (at) { *val = dtrim(dtrim(dtrim(*val, 32), 9), 34); /* '\"' */ } if (*key != 0) { return READCONF_TRUE; } else { return READCONF_FALSE; } } NOWARNING_UNUSED(static) char** _SectionListAlloc (int numSections) { char **secs = (char**) ConfMemAlloc(numSections+1, sizeof(char*)); secs[0] = (char*) (uintptr_t) numSections; return secs; } void * ConfMemAlloc (int numElems, int sizeElem) { void *p = calloc(numElems, sizeElem); if (!p) { exit(READCONF_RET_OUTMEM); } return p; } void * ConfMemRealloc (void *oldBuffer, int oldSize, int newSize) { void *newBuffer = 0; assert(newSize >= 0); if (newSize==0) { ConfMemFree(oldBuffer); return newBuffer; } if (oldSize==newSize) { return oldBuffer? oldBuffer : ConfMemAlloc(1, newSize); } newBuffer = realloc(oldBuffer, newSize); if (!newBuffer) { exit(READCONF_RET_OUTMEM); } if (newSize > oldSize) { memset((char*)newBuffer+oldSize, 0, (size_t)(newSize-oldSize)); } return newBuffer; } void ConfMemFree (void *pBuffer) { if (pBuffer) { free(pBuffer); } } char * ConfMemCopyString (char **dst, const char *src) { *dst = 0; if (src) { size_t cb = strlen(src) + 1; *dst = (char*) malloc(cb); memcpy(*dst, src, cb); } return *dst; } CONF_position ConfOpenFile (const char *conf) { CONF_position cpos; FILE *fp = fopen(conf, "rb"); if (! fp) { return 0; } cpos = (CONF_position) ConfMemAlloc(1, sizeof(conf_position_t)); cpos->_fp = fp; return cpos; } void ConfCloseFile (CONF_position cpos) { fclose(cpos->_fp); ConfMemFree(cpos); } char * ConfGetNextPair (CONF_position cpos, char **key, char **val) { char *start; int nch; for (;;) { nch = readln(cpos->_fp, cpos->_linebuf, READCONF_MAX_LINESIZE); if (nch < 0) { return 0; } start = dtrim(dtrim(cpos->_linebuf, 32), 9); if (*start == READCONF_NOTE_CHAR) { /* # */ continue; } nch = (int) strlen(start); if (nch > 2) { if (nch <= READCONF_MAX_SECNAME && *start==READCONF_SEC_BEGIN && *(start+nch-1)==READCONF_SEC_END) { /* find a section */ memcpy(cpos->_secname, start+1, nch-1); cpos->_secname[nch-1] = 0; cpos->_secname[nch-2] = 0; continue; } if (splitpair(start, READCONF_SEPARATOR, key, val)==READCONF_TRUE) { return start; } } } return 0; } char * ConfGetFirstPair (CONF_position cpos, char **key, char **val) { if (! cpos) { return 0; } rewind(cpos->_fp); return ConfGetNextPair(cpos, key, val); } const char * ConfGetSection (CONF_position cpos) { return cpos->_secname; } READCONF_RESULT ConfCopySection (CONF_position cpos, char *secName) { if (!cpos->_secname) { return READCONF_RET_ERROR; } if (!secName) { return (int) strlen(cpos->_secname)+2; } memcpy(secName, cpos->_secname, strlen(cpos->_secname)+2); return READCONF_RET_SUCCESS; } int ConfReadValue (const char *confFile, const char *sectionName, const char *keyName, char *valbuf, size_t maxbufsize) { char *str, *key, *val, endchr; int valsz; CONF_position cpos = ConfOpenFile(confFile); str = ConfGetFirstPair(cpos, &key, &val); while (str) { if (! sectionName || ! strcmp(ConfGetSection(cpos), sectionName)) { if (! strcmp(key, keyName)) { if (val) { valsz = (int) strlen(val) + 1; if (! valbuf) { ConfCloseFile(cpos); return valsz; } memcpy(valbuf, val, valsz); /* check last char: '\' */ if (valbuf[valsz - 2] != '\\') { /* end of val */ ConfCloseFile(cpos); return valsz; } endchr = valbuf[valsz - 2]; while (endchr == '\\') { char *start; /* read next line for: '+' */ int nch = readln(cpos->_fp, cpos->_linebuf, READCONF_MAX_LINESIZE); if (nch < 0) { /* end of val */ ConfCloseFile(cpos); return valsz; } start = dtrim(dtrim(cpos->_linebuf, 32), 9); if (*start == READCONF_NOTE_CHAR) { /* # */ continue; } if (*start != '+') { /* end of val */ valbuf[valsz-- - 2] = '\0'; ConfCloseFile(cpos); return valsz; } start = dtrim(dtrim(start+1, 32), 9); nch = (int) strlen(start); endchr = start[nch - 1]; if (valsz - 2 + nch < (int)maxbufsize) { memcpy(valbuf + valsz - 2, start, nch + 1); } valsz = valsz - 2 + nch + 1; } ConfCloseFile(cpos); return valsz; } else { *valbuf = 0; ConfCloseFile(cpos); return 1; } } } str = ConfGetNextPair(cpos, &key, &val); } ConfCloseFile(cpos); return 0; } READCONF_BOOL ConfReadValueRef (const char *confFile, const char *sectionName, const char *keyName, char **ppRefVal) { char *str; char *key; char *val; CONF_position cpos = ConfOpenFile(confFile); str = ConfGetFirstPair(cpos, &key, &val); while (str) { if (! sectionName || ! strcmp(ConfGetSection(cpos), sectionName)) { if (! strcmp(key, keyName)) { *ppRefVal = val; ConfCloseFile(cpos); return READCONF_TRUE; } } str = ConfGetNextPair(cpos, &key, &val); } ConfCloseFile(cpos); return READCONF_FALSE; } int ConfReadValueParsed (const char *confFile, const char *family, const char *qualifier, const char *key, char *valbuf, size_t maxbufsize) { if (! qualifier) { return ConfReadValue(confFile, family, key, valbuf, maxbufsize); } else { char section[READCONF_MAX_SECNAME + 4]; snprintf(section, sizeof(section), "%s:%s", family, qualifier); return ConfReadValue(confFile, section, key, valbuf, maxbufsize); } } int ConfReadValueParsedAlloc (const char *confFile, const char *family, const char *qualifier, const char *key, char **value) { int maxbufsize = READCONF_MAX_LINESIZE; char *valbuf = ConfMemAlloc(1, maxbufsize); int valsz = ConfReadValueParsed(confFile, family, qualifier, key, valbuf, maxbufsize); if (valsz > maxbufsize) { maxbufsize = valsz; ConfMemFree(valbuf); valbuf = ConfMemAlloc(1, maxbufsize); valsz = ConfReadValueParsed(confFile, family, qualifier, key, valbuf, maxbufsize); } *value = valbuf; return valsz; } int ConfGetSectionList (const char *confFile, void **sectionList) { char *key; char *val; int numSections = 0; *sectionList = 0; CONF_position cpos = ConfOpenFile(confFile); if (!cpos) { return READCONF_RET_ERROR; } /* get count of secions */ char secName[READCONF_MAX_SECNAME]; secName[0] = 0; while (ConfGetNextPair(cpos, &key, &val) != 0) { const char *sec = ConfGetSection(cpos); if (strcmp(sec, secName)) { ConfCopySection(cpos, secName); numSections++; } } ConfCloseFile(cpos); if (numSections > 0) { int secNo = 1; char **secs = _SectionListAlloc(numSections); /* again get all of secions */ cpos = ConfOpenFile(confFile); if (cpos) { while (secNo <= numSections && ConfGetNextPair(cpos, &key, &val) != 0) { const char *sec = ConfGetSection(cpos); if (secNo==1 || strcmp(sec, secs[secNo-1])) { int secSize = ConfCopySection(cpos, 0); secs[secNo] = (char*) ConfMemAlloc(secSize, sizeof(char)); ConfCopySection(cpos, secs[secNo]); secNo++; } } ConfCloseFile(cpos); } *sectionList = (void*) secs; } return numSections; } void ConfSectionListFree (void *sections) { if (sections) { char ** secs = (char **) sections; int numSections = (int) (uintptr_t) secs[0]; while(numSections>0) { ConfMemFree(secs[numSections--]); } ConfMemFree(secs); } } char * ConfSectionListGetAt (void *sections, int secIndex) { char ** secs = (char **) sections; int numSections = (int) (uintptr_t) secs[0]; if (secIndex < 0 || secIndex >= numSections) { return (char *) 0; } return secs[secIndex+1]; } int ConfSectionParse (char *sectionName, char **family, char **qualifier) { char *p, *q; if (! sectionName) { /* null string */ return -1; } if (! sectionName[0]) { /* empty string */ return 0; } *qualifier = 0; *family = sectionName; p = strchr(sectionName, (char)READCONF_SEC_SEMI); q = strrchr(sectionName, (char)READCONF_SEC_SEMI); if (p == q && p) { *p++ = 0; *qualifier = p; return 2; } return 1; } /** * 1 true * 0 false * * -1 error */ #ifdef _MSC_VER # define StrNCaseComp strnicmp #else # define StrNCaseComp strncasecmp #endif int ConfParseBoolValue (const char *value, int defvalue) { int c; if (! value || *value == '\0') { return defvalue; } c = (int) strnlen(value, 10); if (c > 8) { return (-1); } if (! StrNCaseComp("1", value, c) || ! StrNCaseComp("yes", value, c) || ! StrNCaseComp("y", value, c) || ! StrNCaseComp("on", value, c) || ! StrNCaseComp("open", value, c) || ! StrNCaseComp("true", value, c) || ! StrNCaseComp("t", value, c)) { return 1; } if (! StrNCaseComp("0", value, c) || ! StrNCaseComp("no", value, c) || ! StrNCaseComp("n", value, c) || ! StrNCaseComp("off", value, c) || ! StrNCaseComp("close", value, c) || ! StrNCaseComp("false", value, c) || ! StrNCaseComp("f", value, c)) { return 0; } return (-1); } /** * ----------------------------------------------------------- * NAME ABBR. BYTES NAME ABBR. BYTES * ----------------------------------------------------------- * bit *bit 1/8 Byte B 1 * kilobyte KB 10^3 (1000) kibibyte KiB 2^10 (1024) * megabyte MB 10^6 mebibyte MiB 2^20 * gigabyte GB 10^9 gibibyte GiB 2^30 * terabyte TB 10^12 tebibyte TiB 2^40 * petabyte PB 10^15 pebibyte PiB 2^50 * exabyte EB 10^18 exbibyte EiB 2^60 * zettabyte ZB 10^21 zebibyte ZiB 2^70 * yottabyte YB 10^24 yobibyte YiB 2^80 * ----------------------------------------------------------- */ double ConfParseSizeBytesValue(char *valuebuf, double defvalue, int *base, int *exponent) { static const struct { char name[4]; int base; int exponent; } namebytes[] = { {"B", 10, 0}, {"KiB", 2, 10}, {"KB", 10, 3}, {"K", 10, 3}, {"MiB", 2, 20}, {"MB", 10, 6}, {"M", 10, 6}, {"GiB", 2, 30}, {"GB", 10, 9}, {"G", 10, 9}, {"TiB", 2, 40}, {"TB", 10, 12}, {"T", 10, 12}, {"PiB", 2, 50}, {"PB", 10, 15}, {"P", 10, 15}, {"EiB", 2, 60}, {"EB", 10, 18}, {"E", 10, 18}, {"ZiB", 2, 70}, {"ZB", 10, 21}, {"Z", 10, 21}, {"YiB", 2, 80}, {"YB", 10, 24}, {"Y", 10, 24} }; if (base && exponent) { *base = 10; *exponent = 0; } if (valuebuf) { size_t num = sizeof(namebytes)/sizeof(namebytes[0]); char *value = trim_whitespace(valuebuf); int len = (int) strnlen(value, 128); int end; for (end = len - 1; end >= 0; end--) { if (value[end] >= '0' && value[end] <= '9') { size_t i; double retbytes = defvalue; char *name = &value[end + 1]; for (i = 0; i != num; i++) { if (!memcmp(namebytes[i].name, name, len - end)) { if (base && exponent) { *base = namebytes[i].base; *exponent = namebytes[i].exponent; } *name = 0; retbytes = atof(value); if (base && exponent) { return retbytes; } else { return retbytes * pow(namebytes[i].base, namebytes[i].exponent); } } } } } } return defvalue; }
pepstack/pytools
templates/%clib%/src/common/readconf.h
<filename>templates/%clib%/src/common/readconf.h /*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename readconf.h * read ini file api for Linux and Windows. * * @author <NAME> <<EMAIL>> * @version 0.0.9 * @create 2012-05-21 * @update 2021-04-02 15:32:50 */ #ifndef _READCONF_H__ #define _READCONF_H__ #if defined(__cplusplus) extern "C" { #endif #include <stdio.h> #include <errno.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <ctype.h> #ifndef _MSC_VER #include <unistd.h> #endif typedef int READCONF_BOOL; #define READCONF_TRUE 1 #define READCONF_FALSE 0 typedef int READCONF_RESULT; #define READCONF_RET_SUCCESS (0) #define READCONF_RET_ERROR (-1) #define READCONF_RET_OUTMEM (-4) #define READCONF_SEC_BEGIN 91 /* '[' */ #define READCONF_SEC_END 93 /* ']' */ #define READCONF_SEPARATOR 61 /* '=' */ #define READCONF_NOTE_CHAR 35 /* '#' */ #define READCONF_SEC_SEMI 58 /* ':' */ #ifndef READCONF_MAX_LINESIZE # define READCONF_MAX_LINESIZE 4096 #endif #ifndef READCONF_MAX_SECNAME # define READCONF_MAX_SECNAME READCONF_MAX_LINESIZE #endif typedef struct _conf_position_t * CONF_position; extern void* ConfMemAlloc (int numElems, int sizeElem); extern void* ConfMemRealloc (void *oldBuffer, int oldSize, int newSize); extern void ConfMemFree (void *pBuffer); extern char* ConfMemCopyString (char **dst, const char *src); extern CONF_position ConfOpenFile (const char *conf); extern void ConfCloseFile (CONF_position cpos); extern char *ConfGetNextPair (CONF_position cpos, char **key, char **val); extern char *ConfGetFirstPair (CONF_position cpos, char **key, char **val); extern const char *ConfGetSection (CONF_position cpos); extern READCONF_RESULT ConfCopySection (CONF_position cpos, char *secName); extern int ConfReadValue (const char *confFile, const char *sectionName, const char *keyName, char *valbuf, size_t maxbufsize); extern int ConfReadValueRef (const char *confFile, const char *sectionName, const char *keyName, char **ppRefVal); extern int ConfReadValueParsed (const char *confFile, const char *family, const char *qualifier, const char *key, char *valbuf, size_t maxbufsize); extern int ConfReadValueParsedAlloc (const char *confFile, const char *family, const char *qualifier, const char *key, char **value); extern int ConfGetSectionList (const char *confFile, void **sectionList); extern void ConfSectionListFree (void *sectionList); extern char * ConfSectionListGetAt (void *sectionList, int secIndex); extern READCONF_BOOL ConfSectionGetFamily (const char *sectionName, char *family); extern READCONF_BOOL ConfSectionGetQualifier (const char *sectionName, char *qualifier); extern int ConfSectionParse (char *sectionName, char **family, char **qualifier); extern int ConfParseBoolValue (const char *value, int defvalue); extern double ConfParseSizeBytesValue (char *valuebuf, double defvalue, int *base, int *exponent); #if defined(__cplusplus) } #endif #endif /* _READCONF_H__ */
pepstack/pytools
templates/%clib%/deps/libclogger/include/clogger/clogger_api.h
<reponame>pepstack/pytools<filename>templates/%clib%/deps/libclogger/include/clogger/clogger_api.h /** * clogger_api.h */ #ifndef CLOGGER_API_H_PUBLIC #define CLOGGER_API_H_PUBLIC #ifdef __cplusplus extern "C" { #endif #include "clogger_def.h" CLOGGER_API const char * clogger_lib_version(const char **_libname); CLOGGER_API const char * logger_manager_version (); /*! * @brief logger_manager_init * Initialize logger manager by an optional config file. * This function should be called in main entry of application. * * YOU SHOULD NEVER CALL THIS METHOD IN ANY DLL (OR SO) MODULES. * * @param[in] logger_cfg path file to a clooger config file. * If 0 provided, clogger uses default search order for a logger.cfg. * See clogger.cfg for more. * * @param[in] app_ident optional ident for application logger. * If provided, application logger can be retrieved anywhere by calling: * logger_manager_load(NULL); */ CLOGGER_API void logger_manager_init (const char *logger_cfg, ...); /*! * @brief logger_manager_uninit * * YOU SHOULD NEVER CALL THIS METHOD IN ANY DLL (OR SO) MODULES. * * Finalize all loggers within manager. * This function should be called like the following: * atexit(logger_manager_uninit); * */ CLOGGER_API void logger_manager_uninit (void); CLOGGER_API logger_manager get_logger_manager(); /*! * @brief logger_manager_load * Load a specified logger by ident name. * clogger would create a logger for the ident and cache it. * A Cached logger should be retrieved using logger_manager_get() function * provided a loggerid returned by logger_manager_load(). * * @param[in] ident name identifier for logger to load * @param[in] ident load clogger from logger_manager given it's ident. * if it is NULL, get (app_ident) logger set when calling logger_manager_init. * * @return * -<em>a clog_logger object</em> succeed * -<em>0</em> fail */ CLOGGER_API clog_logger logger_manager_load (const char *ident); /*! * @brief logger_manager_get * Get a cached logger by 1-based id. * This method is fast enough and threads-safety. * * @param[in] loggerid an int identifier for cached logger. * if 0 provided, get the first logger; * if -1 provided, get the last logger; * Get an id for logger uses: * clog_logger_get_loggerid(logger); * * @param[in] pvmgr pointer to logger_manager returned by get_logger_manager() * * @return * -<em>a clog_logger object</em> succeed * -<em>0</em> fail */ CLOGGER_API clog_logger logger_manager_get (int loggerid); CLOGGER_API int logger_manager_get_stampid (char *stampidfmt, int fmtsize); /** * logger conf api */ CLOGGER_API void logger_conf_init_default (clogger_conf conf, const char *ident, const char *pathprefix, const char *winsyslogconf); CLOGGER_API void logger_conf_final_release (clogger_conf conf); CLOGGER_API int logger_conf_get_creatflags (const clogger_conf conf); CLOGGER_API int logger_conf_load_config (const char *cfgfile, const char *ident, clogger_conf conf); /** * logger api */ CLOGGER_API clog_logger clog_logger_create (clogger_conf conf, logger_manager mgr); CLOGGER_API void clog_logger_destroy (clog_logger logger); CLOGGER_API int clog_logger_get_loggerid (clog_logger logger); CLOGGER_API const char * clog_logger_get_ident (clog_logger logger); CLOGGER_API int clog_logger_get_maxmsgsize (clog_logger logger); CLOGGER_API int64_t clog_logger_get_logmessages (clog_logger logger, int64_t *round); CLOGGER_API int clog_logger_level_enabled(clog_logger logger, clog_level_t level); CLOGGER_API void clog_logger_log_message (clog_logger logger, clog_level_t level, uint16_t maxwaitms, const char *message, int msglen); CLOGGER_API void clog_logger_log_format (clog_logger logger, clog_level_t level, uint16_t maxwaitms, const char *filename, int lineno, const char *funcname, const char *format, ...); /** * real time clock api */ CLOGGER_API int clog_logger_get_timezone (clog_logger logger, const char **timezonefmt); CLOGGER_API int clog_logger_get_daylight (clog_logger logger); CLOGGER_API int64_t clog_logger_get_ticktime (clog_logger logger, struct timespec *ticktime); CLOGGER_API void clog_logger_get_localtime (clog_logger logger, int timezone, int daylight, struct tm *tmloc, struct timespec *now); /** * helper api */ CLOGGER_API const char * clog_logger_file_basename (const char *pathfile, int *namelen); CLOGGER_API void clog_set_levelcolor (clog_logger logger, clog_level_t level, clog_color_t color); CLOGGER_API void clog_set_levelstyle (clog_logger logger, clog_level_t level, clog_style_t style); CLOGGER_API int clog_level_from_string (const char *levelstring, int length, clog_level_t *level); CLOGGER_API int clog_layout_from_string (const char *layoutstring, int length, clog_layout_t *layout); CLOGGER_API int clog_dateformat_from_string (const char *datefmtstring, int length, clog_dateformat_t *dateformat); CLOGGER_API int clog_appender_from_string (const char *appenderstring, int length, int *appender); #ifdef __cplusplus } #endif #endif /* CLOGGER_API_H_PUBLIC */
pepstack/pytools
templates/%clib%/src/common/win32/mman.h
/** * mman.h * mmap api for windows only. * * In particular, mmap, munmap, and msync are not available on Windows. These * replacements are used on both Cygwin and MinGW. (On Cygwin the built-in mmap * has no write support, and is not used). * * Special thanks to <NAME> for contributing mmap.c and mman.h * Original Author is <NAME>, April 2007 * Updated by ZhangLiang to support 64bits, 2015 */ #ifndef _MMAN_H_ #define _MMAN_H_ #if defined(__cplusplus) extern "C" { #endif /* Protections */ #define PROT_NONE 0x00 /* no permissions */ #define PROT_READ 0x01 /* pages can be read */ #define PROT_WRITE 0x02 /* pages can be written */ #define PROT_EXEC 0x04 /* pages can be executed */ /* Sharing type and options */ #define MAP_SHARED 0x0001 /* share changes */ #define MAP_PRIVATE 0x0002 /* changes are private */ #define MAP_COPY MAP_PRIVATE /* Obsolete */ #define MAP_FIXED 0x0010 /* map addr must be exactly as requested */ #define MAP_RENAME 0x0020 /* Sun: rename private pages to file */ #define MAP_NORESERVE 0x0040 /* Sun: don't reserve needed swap area */ #define MAP_INHERIT 0x0080 /* region is retained after exec */ #define MAP_NOEXTEND 0x0100 /* for MAP_FILE, don't change file size */ #define MAP_HASSEMAPHORE 0x0200 /* region may contain semaphores */ #define MAP_STACK 0x0400 /* region grows down, like a stack */ /* Error returned from mmap() */ #define MAP_FAILED ((void *)-1) /* Flags to msync */ #define MS_ASYNC 0x01 /* perform asynchronous writes */ #define MS_SYNC 0x02 /* perform synchronous writes */ #define MS_INVALIDATE 0x04 /* invalidate cached data */ /* File modes for 'open' not defined in MinGW32 (not used by mmap) */ #ifndef S_IWGRP #define S_IWGRP 0 #define S_IRGRP 0 #define S_IROTH 0 #endif /* for 64bits */ #ifndef HIDWORD # define HIDWORD(x) ((DWORD)(((DWORD64)(x) >> 32) & 0xFFFFFFFF)) #endif #ifndef LODWORD # define LODWORD(x) ((DWORD)(((DWORD_PTR)(x)) & 0xFFFFFFFF)) #endif /** * Map a file to a memory region */ extern void *mmap(void *addr, size_t len, int prot, int flags, int fd, unsigned int offset); /** * Unmap a memory region */ extern int munmap(void *addr, size_t len); /** * Synchronize a mapped region */ extern int msync(char *addr, size_t len, int flags); #ifdef __cplusplus } #endif #endif /* _MMAN_H_ */
pepstack/pytools
templates/%clib%/src/common/uatomic.h
<gh_stars>0 /*********************************************************************** * Copyright (c) 2008-2080 pepstack.<EMAIL>, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename uatomic.h * user CAS atomic api both for Windows and Linux * * Usage: * uatomic_int i; * uatomic_int_set(&i, 0); * uatomic_int_add(&i); * * @author <NAME> <<EMAIL>> * @version 0.0.2 * @create 2019-12-15 12:46:50 * @update 2020-12-05 23:12:10 */ #ifndef _U_ATOMIC_H_ #define _U_ATOMIC_H_ #if defined(__cplusplus) extern "C" { #endif #if defined(_WIN32) // Windows # include <Windows.h> # include <process.h> # include <stdint.h> # include <time.h> # include <limits.h> # ifdef _LINUX_GNUC # undef _LINUX_GNUC # endif #elif defined(__GNUC__) // Linux #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 1) #error GCC version must be greater or equal than 4.1.2 #endif # include <sched.h> # include <pthread.h> # include <unistd.h> # include <stdint.h> # include <time.h> # include <signal.h> # include <errno.h> # include <limits.h> # include <sys/time.h> # include <sys/sysinfo.h> # ifndef _LINUX_GNUC # define _LINUX_GNUC # endif # ifdef _WIN32 # undef _WIN32 # endif #else // TODO: MACOSX # error Currently only Windows and Linux os are supported. #endif #if defined(_LINUX_GNUC) typedef volatile int uatomic_int; # define uatomic_int_add(a) __sync_add_and_fetch(a, 1) # define uatomic_int_sub(a) __sync_sub_and_fetch(a, 1) # define uatomic_int_set(a, newval) __sync_lock_test_and_set(a, (newval)) # define uatomic_int_get(a) __sync_fetch_and_add(a, 0) # define uatomic_int_zero(a) __sync_lock_release(a) # define uatomic_int_comp_exch(a, comp, exch) __sync_val_compare_and_swap(a, (comp), (exch)) # define uatomic_int_add_n(a) __sync_add_and_fetch(a, (n)) # define uatomic_int_sub_n(a) __sync_sub_and_fetch(a, (n)) typedef volatile int64_t uatomic_int64; # define uatomic_int64_add(a) uatomic_int_add(a) # define uatomic_int64_sub(a) uatomic_int_sub(a) # define uatomic_int64_set(a, newval) uatomic_int_set(a, (newval)) # define uatomic_int64_get(a) uatomic_int_get(a) # define uatomic_int64_zero(a) uatomic_int_zero(a) # define uatomic_int64_comp_exch(a, comp, exch) uatomic_int_comp_exch(a, (comp), (exch)) # define uatomic_int64_add_n(a, n) uatomic_int_add_n(a, (n)) # define uatomic_int64_sub_n(a, n) uatomic_int_sub_n(a, (n)) typedef volatile void * uatomic_ptr; # define uatomic_ptr_set(a, newval) uatomic_int_set(((void**)(a)), (newval)) # define uatomic_ptr_get(a) uatomic_int_get(((void**)(a))) # define uatomic_ptr_zero(a) uatomic_int_zero(((void**)(a))) # define uatomic_ptr_comp_exch(a, comp, exch) uatomic_int_comp_exch(((void**)(a)), (comp), (exch)) #elif defined(_WIN32) typedef volatile LONG uatomic_int; # define uatomic_int_add(a) InterlockedIncrement(a) # define uatomic_int_sub(a) InterlockedDecrement(a) # define uatomic_int_set(a, newval) InterlockedExchange(a, (newval)) # define uatomic_int_get(a) InterlockedCompareExchange(a, 0, 0) # define uatomic_int_zero(a) InterlockedExchange(a, 0) # define uatomic_int_comp_exch(a, comp, exch) InterlockedCompareExchange(a, (exch), (comp)) # define uatomic_int_add_n(a, n) InterlockedAnd(a, (n)) # define uatomic_int_sub_n(a, n) InterlockedAnd(a, -(n)) typedef volatile LONG64 uatomic_int64; # define uatomic_int64_add(a) InterlockedIncrement64(a) # define uatomic_int64_sub(a) InterlockedDecrement64(a) # define uatomic_int64_set(a, newval) InterlockedExchange64(a, (newval)) # define uatomic_int64_get(a) InterlockedCompareExchange64(a, 0, 0) # define uatomic_int64_zero(a) InterlockedExchange64(a, 0) # define uatomic_int64_comp_exch(a, comp, exch) InterlockedCompareExchange64(a, (exch), (comp)) # define uatomic_int64_add_n(a, n) InterlockedAnd64(a, (n)) # define uatomic_int64_sub_n(a, n) InterlockedAnd64(a, -(n)) typedef volatile PVOID uatomic_ptr; # define uatomic_ptr_set(a, newval) InterlockedExchangePointer(a, (newval)) # define uatomic_ptr_get(a) InterlockedCompareExchangePointer(a, 0, 0) # define uatomic_ptr_zero(a) InterlockedExchangePointer(a, 0) # define uatomic_ptr_comp_exch(a, comp, exch) InterlockedCompareExchangePointer(a, (exch), (comp)) #else # error Currently only Windows and Linux os are supported. #endif #ifdef __cplusplus } #endif #endif /* _U_ATOMIC_H_ */
pepstack/pytools
templates/%clib%/src/common/smallregex.h
<gh_stars>0 /****************************************************************************** * Copyright (c) 2017-2018 Relkom s.r.o <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. *****************************************************************************/ /** * smallregex.h * * https://gitlab.com/relkom/small-regex * * Supports: * --------- * '.' Dot, matches any character * '^' Start anchor, matches beginning of string * '$' End anchor, matches end of string * '*' Asterisk, match zero or more (greedy) * '+' Plus, match one or more (greedy) * '?' Question, match zero or one (non-greedy) * '[abc]' Character class, match if one of {'a', 'b', 'c'} * '[^abc]' Inverted class, match if NOT one of {'a', 'b', 'c'} -- NOTE: feature is currently broken! * '[a-zA-Z]' Character ranges, the character set of the ranges { a-z | A-Z } * '\s' Whitespace, \t \f \r \n \v and spaces * '\S' Non-whitespace * '\w' Alphanumeric, [a-zA-Z0-9_] * '\W' Non-alphanumeric * '\d' Digits, [0-9] * '\D' Non-digits * '(' Group start * ')' Group ends * '|' Branch **/ #ifndef SMALL_REGEX_H_ #define SMALL_REGEX_H_ #if defined(__cplusplus) extern "C" { #endif #ifndef _STDINT #include <stdint.h> #endif #ifndef _KERNEL #include <stdint.h> #endif /** only enable below defines if debug * * #define RE_BUILDWITH_DEBUG * #define RE_BUILDWITH_PROBES * #define BUILD_WITH_ERRORMSG * #define RE_BUILDWITH_TRACEMATCH_PROC */ // exporting #ifdef _KERNEL MALLOC_DECLARE(MC_RE); #endif //_KERNEL #ifndef DEFAULT_TEMP_LEN // the initial buffer allocated for the initial offset calculations (in compiler) #define DEFAULT_TEMP_LEN 40UL #endif #ifndef MAX_TEMP_REALLOCS // maximum stack depth i.e 10 will be 10*DEFAULT_TEMP_LEN(40)*sizeof(struct re_temp i.e 8) = 3.2kB #define MAX_TEMP_REALLOCS 10UL #endif #ifndef DEFAULT_STATES_DEP // the initial stack length #define DEFAULT_STATES_DEP 40UL #endif #ifndef MAX_STATE_REALLOCS // maximum stack depth i.e 10 will be 10*DEFAULT_STACK_DEP(40)*sizeof(struct stack i.e 16) = 6.4kB #define MAX_STATE_REALLOCS 10UL #endif /* * struct regex_objs_t * the regex node */ typedef struct regex_objs_t { uint8_t type; // CHAR, STAR, etc. uint32_t trueoffset; // offset when eval is true uint32_t falseoffset; // offset when eval is false union { uint8_t ch; //the character itself uint32_t ccl; //an offset to characters in class }; } regex_objs_t; /* * struct small_regex * An instance of the compiled regex */ typedef struct small_regex { uint32_t objoffset; // indicates the start of the regex objs uint32_t totalsize; // total size of data[] uint32_t pstsize; // predicted stack size uint8_t data[]; // data } small_regex_t; /* returns the pointer to the struct regex_objs_t instances */ #define SECTION_OBJECTS(_pat_) \ (struct regex_objs_t *) &_pat_->data[_pat_->objoffset] /* pointer to the pattern from offset */ #define OFFSET_TO_PATTERN(_pat_, _off_) \ &_pat_->data[_off_] /* calculate nodes */ #define COUNT_NODES(_pat_) \ (_pat_->totalsize - _pat_->objoffset) / sizeof(struct regex_objs_t) #define RE_REGEX_SIZE(_pat_) \ (sizeof(struct small_regex) + _pat_->totalsize) /* * regex_validate * Validates the offsets to avoid jump out of the scope. * Takes O(n) time. * * regex (struct small_regex*) a valid pointer to the compiled regex pattern * returns: 0 on success, 1 on error and LOGERR message */ int32_t regex_validate(struct small_regex * regex); /* * regex_free * Deallocates the regex_instance * * regex (struct small_regex*) a valid pointer to the compiled regex pattern * returns: void */ void regex_free(struct small_regex * regex); /* regex_compile * * Compiles the regex string pattern to struct regex_objs_t array and stored * in the data section of the struct small_regex. * The returned result located in HEAP! use free(); * The size of the data section is stored in the field totalsize. * But, the array can be readed until the instance of struct regex_objs_t field.type == UNUSED * * pattern (const char*) regex pattern (null terminated string) * returns: a valid pointer to the intance or NULL on fail */ struct small_regex * regex_compile(const char* pattern); /* regex_get_size * * Returns the value of totalsize field. * calculated with formula: totallen - sizeof(struct small_regex); * * regex (struct small_regex*) a valid pointer to the compiled regex pattern * returns: (uint32_t) totallen in bytes exc size of struct small_regex */ uint32_t regex_get_size(struct small_regex * regex); /* regex_matchp * Find matches of the compiled pattern inside text. * * regex (struct small_regex*) a valid pointer to the compiled regex pattern * text (const char*) a text on which pattern is applied * returns: 0 or larger on success, -1 on error */ int32_t regex_matchp(struct small_regex * pattern, const char* text); /* regex_match * Find matches of the txt pattern inside text (will compile automatically first). */ int32_t regex_match(const char* pattern, const char* text); #ifndef BUILD_WITH_ERRORMSG #define LOGERR(...) #else #ifdef _KERNEL #define LOGERR(...) printf(__VA_ARGS__) #else #define LOGERR(...) fprintf(stderr, __VA_ARGS__) #endif #endif #ifdef RE_BUILDWITH_DEBUG // debug #define DCOLOR_RED "\x1b[31m" #define DCOLOR_GREEN "\x1b[32m" #define DCOLOR_YELLOW "\x1b[33m" #define DCOLOR_BLUE "\x1b[34m" #define DCOLOR_MAGENTA "\x1b[35m" #define DCOLOR_CYAN "\x1b[36m" #define DCOLOR_RESET "\x1b[0m" #ifdef RE_BUILDWITH_PROBES #define DPROBE(...) fprintf(stdout, __VA_ARGS__) #else #define DPROBE(...) #endif struct state; void regex_trace(struct small_regex * pattern); void regex_print(struct small_regex * pattern); #ifdef RE_BUILDWITH_TRACEMATCH_PROC void regex_printstrlegend(void); void regex_printstr(const char * text, size_t textlen, struct state * state); #else #define regex_printstr(...) #define regex_printstrlegend(...) #endif #else #define regex_trace(...) #define regex_print(...) #define regex_printstr(...) #define regex_printstrlegend(...) #define DPROBE(...) #endif #ifdef __cplusplus } #endif #endif /* SMALL_REGEX_H_ */
pepstack/pytools
templates/%clib%/src/common/uthash_incl.h
/*********************************************************************** * Copyright (c) 2008-2080 cheungmine, pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ /* uthash.h Copyright (c) 2003-2020, <NAME> http://troydhanson.github.com/uthash/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTHASH_INCL_H #define UTHASH_INCL_H #ifdef MEMAPI_USE_LIBJEMALLOC #define uthash_malloc(sz) je_malloc(sz) #define uthash_free(ptr,sz) je_free(ptr) #endif #include "uthash/uthash.h" #define HASH_FIND_STR_LEN(head,findstr,findstrlen,out) \ do { \ unsigned _uthash_hfstr_keylen = (unsigned)(findstrlen); \ HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out); \ } while (0) #define HASH_ADD_STR_LEN(head,strfield,strfieldlen,add) \ do { \ unsigned _uthash_hastr_keylen = (unsigned)(strfieldlen); \ HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add); \ } while (0) #define HASH_REPLACE_STR_LEN(head,strfield,strfieldlen,add,replaced) \ do { \ unsigned _uthash_hrstr_keylen = (unsigned)(strfieldlen); \ HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced); \ } while (0) #endif /* UTHASH_INCL_H */
pepstack/pytools
templates/%clib%/src/common/win32/mmap.c
/** * mman.c * mmap api for windows only. * * In particular, mmap, munmap, and msync are not available on Windows. These * replacements are used on both Cygwin and MinGW. (On Cygwin the built-in mmap * has no write support, and is not used). * * Special thanks to <NAME> for contributing mmap.c and mman.h * Original Author is <NAME>, April 2007 * Updated by ZhangLiang to support 64bits, 2015 */ #include <stdlib.h> #include <Windows.h> #ifdef _WIN32 # include <io.h> #endif #include <errno.h> #include "mman.h" /** * @brief Map a file to a memory region * * This function emulates the POSIX mmap() using CreateFileMapping() and * MapViewOfFile() * * @param addr the suggested start address (if != 0) * @param len length of the region * @param prot region accesibility, bitwise OR of PROT_READ, PROT_WRITE, PROT_EXEC * @param flags mapping type and options (ignored) * @param fd object to be mapped into memory * @param offset offset into mapped object * @return pointer to the memory region, or NULL in case of error */ void *mmap(void *addr, size_t len, int prot, int flags, int fd, unsigned int offset) { DWORD wprot; DWORD waccess; HANDLE h; void *region; /* Translate read/write/exec flags into WIN32 constants */ switch (prot) { case PROT_READ: wprot = PAGE_READONLY; break; case PROT_EXEC: wprot = PAGE_EXECUTE_READ; break; case PROT_READ | PROT_EXEC: wprot = PAGE_EXECUTE_READ; break; case PROT_WRITE: wprot = PAGE_READWRITE; break; case PROT_READ | PROT_WRITE: wprot = PAGE_READWRITE; break; case PROT_READ | PROT_WRITE | PROT_EXEC: wprot = PAGE_EXECUTE_READWRITE; break; case PROT_WRITE | PROT_EXEC: wprot = PAGE_EXECUTE_READWRITE; break; } /* Obtaing handle to map region */ h = CreateFileMappingA((HANDLE) _get_osfhandle(fd), 0, wprot, HIDWORD(len), LODWORD(len), 0); if (h == NULL) { DWORD error = GetLastError(); /* Try and translate some error codes */ switch (error) { case ERROR_ACCESS_DENIED: case ERROR_INVALID_ACCESS: errno = EACCES; break; case ERROR_OUTOFMEMORY: case ERROR_NOT_ENOUGH_MEMORY: errno = ENOMEM; break; default: errno = EINVAL; break; } return MAP_FAILED; } /* Translate sharing options into WIN32 constants */ switch (wprot) { case PAGE_READONLY: waccess = FILE_MAP_READ; break; case PAGE_READWRITE: waccess = FILE_MAP_WRITE; break; } /* Map file and return pointer */ region = MapViewOfFile(h, waccess, 0, 0, 0); if (region == NULL) { DWORD error = GetLastError(); /* Try and translate some error codes */ switch (error) { case ERROR_ACCESS_DENIED: case ERROR_INVALID_ACCESS: errno = EACCES; break; case ERROR_INVALID_HANDLE: errno = EBADF; break; default: errno = EINVAL; break; } CloseHandle(h); return MAP_FAILED; } /* OK to call UnmapViewOfFile after this */ CloseHandle(h); /* All fine */ return region; } /** * @brief Unmap a memory region * * This is a wrapper around UnmapViewOfFile in the win32 API * * @param addr start address * @param len length of the region * @return 0 for success, -1 for error */ int munmap(void *addr, size_t len) { if (UnmapViewOfFile(addr)) { return 0; } else { errno = EINVAL; return -1; } } /** * Synchronize a mapped region * * This is a wrapper around FlushViewOfFile * * @param addr start address * @param len number of bytes to flush * @param flags sync options -- currently ignored * @return 0 for success, -1 for error */ int msync(char *addr, size_t len, int flags) { if (FlushViewOfFile(addr, len) == 0) { DWORD error = GetLastError(); /* Try and translate some error codes */ switch (error) { case ERROR_INVALID_PARAMETER: errno = EINVAL; break; case ERROR_WRITE_FAULT: errno = EIO; break; default: errno = EINVAL; break; } return -1; } /* Success */ return 0; }
pepstack/pytools
templates/%clib%/deps/libclogger/include/clogger/clogger_def.h
/** * clogger_def.h */ #ifndef CLOGGER_DEF_H_INCLUDED #define CLOGGER_DEF_H_INCLUDED #if defined(__cplusplus) extern "C" { #endif #include <stdint.h> #include <time.h> #if defined(CLOGGER_DLL) /* win32 dynamic dll */ # ifdef CLOGGER_EXPORTS # define CLOGGER_API __declspec(dllexport) # else # define CLOGGER_API __declspec(dllimport) # endif #else /* static lib or linux so */ # define CLOGGER_API extern #endif #if defined(_WIN32) || defined(__MINGW__) # define CLOG_PATH_SEPARATOR '\\' # define CLOG_PATHPREFIX_DEFAULT "C:\\TEMP\\clogger\\win32\\" #elif defined (__CYGWIN__) # define CLOG_PATH_SEPARATOR '/' # define CLOG_PATHPREFIX_DEFAULT "/cygdrive/c/TEMP/clogger/cygwin/" #else # define CLOG_PATH_SEPARATOR '/' # define CLOG_PATHPREFIX_DEFAULT "/var/log/clogger/" #endif /** * process-wide realtime clock */ typedef struct logger_manager_t * logger_manager; typedef struct _clog_logger_t * clog_logger; typedef struct _logger_conf_t * clogger_conf; /** * available patterns: * <PID> - process id * <IDENT> - ident name * <DATE> - date format */ #define CLOG_NAMEPATTERN_DEFAULT "<IDENT>-<PID>.<DATE>.log" /** * max error message length */ #define CLOG_ERRMSG_LEN_MAX 255 /* message buffer size */ #define CLOG_MSGBUF_SIZE_MIN 1000 #define CLOG_MSGBUF_SIZE_DEFAULT 4000 #ifndef CLOG_MSGBUF_SIZE_MAX # define CLOG_MSGBUF_SIZE_MAX 32640 #endif /* max and enough size for datetime format */ #define CLOG_DATEFMT_SIZE_MAX 48 /* wait forever to log one message */ #define CLOG_MSGWAIT_INFINITE ((-1)) /* nowait to log one message */ #define CLOG_MSGWAIT_NOWAIT 0 /* wait interval in ms to push msg: 1 up to 50 is good */ #define CLOG_MSGWAIT_INSTANT (1) /** * bit flags configuration for logger */ /* appender type which can be combined */ #define CLOG_APPENDER_STDOUT 0x1 #define CLOG_APPENDER_SYSLOG 0x2 #define CLOG_APPENDER_ROFILE 0x4 #define CLOG_APPENDER_SHMMAP 0x8 /* rolling policy for rollingfile appender which can be combined */ #define CLOG_ROLLING_SIZE_BASED 0x10 #define CLOG_ROLLING_TIME_BASED 0x20 /* time accuracy unit using second (default): s * format: YYYYMMDD-hhmmss+0800 */ #define CLOG_TIMEUNIT_SEC 0x0 /* time accuracy unit using milli-second (default is second): ms * format: YYYYMMDD-hhmmss.nnn+0800 */ #define CLOG_TIMEUNIT_MSEC 0x40 /* time accuracy unit using micro-second: us = 1/1000 ms * format: YYYYMMDD-hhmmss.nnnuuu GMT+8:00 */ #define CLOG_TIMEUNIT_USEC 0x80 /* nanosecond based timestamp id for message * sample: {1576463937.089604916} */ #define CLOG_TIMESTAMP_ID 0x100 /* default to use UTC(+0000) timezone */ #define CLOG_TIMEZONE_LOC 0x200 /* levelcolors enable flag */ #define CLOG_LEVEL_COLORS 0x400 /* levelstyles enable flag */ #define CLOG_LEVEL_STYLES 0x800 /* __FILE__:__LINE__ */ #define CLOG_FILE_LINENO 0x1000 /* __FUNCTION__ */ #define CLOG_FUNCTION_NAME 0x2000 /** * never change below lines */ #define ROF_PATHPREFIX_LEN_MAX 248 #define ROF_NAMEPATTERN_LEN_MAX 120 #define ROF_DATE_SYMBOL "<DATE>" #define ROF_DATE_SYMBOLLEN 6 #define ROF_IDENT_SYMBOL "<IDENT>" #define ROF_IDENT_SYMBOLLEN 7 #define ROF_PID_SYMBOL "<PID>" #define ROF_PID_SYMBOLLEN 5 #define ROF_DATEMINUTE_SIZE 16 /* max file is up to: 64 GB */ #define ROF_MAXFILESIZE ((uint64_t)68719476736UL) /* max count of files is up to: 1,000,000 */ #define ROF_MAXFILECOUNT 1000000 typedef enum { CLOG_LAYOUT_PLAIN = 0, CLOG_LAYOUT_DATED = 1 } clog_layout_t; typedef enum { CLOG_DATEFMT_RFC_3339 = 0, /* `date --rfc-3339=seconds` = "2019-12-26 10:13:41+08:00" */ CLOG_DATEFMT_ISO_8601 = 1, /* `date --iso-8601=seconds = "2019-12-26T10:14:32+08:00" */ CLOG_DATEFMT_RFC_2822 = 2, /* `date --rfc-2822` = "Thu, 26 Dec 2019 10:12:45 +0800" */ CLOG_DATEFMT_UNIVERSAL = 3, /* `date -u,--universal` = "Thu Dec 26 02:16:02 UTC 2019" */ CLOG_DATEFMT_NUMERIC_2 = 4, /* = "20191226-101245+0800" */ CLOG_DATEFMT_NUMERIC_1 = 5 /* = "20191226101245+0800" */ } clog_dateformat_t; typedef enum { CLOG_LEVEL_OFF = 0, CLOG_LEVEL_FATAL = 4, CLOG_LEVEL_ERROR = 5, CLOG_LEVEL_WARN = 6, CLOG_LEVEL_INFO = 7, CLOG_LEVEL_DEBUG = 8, CLOG_LEVEL_TRACE = 9, CLOG_LEVEL_ALL = 10 } clog_level_t; /** * "\033[0;31m RED \033[0m" * "\033[1;31m LIGHT RED \033[0m" * "\033[0;32m GREEN \033[0m" * "\033[3;32m LIGHT GREEN \033[0m" */ typedef enum { CLOG_STYLE_NORMAL = 0, CLOG_STYLE_BOLD = 1, CLOG_STYLE_LIGHT = CLOG_STYLE_BOLD, CLOG_STYLE_DIM = 2, CLOG_STYLE_ITALIC = 3, CLOG_STYLE_UNDERLINED = 4, CLOG_STYLE_BLINKING = 5, CLOG_STYLE_REVERSE = 7, CLOG_STYLE_INVISIBLE = 8 } clog_style_t; typedef enum { CLOG_COLOR_NOCLR = 0, CLOG_COLOR_DARK = 30, CLOG_COLOR_RED = 31, CLOG_COLOR_GREEN = 32, CLOG_COLOR_YELLOW = 33, CLOG_COLOR_BLUE = 34, CLOG_COLOR_PURPLE = 35, CLOG_COLOR_CYAN = 36, CLOG_COLOR_WHITE = 37 } clog_color_t; typedef enum { ROLLING_TM_NONE = 0, ROLLING_TM_MIN_1 = 1, ROLLING_TM_MIN_5 = 2, ROLLING_TM_MIN_10 = 3, ROLLING_TM_MIN_30 = 4, ROLLING_TM_HOUR = 5, ROLLING_TM_DAY = 6, ROLLING_TM_MON = 7, ROLLING_TM_YEAR = 8 } rollingtime_t; #if defined(__cplusplus) } #endif #endif /* CLOGGER_DEF_H_INCLUDED */
pepstack/pytools
templates/%clib%/src/common/md5sum.h
<reponame>pepstack/pytools /*********************************************************************** * Copyright (c) 2008-2080 pep<EMAIL>, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename md5sum.h * MD5 implementation. * * md5sum("hello") == echo -n "hello" | md5sum * * md5("hello") = {5d41402abc4b2a76b9719d911017c592} * * Usage: * * char hash[MD5SUM_STRING_LEN + 1]; * char msg[] = "<EMAIL>"; * * md5sum_t ctx; * md5sum_init(&ctx, 0); * md5sum_updt(&ctx, msg, strlen(msg)); * md5sum_done(&ctx, ctx.digest); * * md5print(ctx.digest, hash); * * printf(">>>> {%s}\n", hash); * * >>>> {bdc0bb1f6bea9f3b546657614918bc1d} * * md5file("/root/Downloads/ebooks1.tar.gz", 0, ctx.digest); * * md5print(ctx.digest, hash); * printf("%s\n", hash); * * @author <NAME> <<EMAIL>> * @version 0.0.10 * @create 2017-08-28 * @update 2019-11-21 15:18:19 */ #ifndef MD5SUM_H_INCLUDED #define MD5SUM_H_INCLUDED #if defined(__cplusplus) extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #if defined(_MSC_VER) # include <BaseTsd.h> typedef SSIZE_T ssize_t; #endif /** * fix length string buffer with 32 chars */ #define MD5SUM_STRING_LEN 32 /** * size in byets for read file * MUST = 64 x N (N = 8, 16, ...) */ #ifndef MD5FILE_CHUNK_SIZE # define MD5FILE_CHUNK_SIZE 4096 #endif typedef struct { uint32_t count[2]; uint32_t state[4]; uint8_t buffer[64]; uint8_t digest[16]; } md5sum_t; /** * private typedef and functions */ static const uint8_t __md5sum_padding__[] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #define __md5sum_F__(x,y,z) ((x & y) | (~x & z)) #define __md5sum_G__(x,y,z) ((x & z) | (y & ~z)) #define __md5sum_H__(x,y,z) (x^y^z) #define __md5sum_I__(x,y,z) (y ^ (x | ~z)) #define __md5sum_LR__(x,n) ((x << n) | (x >> (32-n))) #define __md5sum_FF__(a,b,c,d,x,s,ac) do { \ a += __md5sum_F__(b,c,d) + x + ac; \ a = __md5sum_LR__(a,s); \ a += b; \ } while(0) #define __md5sum_GG__(a,b,c,d,x,s,ac) do { \ a += __md5sum_G__(b,c,d) + x + ac; \ a = __md5sum_LR__(a,s); \ a += b; \ } while(0) #define __md5sum_HH__(a,b,c,d,x,s,ac) do { \ a += __md5sum_H__(b,c,d) + x + ac; \ a = __md5sum_LR__(a,s); \ a += b; \ } while(0) #define __md5sum_II__(a,b,c,d,x,s,ac) do { \ a += __md5sum_I__(b,c,d) + x + ac; \ a = __md5sum_LR__(a,s); \ a += b; \ } while(0) #define __md5sum_encode__(output, input, len) do { \ uint32_t i = 0; \ uint32_t j = 0; \ while (j < len) { \ output[j] = input[i] & 0xFF; \ output[j+1] = (input[i] >> 8) & 0xFF; \ output[j+2] = (input[i] >> 16) & 0xFF; \ output[j+3] = (input[i] >> 24) & 0xFF; \ i++; \ j += 4; \ } \ } while(0) #define __md5sum_decode__(output, input, len) do { \ uint32_t i = 0; \ uint32_t j = 0; \ while (j < len) { \ output[i] = (input[j]) | (input[j+1] << 8) | (input[j+2] << 16) | (input[j+3] << 24); \ i++; \ j += 4; \ } \ } while(0) static void __md5sum_trans__(uint32_t state[4], const uint8_t block[64]) { uint32_t x[64]; uint32_t a = state[0]; uint32_t b = state[1]; uint32_t c = state[2]; uint32_t d = state[3]; __md5sum_decode__(x, block, 64); /* Round 1 */ __md5sum_FF__(a, b, c, d, x[ 0], 7, 0xd76aa478); __md5sum_FF__(d, a, b, c, x[ 1], 12, 0xe8c7b756); __md5sum_FF__(c, d, a, b, x[ 2], 17, 0x242070db); __md5sum_FF__(b, c, d, a, x[ 3], 22, 0xc1bdceee); __md5sum_FF__(a, b, c, d, x[ 4], 7, 0xf57c0faf); __md5sum_FF__(d, a, b, c, x[ 5], 12, 0x4787c62a); __md5sum_FF__(c, d, a, b, x[ 6], 17, 0xa8304613); __md5sum_FF__(b, c, d, a, x[ 7], 22, 0xfd469501); __md5sum_FF__(a, b, c, d, x[ 8], 7, 0x698098d8); __md5sum_FF__(d, a, b, c, x[ 9], 12, 0x8b44f7af); __md5sum_FF__(c, d, a, b, x[10], 17, 0xffff5bb1); __md5sum_FF__(b, c, d, a, x[11], 22, 0x895cd7be); __md5sum_FF__(a, b, c, d, x[12], 7, 0x6b901122); __md5sum_FF__(d, a, b, c, x[13], 12, 0xfd987193); __md5sum_FF__(c, d, a, b, x[14], 17, 0xa679438e); __md5sum_FF__(b, c, d, a, x[15], 22, 0x49b40821); /* Round 2 */ __md5sum_GG__(a, b, c, d, x[ 1], 5, 0xf61e2562); __md5sum_GG__(d, a, b, c, x[ 6], 9, 0xc040b340); __md5sum_GG__(c, d, a, b, x[11], 14, 0x265e5a51); __md5sum_GG__(b, c, d, a, x[ 0], 20, 0xe9b6c7aa); __md5sum_GG__(a, b, c, d, x[ 5], 5, 0xd62f105d); __md5sum_GG__(d, a, b, c, x[10], 9, 0x2441453); __md5sum_GG__(c, d, a, b, x[15], 14, 0xd8a1e681); __md5sum_GG__(b, c, d, a, x[ 4], 20, 0xe7d3fbc8); __md5sum_GG__(a, b, c, d, x[ 9], 5, 0x21e1cde6); __md5sum_GG__(d, a, b, c, x[14], 9, 0xc33707d6); __md5sum_GG__(c, d, a, b, x[ 3], 14, 0xf4d50d87); __md5sum_GG__(b, c, d, a, x[ 8], 20, 0x455a14ed); __md5sum_GG__(a, b, c, d, x[13], 5, 0xa9e3e905); __md5sum_GG__(d, a, b, c, x[ 2], 9, 0xfcefa3f8); __md5sum_GG__(c, d, a, b, x[ 7], 14, 0x676f02d9); __md5sum_GG__(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* Round 3 */ __md5sum_HH__(a, b, c, d, x[ 5], 4, 0xfffa3942); __md5sum_HH__(d, a, b, c, x[ 8], 11, 0x8771f681); __md5sum_HH__(c, d, a, b, x[11], 16, 0x6d9d6122); __md5sum_HH__(b, c, d, a, x[14], 23, 0xfde5380c); __md5sum_HH__(a, b, c, d, x[ 1], 4, 0xa4beea44); __md5sum_HH__(d, a, b, c, x[ 4], 11, 0x4bdecfa9); __md5sum_HH__(c, d, a, b, x[ 7], 16, 0xf6bb4b60); __md5sum_HH__(b, c, d, a, x[10], 23, 0xbebfbc70); __md5sum_HH__(a, b, c, d, x[13], 4, 0x289b7ec6); __md5sum_HH__(d, a, b, c, x[ 0], 11, 0xeaa127fa); __md5sum_HH__(c, d, a, b, x[ 3], 16, 0xd4ef3085); __md5sum_HH__(b, c, d, a, x[ 6], 23, 0x4881d05); __md5sum_HH__(a, b, c, d, x[ 9], 4, 0xd9d4d039); __md5sum_HH__(d, a, b, c, x[12], 11, 0xe6db99e5); __md5sum_HH__(c, d, a, b, x[15], 16, 0x1fa27cf8); __md5sum_HH__(b, c, d, a, x[ 2], 23, 0xc4ac5665); /* Round 4 */ __md5sum_II__(a, b, c, d, x[ 0], 6, 0xf4292244); __md5sum_II__(d, a, b, c, x[ 7], 10, 0x432aff97); __md5sum_II__(c, d, a, b, x[14], 15, 0xab9423a7); __md5sum_II__(b, c, d, a, x[ 5], 21, 0xfc93a039); __md5sum_II__(a, b, c, d, x[12], 6, 0x655b59c3); __md5sum_II__(d, a, b, c, x[ 3], 10, 0x8f0ccc92); __md5sum_II__(c, d, a, b, x[10], 15, 0xffeff47d); __md5sum_II__(b, c, d, a, x[ 1], 21, 0x85845dd1); __md5sum_II__(a, b, c, d, x[ 8], 6, 0x6fa87e4f); __md5sum_II__(d, a, b, c, x[15], 10, 0xfe2ce6e0); __md5sum_II__(c, d, a, b, x[ 6], 15, 0xa3014314); __md5sum_II__(b, c, d, a, x[13], 21, 0x4e0811a1); __md5sum_II__(a, b, c, d, x[ 4], 6, 0xf7537e82); __md5sum_II__(d, a, b, c, x[11], 10, 0xbd3af235); __md5sum_II__(c, d, a, b, x[ 2], 15, 0x2ad7d2bb); __md5sum_II__(b, c, d, a, x[ 9], 21, 0xeb86d391); state[0] += a; state[1] += b; state[2] += c; state[3] += d; } /** * public api */ static void md5sum_init(md5sum_t *ctx, uint32_t seed) { memset(ctx, 0, sizeof(md5sum_t)); ctx->state[0] = 0x67452301 + (seed * 11); ctx->state[1] = 0xEFCDAB89 + (seed * 71); ctx->state[2] = 0x98BADCFE + (seed * 37); ctx->state[3] = 0x10325476 + (seed * 97); } static void md5sum_updt (md5sum_t *ctx, const uint8_t *input, uint32_t inputlen) { uint32_t i = 0, index = 0, partlen = 0; index = (ctx->count[0] >> 3) & 0x3F; partlen = 64 - index; ctx->count[0] += inputlen << 3; if(ctx->count[0] < (inputlen << 3)) { ctx->count[1]++; } ctx->count[1] += inputlen >> 29; if (inputlen >= partlen) { memcpy(&ctx->buffer[index], input, partlen); __md5sum_trans__(ctx->state, ctx->buffer); for (i = partlen; i+64 <= inputlen; i+=64) { __md5sum_trans__(ctx->state, &input[i]); } index = 0; } else { i = 0; } memcpy(&ctx->buffer[index], &input[i], inputlen - i); } static void md5sum_done (md5sum_t *ctx, uint8_t digest[16]) { uint32_t index = 0, padlen = 0; uint8_t bits[8]; index = (ctx->count[0] >> 3) & 0x3F; padlen = (index < 56)?(56-index):(120-index); __md5sum_encode__(bits,ctx->count,8); md5sum_updt(ctx, __md5sum_padding__, padlen); md5sum_updt(ctx, bits, 8); __md5sum_encode__(digest, ctx->state, 16); } static const char * md5print (const uint8_t digest[16], char outbuf[MD5SUM_STRING_LEN + 1]) { int i; char *out = outbuf; const uint8_t *pch = digest; for (i = 0; i < 16; i++) { sprintf(out + i*2, "%2.2x", *pch++); } out[i*2] = 0; return outbuf; } /** * both result and speed are same with linux: * * md5sum $filename */ static int md5file (const char *pathfile, uint32_t seed, uint8_t digest[16]) { FILE * fp; fp = fopen(pathfile, "rb"); if (! fp) { /* read file error */ return (-1); } else { char rdbuf[MD5FILE_CHUNK_SIZE]; size_t rcb = 0; md5sum_t ctx; md5sum_init(&ctx, seed); for (;;) { rcb = fread(rdbuf, 1, MD5FILE_CHUNK_SIZE, fp); if (rcb < MD5FILE_CHUNK_SIZE) { /* If an error occurs, or the end of the file is reached, * the return value is a short item count (or zero). */ if (feof(fp) && ! ferror(fp)) { /* read success to end of file */ if (rcb != 0) { md5sum_updt(&ctx, (const uint8_t *)rdbuf, (uint32_t) rcb); } break; } /* read file error */ fclose(fp); return (-1); } md5sum_updt(&ctx, (const uint8_t *)rdbuf, (uint32_t) rcb); } md5sum_done(&ctx, digest); /* success */ fclose(fp); return 0; } } #if defined(__cplusplus) } #endif #endif /* MD5SUM_H_INCLUDED */
pepstack/pytools
templates/%clib%/src/common/rtclock.h
<filename>templates/%clib%/src/common/rtclock.h /*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename rtclock.h * real time clock up to year 2484. * * @author <NAME> <<EMAIL>> * @version 0.0.1 * @create 2019-12-20 11:15:05 * @update 2020-12-14 10:44:05 */ #ifndef _RTCLOCK_H__ #define _RTCLOCK_H__ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> /** * strftime - format date and time * https://linux.die.net/man/3/strftime */ #include <time.h> /* +0000, +0800, -0200 */ #define TIMEZONE_FORMAT_LEN 5 static const char TIMEZONE_FORMAT_UTC[] = "+0000"; /** * process-wide realtime clock */ typedef struct _rtclock_t *rtclock_handle; typedef enum { RTCLOCK_FREQ_SEC = 0, /* second */ RTCLOCK_FREQ_MSEC = 1 /* millisecond */ } rtclock_frequency_t; /** * real time clock api */ extern rtclock_handle rtclock_init (rtclock_frequency_t frequency); extern void rtclock_uninit (rtclock_handle rtc); extern int rtclock_timezone (rtclock_handle rtc, const char **tzfmt); extern int rtclock_daylight (rtclock_handle rtc); extern int64_t rtclock_ticktime (rtclock_handle rtc, struct timespec *ticktime); extern void rtclock_localtime(rtclock_handle rtc, int timezone, int daylight, struct tm *tmloc, struct timespec *now); #ifdef __cplusplus } #endif #endif /* _RTCLOCK_H__ */
pepstack/pytools
templates/%clib%/src/common/colib_api.h
/** * colib_api.h */ #ifndef _COLIB_API_H_ #define _COLIB_API_H_ #if defined(__cplusplus) extern "C" { #endif #include <common/memapi.h> #include <common/unitypes.h> #ifndef coiid_t typedef ub8 coiid_t; #endif #define IID_CompntBase ((coiid_t) 0x00000000) /** * Component library (XXX_colib.so) must implement the following 4 APIs */ typedef struct CompntLibBase { const char * (*colibVersion)(); int (*colibInit)(void *, void**); void (*colibUninit)(void *); int (*colibCoCreate)(void *,coiid_t, void **); } ICompntLibBase; /** * Component must inherit ICompntBase from CompntBaseClass */ typedef struct CompntBaseClass { coiid_t iid; void *libstub; void (*codestroy)(void *cobase); } ICompntBase; static void CompntClassFree(void *coaddr) { ICompntBase *base = (ICompntBase*) coaddr; base--; mem_free(base); } /** * CompntCreate(NULL, IID_PolygonCompnt, sizeof(PolygonCompnt), PolygonCompntDtor); */ static void * CompntClassCreate(size_t cobodysize, coiid_t iid, void *libstub, void (*codestroy)(void *)) { ICompntBase *cobase = (ICompntBase *) mem_alloc_zero(1, sizeof(ICompntBase) + cobodysize); cobase->iid = iid; cobase->libstub = libstub; cobase->codestroy = codestroy; return (void *) &cobase[1]; } #if defined(__cplusplus) } #endif #endif /* _COLIB_API_H_ */
pepstack/pytools
templates/%clib%/src/common/jniutils.h
<filename>templates/%clib%/src/common/jniutils.h<gh_stars>0 /** * jniutils.h * JNI utility api. */ #include "misc.h" #include <jni.h> #ifndef _JNI_UTILS_H_ #define _JNI_UTILS_H_ #ifdef __cplusplus extern "C" { #endif struct JNIRuntimeContext { jint jniVersion; HINSTANCE jvmdll; JavaVM * jvm; JNIEnv * jenv; }; NOWARNING_UNUSED(static) int JNIRuntimeContextInit (int jniMajorVersion, int jniMinorVersion, struct JNIRuntimeContext *jniCtx) { typedef jint(JNICALL *ProcCreateJavaVM)(JavaVM **, void**, void *); jint jniVersion = JNI_VERSION_1_8; HINSTANCE jvmdll = NULL; JavaVM * jvm = NULL; JNIEnv * jenv = NULL; jint res; ProcCreateJavaVM jvm_CreateJavaVM; char javahome[200]; char jvmdllpath[260]; char classpath[1200]; JavaVMInitArgs vm_args; JavaVMOption options[30]; memset(&vm_args, 0, sizeof(vm_args)); memset(&options, 0, sizeof(options)); jniCtx->jniVersion = 0; res = getenv_with_prefix("JAVA_HOME", NULL, javahome, sizeof(javahome)); if (! res) { printf("env not found: JAVA_HOME\n"); return (-1); } if (res < 0) { printf("insufficent buf for env: JAVA_HOME\n"); return (-1); } res = getenv_with_prefix("CLASSPATH", "-Djava.class.path=", classpath, sizeof(classpath)); if (! res) { printf("env not found: CLASSPATH\n"); return (-1); } if (res < 0) { printf("insufficent buf for env: CLASSPATH\n"); return (-1); } snprintf_chkd_V1(jvmdllpath, sizeof(jvmdllpath), "%s\\jre\\bin\\server\\jvm.dll", javahome); // 注意: 务必使用动态载入 jvm.dll 方式调用 JNI_CreateJavaVM jvmdll = LoadLibraryA(jvmdllpath); if (!jvmdll) { printf("failed to load: %s\n", jvmdllpath); return (-1); } printf("success load: %s\n", jvmdllpath); jvm_CreateJavaVM = (ProcCreateJavaVM) GetProcAddress(jvmdll, "JNI_CreateJavaVM"); if (!jvm_CreateJavaVM) { printf("failed to GetProcAddress: JNI_CreateJavaVM\n"); FreeLibrary(jvmdll); return (-1); } options[0].optionString = "-Djava.compiler=NONE"; options[1].optionString = classpath; options[2].optionString = "-verbose:jni"; if (jniMajorVersion && jniMinorVersion) { jniVersion = (jniMajorVersion << 16) | jniMinorVersion; } vm_args.version = jniVersion; vm_args.ignoreUnrecognized = JNI_TRUE; vm_args.options = options; vm_args.nOptions = 3; // 务必关闭异常: (VS2015: Ctrl+Alt+E -> Win32 Exceptioins -> 0xc0000005 Access violation) // https://stackoverflow.com/questions/36250235/exception-0xc0000005-from-jni-createjavavm-jvm-dll res = jvm_CreateJavaVM(&jvm, (void**)&jenv, &vm_args); if (res == 0) { printf("successfully created JVM.\n"); jniCtx->jvmdll = jvmdll; jniCtx->jvm = jvm; jniCtx->jenv = jenv; jniCtx->jniVersion = jniVersion; return 0; } else { printf("failed to create JVM.\n"); FreeLibrary(jvmdll); return (-1); } } NOWARNING_UNUSED(static) void JNIRuntimeContextUninit (struct JNIRuntimeContext *jniCtx) { JavaVM * jvm = jniCtx->jvm; if (jniCtx->jniVersion) { jniCtx->jniVersion = 0; if (jvm) { (*jvm)->DetachCurrentThread(jniCtx->jvm); (*jvm)->DestroyJavaVM(jniCtx->jvm); FreeLibrary(jniCtx->jvmdll); } } } #ifdef __cplusplus } #endif #endif /* _JNI_UTILS_H_ */
pepstack/pytools
templates/%clib%/src/common/shmmbuf-win.h
<filename>templates/%clib%/src/common/shmmbuf-win.h /*********************************************************************** * Copyright (c) 2008-2080, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename shmmbuf-win.h * MP and MT-safe shared memory IO for Windows and Cygwin * * @author <NAME> <<EMAIL>> * @version 1.0.0 * @create 2020-06-01 12:46:50 * @update 2020-06-05 11:25:08 * * NOTES: * Prior to include this file, define as following to enable * trace print in spite of speed penalty. * * #define SHMMBUF_TRACE_PRINT_ON * #include "shmmbuf-win.h" */ #ifndef SHMMBUF_WIN_H__ #define SHMMBUF_WIN_H__ #if defined(__cplusplus) extern "C" { #endif #include "unitypes.h" #if defined(__WINDOWS__) || defined(__CYGWIN__) # include <Windows.h> # else #error Not a Win32 platform. #endif #ifndef __STDC_FORMAT_MACROS # define __STDC_FORMAT_MACROS #endif #include <inttypes.h> /** * random generator for cryptography */ #include "randctx.h" #include "md5sum.h" #ifndef NOWARNING_UNUSED # if defined(__GNUC__) || defined(__CYGWIN__) # define NOWARNING_UNUSED(x) __attribute__((unused)) x # else # define NOWARNING_UNUSED(x) x # endif #endif /** * Default constants only show you the usage for shmmap api. * * Shared memory file lies in: "C:\TEMP\clogger\shmmap-buffer-default" */ #define SHMMBUF_FILENAME_DEFAULT "C:\\TEMP\\clogger\\shmmap-buffer-default" #define SHMMBUF_FILEMODE_DEFAULT 0666 #define SHMMBUF_SEMAPHORE_MAXVAL 65535 /** * Below definitions SHOULD NOT be changed! */ #define SHMMBUF_PAGE_SIZE ((size_t)4096) #define SHMMBUF_INVALID_STATE ((size_t)(-1)) #define SHMMBUF_TIMEOUT_INFINITE ((size_t)(-1)) #define SHMMBUF_TIMEOUT_NOWAIT (0) #define SHMMBUF_ENTRY_HDRSIZE (sizeof(shmmbuf_entry_t)) #define SHMMBUF_ALIGN_BSIZE(bsz, alignsize) \ ((size_t)((((size_t)(bsz)+(alignsize)-1)/(alignsize))*(alignsize))) #define SHMMBUF_ALIGN_PAGESIZE(fsz) \ SHMMBUF_ALIGN_BSIZE((fsz), SHMMBUF_PAGE_SIZE) #define SHMMBUF_ALIGN_ENTRYSIZE(chunksz) \ SHMMBUF_ALIGN_BSIZE((chunksz + SHMMBUF_ENTRY_HDRSIZE), SHMMBUF_ENTRY_HDRSIZE) #define SHMMBUF_BUFFER_HDRSIZE \ SHMMBUF_ALIGN_BSIZE(sizeof(shmmap_buffer_t), SHMMBUF_PAGE_SIZE) #define SHMMBUF_ENTRY_CAST(p) ((shmmbuf_entry_t *)(p)) #define SHMMBUF_VERIFY_STATE(val) do { \ if ((val) == SHMMBUF_INVALID_STATE) { \ exit(EXIT_FAILURE); \ } \ } while(0) /** * Returns of shmmap_buffer_create() */ #define SHMMBUF_CREATE_SUCCESS 0 #define SHMMBUF_CREATE_ERROPEN (1) #define SHMMBUF_CREATE_ERRMMAP (2) #define SHMMBUF_CREATE_ERRSIZE (3) #define SHMMBUF_CREATE_ERRTRUNC (4) #define SHMMBUF_CREATE_ERRTOKEN (5) /** * Should never run to this! */ #define SHMMBUF_CREATE_FAILED (-1) /** * Returns of shmmap_buffer_write() */ #define SHMMBUF_WRITE_SUCCESS ((int)(1)) #define SHMMBUF_WRITE_AGAIN ((int)(0)) #define SHMMBUF_WRITE_FATAL ((int)(-1)) /** * Returns of shmmap_buffer_read_?() */ #define SHMMBUF_READ_NEXT ((int)(1)) #define SHMMBUF_READ_AGAIN ((int)(0)) #define SHMMBUF_READ_FATAL ((int)(-1)) /** * default token cryptographic algorithm */ typedef __ub8_t ub8token_t; NOWARNING_UNUSED(static) ub8token_t shmmbuf_encipher_token (const ub8token_t magic, ub8token_t *token) { ub8token_t cipher = magic ^ (*token); return cipher; } NOWARNING_UNUSED(static) ub8token_t shmmbuf_decipher_token (const ub8token_t cipher, ub8token_t *token) { ub8token_t magic = cipher ^ (*token); return magic; } NOWARNING_UNUSED(static) void ProcessMutexInit (HANDLE *mutexp, const char *name) { DWORD dwErr; HANDLE mutex; mutex = CreateMutexA(NULL, FALSE, name); if (! mutex) { exit(EXIT_FAILURE); } dwErr = GetLastError(); if ( dwErr && dwErr != ERROR_ALREADY_EXISTS ) { CloseHandle(mutex); exit(EXIT_FAILURE); } *mutexp = mutex; } NOWARNING_UNUSED(static) int ProcessMutexTryLock (HANDLE mutex) { return (int) WaitForSingleObject(mutex, 0); } NOWARNING_UNUSED(static) int ProcessMutexTimedLock (HANDLE mutex, int dwMilliSeconds) { return (int) WaitForSingleObject(mutex, (DWORD) dwMilliSeconds); } NOWARNING_UNUSED(static) int ProcessMutexLock (HANDLE mutex) { return (int) WaitForSingleObject(mutex, INFINITE); } NOWARNING_UNUSED(static) int ProcessMutexUnlock (HANDLE mutex) { return ReleaseMutex(mutex)? 0 : (-1); } NOWARNING_UNUSED(static) void ProcessMutexFixLockErr(HANDLE mutex, int err) { // TODO: printf("(shmmbuf-win.h:%d) ProcessMutexFixLockErr: invalid mutex.\n", __LINE__); exit(EXIT_FAILURE); } /** * The layout of memory for any one entry in shmmap. */ typedef struct _shmmbuf_entry_t { size_t size; char chunk[0]; } shmmbuf_entry_t; /** * The atomic struct for state of shmmap. */ typedef struct _shmmbuf_state_t { /* atomic state value */ size_t state; /* process-wide state lock */ HANDLE mutex; } shmmbuf_state_t; NOWARNING_UNUSED(static) void shmmap_gettimeofday (struct timespec *now) { FILETIME tmfile; ULARGE_INTEGER _100nanos; GetSystemTimeAsFileTime(&tmfile); _100nanos.LowPart = tmfile.dwLowDateTime; _100nanos.HighPart = tmfile.dwHighDateTime; _100nanos.QuadPart -= 0x19DB1DED53E8000; /* Convert 100ns units to seconds */ now->tv_sec = (time_t)(_100nanos.QuadPart / (10000 * 1000)); /* Convert remainder to nanoseconds */ now->tv_nsec = (long) ((_100nanos.QuadPart % (10000 * 1000)) * 100); } NOWARNING_UNUSED(static) sb8 shmmap_difftime_msec (const struct timespec *t1, const struct timespec *t2) { sb8 sec = (sb8)(t2->tv_sec - t1->tv_sec); sb8 nsec = (sb8)(t2->tv_nsec - t1->tv_nsec); if (sec > 0) { if (nsec >= 0) { return ((sec * 1000UL) + nsec / 1000000UL); } else { /* nsec < 0 */ return (sec-1) * 1000UL + (nsec + 1000000000UL) / 1000000UL; } } else if (sec < 0) { if (nsec <= 0) { return ((sec * 1000UL) + nsec / 1000000UL); } else { /* nsec > 0 */ return (sec+1) * 1000UL + (nsec - 1000000000UL) / 1000000UL; } } else { /* sec = 0 */ return nsec / 1000000UL; } } NOWARNING_UNUSED(static) size_t shmmbuf_state_get (shmmbuf_state_t *st) { size_t val = SHMMBUF_INVALID_STATE; int err = ProcessMutexLock(st->mutex); if (! err) { val = st->state; ProcessMutexUnlock(st->mutex); return val; } else { ProcessMutexFixLockErr(st->mutex, err); return shmmbuf_state_get(st); } SHMMBUF_VERIFY_STATE(val); return val; } NOWARNING_UNUSED(static) size_t shmmbuf_state_set (shmmbuf_state_t *st, size_t newval) { size_t oldval = SHMMBUF_INVALID_STATE; int err = ProcessMutexLock(st->mutex); if (! err) { oldval = st->state; st->state = newval; ProcessMutexUnlock(st->mutex); return oldval; } else { ProcessMutexFixLockErr(st->mutex, err); return shmmbuf_state_set(st, newval); } SHMMBUF_VERIFY_STATE(oldval); return oldval; } NOWARNING_UNUSED(static) size_t shmmbuf_state_comp_exch (shmmbuf_state_t *st, size_t comp, size_t exch) { size_t oldval = SHMMBUF_INVALID_STATE; int err = ProcessMutexLock(st->mutex); if (! err) { oldval = st->state; if (st->state == comp) { st->state = exch; } ProcessMutexUnlock(st->mutex); return oldval; } else { ProcessMutexFixLockErr(st->mutex, err); return shmmbuf_state_comp_exch(st, comp, exch); } SHMMBUF_VERIFY_STATE(oldval); return oldval; } typedef struct _shmmbuf_semaphore_t { HANDLE nonzero; int maxcount; } shmmbuf_semaphore_t, *shmmbuf_semaphore; NOWARNING_UNUSED(static) void shmmbuf_semaphore_init (shmmbuf_semaphore_t *semap, int maxcount, const char *name) { DWORD dwErr; HANDLE semaph; semaph = CreateSemaphoreA(NULL, 0, maxcount, name); if (! semaph) { exit(EXIT_FAILURE); } dwErr = GetLastError(); if ( dwErr && dwErr != ERROR_ALREADY_EXISTS ) { CloseHandle(semaph); exit(EXIT_FAILURE); } /* success */ semap->maxcount = maxcount; semap->nonzero = semaph; } NOWARNING_UNUSED(static) int shmmbuf_semaphore_post (shmmbuf_semaphore_t * semap, size_t timeout_us) { return ReleaseSemaphore(semap->nonzero, 1, 0)? 0 : (-1); } NOWARNING_UNUSED(static) int shmmbuf_semaphore_wait (shmmbuf_semaphore_t * semap, size_t timeout_us) { int ret = -1; if (timeout_us == SHMMBUF_TIMEOUT_INFINITE) { ret = WaitForSingleObject(semap->nonzero, INFINITE); } else { ret = WaitForSingleObject(semap->nonzero, (DWORD)(timeout_us/1000UL)); } return ret; } /** * shared memory mmap file with a layout of ring buffer. * See also: * https://github.com/pepstack/clogger/blob/master/src/ringbuf.h */ typedef struct _shmmap_buffer_t { /** * total size in bytes for this shmmap file * struct _shmmap_buffer_t *this; * shmfilesize = sizeof(*this) + this->Length */ size_t shmfilesize; /** * magic ^ token => cipher * cipher ^ token == magic */ ub8token_t magic; ub8token_t cipher; shmmbuf_semaphore_t semaphore; /* Read Lock */ HANDLE RLock; /* Write Lock */ HANDLE WLock; /* Write Offset to the Buffer start */ shmmbuf_state_t WOffset; /* Read Offset to the Buffer start */ shmmbuf_state_t ROffset; /* Length of ring Buffer: total size in bytes */ size_t Length; /* ring buffer in shared memory with Length */ char Buffer[0]; } shmmap_buffer_t; #define SHMRINGBUF_RESTORE_WRAP(Ro, Wo, L) \ ((ssize_t)((Ro)/(L) == (Wo)/(L) ? 0 : 1)) #define SHMRINGBUF_RESTORE_STATE(Ro, Wo, L) \ ssize_t wrap = SHMRINGBUF_RESTORE_WRAP(Ro, Wo, L); \ ssize_t R = (ssize_t)((Ro) % (L)); \ ssize_t W = (ssize_t)((Wo) % (L)) #define SHMRINGBUF_NORMALIZE_OFFSET(Ao, L) \ ((((Ao)/(L))%2)*L + (Ao)%(L)) NOWARNING_UNUSED(static) int __shmmap_buffer_read_internal (shmmap_buffer_t *shmbuf, ssize_t wrap, ssize_t R, ssize_t W, ssize_t L, int (*nextentry_cb)(const shmmbuf_entry_t *, void *), void *arg); NOWARNING_UNUSED(static) void shmmap_buffer_close (shmmap_buffer_t *shmbuf) { CloseHandle(shmbuf->RLock); CloseHandle(shmbuf->WLock); CloseHandle(shmbuf->WOffset.mutex); CloseHandle(shmbuf->ROffset.mutex); CloseHandle(shmbuf->semaphore.nonzero); UnmapViewOfFile(shmbuf); } NOWARNING_UNUSED(static) int shmmap_buffer_delete (const char *shmfilename) { return DeleteFileA(shmfilename)? 0 : (-1); } NOWARNING_UNUSED(static) int shmmap_verify_token (shmmap_buffer_t *shmbuf, ub8token_t *token, ub8token_t (decipher_cb)(const ub8token_t, ub8token_t *)) { ub8token_t magic; if (! shmbuf->cipher) { /* true: cipher disabled */ return 1; } if (! token) { /* true: token not given */ return 0; } /* cipher and token are all given */ if (decipher_cb) { magic = decipher_cb(shmbuf->cipher, token); } else { magic = shmmbuf_decipher_token(shmbuf->cipher, token); } if (! memcmp(&magic, &shmbuf->magic, sizeof(shmbuf->magic))) { /* validate success when: magic == shmbuf->magic */ return 1; } /* validate failed */ return 0; } /** * shmmap_buffer_create() * Create if not exists or open an existing shmmap file. * * Params: * token - Point to a buffer with 8 bytes-length taken a plain token text. * Whether the content in token changes or not will depend on the * implementation of cipher_cb. * * cipher_cb - A cryptography callback provided by caller to generate an * encrypted cipher with 8 bytes-length from given token. * * Below sample creates a 4 MB encrypted shmmap buffer using token number: * * const char shmname[] = "shmmap-sample"; * char msgbuf[4096]; * ub8token_t token = <PASSWORD>; * size_t bsize = 4*1024*1024; * * // producer application * void produce (void) { * int wok; * shmmap_buffer_t *shmb; * * if (shmmap_buffer_create(&shmb, shmname, 0666, bsize, &token, 0, 0) == SHMMBUF_CREATE_SUCCESS) { * wok = shmmap_buffer_write(shmb, "Hello Shmmap Sample", strlen("Hello Shmmap Sample")); * // ... * shmmap_buffer_close(shmb); * } * } * * // consumer application * void consume (void) { * size_t rdlen; * shmmap_buffer_t *shmb; * * if (shmmap_buffer_create(&shmb, shmname, 0666, 0, &token, 0, 0) == SHMMBUF_CREATE_SUCCESS) { * rdlen = shmmap_buffer_read_copy(shmb, msgbuf, sizeof(msgbuf)); * // ... * shmmap_buffer_close(shmb); * } * } * * Returns: * see Returns of shmmap_buffer_create() in above */ NOWARNING_UNUSED(static) int shmmap_buffer_create (shmmap_buffer_t **outshmbuf, const char *shmfilename, int filemode, size_t filesize, ub8token_t *token, ub8token_t (*encipher_cb)(const ub8token_t magic, ub8token_t *token), ub8token_t (*decipher_cb)(const ub8token_t magic, ub8token_t *token)) { shmmap_buffer_t *shmbuf; char *nameprefix; char namebuf[128] = {0}; /* total size in bytes of shmmap file */ size_t mapfilesize = 0; /* aligned shared memory size as Length of ring buffer */ size_t bufferLength = 0; int exist = 0; if (filesize == SHMMBUF_INVALID_STATE) { printf("(shmmbuf-win.h:%d) invalid filesize.\n", __LINE__); return SHMMBUF_CREATE_ERRSIZE; } /* create or open mapping file */ HANDLE hshmfile; HANDLE hfilemapping; /* Default permission required to read and write to the shared memory. */ DWORD protection = PAGE_READWRITE; /* Comment out this line to enable page caching, which delivers a * slightly better performance, but which prevents the logger from * immediately seeing changes (meaning that the last range of data * written to shared memory before a crash may end up being lost -- * exercise caution when commenting out these flags). */ protection |= SEC_COMMIT | SEC_NOCACHE; if (filesize) { bufferLength = SHMMBUF_ALIGN_PAGESIZE(filesize); mapfilesize = SHMMBUF_BUFFER_HDRSIZE + bufferLength; } hshmfile = CreateFileA(shmfilename, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hshmfile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_EXISTS) { hshmfile = CreateFileA(shmfilename, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); exist = 1; } if (hshmfile == INVALID_HANDLE_VALUE) { printf("(shmmbuf-win.h:%d) CreateFile failed: %s\n", __LINE__, shmfilename); return SHMMBUF_CREATE_ERROPEN; } /* Creates or opens a named or unnamed file mapping object for a specified file. * If the object exists before the function call, the function returns a handle * to the existing object (with its current size, not the specified size) */ if (exist) { hfilemapping = CreateFileMappingA(hshmfile, NULL, protection, (DWORD) 0, (DWORD) SHMMBUF_BUFFER_HDRSIZE, NULL); } else { hfilemapping = CreateFileMappingA(hshmfile, NULL, protection, (DWORD)((ub8)mapfilesize >> 32), (DWORD)((ub8)mapfilesize & 0xffffffff), NULL); } if (! hfilemapping) { printf("(shmmbuf-win.h:%d) CreateFileMapping failed: %s\n", __LINE__, shmfilename); CloseHandle(hshmfile); return SHMMBUF_CREATE_ERROPEN; } if (exist) { /* Check whether the buffer already exists. If so, another app * has already created the buffer (possibly due to two instances * of the logging utility), so we should not clear out the header * at the start of shared memory. */ shmbuf = (shmmap_buffer_t *) MapViewOfFile(hfilemapping, FILE_MAP_ALL_ACCESS, 0, 0, SHMMBUF_BUFFER_HDRSIZE); if (! shmbuf) { CloseHandle(hfilemapping); CloseHandle(hshmfile); return SHMMBUF_CREATE_ERRMMAP; } if (! filesize) { bufferLength = shmbuf->Length; mapfilesize = shmbuf->shmfilesize; } if (mapfilesize != shmbuf->shmfilesize || bufferLength != shmbuf->Length) { UnmapViewOfFile(shmbuf); CloseHandle(hfilemapping); CloseHandle(hshmfile); return SHMMBUF_CREATE_ERRSIZE; } if (! shmmap_verify_token(shmbuf, token, decipher_cb)) { UnmapViewOfFile(shmbuf); CloseHandle(hfilemapping); CloseHandle(hshmfile); return SHMMBUF_CREATE_ERRTOKEN; } UnmapViewOfFile(shmbuf); CloseHandle(hfilemapping); /* reopen again */ hfilemapping = CreateFileMappingA(hshmfile, NULL, protection, (DWORD)((ub8)mapfilesize >> 32), (DWORD)((ub8)mapfilesize & 0xffffffff), NULL); if (! hfilemapping) { CloseHandle(hshmfile); return SHMMBUF_CREATE_ERROPEN; } } CloseHandle(hshmfile); if (mapfilesize < SHMMBUF_BUFFER_HDRSIZE + SHMMBUF_ALIGN_PAGESIZE(0)) { CloseHandle(hfilemapping); return SHMMBUF_CREATE_ERRSIZE; } shmbuf = (shmmap_buffer_t *) MapViewOfFile(hfilemapping, FILE_MAP_ALL_ACCESS, (DWORD)0, (DWORD)0, (SIZE_T)mapfilesize); if (! shmbuf) { CloseHandle(hfilemapping); return SHMMBUF_CREATE_ERRMMAP; } CloseHandle(hfilemapping); nameprefix = strrchr(shmfilename, '/'); if (!nameprefix) { nameprefix = strrchr(shmfilename, '\\'); } if (!nameprefix) { nameprefix = (char *) shmfilename; } else { nameprefix++; } if (! exist) { randctx64 rctx; struct timespec now; __ub8_t seedus; bzero(shmbuf, mapfilesize); shmmap_gettimeofday(&now); seedus = now.tv_sec; seedus *= 1000000UL; seedus += (now.tv_nsec / 1000UL); randctx64_init(&rctx, seedus); shmbuf->magic = rand64_gen_int(&rctx, 0x0111111111111111, 0x1fffffffffffffff); if (token) { if (encipher_cb) { shmbuf->cipher = encipher_cb(shmbuf->magic, token); } else { shmbuf->cipher = shmmbuf_encipher_token(shmbuf->magic, token); } } shmbuf->Length = bufferLength; shmbuf->shmfilesize = mapfilesize; } snprintf_chkd_V1(namebuf, 127, "SHMMAP.%s.semaphore", nameprefix); shmmbuf_semaphore_init(&shmbuf->semaphore, SHMMBUF_SEMAPHORE_MAXVAL, namebuf); snprintf_chkd_V1(namebuf, 127, "SHMMAP.%s.readlock", nameprefix); ProcessMutexInit(&shmbuf->RLock, namebuf); snprintf_chkd_V1(namebuf, 127, "SHMMAP.%s.writelock", nameprefix); ProcessMutexInit(&shmbuf->WLock, namebuf); snprintf_chkd_V1(namebuf, 127, "SHMMAP.%s.writeofflock", nameprefix); ProcessMutexInit(&shmbuf->WOffset.mutex, namebuf); snprintf_chkd_V1(namebuf, 127, "SHMMAP.%s.readofflock", nameprefix); ProcessMutexInit(&shmbuf->ROffset.mutex, namebuf); if (! shmmap_verify_token(shmbuf, token, decipher_cb)) { shmmap_buffer_close(shmbuf); return SHMMBUF_CREATE_ERRTOKEN; } /* create or open success */ *outshmbuf = shmbuf; return SHMMBUF_CREATE_SUCCESS; } /** * shmmap_buffer_write() * Write chunk data of entry into shmmap ring buffer. * * Returns: * SHMMBUF_WRITE_SUCCESS(1) - write success * SHMMBUF_WRITE_AGAIN(0) - write again * SHMMBUF_WRITE_FATAL(-1) - fatal write error */ NOWARNING_UNUSED(static) int shmmap_buffer_write (shmmap_buffer_t *shmbuf, const void *chunk, size_t chunksz) { shmmbuf_entry_t *entry; ssize_t Ro, Wo, L = (ssize_t)shmbuf->Length, AENTSZ = (ssize_t)SHMMBUF_ALIGN_ENTRYSIZE(chunksz); if (! AENTSZ || AENTSZ == (ssize_t) SHMMBUF_INVALID_STATE || AENTSZ > (ssize_t) (L / SHMMBUF_ENTRY_HDRSIZE)) { /* fatal error should not occurred! */ # ifdef SHMMBUF_TRACE_PRINT_ON printf("(shmmbuf.h:%d) fatal error: invalid chunksz(=%" PRIu64").\n", __LINE__, chunksz); # endif return SHMMBUF_WRITE_FATAL; } if (ProcessMutexTryLock(shmbuf->WLock) == 0) { /* Get original ROffset */ Ro = shmmbuf_state_get(&shmbuf->ROffset); Wo = shmbuf->WOffset.state; SHMRINGBUF_RESTORE_STATE(Ro, Wo, L); # ifdef SHMMBUF_TRACE_PRINT_ON if (wrap) { printf("(shmmbuf.h:%d) shmmap_buffer_write(%" PRIu64":%" PRIu64"): W=%" PRId64" R=%" PRId64" L=%" PRId64"\n", __LINE__, chunksz, AENTSZ, W, R, L); } else { printf("(shmmbuf.h:%d) shmmap_buffer_write(%" PRIu64":%" PRIu64"): R=%" PRId64" W=%" PRId64" L=%" PRId64"\n", __LINE__, chunksz, AENTSZ, R, W, L); } # endif /* Sw = L - (wrap*L + W - R) */ if (L - (wrap*L + W - R) >= AENTSZ) { if (wrap) { /* wrap(1): 0 .. W < R < L */ entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[W]); entry->size = chunksz; memcpy(entry->chunk, chunk, chunksz); /* WOffset = Wo + AENTSZ */ W = SHMRINGBUF_NORMALIZE_OFFSET(Wo + AENTSZ, L); shmmbuf_state_set(&shmbuf->WOffset, W); } else { /* wrap(0): 0 .. R < W < L */ if (L - W >= AENTSZ) { entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[W]); entry->size = chunksz; memcpy(entry->chunk, chunk, chunksz); /* WOffset = Wo + AENTSZ */ W = SHMRINGBUF_NORMALIZE_OFFSET(Wo + AENTSZ, L); shmmbuf_state_set(&shmbuf->WOffset, W); } else if (R - 0 >= AENTSZ) { /* clear W slot before wrap W */ bzero(&shmbuf->Buffer[W], L - W); /* wrap W to 0 */ entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[0]); entry->size = chunksz; memcpy(entry->chunk, chunk, chunksz); /* WOffset = AENTSZ, wrap = 1 */ W = AENTSZ + (1 - (int)(Ro/L))*L; shmmbuf_state_set(&shmbuf->WOffset, W); } else { /* no space left to write, expect to call again */ ProcessMutexUnlock(shmbuf->WLock); return SHMMBUF_WRITE_AGAIN; } } ProcessMutexUnlock(shmbuf->WLock); return SHMMBUF_WRITE_SUCCESS; } /* no space left to write */ ProcessMutexUnlock(shmbuf->WLock); return SHMMBUF_WRITE_AGAIN; } /* lock fail to write, expect to call again */ return SHMMBUF_WRITE_AGAIN; } /** * shmmap_buffer_read_copy() * Copy entry from shmmap ringbuffer into rdbuf. * * returns: * SHMMBUF_READ_AGAIN(0) - read again * SHMMBUF_READ_FATAL(-1) - fatal read error * * ret > 0 and ret <= rdbufsz - read success * ret > rdbufsz - no read for insufficient buffer */ NOWARNING_UNUSED(static) size_t shmmap_buffer_read_copy (shmmap_buffer_t *shmbuf, char *rdbuf, size_t rdbufsz) { shmmbuf_entry_t *entry; ssize_t Ro, Wo, entsize, AENTSZ, L = (ssize_t)shmbuf->Length, HENTSZ = (ssize_t)SHMMBUF_ALIGN_ENTRYSIZE(0); if (ProcessMutexTryLock(shmbuf->RLock) == 0) { Wo = shmmbuf_state_get(&shmbuf->WOffset); Ro = shmbuf->ROffset.state; SHMRINGBUF_RESTORE_STATE(Ro, Wo, L); # ifdef SHMMBUF_TRACE_PRINT_ON if (wrap) { printf("(shmmbuf.h:%d) shmmap_buffer_read_copy(): W=%" PRId64" R=%" PRId64" L=%" PRId64"\n", __LINE__, W, R, L); } else { printf("(shmmbuf.h:%d) shmmap_buffer_read_copy(): R=%" PRId64" W=%" PRId64" L=%" PRId64"\n", __LINE__, R, W, L); } # endif /* Sr = f*L + W - R */ if (wrap*L + W - R > HENTSZ) { if (wrap) { /* wrap(1): 0 .. W < R < L */ if (L - R > HENTSZ) { entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMBUF_ALIGN_ENTRYSIZE(entry->size); if (L - R >= AENTSZ) { entsize = entry->size; if (entsize > (ssize_t) rdbufsz) { /* read buf is insufficient for entry. * read nothing if returned entsize > rdbufsz */ ProcessMutexUnlock(shmbuf->RLock); return (size_t)entsize; } /* read entry chunk into rdbuf ok */ memcpy(rdbuf, entry->chunk, entsize); R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmbuf_state_set(&shmbuf->ROffset, R); /* read success if returned entsize <= rdbufsz */ ProcessMutexUnlock(shmbuf->RLock); return (size_t)entsize; } printf("(shmmbuf.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); ProcessMutexUnlock(shmbuf->RLock); return SHMMBUF_READ_FATAL; } else { /* reset ROffset to 0 (set wrap = 0) */ shmmbuf_state_set(&shmbuf->ROffset, (Wo/L) * L); /* expect to read again */ ProcessMutexUnlock(shmbuf->RLock); return shmmap_buffer_read_copy(shmbuf, rdbuf, rdbufsz); } } else if (W - 0 > HENTSZ) { /* reset ROffset to 0 */ entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[0]); if (entry->size) { AENTSZ = SHMMBUF_ALIGN_ENTRYSIZE(entry->size); if (W - 0 >= AENTSZ) { entsize = entry->size; if (entsize > (ssize_t) rdbufsz) { /* read buf is insufficient for entry. * read nothing if returned entsize > rdbufsz */ ProcessMutexUnlock(shmbuf->RLock); return (size_t)entsize; } /* read entry chunk into rdbuf ok */ memcpy(rdbuf, entry->chunk, entsize); /* ROffset = AENTSZ, wrap = 0 */ shmmbuf_state_set(&shmbuf->ROffset, AENTSZ + (Wo/L)*L); /* read success if returned entsize <= rdbufsz */ ProcessMutexUnlock(shmbuf->RLock); return (size_t)entsize; } } printf("(shmmbuf.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); ProcessMutexUnlock(shmbuf->RLock); return SHMMBUF_READ_FATAL; } } else { /* wrap(0): 0 .. R < W < L */ entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMBUF_ALIGN_ENTRYSIZE(entry->size); if (W - R >= AENTSZ) { entsize = entry->size; if (entsize > (ssize_t) rdbufsz) { /* read buf is insufficient for entry. * read nothing if returned entsize > rdbufsz */ ProcessMutexUnlock(shmbuf->RLock); return (size_t)entsize; } /* read entry chunk into rdbuf ok */ memcpy(rdbuf, entry->chunk, entsize); R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmbuf_state_set(&shmbuf->ROffset, R); /* read success if returned entsize <= rdbufsz */ ProcessMutexUnlock(shmbuf->RLock); return (size_t)entsize; } } printf("(shmmbuf.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); ProcessMutexUnlock(shmbuf->RLock); return SHMMBUF_READ_FATAL; } } /* no entry to read, retry again */ ProcessMutexUnlock(shmbuf->RLock); return SHMMBUF_READ_AGAIN; } /* read locked fail, retry again */ return SHMMBUF_READ_AGAIN; } /** * shmmap_buffer_read_next() * Read next one entry from shmmap ring buffer into callback (no copy data). * * params: * nextentry_cb() - Callback implemented by caller should ONLY * return SHMMBUF_READ_NEXT(1) or SHMMBUF_READ_AGAIN(0) * DO NOT change and members of entry in nextentry_cb(). * returns: * SHMMBUF_READ_NEXT(1) - read for next one * SHMMBUF_READ_AGAIN(0) - read current one again * SHMMBUF_READ_FATAL(-1) - fatal read error */ NOWARNING_UNUSED(static) int shmmap_buffer_read_next (shmmap_buffer_t *shmbuf, int (*nextentry_cb)(const shmmbuf_entry_t *entry, void *arg), void *arg) { int ret = SHMMBUF_READ_AGAIN; if (ProcessMutexTryLock(shmbuf->RLock) == 0) { ssize_t Wo = shmmbuf_state_get(&shmbuf->WOffset); ssize_t Ro = shmbuf->ROffset.state; ssize_t wrap = SHMRINGBUF_RESTORE_WRAP(Ro, Wo, shmbuf->Length); ret = __shmmap_buffer_read_internal(shmbuf, wrap, Ro, Wo, (ssize_t)shmbuf->Length, nextentry_cb, arg); ProcessMutexUnlock(shmbuf->RLock); } return ret; } /** * shmmap_buffer_read_next_batch() * Read next batch entries from shmmap ring buffer into callback (no copy data). */ NOWARNING_UNUSED(static) int shmmap_buffer_read_next_batch (shmmap_buffer_t *shmbuf, int (*nextentry_cb)(const shmmbuf_entry_t *entry, void *arg), void *arg, int batch) { int num = 0, ret = SHMMBUF_READ_AGAIN; if (ProcessMutexTryLock(shmbuf->RLock) == 0) { ssize_t wrap, Wo, Ro; while (batch-- > 0) { Wo = shmmbuf_state_get(&shmbuf->WOffset); Ro = shmbuf->ROffset.state; wrap = SHMRINGBUF_RESTORE_WRAP(Ro, Wo, shmbuf->Length); ret = __shmmap_buffer_read_internal(shmbuf, wrap, Ro, Wo, (ssize_t)shmbuf->Length, nextentry_cb, arg); if (ret == SHMMBUF_READ_NEXT) { num++; continue; } if (ret == SHMMBUF_READ_AGAIN) { /* stop current batch */ break; } if (ret == SHMMBUF_READ_FATAL) { num = (int) SHMMBUF_READ_FATAL; break; } /* SHOULD NEVER RUN TO THIS ! */ } ProcessMutexUnlock(shmbuf->RLock); } return num; } NOWARNING_UNUSED(static) int shmmap_buffer_post (shmmap_buffer_t *shmbuf, size_t timeout_us) { return shmmbuf_semaphore_post(&shmbuf->semaphore, timeout_us); } NOWARNING_UNUSED(static) int shmmap_buffer_wait (shmmap_buffer_t *shmbuf, size_t timeout_us) { return shmmbuf_semaphore_wait(&shmbuf->semaphore, timeout_us); } /** * shmmap_buffer_force_unlock() * Force unlock state lock. statelock can be one or combination of below: * * SHMMBUF_READSTATE_LOCK * SHMMBUF_WRITESTATE_LOCK * NOTES: * Make sure prior to force unlocking statelock, all the applications using * the same shmmap file should be paused! */ #define SHMMBUF_READSTATE_LOCK 1 #define SHMMBUF_WRITESTATE_LOCK 2 NOWARNING_UNUSED(static) void shmmap_buffer_force_unlock (shmmap_buffer_t *shmbuf, int statelock) { if (SHMMBUF_READSTATE_LOCK & statelock) { ProcessMutexUnlock(shmbuf->RLock); } if (SHMMBUF_WRITESTATE_LOCK & statelock) { ProcessMutexUnlock(shmbuf->WLock); } } /** * __shmmap_buffer_read_internal() * Private function. do not call it in your code !! */ int __shmmap_buffer_read_internal (shmmap_buffer_t *shmbuf, ssize_t wrap, ssize_t Ro, ssize_t Wo, ssize_t L, int (*nextentry_cb)(const shmmbuf_entry_t *, void *), void *arg) { shmmbuf_entry_t *entry; ssize_t AENTSZ, HENTSZ = (ssize_t)SHMMBUF_ALIGN_ENTRYSIZE(0); ssize_t R = Ro % L; ssize_t W = Wo % L; # ifdef SHMMBUF_TRACE_PRINT_ON if (wrap) { printf("(shmmbuf.h:%d) shmmap_buffer_read_next(): W=%" PRId64" R=%" PRId64" L=%" PRId64"\n", __LINE__, W, R, L); } else { printf("(shmmbuf.h:%d) shmmap_buffer_read_next(): R=%" PRId64" W=%" PRId64" L=%" PRId64"\n", __LINE__, R, W, L); } # endif /* Sr = f*L + W - R */ if (wrap*L + W - R > HENTSZ) { if (wrap) { /* wrap(1): 0 .. W < R < L */ if (L - R > HENTSZ) { entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMBUF_ALIGN_ENTRYSIZE(entry->size); if (L - R >= AENTSZ) { if (nextentry_cb(entry, arg)) { /* read success and set ROffset to next entry */ R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmbuf_state_set(&shmbuf->ROffset, R); return SHMMBUF_READ_NEXT; } else { /* read paused by caller */ return SHMMBUF_READ_AGAIN; } } printf("(shmmbuf.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); return SHMMBUF_READ_FATAL; } else { /* reset ROffset to 0 (set wrap = 0) */ shmmbuf_state_set(&shmbuf->ROffset, (Wo/L) * L); return shmmap_buffer_read_next(shmbuf, nextentry_cb, arg); } } else if (W - 0 > HENTSZ) { /* reset ROffset to 0 */ entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[0]); if (entry->size) { AENTSZ = SHMMBUF_ALIGN_ENTRYSIZE(entry->size); if (W - 0 >= AENTSZ) { if (nextentry_cb(entry, arg)) { /* read success and set ROffset to next entry */ shmmbuf_state_set(&shmbuf->ROffset, AENTSZ + (Wo/L)*L); return SHMMBUF_READ_NEXT; } else { /* read paused by caller */ return SHMMBUF_READ_AGAIN; } } } printf("(shmmbuf.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); return SHMMBUF_READ_FATAL; } } else { /* wrap(0): 0 .. R < W < L */ entry = SHMMBUF_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMBUF_ALIGN_ENTRYSIZE(entry->size); if (W - R >= AENTSZ) { if (nextentry_cb(entry, arg)) { /* read success and set ROffset to next entry */ R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmbuf_state_set(&shmbuf->ROffset, R); return SHMMBUF_READ_NEXT; } else { /* read paused by caller */ return SHMMBUF_READ_AGAIN; } } } printf("(shmmbuf.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); return SHMMBUF_READ_FATAL; } } /* no entry to read, retry again */ return SHMMBUF_READ_AGAIN; } #ifdef __cplusplus } #endif #endif /* SHMMBUF_WIN_H__ */
pepstack/pytools
templates/%clib%/src/common/smallregex.c
/****************************************************************************** * Copyright (c) 2017-2018 Relkom s.r.o <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. *****************************************************************************/ /** * smallregex.c * * Supports: * --------- * '.' Dot, matches any character * '^' Start anchor, matches beginning of string * '$' End anchor, matches end of string * '*' Asterisk, match zero or more (greedy) * '+' Plus, match one or more (greedy) * '?' Question, match zero or one (non-greedy) * '[abc]' Character class, match if one of {'a', 'b', 'c'} * '[^abc]' Inverted class, match if NOT one of {'a', 'b', 'c'} -- NOTE: feature is currently broken! * '[a-zA-Z]' Character ranges, the character set of the ranges { a-z | A-Z } * '\s' Whitespace, \t \f \r \n \v and spaces * '\S' Non-whitespace * '\w' Alphanumeric, [a-zA-Z0-9_] * '\W' Non-alphanumeric * '\d' Digits, [0-9] * '\D' Non-digits * '(' Group start * ')' Group ends * '|' Branch **/ #ifdef _KERNEL #include <sys/cdefs.h> #include <sys/param.h> #include <sys/kernel.h> #include <sys/errno.h> #include <sys/types.h> #include <sys/malloc.h> #include <sys/libkern.h> #else #include <stdio.h> #include <stdlib.h> #include <string.h> #endif // _KERNEL #include "smallregex.h" // Definitions: #ifdef _KERNEL MALLOC_DEFINE(MC_RE, "mc_re", "Small C regex in kernel"); #define KMALLOC(_CNT_, _SIZE_) malloc( (_CNT_ * _SIZE_), MC_RE, M_WAITOK|M_ZERO) #define KREALLOC(_ADDR_, _SIZE_) realloc(_ADDR_, _SIZE_, MC_RE, M_WAITOK|M_ZERO) #define KFREE(_ADDR_) if (_ADDR_ != NULL) free((void*)_ADDR_, MC_RE) #else #define KMALLOC(_CNT_, _SIZE_) calloc(_CNT_, _SIZE_) #define KREALLOC(_ADDR_, _SIZE_) realloc(_ADDR_, _SIZE_) #define KFREE(_ADDR_) if (_ADDR_ != NULL) free((void*)_ADDR_) #endif // _KERNEL #ifndef _KERNEL #include <assert.h> #endif #ifndef _KERNEL #define ASSERT_NULL_R(_VAR_, _RETURN_) assert(_VAR_ != NULL) #else #define ASSERT_NULL_R(_VAR_, _RETURN_) \ if (_VAR_ == NULL) { \ printf("ASSERT_NULL:[%s:%u] var: %s\r\n", __FUNCTION__, __LINE__, #_VAR_); \ return _RETURN_; \ } #endif #define GENERATE_ENUM_ANY(ENUM, ...) ENUM, #define GENERATE_VAL_STRINGS_VAL(STRING, VAL) VAL, #define GENERATE_VAR_NAMES_VAL(STRING, VAL) #STRING, #define FOREACH_GLOBAL_TYPE(DV)\ DV(UNUSED, " " )\ DV(DOT, "." )\ DV(BEGIN, "^" )\ DV(END, "$" )\ DV(QUESTIONMARK, "?" )\ DV(STAR, "*" )\ DV(PLUS, "+" )\ DV(CHAR, "char" )\ DV(CHAR_CLASS, "[]" )\ DV(INV_CHAR_CLASS, "^[]" )\ DV(DIGIT, "\\d" )\ DV(NOT_DIGIT, "\\D" )\ DV(ALPHA, "\\w" )\ DV(NOT_ALPHA, "\\W" )\ DV(WHITESPACE, "\\s" )\ DV(NOT_WHITESPACE, "\\S" )\ DV(BRANCH, "|" )\ DV(GROUPSTART, "(" )\ DV(GROUPEND, ")" ) enum { FOREACH_GLOBAL_TYPE(GENERATE_ENUM_ANY) }; // stack instance struct sstate_t { uint32_t matchcnt; //for *+ match count int32_t offset; //current offset int32_t st0; //the last st0 accomulator int32_t st; //current st }; // push stack #define PUSH() sstate[sp+1].offset = sstate[sp].offset; sstate[sp+1].st = sstate[sp].st; sp++; // pop from stack #define POP() sp-- // restore (unused) #define RESTORE() sp = 0 // the fast access #define SSTP sstate[sp] /** * A structure for grouping instancing */ struct re_pair_inst { uint32_t trueoff; // offset for eval true uint32_t failoff; // offset for eval false }; /** * Compilation args */ struct args_reg_compile { struct re_pair_inst *inst; // start end of groups (offsets) uint32_t objs; // amount of the objects uint32_t strln; // the length of the class length uint32_t ecnt; // the length og the inst uint32_t stcnt; // how large the sstate table may be in the worst case }; #ifdef RE_BUILDWITH_DEBUG static const char* typestr[] = { FOREACH_GLOBAL_TYPE(GENERATE_VAL_STRINGS_VAL) }; const char* typenames[] = { FOREACH_GLOBAL_TYPE(GENERATE_VAR_NAMES_VAL) }; #endif // Private function declarations: static int32_t matchpattern(struct small_regex * reg, struct regex_objs_t * pattern, const char* text); static int32_t matchcharclass(char c, const char* str); static int32_t matchone(struct small_regex * pattern, struct regex_objs_t p, char c); static int32_t matchdigit(char c); static int32_t matchalpha(char c); static int32_t matchwhitespace(char c); static int32_t matchmetachar(char c, const char* str); static int32_t matchrange(char c, const char* str); static int32_t ismetachar(char c); static int32_t __regex_compile_count(const char* pattern, struct args_reg_compile * args); static int32_t __check_state_size(uint32_t sp, uint32_t * reacnt, uint32_t default_dep, void ** ptr, size_t structsize, uint32_t max_reallocs) { // check if the stack pointer (SP) went out of range if (( sp >= ( (*reacnt)*default_dep) ) && (max_reallocs != 0)) { if ( (*reacnt) >= max_reallocs) { LOGERR("%s can't realloc because limit was reached max: %u\r\n", __FUNCTION__, max_reallocs); return 1; } else { void * tmp = KREALLOC((*ptr), (*reacnt) * default_dep * structsize); if (tmp == NULL) { LOGERR("%s realloc failed\r\n", __FUNCTION__); // KFREE(stack); return 1; } DPROBE("reallocating: sp: %u reacnt:%u new size: %lu\r\n", sp, *reacnt, (*reacnt) * default_dep * structsize); (*reacnt)++; // dereferencing pointer does break strict-aliasing rules // *ptr = tmp; memcpy(*ptr, tmp, sizeof(void *)); } } return 0; } // Public functions int32_t regex_validate(struct small_regex * regex) { ASSERT_NULL_R(regex, 1); uint32_t i; uint32_t count = COUNT_NODES(regex); //convert pattern struct regex_objs_t * objs = SECTION_OBJECTS(regex); for (i = 0; objs[i].type != UNUSED; ++i) { if ((count != 0) && (i >= count)) { LOGERR("regex_validator: reached end (count: %u) before the UNUSED node was reached\r\n", count); return 1; } if (objs[i].trueoffset >= count) { LOGERR("regex_validator: true offset is out of bound has: %u max: %u\r\n", objs[i].trueoffset, count); return 1; } else if (objs[i].falseoffset >= count) { LOGERR("regex_validator: false offset is out of bound has: %u max: %u\r\n", objs[i].falseoffset, count); return 1; } } return 0; } void regex_free(struct small_regex * regex) { KFREE(regex); } int32_t regex_match(const char* pattern, const char* text) { int32_t ret = -1; struct small_regex * reg = regex_compile(pattern); if (!reg) { LOGERR("failed at %s:%u\r\n", __FUNCTION__, __LINE__); } else { ret = regex_matchp(reg, text); KFREE(reg); } return ret; } int32_t regex_matchp(struct small_regex * regx, const char* text) { ASSERT_NULL_R(regx, -1); ASSERT_NULL_R(text, -1); struct regex_objs_t * objs = SECTION_OBJECTS(regx); int idx = -1; if (objs[0].type == BEGIN) { // starts from begin ^ return ( (matchpattern(regx, objs, text)) ? 0 : -1 ); } else { do { idx += 1; if (matchpattern(regx, objs, text)) { return idx; } } while (*text++ != '\0'); return -1; } } static int32_t __regex_compile_count(const char* pattern, struct args_reg_compile * args) { uint32_t i = 0; // current character index unsigned char c = 0; // character int32_t brcnt = 0; // open brackets counter uint32_t realcnt = 1; // reallocations args->ecnt++; args->stcnt = 1; while (pattern[i] != '\0') { c = pattern[i]; if( c =='\\') { if (pattern[i+1] == '\0') { LOGERR("the escape charater without character, unexpected EOL\r\n" "--> i=%u value=%s at %s:%u\r\n", i, &pattern[i], __FUNCTION__, __LINE__); return 1; } i++; } else if ( (c == '*') || (c == '+') ) { // trying to predict how large the stack will be required args->stcnt++; } else if (c == '(') { brcnt++; args->inst[args->ecnt].trueoff = args->objs; args->ecnt++; // reallocate temp if necessary if (__check_state_size(args->ecnt, &realcnt, DEFAULT_TEMP_LEN, (void**)&args->inst, sizeof(struct re_pair_inst), MAX_TEMP_REALLOCS) == 1) { return 1; } } else if (c == ')') { args->inst[args->ecnt-(args->ecnt-brcnt)].failoff = args->objs; brcnt--; } else if (c == '[') { // Remember where pattern starts. uint32_t pat_begin = 0; uint32_t pat_len = 0; // Look-ahead to determine if negated if (pattern[i+1] == '^') { i += 1; // Increment i to avoid including '^' in the char-buffer } // [test] // storing start offset of the pattern pat_begin = i + 1; /* Copy characters inside [..] to buffer */ while (pattern[++i] != ']') { // check if next is not null if (pattern[i] == '\0') { LOGERR("the next element in pattern [] is NULL before reaching ] symbol\r\n" "--> i=%u value=%s at %s:%u\r\n", i, &pattern[pat_begin], __FUNCTION__, __LINE__); return 1; } } // calculating the patt length pat_len = (i - pat_begin); args->strln += pat_len + 1; // + NULL } i++; args->objs++; } if (brcnt != 0) { LOGERR("round brackets mismatch has: %d at %s:%u\r\n", brcnt, __FUNCTION__, __LINE__); return 1; } if (args->stcnt >= DEFAULT_STATES_DEP * MAX_STATE_REALLOCS) { LOGERR("it seems that in the worst case there will be required more states than it can handle max: %lu have: %d\r\n", DEFAULT_STATES_DEP * MAX_STATE_REALLOCS, args->stcnt); } // 'UNUSED' is a sentinel used to indicate end-of-pattern args->objs++; if (pattern[i-1] == '$') { // calculating the end of the main block begin..end args->inst[0].failoff = args->objs-2; } else { // calculating the end of the main block start..unused args->inst[0].failoff = args->objs-1; } return 0; } struct small_regex * regex_compile(const char* pattern) { ASSERT_NULL_R(pattern, NULL); struct re_pair_inst * inst = NULL; struct small_regex * re_compiled = NULL; struct regex_objs_t * re_obj = NULL; // temp inst = (struct re_pair_inst*) KMALLOC(DEFAULT_TEMP_LEN, sizeof(struct re_pair_inst)); if (inst == NULL) { LOGERR("calloc returned NULL at %s:%u\r\n", __FUNCTION__, __LINE__); goto re_temp_error; } // calculating the length struct args_reg_compile args = {inst, 0,0,0,0}; if (__regex_compile_count(pattern, &args) != 0) { // leave goto re_temp_error; } // calculating total size size_t totallen = ( args.objs * sizeof(struct regex_objs_t) ) + args.strln + sizeof(struct small_regex); re_compiled = (struct small_regex *) KMALLOC(1, totallen); if (re_compiled == NULL) { LOGERR("calloc returned NULL at %s:%u\r\n", __FUNCTION__, __LINE__); goto re_temp_error; } // setting the fields re_compiled->objoffset = args.strln; re_compiled->pstsize = args.stcnt; re_compiled->totalsize = (uint32_t)(totallen - sizeof(struct small_regex)); DPROBE("objs: %u pstsize: %u total data len: %u\r\n", re_compiled->objoffset, re_compiled->pstsize, re_compiled->totalsize); char * patrns = (char *) &re_compiled->data[0]; // objects starts at end of the strln re_obj = (struct regex_objs_t *) &re_compiled->data[args.strln]; char c; // current char in pattern uint32_t i = 0; // index into pattern uint32_t j = 0; // index into re_compiled uint32_t patoff = 0; // pattern offset uint32_t ecnt = 0; // grouping depth counter uint32_t ecntdip = 0; // grouping index uint32_t resel = 0; // instance selector i.e resel = ecntdip - (ecntdip - ecnt); or resel = ecntdip while (pattern[i] != '\0') { c = pattern[i]; switch (c) { // Meta-characters: case '^': re_obj[j].type = BEGIN; re_obj[j].falseoffset = inst[resel].failoff; re_obj[j].trueoffset = j+1; break; case '$': re_obj[j].type = END; re_obj[j].falseoffset = 0; re_obj[j].trueoffset = j+1; // UNUSED break; case '.': re_obj[j].type = DOT; re_obj[j].falseoffset = 0; // can't fail (ANY) re_obj[j].trueoffset = j+1; break; case '*': re_obj[j].type = STAR; if (re_obj[j-1].type == GROUPEND) { re_obj[j].falseoffset = inst[resel].failoff; // can fail because 0 or more re_obj[j].trueoffset = inst[resel+1].trueoff; } else { re_obj[j].falseoffset = inst[resel].failoff; // can't fail (from 0 or more) re_obj[j].trueoffset = j-1; } // ovveride the false of previous object to us re_obj[j-1].falseoffset = j; break; case '+': re_obj[j].type = PLUS; re_obj[j].falseoffset = inst[resel].failoff; //can fail because 1 or more if (re_obj[j-1].type == GROUPEND) { re_obj[j].trueoffset = inst[resel+1].trueoff; } else { re_obj[j].trueoffset = j-1; } // ovveride the false of previous object to + re_obj[j-1].falseoffset = j; break; case '?': re_obj[j].type = QUESTIONMARK; re_obj[j].falseoffset = 0; // can't fail because 0 to 1 re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[resel].failoff; // can fail because 1 or more // ovveride the false of previous object to us re_obj[j-1].falseoffset = j; break; case '|': { uint32_t i; // we need to modify objects failoffset before the branch re_obj[j].type = BRANCH; re_obj[j].falseoffset = j+1; // previous match failed re_obj[j].trueoffset = inst[resel].failoff; // previous match successfull DPROBE("j: %d F: %d T: %d resel:%d\r\n", j, re_obj[j].falseoffset, re_obj[j].trueoffset, resel); for (i = j-1; i >= inst[resel].trueoff; i++) { //trace back and change fail offset if (re_obj[i].type == BRANCH) { break; } DPROBE("-[%d - %d]->%d\r\n", i, j-1, re_obj[i].falseoffset); re_obj[i].falseoffset = j; DPROBE("-->%d\r\n", re_obj[i].falseoffset); } } break; case '(': ecnt++; ecntdip++; resel = ecntdip; re_obj[j].type = GROUPSTART; re_obj[j].falseoffset = inst[resel].failoff; // offset to the end of the group re_obj[j].trueoffset = j+1; break; case ')': DPROBE("ecnt: %d ecntdip: %d recel: %d-->", ecnt, ecntdip, resel); ecnt--; if (ecnt == 0) { resel = 0; } else { resel = ecntdip - (ecntdip - ecnt); } DPROBE("ecnt: %d ecntdip: %d recel: %d \r\n", ecnt, ecntdip, resel); re_obj[j].type = GROUPEND; re_obj[j].falseoffset = inst[resel].failoff; // offset to the end of the block/group re_obj[j].trueoffset = j+1; break; /* Escaped character-classes (\s \w ...): */ case '\\': if (pattern[i+1] != '\0') { /* ... and check the next */ switch (pattern[i+1]) { /* Meta-character: */ case 'd': re_obj[j].type = DIGIT; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; case 'D': re_obj[j].type = NOT_DIGIT; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; case 'w': re_obj[j].type = ALPHA; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; case 'W': re_obj[j].type = NOT_ALPHA; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; case 's': re_obj[j].type = WHITESPACE; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; case 'S': re_obj[j].type = NOT_WHITESPACE; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; /* Escaped character, e.g. '.' or '$' */ default: re_obj[j].type = CHAR; re_obj[j].ch = pattern[i+1]; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; } // skip character i++; } else { LOGERR("%s:%u unexpected EOL\r\n", __FUNCTION__, __LINE__); goto re_temp_error; } break; /* Character class: */ case '[': { // Remember where pattern starts. uint32_t pat_begin = 0; uint32_t pat_len = 0; // Look-ahead to determine if negated if (pattern[i+1] == '^') { re_obj[j].type = INV_CHAR_CLASS; i += 1; // Increment i to avoid including '^' in the char-buffer } else { re_obj[j].type = CHAR_CLASS; } // [test] // storing start offset of the pattern pat_begin = i + 1; /* Copy characters inside [..] to buffer */ while (pattern[++i] != ']') { // check if next is not null if (pattern[i] == '\0') { LOGERR("the next element in pattern [] is NULL before reaching ] symbol\r\n" "--> i=%u value=%s at %s:%u\r\n", i, &pattern[pat_begin], __FUNCTION__, __LINE__); goto re_temp_error; } } // calculating the patt length pat_len = (i - pat_begin); re_obj[j].ccl = patoff; // copy data to the structure, unsafe operation memmove((void*)&patrns[patoff], (const void*) &pattern[pat_begin], pat_len); patoff += pat_len + 1; //+null re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; } break; // Other characters: default: re_obj[j].type = CHAR; re_obj[j].ch = c; re_obj[j].trueoffset = j+1; re_obj[j].falseoffset = inst[ecnt].failoff; break; } i++; j++; } // 'UNUSED' is a sentinel used to indicate end-of-pattern re_obj[j].type = UNUSED; // move next, j now indicates the amount of the recs from 0..j-1 j++; KFREE(inst); return re_compiled; re_temp_error: KFREE(inst); KFREE(re_compiled); return NULL; } uint32_t regex_get_size(struct small_regex * regex) { return (regex? regex->totalsize : 0); } #ifdef RE_BUILDWITH_DEBUG void regex_print(struct small_regex * pattern) { ASSERT_NULL_R(pattern, ); uint32_t i; uint32_t count = COUNT_NODES(pattern); //convert pattern struct regex_objs_t * objs = SECTION_OBJECTS(pattern); for (i = 0; objs[i].type != UNUSED; ++i) { if ((count != 0) && (i >= count)) { printf("!!!<>>\r\n"); break; } switch (objs[i].type) { case CHAR_CLASS: case INV_CHAR_CLASS: printf("["); printf("%s", OFFSET_TO_PATTERN(pattern, objs[i].ccl)); printf("]"); break; case CHAR: printf("%c", objs[i].ch); break; default: printf("%s", typestr[objs[i].type]); break; } } printf("\r\n"); return; } void regex_trace(small_regex_t * pattern) { ASSERT_NULL_R(pattern, ); uint32_t count = COUNT_NODES(pattern); //convert pattern struct regex_objs_t * objs = SECTION_OBJECTS(pattern); uint32_t i = 0; for ( i = 0; objs[i].type != UNUSED; ++i) { if ((count != 0) && (i >= count)) { printf("reached end (count: %u) before the UNUSED node was reached\r\n", count); break; } printf("[%u] type: %s true: %u false: %u ", i, typenames[objs[i].type], objs[i].trueoffset, objs[i].falseoffset); if (objs[i].type == CHAR_CLASS || objs[i].type == INV_CHAR_CLASS) { printf(" ["); printf("%s", OFFSET_TO_PATTERN(pattern, objs[i].ccl)); printf("]"); } else if (objs[i].type == CHAR) { printf(" '%c'", objs[i].ch); } printf("\n"); } printf("[%u] type: %s\r\n", i, typenames[objs[i].type]); return; } void regex_printstrlegend(void) { printf(DCOLOR_RED"RED - st0"DCOLOR_RESET" / "DCOLOR_GREEN"GREEN - matchcnt"DCOLOR_RESET" / "DCOLOR_BLUE" BLUE - < st"DCOLOR_RESET" / "DCOLOR_YELLOW" YELLOW - =st"DCOLOR_RESET " / WHITE - rest\r\n"); } void regex_printstr(const char * text, size_t textlen, struct sstate_t * sstate) { for (size_t i = 0; i<textlen; i++) { if (i == sstate->st0) { printf(DCOLOR_RED"%c"DCOLOR_RESET, text[i]); } else if ( ((sstate->st - sstate->matchcnt) < i) && (i < sstate->st) && (sstate->matchcnt != 0) ) { printf(DCOLOR_GREEN"%c"DCOLOR_RESET, text[i]); } else if ( (i != sstate->st0) && (i < sstate->st)) { printf(DCOLOR_BLUE"%c"DCOLOR_RESET, text[i]); } else if (i == sstate->st) { printf(DCOLOR_YELLOW"%c"DCOLOR_RESET, text[i]); } else { printf("%c", text[i]); } } printf("\r\n"); } #endif static int32_t matchdigit(char c) { DPROBE("-->%s \\d with %c\r\n", __FUNCTION__, c); return ((c >= '0') && (c <= '9')); } static int32_t matchalpha(char c) { return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); } static int32_t matchwhitespace(char c) { DPROBE("-->%s \\s with %c\r\n", __FUNCTION__, c); return ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r') || (c == '\f') || (c == '\v')); } static int32_t matchalphanum(char c) { DPROBE("-->%s \\w with %c\r\n", __FUNCTION__, c); return ((c == '_') || matchalpha(c) || matchdigit(c)); } static int32_t matchrange(char c, const char* str) { DPROBE("-->%s %s with %c\r\n", __FUNCTION__, str, c); return ((c != '-') && (str[0] != '-') && (str[1] == '-') && (str[2] != '\0') && ((c >= str[0]) && (c <= str[2]))); } static int32_t ismetachar(char c) { return ((c == 's') || (c == 'S') == (c == 'w') || (c == 'W') || (c == 'd') || (c == 'D')); } static int32_t matchmetachar(char c, const char* str) { switch (str[0]) { case 'd': return matchdigit(c); case 'D': DPROBE("-->%s not \\D with %c\r\n", __FUNCTION__, c); return !matchdigit(c); case 'w': return matchalphanum(c); case 'W': DPROBE("-->%s not \\W with %c\r\n", __FUNCTION__, c); return !matchalphanum(c); case 's': return matchwhitespace(c); case 'S': DPROBE("-->%s \\S with %c\r\n", __FUNCTION__, c); return !matchwhitespace(c); default: DPROBE("-->%s %c with %c\r\n", __FUNCTION__, str[0], c); return (c == str[0]); } return (c == str[0]); } static int32_t matchcharclass(char c, const char* str) { do { if (matchrange(c, str)) { return 1; } else if (str[0] == '\\') { // Escape-char: increment str-ptr and match on next char str += 1; if (matchmetachar(c, str)) { return 1; } else if ((c == str[0]) && !ismetachar(c)) { return 1; } } else if (c == str[0]) { if (c == '-') { return ((str[-1] == '\0') || (str[1] == '\0')); } else { return 1; } } } while (*str++ != '\0'); return 0; } static int32_t matchone(struct small_regex * pattern, struct regex_objs_t p, char c) { switch (p.type) { case DOT: DPROBE("-->%s . with %c\r\n", __FUNCTION__, c); if ( (c == '\n') || (c == '\r') ) { return 0; } else { return 1; } case CHAR_CLASS: return matchcharclass(c, (const char*)OFFSET_TO_PATTERN(pattern, p.ccl)); case INV_CHAR_CLASS: return !matchcharclass(c, (const char*)OFFSET_TO_PATTERN(pattern, p.ccl)); case DIGIT: return matchdigit(c); case NOT_DIGIT: return !matchdigit(c); case ALPHA: return matchalphanum(c); case NOT_ALPHA: return !matchalphanum(c); case WHITESPACE: return matchwhitespace(c); case NOT_WHITESPACE: return !matchwhitespace(c); case CHAR: DPROBE("-->%s %c with %c\r\n",__FUNCTION__, p.ch, c); return (p.ch == c); default: return -1; } // SHOULD NOT REACH THIS POINT return (p.ch == c); } static int32_t matchpattern(struct small_regex * reg, struct regex_objs_t * pattern, const char* text) { uint32_t stackrealcnt = 1; if (reg->pstsize == 0) { reg->pstsize = DEFAULT_STATES_DEP; } struct sstate_t * sstate = (struct sstate_t *) KMALLOC(reg->pstsize, sizeof(struct sstate_t)); if (sstate == NULL) { LOGERR("%s malloc failed\r\n", __FUNCTION__); return 0; } #ifdef RE_BUILDWITH_DEBUG size_t textlen = strlen(text); // length of the string #endif uint32_t sp = 0; // sstate pointer int32_t evalres = 0; // evaluation result accomulator int32_t evalres0 = 0; // evaluation result accomulator int32_t brtxcoff = 0; // used for group+branch // reset first intance memset(&SSTP, 0, sizeof(struct sstate_t)); SSTP.st0 = -1; // print legend if compiled with the debug regex_printstrlegend(); for (;;) { regex_printstr(text, textlen, &SSTP); switch (pattern[SSTP.offset].type) { case BEGIN: DPROBE("BEGIN\r\n"); SSTP.offset = pattern[SSTP.offset].trueoffset; break; case UNUSED: case END: if ( (evalres == 0) && (sp > 0)) { POP(); DPROBE("returning to [%.4d](%s) sp:%d st:%d st0:%d text[st]:%c\r\n", SSTP.offset, typenames[pattern[SSTP.offset].type], sp, SSTP.st, SSTP.st0, text[SSTP.st]); } else { DPROBE("EXIT\r\n"); if (pattern[SSTP.offset].type == END) { uint32_t est = SSTP.st; KFREE(sstate); return (text[est] == '\0') ? evalres : 0; } else { KFREE(sstate); return evalres; } } break; case QUESTIONMARK: SSTP.offset = pattern[SSTP.offset].trueoffset; evalres = 1; // anyway it is true SSTP.matchcnt = 0; break; case STAR: case PLUS: { if ( evalres == 1 ) { // increent counter SSTP.matchcnt++; } if ( ( evalres == 1 ) && (text[SSTP.st] != '\0') ) { int32_t offset0 = SSTP.offset + 1; SSTP.offset = pattern[SSTP.offset].trueoffset; // check further if it matches the next char if ( ( (pattern[offset0].type != END) && (pattern[offset0].type != UNUSED)) && (pattern[offset0].type != BRANCH) && (SSTP.st0 != SSTP.st) ) { DPROBE("PROBING FORWARD: offset0: %d text: %c st: %d\r\n", offset0, text[SSTP.st], SSTP.st); // check next character in order to see how likely the + or * should be left int32_t tr = matchone(reg, pattern[offset0], text[SSTP.st]); switch (tr) { case -1: //unknown operation case 1: DPROBE("PROBING FORWARD: SUCCESS\r\n"); // store where we was before the push SSTP.st0 = SSTP.st; DPROBE("PUSH from [%.4d](%s) sp:%d st:%d st0:%d text[st]:%c\r\n", SSTP.offset, typenames[pattern[SSTP.offset].type], sp, SSTP.st, SSTP.st0, text[SSTP.st]); // push to the stack PUSH(); // check if stack requires to be extended if (__check_state_size(sp, &stackrealcnt, DEFAULT_STATES_DEP, (void**)&sstate, sizeof(struct sstate_t), MAX_STATE_REALLOCS) == 1) { goto somethingwentwrong; } // reset new instance // SSTP.offset = offset0; SSTP.st0 = -1; SSTP.offset = pattern[offset0].trueoffset; SSTP.st++;// increment current section match DPROBE("PUSH to [%.4d](%s) sp:%d st:%d st0:%d text[st]:%c\r\n", SSTP.offset, typenames[pattern[SSTP.offset].type], sp, SSTP.st, SSTP.st0, text[SSTP.st]); break; case 0: break; } } } else { if ( pattern[SSTP.offset].type == PLUS ) { if (SSTP.matchcnt > 0) { // SSTP.txshift++; evalres = 1; } else { evalres = 0; } } else if (pattern[SSTP.offset].type == STAR) { evalres = 1; } if (evalres == 1) { SSTP.offset++; } else { SSTP.offset = pattern[SSTP.offset].falseoffset; } SSTP.matchcnt = 0; } } break; case GROUPSTART: // entering group DPROBE("ENTERING GROUP from [%.4d](%s) ", SSTP.offset, typenames[pattern[SSTP.offset].type]); SSTP.offset++; brtxcoff = SSTP.st; // reset current offset DPROBE("nextoffset [%.4d](%s) st: %d brtxcoff: %d\r\n", SSTP.offset, typenames[pattern[SSTP.offset].type], SSTP.st, brtxcoff); break; case GROUPEND: // leaving group T: next F: EXIT or next GROUPEND/BRANCH DPROBE("LEAVING GROUP from [%.4d](%s) ", SSTP.offset, typenames[pattern[SSTP.offset].type]); if (evalres == 0) { // restore the st SSTP.st = brtxcoff; SSTP.offset = pattern[SSTP.offset].falseoffset; } else { SSTP.offset = pattern[SSTP.offset].trueoffset; brtxcoff = 0; // reset current offset } DPROBE("nextoffset [%.4d](%s) st: %d brtxcoff: %d\r\n", SSTP.offset, typenames[pattern[SSTP.offset].type], SSTP.st, brtxcoff); break; case BRANCH: // BRANCHING { DPROBE("BRANCHING from [%.4d](%s) ", SSTP.offset, typenames[pattern[SSTP.offset].type]); if (evalres == 0) { // restore the st SSTP.st = brtxcoff; SSTP.offset = pattern[SSTP.offset].falseoffset; } else { SSTP.offset = pattern[SSTP.offset].trueoffset; brtxcoff = 0; // reset current offset } DPROBE("nextoffset [%.4d](%s) st: %d brtxcoff: %d\r\n", SSTP.offset, typenames[pattern[SSTP.offset].type], SSTP.st, brtxcoff); } break; default: // call handler if ( /*(evalres == 0) &&*/ (text[SSTP.st] == '\0') ) { SSTP.offset = pattern[SSTP.offset].falseoffset; evalres = 0; continue; } // store previous sstate of operation evaluation evalres0 = evalres; evalres = matchone(reg, pattern[SSTP.offset], text[SSTP.st]); switch (evalres) { case 1: SSTP.offset = pattern[SSTP.offset].trueoffset; SSTP.st++;// increment current section match break; case 0: SSTP.offset = pattern[SSTP.offset].falseoffset; break; default: case -1: // unknown operation evalres = evalres0; break; } break; } } // while somethingwentwrong: KFREE(sstate); return 0; }
pepstack/pytools
templates/%clib%/src/common/shmmap.h
<gh_stars>0 /*********************************************************************** * Copyright (c) 2008-2080, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename shmmap.h * MP and MT-safe shared memory IO for Linux (POSIX.1-2008, glibc 2.12+). * * @author <NAME> <<EMAIL>> * @version 1.0.0 * @create 2020-05-01 12:46:50 * @update 2020-05-19 18:45:08 * * NOTES: * Prior to include this file, define as following to enable * trace print in spite of speed penalty. * * #define SHMMAP_TRACE_PRINT_ON * #include "shmmap.h" */ #ifndef SHMMAP_H__ #define SHMMAP_H__ #if defined(__cplusplus) extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #ifndef __STDC_FORMAT_MACROS # define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <pthread.h> #include <semaphore.h> /** * random generator for cryptography */ #include "randctx.h" #include "md5sum.h" #include "unitypes.h" #ifndef NOWARNING_UNUSED # if defined(__GNUC__) || defined(__CYGWIN__) # define NOWARNING_UNUSED(x) __attribute__((unused)) x # else # define NOWARNING_UNUSED(x) x # endif #endif /** * Default constants only show you the usage for shmmap api. * * Shared memory file lies in: "/dev/shm/shmmap-buffer-default" */ #define SHMMAP_FILENAME_DEFAULT "shmmap-buffer-default" #define SHMMAP_FILEMODE_DEFAULT 0666 /** * Below definitions SHOULD NOT be changed! */ #define SHMMAP_PAGE_SIZE ((size_t)4096) #define SHMMAP_INVALID_STATE ((size_t)(-1)) #define SHMMAP_TIMEOUT_INFINITE ((size_t)(-1)) #define SHMMAP_TIMEOUT_NOWAIT (0) #define SHMMAP_ENTRY_HDRSIZE (sizeof(shmmap_entry_t)) #define SHMMAP_ALIGN_BSIZE(bsz, alignsize) \ ((size_t)((((size_t)(bsz)+(alignsize)-1)/(alignsize))*(alignsize))) #define SHMMAP_ALIGN_PAGESIZE(fsz) \ SHMMAP_ALIGN_BSIZE((fsz), SHMMAP_PAGE_SIZE) #define SHMMAP_ALIGN_ENTRYSIZE(chunksz) \ SHMMAP_ALIGN_BSIZE((chunksz + SHMMAP_ENTRY_HDRSIZE), SHMMAP_ENTRY_HDRSIZE) #define SHMMAP_BUFFER_HDRSIZE \ SHMMAP_ALIGN_BSIZE(sizeof(shmmap_buffer_t), SHMMAP_PAGE_SIZE) #define SHMMAP_ENTRY_CAST(p) ((shmmap_entry_t *)(p)) #define SHMMAP_VERIFY_STATE(val) do { \ if ((val) == SHMMAP_INVALID_STATE) { \ exit(EXIT_FAILURE); \ } \ } while(0) /** * Returns of shmmap_buffer_create() */ #define SHMMAP_CREATE_SUCCESS 0 #define SHMMAP_CREATE_ERROPEN (1) #define SHMMAP_CREATE_ERRMMAP (2) #define SHMMAP_CREATE_ERRSIZE (3) #define SHMMAP_CREATE_ERRTRUNC (4) #define SHMMAP_CREATE_ERRTOKEN (5) /** * Returns of shmmap_buffer_write() */ #define SHMMAP_WRITE_SUCCESS ((int)(1)) #define SHMMAP_WRITE_AGAIN ((int)(0)) #define SHMMAP_WRITE_FATAL ((int)(-1)) /** * Returns of shmmap_buffer_read_?() */ #define SHMMAP_READ_NEXT ((int)(1)) #define SHMMAP_READ_AGAIN ((int)(0)) #define SHMMAP_READ_FATAL ((int)(-1)) /** * default token cryptographic algorithm */ typedef __ub8_t ub8token_t; NOWARNING_UNUSED(static) ub8token_t shmmap_encipher_token (const ub8token_t magic, ub8token_t *token) { ub8token_t cipher = magic ^ (*token); return cipher; } NOWARNING_UNUSED(static) ub8token_t shmmap_decipher_token (const ub8token_t cipher, ub8token_t *token) { ub8token_t magic = cipher ^ (*token); return magic; } /** * The layout of memory for any one entry in shmmap. */ typedef struct _shmmap_entry_t { size_t size; char chunk[0]; } shmmap_entry_t; /** * The atomic struct for state of shmmap. */ typedef struct _shmmap_state_t { /* atomic state value */ size_t state; /* process-wide state lock */ pthread_mutex_t mutex; } shmmap_state_t; NOWARNING_UNUSED(static) void shmmap_gettimeofday (struct timespec *now) { #if defined(__WINDOWS__) FILETIME tmfile; ULARGE_INTEGER _100nanos; GetSystemTimeAsFileTime(&tmfile); _100nanos.LowPart = tmfile.dwLowDateTime; _100nanos.HighPart = tmfile.dwHighDateTime; _100nanos.QuadPart -= 0x19DB1DED53E8000; /* Convert 100ns units to seconds */ now->tv_sec = (time_t)(_100nanos.QuadPart / (10000 * 1000)); /* Convert remainder to nanoseconds */ now->tv_nsec = (long) ((_100nanos.QuadPart % (10000 * 1000)) * 100); #else clock_gettime(CLOCK_REALTIME, now); #endif } NOWARNING_UNUSED(static) sb8 shmmap_difftime_msec (const struct timespec *t1, const struct timespec *t2) { sb8 sec = (sb8)(t2->tv_sec - t1->tv_sec); sb8 nsec = (sb8)(t2->tv_nsec - t1->tv_nsec); if (sec > 0) { if (nsec >= 0) { return ((sec * 1000UL) + nsec / 1000000UL); } else { /* nsec < 0 */ return (sec-1) * 1000UL + (nsec + 1000000000UL) / 1000000UL; } } else if (sec < 0) { if (nsec <= 0) { return ((sec * 1000UL) + nsec / 1000000UL); } else { /* nsec > 0 */ return (sec+1) * 1000UL + (nsec - 1000000000UL) / 1000000UL; } } else { /* sec = 0 */ return nsec / 1000000UL; } } /** * http://www.linuxhowtos.org/manpages/3/pthread_mutexattr_setrobust.htm */ NOWARNING_UNUSED(static) void shmmap_mutex_consistent (pthread_mutex_t *mutexp) { if (pthread_mutex_consistent(mutexp)) { perror("pthread_mutex_consistent"); exit(EXIT_FAILURE); } if (pthread_mutex_unlock(mutexp)) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } } NOWARNING_UNUSED(static) void process_shared_mutex_init (pthread_mutex_t *mutexp) { pthread_mutexattr_t attr; int err = pthread_mutexattr_init(&attr); if (err) { printf("(shmmap.h:%d) pthread_mutexattr_init error(%d): %s.\n", __LINE__, err, strerror(err)); exit(EXIT_FAILURE); } err = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); if (err) { printf("(shmmap.h:%d) pthread_mutexattr_setpshared error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&attr); exit(EXIT_FAILURE); } err = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); if (err) { printf("(shmmap.h:%d) pthread_mutexattr_setrobust error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&attr); exit(EXIT_FAILURE); } err = pthread_mutex_init(mutexp, &attr); if (err) { printf("(shmmap.h:%d) pthread_mutex_init error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&attr); exit(EXIT_FAILURE); } pthread_mutexattr_destroy(&attr); } NOWARNING_UNUSED(static) int process_shared_mutex_lock (pthread_mutex_t *mutexp, int istry) { int err; if (istry) { err = pthread_mutex_trylock(mutexp); } else { err = pthread_mutex_lock(mutexp); } if (err == EOWNERDEAD) { shmmap_mutex_consistent(mutexp); err = process_shared_mutex_lock(mutexp, istry); } return err; } #define process_shared_mutex_unlock(mutexp) \ pthread_mutex_unlock(mutexp) NOWARNING_UNUSED(static) void shmmap_state_init (shmmap_state_t *st, size_t state) { process_shared_mutex_init(&st->mutex); st->state = state; } NOWARNING_UNUSED(static) int shmmap_state_uninit (shmmap_state_t *st) { int err = pthread_mutex_destroy(&st->mutex); return err; } NOWARNING_UNUSED(static) size_t shmmap_state_get (shmmap_state_t *st) { size_t val = SHMMAP_INVALID_STATE; int err = pthread_mutex_lock(&st->mutex); if (! err) { val = st->state; pthread_mutex_unlock(&st->mutex); return val; } else if (err == EOWNERDEAD) { shmmap_mutex_consistent(&st->mutex); return shmmap_state_get(st); } printf("pthread_mutex_lock fatal(%d): %s.\n", err, strerror(err)); SHMMAP_VERIFY_STATE(val); return val; } NOWARNING_UNUSED(static) size_t shmmap_state_set (shmmap_state_t *st, size_t newval) { size_t oldval = SHMMAP_INVALID_STATE; int err = pthread_mutex_lock(&st->mutex); if (! err) { oldval = st->state; st->state = newval; pthread_mutex_unlock(&st->mutex); return oldval; } else if (err == EOWNERDEAD) { shmmap_mutex_consistent(&st->mutex); return shmmap_state_set(st, newval); } printf("pthread_mutex_lock fatal(%d): %s.\n", err, strerror(err)); SHMMAP_VERIFY_STATE(oldval); return oldval; } NOWARNING_UNUSED(static) size_t shmmap_state_comp_exch (shmmap_state_t *st, size_t comp, size_t exch) { size_t oldval = SHMMAP_INVALID_STATE; int err = pthread_mutex_lock(&st->mutex); if (! err) { oldval = st->state; if (st->state == comp) { st->state = exch; } pthread_mutex_unlock(&st->mutex); return oldval; } else if (err == EOWNERDEAD) { shmmap_mutex_consistent(&st->mutex); return shmmap_state_comp_exch(st, comp, exch); } printf("pthread_mutex_lock fatal(%d): %s.\n", err, strerror(err)); SHMMAP_VERIFY_STATE(oldval); return oldval; } typedef struct _shmmap_semaphore_t { pthread_mutex_t lock; pthread_cond_t nonzero; ssize_t count; } shmmap_semaphore_t, *shmmap_semaphore; NOWARNING_UNUSED(static) void shmmap_semaphore_init (shmmap_semaphore_t *semap) { pthread_mutexattr_t mattr; pthread_condattr_t cattr; int err = pthread_mutexattr_init(&mattr); if (err) { printf("(shmmap.h:%d) pthread_mutexattr_init error(%d): %s.\n", __LINE__, err, strerror(err)); exit(EXIT_FAILURE); } err = pthread_condattr_init(&cattr); if (err) { printf("(shmmap.h:%d) pthread_condattr_init error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&mattr); exit(EXIT_FAILURE); } err = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); if (err) { printf("(shmmap.h:%d) pthread_mutexattr_setpshared error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&mattr); pthread_condattr_destroy(&cattr); exit(EXIT_FAILURE); } err = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST); if (err) { printf("(shmmap.h:%d) pthread_mutexattr_setrobust error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&mattr); pthread_condattr_destroy(&cattr); exit(EXIT_FAILURE); } err = pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED); if (err) { printf("(shmmap.h:%d) pthread_condattr_setpshared error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&mattr); pthread_condattr_destroy(&cattr); exit(EXIT_FAILURE); } err = pthread_mutex_init(&semap->lock, &mattr); if (err) { printf("(shmmap.h:%d) pthread_mutex_init error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&mattr); pthread_condattr_destroy(&cattr); exit(EXIT_FAILURE); } err = pthread_cond_init(&semap->nonzero, &cattr); if (err) { printf("(shmmap.h:%d) pthread_cond_init error(%d): %s.\n", __LINE__, err, strerror(err)); pthread_mutexattr_destroy(&mattr); pthread_condattr_destroy(&cattr); pthread_mutex_destroy(&semap->lock); exit(EXIT_FAILURE); } /* success */ semap->count = 0; } NOWARNING_UNUSED(static) int shmmap_semaphore_lock (shmmap_semaphore_t * semap, size_t timeout_us) { if (timeout_us == SHMMAP_TIMEOUT_NOWAIT) { return pthread_mutex_trylock(&semap->lock); } else if (timeout_us == SHMMAP_TIMEOUT_INFINITE) { return pthread_mutex_lock(&semap->lock); } else { struct timespec now, abstime; shmmap_gettimeofday(&now); abstime.tv_sec = now.tv_sec + timeout_us / 1000000UL; abstime.tv_nsec = now.tv_nsec + (timeout_us % 1000000UL) * 1000UL; return pthread_mutex_timedlock(&semap->lock, &abstime); } } NOWARNING_UNUSED(static) int shmmap_semaphore_post (shmmap_semaphore_t * semap, size_t timeout_us) { int err = shmmap_semaphore_lock(semap, timeout_us); if (! err) { if (semap->count == 0) { pthread_cond_signal(&semap->nonzero); } semap->count++; return pthread_mutex_unlock(&semap->lock); } else if (err == EOWNERDEAD) { shmmap_mutex_consistent(&semap->lock); return shmmap_semaphore_post(semap, timeout_us); } else if (err == EEXIST) { /* DO NOTHING ! */ } else if (err != EBUSY && err != ETIMEDOUT) { /* SHOULD NEVER RUN TO THIS! */ perror("pthread_mutex_lock"); } return err; } NOWARNING_UNUSED(static) int shmmap_semaphore_wait (shmmap_semaphore_t * semap, size_t timeout_us) { int err = shmmap_semaphore_lock(semap, timeout_us); if (! err) { while (semap->count == 0) { if (timeout_us == SHMMAP_TIMEOUT_INFINITE) { pthread_cond_wait(&semap->nonzero, &semap->lock); continue; } else { struct timespec now, abstime; shmmap_gettimeofday(&now); abstime.tv_sec = now.tv_sec + timeout_us / 1000000UL; abstime.tv_nsec = now.tv_nsec + (timeout_us % 1000000UL) * 1000UL; pthread_cond_timedwait(&semap->nonzero, &semap->lock, &abstime); break; } } if (semap->count > 0) { semap->count--; } return pthread_mutex_unlock(&semap->lock); } else if (err == EOWNERDEAD) { shmmap_mutex_consistent(&semap->lock); return shmmap_semaphore_wait(semap, timeout_us); } else if (err == EEXIST) { /* DO NOTHING ! */ } else if (err != EBUSY && err != ETIMEDOUT) { /* can go here */ perror("pthread_mutex_lock"); } return err; } /** * shared memory mmap file with a layout of ring buffer. * See also: * https://github.com/pepstack/clogger/blob/master/src/ringbuf.h */ typedef struct _shmmap_buffer_t { /** * total size in bytes for this shmmap file * struct _shmmap_buffer_t *this; * shmfilesize = sizeof(*this) + this->Length */ size_t shmfilesize; /** * magic ^ token => cipher * cipher ^ token == magic */ ub8token_t magic; ub8token_t cipher; /** * https://linux.die.net/man/3/pthread_mutexattr_init */ shmmap_semaphore_t semaphore; /** * RingBuffer * * Length(L) = 10, Read(R), Write(W), wrap= 0 or 1 * Space(S) * * + R W + * |--+--+--+--+--+--+--+--+--+--|--|-- * 0 1 2 3 4 5 6 7 8 9 0 1 * * Sw = L - (fL + W - R), W - R < L * Sr = fL + W - R * * Sw > 0: writable * Sr > 0: readable */ /* Read Lock */ pthread_mutex_t RLock; /* Write Lock */ pthread_mutex_t WLock; /* Write Offset to the Buffer start */ shmmap_state_t WOffset; /* Read Offset to the Buffer start */ shmmap_state_t ROffset; /* Length of ring Buffer: total size in bytes */ size_t Length; /* ring buffer in shared memory with Length */ char Buffer[0]; } shmmap_buffer_t; #define SHMRINGBUF_RESTORE_WRAP(Ro, Wo, L) \ ((ssize_t)((Ro)/(L) == (Wo)/(L) ? 0 : 1)) #define SHMRINGBUF_RESTORE_STATE(Ro, Wo, L) \ ssize_t wrap = SHMRINGBUF_RESTORE_WRAP(Ro, Wo, L); \ ssize_t R = (ssize_t)((Ro) % (L)); \ ssize_t W = (ssize_t)((Wo) % (L)) #define SHMRINGBUF_NORMALIZE_OFFSET(Ao, L) \ ((((Ao)/(L))%2)*L + (Ao)%(L)) NOWARNING_UNUSED(static) int __shmmap_buffer_read_internal (shmmap_buffer_t *shmbuf, ssize_t wrap, ssize_t R, ssize_t W, ssize_t L, int (*nextentry_cb)(const shmmap_entry_t *, void *), void *arg); NOWARNING_UNUSED(static) void shmmap_buffer_close (shmmap_buffer_t *shmbuf) { size_t bsize = shmbuf->shmfilesize; munmap(shmbuf, bsize); } NOWARNING_UNUSED(static) int shmmap_buffer_delete (const char *shmfilename) { return shm_unlink(shmfilename); } NOWARNING_UNUSED(static) int shmmap_verify_token (shmmap_buffer_t *shmbuf, ub8token_t *token, ub8token_t (decipher_cb)(const ub8token_t, ub8token_t *)) { ub8token_t magic; if (! shmbuf->cipher) { /* true: cipher disabled */ return 1; } if (! token) { /* true: token not given */ return 0; } /* cipher and token are all given */ if (decipher_cb) { magic = decipher_cb(shmbuf->cipher, token); } else { magic = shmmap_decipher_token(shmbuf->cipher, token); } if (! memcmp(&magic, &shmbuf->magic, sizeof(shmbuf->magic))) { /* validate success when: magic == shmbuf->magic */ return 1; } /* validate failed */ return 0; } /** * shmmap_buffer_create() * Create if not exists or open an existing shmmap file. * * Params: * token - Point to a buffer with 8 bytes-length taken a plain token text. * Whether the content in token changes or not will depend on the * implementation of cipher_cb. * * cipher_cb - A cryptography callback provided by caller to generate an * encrypted cipher with 8 bytes-length from given token. * * Below sample creates a 4 MB encrypted shmmap buffer using token number: * * const char shmname[] = "shmmap-sample"; * char msgbuf[4096]; * ub8token_t token = <PASSWORD>; * size_t bsize = 4*1024*1024; * * // producer application * void produce (void) { * int wok; * shmmap_buffer_t *shmb; * * if (shmmap_buffer_create(&shmb, shmname, 0666, bsize, &token, 0, 0) == SHMMAP_CREATE_SUCCESS) { * wok = shmmap_buffer_write(shmb, "Hello Shmmap Sample", strlen("Hello Shmmap Sample")); * // ... * shmmap_buffer_close(shmb); * } * } * * // consumer application * void consume (void) { * size_t rdlen; * shmmap_buffer_t *shmb; * * if (shmmap_buffer_create(&shmb, shmname, 0666, 0, &token, 0, 0) == SHMMAP_CREATE_SUCCESS) { * rdlen = shmmap_buffer_read_copy(shmb, msgbuf, sizeof(msgbuf)); * // ... * shmmap_buffer_close(shmb); * } * } * * Returns: * see Returns of shmmap_buffer_create() in above */ NOWARNING_UNUSED(static) int shmmap_buffer_create (shmmap_buffer_t **outshmbuf, const char *shmfilename, mode_t filemode, size_t filesize, ub8token_t *token, ub8token_t (*encipher_cb)(const ub8token_t magic, ub8token_t *token), ub8token_t (*decipher_cb)(const ub8token_t magic, ub8token_t *token)) { shmmap_buffer_t *shmbuf; /* total size in bytes of shmmap file */ size_t mapfilesize = 0; /* aligned shared memory size as Length of ring buffer */ size_t bufferLength = 0; int err, fd, exist = 0; if (filesize == SHMMAP_INVALID_STATE) { return SHMMAP_CREATE_ERRSIZE; } fd = shm_open(shmfilename, O_RDWR|O_CREAT|O_EXCL, filemode); if (fd == -1 && errno == EEXIST) { fd = shm_open(shmfilename, O_RDWR|O_CREAT, filemode); exist = 1; } if (fd == -1) { perror("shm_open"); return SHMMAP_CREATE_ERROPEN; } if (! exist && ! filesize) { /* create a new one shmmap requires filesize */ close(fd); return SHMMAP_CREATE_ERRSIZE; } if (filesize) { bufferLength = SHMMAP_ALIGN_PAGESIZE(filesize); mapfilesize = SHMMAP_BUFFER_HDRSIZE + bufferLength; } if (exist) { shmbuf = (shmmap_buffer_t *) mmap(NULL, SHMMAP_BUFFER_HDRSIZE, PROT_READ, MAP_SHARED, fd, 0); if (! shmbuf) { perror("mmap"); close(fd); return SHMMAP_CREATE_ERRMMAP; } if (! filesize) { bufferLength = shmbuf->Length; mapfilesize = shmbuf->shmfilesize; } if (mapfilesize != shmbuf->shmfilesize || bufferLength != shmbuf->Length) { munmap(shmbuf, SHMMAP_BUFFER_HDRSIZE); close(fd); return SHMMAP_CREATE_ERRSIZE; } if (! shmmap_verify_token(shmbuf, token, decipher_cb)) { munmap(shmbuf, SHMMAP_BUFFER_HDRSIZE); close(fd); return SHMMAP_CREATE_ERRTOKEN; } munmap(shmbuf, SHMMAP_BUFFER_HDRSIZE); } if (! mapfilesize) { close(fd); return SHMMAP_CREATE_ERRSIZE; } err = ftruncate(fd, mapfilesize); if (err) { perror("ftruncate"); close(fd); return SHMMAP_CREATE_ERRTRUNC; } shmbuf = (shmmap_buffer_t *) mmap(NULL, mapfilesize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (! shmbuf) { perror("mmap"); close(fd); return SHMMAP_CREATE_ERRMMAP; } if (! exist) { randctx64 rctx; struct timespec now; __ub8_t seedus; bzero(shmbuf, mapfilesize); shmmap_gettimeofday(&now); seedus = now.tv_sec; seedus *= 1000000UL; seedus += (now.tv_nsec / 1000UL); randctx64_init(&rctx, seedus); shmbuf->magic = rand64_gen_int(&rctx, 0x0111111111111111, 0x1fffffffffffffff); if (token) { if (encipher_cb) { shmbuf->cipher = encipher_cb(shmbuf->magic, token); } else { shmbuf->cipher = shmmap_encipher_token(shmbuf->magic, token); } } shmmap_semaphore_init(&shmbuf->semaphore); process_shared_mutex_init(&shmbuf->RLock); process_shared_mutex_init(&shmbuf->WLock); shmmap_state_init(&shmbuf->WOffset, 0); shmmap_state_init(&shmbuf->ROffset, 0); shmbuf->Length = bufferLength; shmbuf->shmfilesize = mapfilesize; } if (! shmmap_verify_token(shmbuf, token, decipher_cb)) { munmap(shmbuf, mapfilesize); close(fd); return SHMMAP_CREATE_ERRTOKEN; } /* create or open success */ close(fd); *outshmbuf = shmbuf; return SHMMAP_CREATE_SUCCESS; } /** * shmmap_buffer_write() * Write chunk data of entry into shmmap ring buffer. * * Returns: * SHMMAP_WRITE_SUCCESS(1) - write success * SHMMAP_WRITE_AGAIN(0) - write again * SHMMAP_WRITE_FATAL(-1) - fatal write error */ NOWARNING_UNUSED(static) int shmmap_buffer_write (shmmap_buffer_t *shmbuf, const void *chunk, size_t chunksz) { shmmap_entry_t *entry; ssize_t Ro, Wo, L = (ssize_t)shmbuf->Length, AENTSZ = (ssize_t)SHMMAP_ALIGN_ENTRYSIZE(chunksz); if (! AENTSZ || AENTSZ == SHMMAP_INVALID_STATE || AENTSZ > (L / SHMMAP_ENTRY_HDRSIZE)) { /* fatal error should not occurred! */ # ifdef SHMMAP_TRACE_PRINT_ON printf("(shmmap.h:%d) fatal error: invalid chunksz(=%" PRIu64").\n", __LINE__, chunksz); # endif return SHMMAP_WRITE_FATAL; } if (process_shared_mutex_lock(&shmbuf->WLock, 1) == 0) { /* Get original ROffset */ Ro = shmmap_state_get(&shmbuf->ROffset); Wo = shmbuf->WOffset.state; SHMRINGBUF_RESTORE_STATE(Ro, Wo, L); # ifdef SHMMAP_TRACE_PRINT_ON if (wrap) { printf("(shmmap.h:%d) shmmap_buffer_write(%" PRIu64":%" PRIu64"): W=%" PRId64" R=%" PRId64" L=%" PRId64"\n", __LINE__, chunksz, AENTSZ, W, R, L); } else { printf("(shmmap.h:%d) shmmap_buffer_write(%" PRIu64":%" PRIu64"): R=%" PRId64" W=%" PRId64" L=%" PRId64"\n", __LINE__, chunksz, AENTSZ, R, W, L); } # endif /* Sw = L - (wrap*L + W - R) */ if (L - (wrap*L + W - R) >= AENTSZ) { if (wrap) { /* wrap(1): 0 .. W < R < L */ entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[W]); entry->size = chunksz; memcpy(entry->chunk, chunk, chunksz); /* WOffset = Wo + AENTSZ */ W = SHMRINGBUF_NORMALIZE_OFFSET(Wo + AENTSZ, L); shmmap_state_set(&shmbuf->WOffset, W); } else { /* wrap(0): 0 .. R < W < L */ if (L - W >= AENTSZ) { entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[W]); entry->size = chunksz; memcpy(entry->chunk, chunk, chunksz); /* WOffset = Wo + AENTSZ */ W = SHMRINGBUF_NORMALIZE_OFFSET(Wo + AENTSZ, L); shmmap_state_set(&shmbuf->WOffset, W); } else if (R - 0 >= AENTSZ) { /* clear W slot before wrap W */ bzero(&shmbuf->Buffer[W], L - W); /* wrap W to 0 */ entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[0]); entry->size = chunksz; memcpy(entry->chunk, chunk, chunksz); /* WOffset = AENTSZ, wrap = 1 */ W = AENTSZ + (1 - (int)(Ro/L))*L; shmmap_state_set(&shmbuf->WOffset, W); } else { /* no space left to write, expect to call again */ process_shared_mutex_unlock(&shmbuf->WLock); return SHMMAP_WRITE_AGAIN; } } process_shared_mutex_unlock(&shmbuf->WLock); return SHMMAP_WRITE_SUCCESS; } /* no space left to write */ process_shared_mutex_unlock(&shmbuf->WLock); return SHMMAP_WRITE_AGAIN; } /* lock fail to write, expect to call again */ return SHMMAP_WRITE_AGAIN; } /** * shmmap_buffer_read_copy() * Copy entry from shmmap ringbuffer into rdbuf. * * returns: * SHMMAP_READ_AGAIN(0) - read again * SHMMAP_READ_FATAL(-1) - fatal read error * * ret > 0 and ret <= rdbufsz - read success * ret > rdbufsz - no read for insufficient buffer */ NOWARNING_UNUSED(static) size_t shmmap_buffer_read_copy (shmmap_buffer_t *shmbuf, char *rdbuf, size_t rdbufsz) { shmmap_entry_t *entry; ssize_t Ro, Wo, entsize, AENTSZ, L = (ssize_t)shmbuf->Length, HENTSZ = (ssize_t)SHMMAP_ALIGN_ENTRYSIZE(0); if (process_shared_mutex_lock(&shmbuf->RLock, 1) == 0) { Wo = shmmap_state_get(&shmbuf->WOffset); Ro = shmbuf->ROffset.state; SHMRINGBUF_RESTORE_STATE(Ro, Wo, L); # ifdef SHMMAP_TRACE_PRINT_ON if (wrap) { printf("(shmmap.h:%d) shmmap_buffer_read_copy(): W=%" PRId64" R=%" PRId64" L=%" PRId64"\n", __LINE__, W, R, L); } else { printf("(shmmap.h:%d) shmmap_buffer_read_copy(): R=%" PRId64" W=%" PRId64" L=%" PRId64"\n", __LINE__, R, W, L); } # endif /* Sr = f*L + W - R */ if (wrap*L + W - R > HENTSZ) { if (wrap) { /* wrap(1): 0 .. W < R < L */ if (L - R > HENTSZ) { entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMAP_ALIGN_ENTRYSIZE(entry->size); if (L - R >= AENTSZ) { entsize = entry->size; if (entsize > rdbufsz) { /* read buf is insufficient for entry. * read nothing if returned entsize > rdbufsz */ process_shared_mutex_unlock(&shmbuf->RLock); return (size_t)entsize; } /* read entry chunk into rdbuf ok */ memcpy(rdbuf, entry->chunk, entsize); R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmap_state_set(&shmbuf->ROffset, R); /* read success if returned entsize <= rdbufsz */ process_shared_mutex_unlock(&shmbuf->RLock); return (size_t)entsize; } printf("(shmmap.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); process_shared_mutex_unlock(&shmbuf->RLock); return SHMMAP_READ_FATAL; } else { /* reset ROffset to 0 (set wrap = 0) */ shmmap_state_set(&shmbuf->ROffset, (Wo/L) * L); /* expect to read again */ process_shared_mutex_unlock(&shmbuf->RLock); return shmmap_buffer_read_copy(shmbuf, rdbuf, rdbufsz); } } else if (W - 0 > HENTSZ) { /* reset ROffset to 0 */ entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[0]); if (entry->size) { AENTSZ = SHMMAP_ALIGN_ENTRYSIZE(entry->size); if (W - 0 >= AENTSZ) { entsize = entry->size; if (entsize > rdbufsz) { /* read buf is insufficient for entry. * read nothing if returned entsize > rdbufsz */ process_shared_mutex_unlock(&shmbuf->RLock); return (size_t)entsize; } /* read entry chunk into rdbuf ok */ memcpy(rdbuf, entry->chunk, entsize); /* ROffset = AENTSZ, wrap = 0 */ shmmap_state_set(&shmbuf->ROffset, AENTSZ + (Wo/L)*L); /* read success if returned entsize <= rdbufsz */ process_shared_mutex_unlock(&shmbuf->RLock); return (size_t)entsize; } } printf("(shmmap.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); process_shared_mutex_unlock(&shmbuf->RLock); return SHMMAP_READ_FATAL; } } else { /* wrap(0): 0 .. R < W < L */ entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMAP_ALIGN_ENTRYSIZE(entry->size); if (W - R >= AENTSZ) { entsize = entry->size; if (entsize > rdbufsz) { /* read buf is insufficient for entry. * read nothing if returned entsize > rdbufsz */ process_shared_mutex_unlock(&shmbuf->RLock); return (size_t)entsize; } /* read entry chunk into rdbuf ok */ memcpy(rdbuf, entry->chunk, entsize); R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmap_state_set(&shmbuf->ROffset, R); /* read success if returned entsize <= rdbufsz */ process_shared_mutex_unlock(&shmbuf->RLock); return (size_t)entsize; } } printf("(shmmap.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); process_shared_mutex_unlock(&shmbuf->RLock); return SHMMAP_READ_FATAL; } } /* no entry to read, retry again */ process_shared_mutex_unlock(&shmbuf->RLock); return SHMMAP_READ_AGAIN; } /* read locked fail, retry again */ return SHMMAP_READ_AGAIN; } /** * shmmap_buffer_read_next() * Read next one entry from shmmap ring buffer into callback (no copy data). * * params: * nextentry_cb() - Callback implemented by caller should ONLY * return SHMMAP_READ_NEXT(1) or SHMMAP_READ_AGAIN(0) * DO NOT change and members of entry in nextentry_cb(). * returns: * SHMMAP_READ_NEXT(1) - read for next one * SHMMAP_READ_AGAIN(0) - read current one again * SHMMAP_READ_FATAL(-1) - fatal read error */ NOWARNING_UNUSED(static) int shmmap_buffer_read_next (shmmap_buffer_t *shmbuf, int (*nextentry_cb)(const shmmap_entry_t *entry, void *arg), void *arg) { int ret = SHMMAP_READ_AGAIN; if (process_shared_mutex_lock(&shmbuf->RLock, 1) == 0) { ssize_t Wo = shmmap_state_get(&shmbuf->WOffset); ssize_t Ro = shmbuf->ROffset.state; ssize_t wrap = SHMRINGBUF_RESTORE_WRAP(Ro, Wo, shmbuf->Length); ret = __shmmap_buffer_read_internal(shmbuf, wrap, Ro, Wo, (ssize_t)shmbuf->Length, nextentry_cb, arg); process_shared_mutex_unlock(&shmbuf->RLock); } return ret; } /** * shmmap_buffer_read_next_batch() * Read next batch entries from shmmap ring buffer into callback (no copy data). */ NOWARNING_UNUSED(static) int shmmap_buffer_read_next_batch (shmmap_buffer_t *shmbuf, int (*nextentry_cb)(const shmmap_entry_t *entry, void *arg), void *arg, int batch) { int num = 0, ret = SHMMAP_READ_AGAIN; if (process_shared_mutex_lock(&shmbuf->RLock, 1) == 0) { ssize_t wrap, Wo, Ro; while (batch-- > 0) { Wo = shmmap_state_get(&shmbuf->WOffset); Ro = shmbuf->ROffset.state; wrap = SHMRINGBUF_RESTORE_WRAP(Ro, Wo, shmbuf->Length); ret = __shmmap_buffer_read_internal(shmbuf, wrap, Ro, Wo, (ssize_t)shmbuf->Length, nextentry_cb, arg); if (ret == SHMMAP_READ_NEXT) { num++; continue; } if (ret == SHMMAP_READ_AGAIN) { /* stop current batch */ break; } if (ret == SHMMAP_READ_FATAL) { num = (int) SHMMAP_READ_FATAL; break; } /* SHOULD NEVER RUN TO THIS ! */ } process_shared_mutex_unlock(&shmbuf->RLock); } return num; } NOWARNING_UNUSED(static) int shmmap_buffer_post (shmmap_buffer_t *shmbuf, size_t timeout_us) { return shmmap_semaphore_post(&shmbuf->semaphore, timeout_us); } NOWARNING_UNUSED(static) int shmmap_buffer_wait (shmmap_buffer_t *shmbuf, size_t timeout_us) { return shmmap_semaphore_wait(&shmbuf->semaphore, timeout_us); } /** * shmmap_buffer_force_unlock() * Force unlock state lock. statelock can be one or combination of below: * * SHMMAP_READSTATE_LOCK * SHMMAP_WRITESTATE_LOCK * NOTES: * Make sure prior to force unlocking statelock, all the applications using * the same shmmap file should be paused! */ #define SHMMAP_READSTATE_LOCK 1 #define SHMMAP_WRITESTATE_LOCK 2 NOWARNING_UNUSED(static) void shmmap_buffer_force_unlock (shmmap_buffer_t *shmbuf, int statelock) { if (SHMMAP_READSTATE_LOCK & statelock) { process_shared_mutex_unlock(&shmbuf->RLock); } if (SHMMAP_WRITESTATE_LOCK & statelock) { process_shared_mutex_unlock(&shmbuf->WLock); } } /** * __shmmap_buffer_read_internal() * Private function. do not call it in your code !! */ int __shmmap_buffer_read_internal (shmmap_buffer_t *shmbuf, ssize_t wrap, ssize_t Ro, ssize_t Wo, ssize_t L, int (*nextentry_cb)(const shmmap_entry_t *, void *), void *arg) { shmmap_entry_t *entry; ssize_t AENTSZ, HENTSZ = (ssize_t)SHMMAP_ALIGN_ENTRYSIZE(0); ssize_t R = Ro % L; ssize_t W = Wo % L; # ifdef SHMMAP_TRACE_PRINT_ON if (wrap) { printf("(shmmap.h:%d) shmmap_buffer_read_next(): W=%" PRId64" R=%" PRId64" L=%" PRId64"\n", __LINE__, W, R, L); } else { printf("(shmmap.h:%d) shmmap_buffer_read_next(): R=%" PRId64" W=%" PRId64" L=%" PRId64"\n", __LINE__, R, W, L); } # endif /* Sr = f*L + W - R */ if (wrap*L + W - R > HENTSZ) { if (wrap) { /* wrap(1): 0 .. W < R < L */ if (L - R > HENTSZ) { entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMAP_ALIGN_ENTRYSIZE(entry->size); if (L - R >= AENTSZ) { if (nextentry_cb(entry, arg)) { /* read success and set ROffset to next entry */ R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmap_state_set(&shmbuf->ROffset, R); return SHMMAP_READ_NEXT; } else { /* read paused by caller */ return SHMMAP_READ_AGAIN; } } printf("(shmmap.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); return SHMMAP_READ_FATAL; } else { /* reset ROffset to 0 (set wrap = 0) */ shmmap_state_set(&shmbuf->ROffset, (Wo/L) * L); return shmmap_buffer_read_next(shmbuf, nextentry_cb, arg); } } else if (W - 0 > HENTSZ) { /* reset ROffset to 0 */ entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[0]); if (entry->size) { AENTSZ = SHMMAP_ALIGN_ENTRYSIZE(entry->size); if (W - 0 >= AENTSZ) { if (nextentry_cb(entry, arg)) { /* read success and set ROffset to next entry */ shmmap_state_set(&shmbuf->ROffset, AENTSZ + (Wo/L)*L); return SHMMAP_READ_NEXT; } else { /* read paused by caller */ return SHMMAP_READ_AGAIN; } } } printf("(shmmap.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); return SHMMAP_READ_FATAL; } } else { /* wrap(0): 0 .. R < W < L */ entry = SHMMAP_ENTRY_CAST(&shmbuf->Buffer[R]); if (entry->size) { AENTSZ = SHMMAP_ALIGN_ENTRYSIZE(entry->size); if (W - R >= AENTSZ) { if (nextentry_cb(entry, arg)) { /* read success and set ROffset to next entry */ R = SHMRINGBUF_NORMALIZE_OFFSET(Ro + AENTSZ, L); shmmap_state_set(&shmbuf->ROffset, R); return SHMMAP_READ_NEXT; } else { /* read paused by caller */ return SHMMAP_READ_AGAIN; } } } printf("(shmmap.h:%d) SHOULD NEVER RUN TO THIS! fatal bug.\n", __LINE__); return SHMMAP_READ_FATAL; } } /* no entry to read, retry again */ return SHMMAP_READ_AGAIN; } #ifdef __cplusplus } #endif #endif /* SHMMAP_H__ */
pepstack/pytools
templates/%clib%/src/common/memord.h
<filename>templates/%clib%/src/common/memord.h /*********************************************************************** * ©2013-2016 <NAME>. * Distributed under the simplified BSD license (see the license file that * should have come with this header). * Uses Jeff Preshing's semaphore implementation (under the terms of its * separate zlib license, embedded below). * * Provides portable (VC++2010+, Intel ICC 13, GCC 4.7+, and anything C++11 compliant) implementation * of low-level memory barriers, plus a few semi-portable utility macros (for inlining and alignment). * Also has a basic atomic type (limited to hardware-supported atomics with no memory ordering guarantees). * Uses the AE_* prefix for macros (historical reasons), and the "moodycamel" namespace for symbols. **********************************************************************/ /** * @filename memord.h * Memory Order operations both for Windows and Linux. * https://git.project-hobbit.eu/dj16/ricec/raw/c9d3dceb1c3b1c03a42077e0461e3ce5a2615a51/data/atomicops.h * https://github.com/preshing/cpp11-on-multicore/blob/master/common/sema.h * https://www.cnblogs.com/lizhanzhe/p/10893016.html * @author <NAME> * @version 1.0.0 * @create 2020-12-08 10:46:50 * @update 2021-07-20 13:12:10 */ #ifndef _MEMORY_ORDER_H_ #define _MEMORY_ORDER_H_ #if defined(__cplusplus) extern "C" { #endif #include <assert.h> /* Platform detection */ #if defined(__INTEL_COMPILER) # define AE_ICC #elif defined(_MSC_VER) # define AE_VCPP #elif defined(__GNUC__) # define AE_GCC #endif #if defined(_M_IA64) || defined(__ia64__) # define AE_ARCH_IA64 #elif defined(_WIN64) || defined(__amd64__) || defined(_M_X64) || defined(__x86_64__) # define AE_ARCH_X64 #elif defined(_M_IX86) || defined(__i386__) # define AE_ARCH_X86 #elif defined(_M_PPC) || defined(__powerpc__) # define AE_ARCH_PPC #else # define AE_ARCH_UNKNOWN #endif #ifndef NOWARNING_UNUSED # if defined(__GNUC__) || defined(__CYGWIN__) # define NOWARNING_UNUSED(x) __attribute__((unused)) x # else # define NOWARNING_UNUSED(x) x # endif #endif #ifndef STATIC_INLINE # if defined(_MSC_VER) # define STATIC_INLINE NOWARNING_UNUSED(static) __forceinline # elif defined(__GNUC__) || defined(__CYGWIN__) # define STATIC_INLINE NOWARNING_UNUSED(static) __attribute__((always_inline)) inline # else # define STATIC_INLINE NOWARNING_UNUSED(static) # endif #endif /* AE_ALIGN */ #if defined(AE_VCPP) || defined(AE_ICC) # define AE_ALIGN(x) __declspec(align(x)) #elif defined(AE_GCC) # define AE_ALIGN(x) __attribute__((aligned(x))) #else /* Assume GCC compliant syntax... */ # define AE_ALIGN(x) __attribute__((aligned(x))) #endif /* Portable atomic fences implemented below */ typedef enum { memory_order_relaxed, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst, /** * memory_order_sync * Forces a full sync: * #LoadLoad, #LoadStore, #StoreStore, and most significantly, #StoreLoad */ memory_order_sync = memory_order_seq_cst } memory_order; #if defined(AE_VCPP) || defined(AE_ICC) // VS2010 and ICC13 don't support std::atomic_*_fence, implement our own fences # include <intrin.h> #if defined(AE_ARCH_X64) || defined(AE_ARCH_X86) # define AeFullSync _mm_mfence # define AeLiteSync _mm_mfence #elif defined(AE_ARCH_IA64) # define AeFullSync __mf # define AeLiteSync __mf #elif defined(AE_ARCH_PPC) # include <ppcintrinsics.h> # define AeFullSync __sync # define AeLiteSync __lwsync #endif #ifdef AE_VCPP # pragma warning(push) // Disable erroneous 'conversion from long to unsigned int, signed/unsigned mismatch' error when using `assert` # pragma warning(disable: 4365) # ifdef __cplusplus_cli # pragma managed(push, off) # endif #endif STATIC_INLINE void __mo_compiler_fence(memory_order order) { switch (order) { case memory_order_relaxed: break; case memory_order_acquire: _ReadBarrier(); break; case memory_order_release: _WriteBarrier(); break; case memory_order_acq_rel: _ReadWriteBarrier(); break; case memory_order_seq_cst: _ReadWriteBarrier(); break; default: assert(0); } } /** * x86/x64 have a strong memory model -- all loads and stores have acquire and * release semantics automatically (so only need compiler barriers for those). */ #if defined(AE_ARCH_X86) || defined(AE_ARCH_X64) STATIC_INLINE void __mo_fence(memory_order order) { switch (order) { case memory_order_relaxed: break; case memory_order_acquire: _ReadBarrier(); break; case memory_order_release: _WriteBarrier(); break; case memory_order_acq_rel: _ReadWriteBarrier(); break; case memory_order_seq_cst: _ReadWriteBarrier(); AeFullSync(); _ReadWriteBarrier(); break; default: assert(0); break; } } #else STATIC_INLINE void __mo_fence(memory_order order) { // Non-specialized arch, use heavier memory barriers everywhere just in case :-( switch (order) { case memory_order_relaxed: break; case memory_order_acquire: _ReadBarrier(); AeLiteSync(); _ReadBarrier(); break; case memory_order_release: _WriteBarrier(); AeLiteSync(); _WriteBarrier(); break; case memory_order_acq_rel: _ReadWriteBarrier(); AeLiteSync(); _ReadWriteBarrier(); break; case memory_order_seq_cst: _ReadWriteBarrier(); AeFullSync(); _ReadWriteBarrier(); break; default: assert(0); break; } } #endif #elif defined(__cplusplus) // Use standard library of atomics for cpp # include <atomic> STATIC_INLINE void __mo_compiler_fence(memory_order order) { switch (order) { case memory_order_relaxed: break; case memory_order_acquire: std::atomic_signal_fence(std::memory_order_acquire); break; case memory_order_release: std::atomic_signal_fence(std::memory_order_release); break; case memory_order_acq_rel: std::atomic_signal_fence(std::memory_order_acq_rel); break; case memory_order_seq_cst: std::atomic_signal_fence(std::memory_order_seq_cst); break; default: assert(0); } } STATIC_INLINE void __mo_fence(memory_order order) { switch (order) { case memory_order_relaxed: break; case memory_order_acquire: std::atomic_thread_fence(std::memory_order_acquire); break; case memory_order_release: std::atomic_thread_fence(std::memory_order_release); break; case memory_order_acq_rel: std::atomic_thread_fence(std::memory_order_acq_rel); break; case memory_order_seq_cst: std::atomic_thread_fence(std::memory_order_seq_cst); break; default: assert(0); } } #endif #if defined(AE_VCPP) && (_MSC_VER < 1700 || defined(__cplusplus_cli)) # pragma warning(pop) # ifdef __cplusplus_cli # pragma managed(pop) # endif #endif #ifdef __cplusplus } #endif #endif /* _MEMORY_ORDER_H_ */
pepstack/pytools
templates/%clib%/src/common/refcobject.h
/*********************************************************************** * Copyright (c) 2008-2080 pepstack.com, <EMAIL> * * ALL RIGHTS RESERVED. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************/ /** * @filename refcobject.h * C reference count object api. * * @author <NAME> <<EMAIL>> * @version 0.0.2 * @create 2020-12-09 21:12:10 * @update 2021-07-20 12:23:00 */ #ifndef _REFC_OBJECT_H_ #define _REFC_OBJECT_H_ #if defined(__cplusplus) extern "C" { #endif #include "uatomic.h" #include "thread_rwlock.h" #define REFCOBJ_ALIGN_SIZE(sz) ((((size_t)(sz) + sizeof(void*) - sizeof(char))/sizeof(void*)) * sizeof(void*)) #define REFCOBJ_CAST_OBJ(pv) refc_object obj = (refc_object) pv; --obj typedef struct { void (*__final)(void *); ThreadRWLock_t __rwlock; uatomic_int __refc; int type; void *addr[0]; } refc_object_t, *refc_object; STATIC_INLINE void * refc_object_new (int type, size_t elemsz, void (*finalize)(void *)) { refc_object p = (refc_object) mem_alloc_zero(1, REFCOBJ_ALIGN_SIZE(sizeof(*p) + elemsz)); p->__refc = 1; p->__final = finalize; p->type = type; RWLockInit(&p->__rwlock); return p->addr; } STATIC_INLINE void* refc_object_inc (void **ppv) { refc_object p = (refc_object)(*ppv); if (p--) { if (uatomic_int_add(&p->__refc) > 0) { return (p->addr); } } return NULL; } STATIC_INLINE void refc_object_dec (void **ppv) { refc_object p = (refc_object)(*ppv); if (p--) { if (uatomic_int_sub(&p->__refc) <= 0) { *ppv = NULL; p->__final(p->addr); RWLockUninit(&p->__rwlock); mem_free(p); } } } STATIC_INLINE int refc_object_type (void *pv) { REFCOBJ_CAST_OBJ(pv); return obj->type; } /* lock for read only */ STATIC_INLINE int refc_object_lock_rd (void *pv, int istry) { REFCOBJ_CAST_OBJ(pv); return RWLockAcquire(&obj->__rwlock, RWLOCK_STATE_READ, istry); } /* unlock for read only */ STATIC_INLINE int refc_object_unlock_rd (void *pv) { REFCOBJ_CAST_OBJ(pv); return RWLockRelease(&obj->__rwlock, RWLOCK_STATE_READ); } /* lock for write and read */ STATIC_INLINE int refc_object_lock (void *pv, int istry) { REFCOBJ_CAST_OBJ(pv); return RWLockAcquire(&obj->__rwlock, RWLOCK_STATE_WRITE, istry); } /* unlock for write and read */ STATIC_INLINE int refc_object_unlock (void *pv) { REFCOBJ_CAST_OBJ(pv); return RWLockRelease(&obj->__rwlock, RWLOCK_STATE_WRITE); } #ifdef __cplusplus } #endif #endif /* _REFC_OBJECT_H_ */
pepstack/pytools
templates/%clib%/src/common/coroutine.h
<reponame>pepstack/pytools /* coroutine.h * * Coroutine mechanics, implemented on top of standard ANSI C. See * https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html for * a full discussion of the theory behind this. * * To use these macros to define a coroutine, you need to write a * function that looks something like this. * * [Simple version using static variables (scr macros)] * int ascending (void) { * static int i; * * scrBegin; * for (i=0; i<10; i++) { * scrReturn(i); * } * scrFinish(-1); * } * * [Re-entrant version using an explicit context structure (ccr macros)] * int ascending (ccrContParam) { * ccrBeginContext; * int i; * ccrEndContext(foo); * * ccrBegin(foo); * for (foo->i=0; foo->i<10; foo->i++) { * ccrReturn(foo->i); * } * ccrFinish(-1); * } * * In the static version, you need only surround the function body * with `scrBegin' and `scrFinish', and then you can do `scrReturn' * within the function and on the next call control will resume * just after the scrReturn statement. Any local variables you need * to be persistent across an `scrReturn' must be declared static. * * In the re-entrant version, you need to declare your persistent * variables between `ccrBeginContext' and `ccrEndContext'. These * will be members of a structure whose name you specify in the * parameter to `ccrEndContext'. * * The re-entrant macros will malloc() the state structure on first * call, and free() it when `ccrFinish' is reached. If you want to * abort in the middle, you can use `ccrStop' to free the state * structure immediately (equivalent to an explicit return() in a * caller-type routine). * * A coroutine returning void type may call `ccrReturnV', * `ccrFinishV' and `ccrStopV', or `scrReturnV', to avoid having to * specify an empty parameter to the ordinary return macros. * * Ground rules: * - never put `ccrReturn' or `scrReturn' within an explicit `switch'. * - never put two `ccrReturn' or `scrReturn' statements on the same * source line. * * The caller of a static coroutine calls it just as if it were an * ordinary function: * * void main(void) { * int i; * do { * i = ascending(); * printf("got number %d\n", i); * } while (i != -1); * } * * The caller of a re-entrant coroutine must provide a context * variable: * * void main(void) { * ccrContext z = 0; * do { * printf("got number %d\n", ascending (&z)); * } while (z); * } * * Note that the context variable is set back to zero when the * coroutine terminates (by crStop, or by control reaching * crFinish). This can make the re-entrant coroutines more useful * than the static ones, because you can tell when they have * finished. * * If you need to dispose of a crContext when it is non-zero (that * is, if you want to stop calling a coroutine without suffering a * memory leak), the caller should call `ccrAbort(ctx)' where `ctx' * is the context variable. * * This mechanism could have been better implemented using GNU C * and its ability to store pointers to labels, but sadly this is * not part of the ANSI C standard and so the mechanism is done by * case statements instead. That's why you can't put a crReturn() * inside a switch() statement. */ /* * coroutine.h is copyright 1995,2000 <NAME>. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL <NAME> BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * $Id$ */ #ifndef COROUTINE_H #define COROUTINE_H #include <stdlib.h> /** * MSVC: error C2051: case expression not constant __LINE__ * * Project -> C/C++/General -> Debug info format = /Zi (NOT ZI) */ /* * `scr' macros for static coroutines. */ #define scrBegin static int scrLine = 0; switch(scrLine) { case 0:; #define scrFinish(z) } return (z) #define scrFinishV } return #define scrReturn(z) \ do {\ scrLine=__LINE__;\ return (z); case __LINE__:;\ } while (0) #define scrReturnV \ do {\ scrLine=__LINE__;\ return; case __LINE__:;\ } while (0) /* * `ccr' macros for re-entrant coroutines. */ #define ccrContParam void **ccrParam #define ccrBeginContext struct ccrContextTag { int ccrLine #define ccrEndContext(x) } *x = (struct ccrContextTag *)*ccrParam #define ccrBegin(x) if(!x) {x= *ccrParam=malloc(sizeof(*x)); x->ccrLine=0;}\ if (x) switch(x->ccrLine) { case 0:; #define ccrFinish(z) } free(*ccrParam); *ccrParam=0; return (z) #define ccrFinishV } free(*ccrParam); *ccrParam=0; return #define ccrReturn(z) \ do {\ ((struct ccrContextTag *)*ccrParam)->ccrLine=__LINE__;\ return (z); case __LINE__:;\ } while (0) #define ccrReturnV \ do {\ ((struct ccrContextTag *)*ccrParam)->ccrLine=__LINE__;\ return; case __LINE__:;\ } while (0) #define ccrStop(z) do{ free(*ccrParam); *ccrParam=0; return (z); }while(0) #define ccrStopV do{ free(*ccrParam); *ccrParam=0; return; }while(0) #define ccrContext void * #define ccrAbort(ctx) do { free (ctx); ctx = 0; } while (0) #endif /* COROUTINE_H */
crnbaker/MONAI
monai/csrc/utils/tensor_description.h
<reponame>crnbaker/MONAI #include <torch/extension.h> // Struct to easily cache descriptive information about a tensor. // This is helpful as regular calls to the size and stride member // functions of tensors appear to cause memory issues. struct TensorDescription { public: TensorDescription(torch::Tensor tensor) { batchCount = tensor.size(0); batchStride = tensor.stride(0); channelCount = tensor.size(1); channelStride = tensor.stride(1); dimensions = tensor.dim() - 2; sizes = new int[dimensions]; strides = new int[dimensions]; for (int i = 0; i < dimensions; i++) { sizes[i] = tensor.size(i + 2); strides[i] = tensor.stride(i + 2); } } ~TensorDescription() { delete[] sizes; delete[] strides; } int batchCount; int batchStride; int channelCount; int channelStride; int dimensions; int* sizes; int* strides; };
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-TCP/FreeRTOS_UDP_IP.c
/* * FreeRTOS+TCP 2.2.x Labs copy * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /* Standard includes. */ #include <stdint.h> #include <stdio.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" #include "FreeRTOS_IP_Private.h" #include "FreeRTOS_UDP_IP.h" #include "FreeRTOS_ARP.h" #include "FreeRTOS_DHCP.h" #include "NetworkInterface.h" #include "NetworkBufferManagement.h" #if( ipconfigUSE_DNS == 1 ) #include "FreeRTOS_DNS.h" #endif /* The expected IP version and header length coded into the IP header itself. */ #define ipIP_VERSION_AND_HEADER_LENGTH_BYTE ( ( uint8_t ) 0x45 ) /* Part of the Ethernet and IP headers are always constant when sending an IPv4 UDP packet. This array defines the constant parts, allowing this part of the packet to be filled in using a simple memcpy() instead of individual writes. */ UDPPacketHeader_t xDefaultPartUDPPacketHeader = { /* .ucBytes : */ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Ethernet source MAC address. */ 0x08, 0x00, /* Ethernet frame type. */ ipIP_VERSION_AND_HEADER_LENGTH_BYTE, /* ucVersionHeaderLength. */ 0x00, /* ucDifferentiatedServicesCode. */ 0x00, 0x00, /* usLength. */ 0x00, 0x00, /* usIdentification. */ 0x00, 0x00, /* usFragmentOffset. */ ipconfigUDP_TIME_TO_LIVE, /* ucTimeToLive */ ipPROTOCOL_UDP, /* ucProtocol. */ 0x00, 0x00, /* usHeaderChecksum. */ 0x00, 0x00, 0x00, 0x00 /* Source IP address. */ } }; /*-----------------------------------------------------------*/ void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ) { UDPPacket_t *pxUDPPacket; IPHeader_t *pxIPHeader; eARPLookupResult_t eReturned; uint32_t ulIPAddress = pxNetworkBuffer->ulIPAddress; size_t uxPayloadSize; /* Map the UDP packet onto the start of the frame. */ pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer; #if ipconfigSUPPORT_OUTGOING_PINGS == 1 if( pxNetworkBuffer->usPort == ipPACKET_CONTAINS_ICMP_DATA ) { uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( ICMPPacket_t ); } else #endif { uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ); } /* Determine the ARP cache status for the requested IP address. */ eReturned = eARPGetCacheEntry( &( ulIPAddress ), &( pxUDPPacket->xEthernetHeader.xDestinationAddress ) ); if( eReturned != eCantSendPacket ) { if( eReturned == eARPCacheHit ) { #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) uint8_t ucSocketOptions; #endif iptraceSENDING_UDP_PACKET( pxNetworkBuffer->ulIPAddress ); /* Create short cuts to the data within the packet. */ pxIPHeader = &( pxUDPPacket->xIPHeader ); #if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) /* Is it possible that the packet is not actually a UDP packet after all, but an ICMP packet. */ if( pxNetworkBuffer->usPort != ipPACKET_CONTAINS_ICMP_DATA ) #endif /* ipconfigSUPPORT_OUTGOING_PINGS */ { UDPHeader_t *pxUDPHeader; pxUDPHeader = &( pxUDPPacket->xUDPHeader ); pxUDPHeader->usDestinationPort = pxNetworkBuffer->usPort; pxUDPHeader->usSourcePort = pxNetworkBuffer->usBoundPort; pxUDPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( UDPHeader_t ) ); pxUDPHeader->usLength = FreeRTOS_htons( pxUDPHeader->usLength ); pxUDPHeader->usChecksum = 0u; } /* memcpy() the constant parts of the header information into the correct location within the packet. This fills in: xEthernetHeader.xSourceAddress xEthernetHeader.usFrameType xIPHeader.ucVersionHeaderLength xIPHeader.ucDifferentiatedServicesCode xIPHeader.usLength xIPHeader.usIdentification xIPHeader.usFragmentOffset xIPHeader.ucTimeToLive xIPHeader.ucProtocol and xIPHeader.usHeaderChecksum */ /* Save options now, as they will be overwritten by memcpy */ #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) ucSocketOptions = pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ]; #endif /* * Offset the memcpy by the size of a MAC address to start at the packet's * Ethernet header 'source' MAC address; the preceding 'destination' should not be altered. */ char *pxUdpSrcAddrOffset = ( char *) pxUDPPacket + sizeof( MACAddress_t ); memcpy( pxUdpSrcAddrOffset, xDefaultPartUDPPacketHeader.ucBytes, sizeof( xDefaultPartUDPPacketHeader ) ); #if ipconfigSUPPORT_OUTGOING_PINGS == 1 if( pxNetworkBuffer->usPort == ipPACKET_CONTAINS_ICMP_DATA ) { pxIPHeader->ucProtocol = ipPROTOCOL_ICMP; pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) ); } else #endif /* ipconfigSUPPORT_OUTGOING_PINGS */ { pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) ); } pxIPHeader->usLength = FreeRTOS_htons( pxIPHeader->usLength ); /* HT:endian: changed back to network endian */ pxIPHeader->ulDestinationIPAddress = pxNetworkBuffer->ulIPAddress; #if( ipconfigUSE_LLMNR == 1 ) { /* LLMNR messages are typically used on a LAN and they're * not supposed to cross routers */ if( pxNetworkBuffer->ulIPAddress == ipLLMNR_IP_ADDR ) { pxIPHeader->ucTimeToLive = 0x01; } } #endif #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) { pxIPHeader->usHeaderChecksum = 0u; pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0UL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER ); pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum ); if( ( ucSocketOptions & ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ) != 0u ) { usGenerateProtocolChecksum( (uint8_t*)pxUDPPacket, pxNetworkBuffer->xDataLength, pdTRUE ); } else { pxUDPPacket->xUDPHeader.usChecksum = 0u; } } #endif } else if( eReturned == eARPCacheMiss ) { /* Add an entry to the ARP table with a null hardware address. This allows the ARP timer to know that an ARP reply is outstanding, and perform retransmissions if necessary. */ vARPRefreshCacheEntry( NULL, ulIPAddress ); /* Generate an ARP for the required IP address. */ iptracePACKET_DROPPED_TO_GENERATE_ARP( pxNetworkBuffer->ulIPAddress ); pxNetworkBuffer->ulIPAddress = ulIPAddress; vARPGenerateRequestPacket( pxNetworkBuffer ); } else { /* The lookup indicated that an ARP request has already been sent out for the queried IP address. */ eReturned = eCantSendPacket; } } if( eReturned != eCantSendPacket ) { /* The network driver is responsible for freeing the network buffer after the packet has been sent. */ #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) { if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES ) { BaseType_t xIndex; for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ ) { pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0u; } pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; } } #endif xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE ); } else { /* The packet can't be sent (DHCP not completed?). Just drop the packet. */ vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); } } /*-----------------------------------------------------------*/ BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t *pxNetworkBuffer, uint16_t usPort ) { BaseType_t xReturn = pdPASS; FreeRTOS_Socket_t *pxSocket; configASSERT(pxNetworkBuffer); configASSERT(pxNetworkBuffer->pucEthernetBuffer); UDPPacket_t *pxUDPPacket = (UDPPacket_t *) pxNetworkBuffer->pucEthernetBuffer; /* Caller must check for minimum packet size. */ pxSocket = pxUDPSocketLookup( usPort ); if( pxSocket ) { /* When refreshing the ARP cache with received UDP packets we must be careful; hundreds of broadcast messages may pass and if we're not handling them, no use to fill the ARP cache with those IP addresses. */ vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); #if( ipconfigUSE_CALLBACKS == 1 ) { /* Did the owner of this socket register a reception handler ? */ if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleReceive ) ) { struct freertos_sockaddr xSourceAddress, destinationAddress; void *pcData = ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ); FOnUDPReceive_t xHandler = ( FOnUDPReceive_t ) pxSocket->u.xUDP.pxHandleReceive; xSourceAddress.sin_port = pxNetworkBuffer->usPort; xSourceAddress.sin_addr = pxNetworkBuffer->ulIPAddress; destinationAddress.sin_port = usPort; destinationAddress.sin_addr = pxUDPPacket->xIPHeader.ulDestinationIPAddress; /* The value of 'xDataLength' was proven to be at least the size of a UDP packet in prvProcessIPPacket(). */ if( xHandler( ( Socket_t ) pxSocket, ( void* ) pcData, ( size_t ) ( pxNetworkBuffer->xDataLength - ipUDP_PAYLOAD_OFFSET_IPv4 ), &xSourceAddress, &destinationAddress ) ) { xReturn = pdFAIL; /* FAIL means that we did not consume or release the buffer */ } } } #endif /* ipconfigUSE_CALLBACKS */ #if( ipconfigUDP_MAX_RX_PACKETS > 0 ) { if( xReturn == pdPASS ) { if ( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) >= pxSocket->u.xUDP.uxMaxPackets ) { FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket: buffer full %ld >= %ld port %u\n", listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ), pxSocket->u.xUDP.uxMaxPackets, pxSocket->usLocalPort ) ); xReturn = pdFAIL; /* we did not consume or release the buffer */ } } } #endif if( xReturn == pdPASS ) { vTaskSuspendAll(); { if( xReturn == pdPASS ) { taskENTER_CRITICAL(); { /* Add the network packet to the list of packets to be processed by the socket. */ vListInsertEnd( &( pxSocket->u.xUDP.xWaitingPacketsList ), &( pxNetworkBuffer->xBufferListItem ) ); } taskEXIT_CRITICAL(); } } xTaskResumeAll(); /* Set the socket's receive event */ if( pxSocket->xEventGroup != NULL ) { xEventGroupSetBits( pxSocket->xEventGroup, eSOCKET_RECEIVE ); } #if( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) { if( ( pxSocket->pxSocketSet != NULL ) && ( ( pxSocket->xSelectBits & eSELECT_READ ) != 0 ) ) { xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, eSELECT_READ ); } } #endif #if( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 ) { if( pxSocket->pxUserSemaphore != NULL ) { xSemaphoreGive( pxSocket->pxUserSemaphore ); } } #endif #if( ipconfigUSE_DHCP == 1 ) { if( xIsDHCPSocket( pxSocket ) ) { xSendEventToIPTask( eDHCPEvent ); } } #endif } } else { /* There is no socket listening to the target port, but still it might be for this node. */ #if( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 ) /* A DNS reply, check for the source port. Although the DNS client does open a UDP socket to send a messages, this socket will be closed after a short timeout. Messages that come late (after the socket is closed) will be treated here. */ if( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usSourcePort ) == ipDNS_PORT ) { vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); xReturn = ( BaseType_t )ulDNSHandlePacket( pxNetworkBuffer ); } else #endif #if( ipconfigUSE_LLMNR == 1 ) /* a LLMNR request, check for the destination port. */ if( ( usPort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) || ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) ) { vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); xReturn = ( BaseType_t )ulDNSHandlePacket( pxNetworkBuffer ); } else #endif /* ipconfigUSE_LLMNR */ #if( ipconfigUSE_NBNS == 1 ) /* a NetBIOS request, check for the destination port */ if( ( usPort == FreeRTOS_ntohs( ipNBNS_PORT ) ) || ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipNBNS_PORT ) ) ) { vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); xReturn = ( BaseType_t )ulNBNSHandlePacket( pxNetworkBuffer ); } else #endif /* ipconfigUSE_NBNS */ { xReturn = pdFAIL; } } return xReturn; } /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/Common/FreeRTOS_Plus_UDP_Demos/TraceMacros/Example1/DemoIPTrace.c
/* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* * This file, along with DemoIPTrace.h, provides a basic example use of the * FreeRTOS+UDP trace macros. The statistics gathered here can be viewed in * the command line interface. * See http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/UDP_IP_Trace.shtml */ /* Standard includes. */ #include <stdint.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" /* FreeRTOS+UDP includes. */ #include "FreeRTOS_UDP_IP.h" #include "DemoIPTrace.h" /* It is possible to remove the trace macros using the configINCLUDE_DEMO_DEBUG_STATS setting in FreeRTOSIPConfig.h. */ #if configINCLUDE_DEMO_DEBUG_STATS == 1 /* * Each row in the xIPTraceValues[] table contains a pointer to a function that * updates the value for that row. Rows that latch the lowest value point to * this function (for example, this function can be used to latch the lowest * number of network buffers that were available during the execution of the * stack). */ static void prvStoreLowest( uint32_t *pulCurrentValue, uint32_t ulCount ); /* * Each row in the xIPTraceValues[] table contains a pointer to a function that * updates the value for that row. Rows that simply increment an event count * point to this function. */ static void prvIncrementEventCount( uint32_t *pulCurrentValue, uint32_t ulCount ); xExampleDebugStatEntry_t xIPTraceValues[] = { /* Comment out array entries to remove individual trace items. */ { iptraceID_NETWORK_INTERFACE_RECEIVE, ( const uint8_t * const ) "Packets received by the network interface", prvIncrementEventCount, 0 }, { iptraceID_NETWORK_INTERFACE_TRANSMIT, ( const uint8_t * const ) "Count of transmitted packets", prvIncrementEventCount, 0 }, { iptraceID_PACKET_DROPPED_TO_GENERATE_ARP, ( const uint8_t * const ) "Count of packets dropped to generate ARP", prvIncrementEventCount, 0 }, { iptraceID_NETWORK_BUFFER_OBTAINED, ( const uint8_t * const ) "Lowest ever available network buffers", prvStoreLowest, 0xffffUL }, { iptraceID_NETWORK_EVENT_RECEIVED, ( const uint8_t * const ) "Lowest ever free space in network event queue", prvStoreLowest, 0xffffUL }, { iptraceID_FAILED_TO_OBTAIN_NETWORK_BUFFER, ( const uint8_t * const ) "Count of failed attempts to obtain a network buffer",prvIncrementEventCount, 0 }, { iptraceID_ARP_TABLE_ENTRY_EXPIRED, ( const uint8_t * const ) "Count of expired ARP entries", prvIncrementEventCount, 0 }, { iptraceID_FAILED_TO_CREATE_SOCKET, ( const uint8_t * const ) "Count of failures to create a socket", prvIncrementEventCount, 0 }, { iptraceID_RECVFROM_DISCARDING_BYTES, ( const uint8_t * const ) "Count of times recvfrom() has discarding bytes", prvIncrementEventCount, 0 }, { iptraceID_ETHERNET_RX_EVENT_LOST, ( const uint8_t * const ) "Count of lost Ethenret Rx events (event queue full?)",prvIncrementEventCount, 0 }, { iptraceID_STACK_TX_EVENT_LOST, ( const uint8_t * const ) "Count of lost IP stack events (event queue full?)", prvIncrementEventCount, 0 }, { ipconfigID_BIND_FAILED, ( const uint8_t * const ) "Count of failed calls to bind()", prvIncrementEventCount, 0 }, { iptraceID_RECVFROM_TIMEOUT, ( const uint8_t * const ) "Count of receive timeouts", prvIncrementEventCount, 0 }, { iptraceID_SENDTO_DATA_TOO_LONG, ( const uint8_t * const ) "Count of failed sends due to oversized payload", prvIncrementEventCount, 0 }, { iptraceID_SENDTO_SOCKET_NOT_BOUND, ( const uint8_t * const ) "Count of failed sends due to unbound socket", prvIncrementEventCount, 0 }, { iptraceID_NO_BUFFER_FOR_SENDTO, ( const uint8_t * const ) "Count of failed transmits due to timeout", prvIncrementEventCount, 0 }, { iptraceID_WAIT_FOR_TX_DMA_DESCRIPTOR, ( const uint8_t * const ) "Number of times task had to wait to obtain a DMA Tx descriptor", prvIncrementEventCount, 0 }, { iptraceID_FAILED_TO_NOTIFY_SELECT_GROUP, ( const uint8_t * const ) "Failed to notify select group", prvIncrementEventCount, 0 } }; /*-----------------------------------------------------------*/ BaseType_t xExampleDebugStatEntries( void ) { /* Return the number of entries in the xIPTraceValues[] table. */ return ( BaseType_t ) ( sizeof( xIPTraceValues ) / sizeof( xExampleDebugStatEntry_t ) ); } /*-----------------------------------------------------------*/ void vExampleDebugStatUpdate( uint8_t ucIdentifier, uint32_t ulValue ) { BaseType_t xIndex; const BaseType_t xEntries = sizeof( xIPTraceValues ) / sizeof( xExampleDebugStatEntry_t ); /* Update an entry in the xIPTraceValues[] table. Each row in the table includes a pointer to a function that performs the actual update. This function just executes the update function from that table row. */ for( xIndex = 0; xIndex < xEntries; xIndex++ ) { if( xIPTraceValues[ xIndex ].ucIdentifier == ucIdentifier ) { xIPTraceValues[ xIndex ].vPerformAction( &( xIPTraceValues[ xIndex ].ulData ), ulValue ); break; } } configASSERT( xIndex != xEntries ); } /*-----------------------------------------------------------*/ static void prvIncrementEventCount( uint32_t *pulCurrentValue, uint32_t ulCount ) { /* Each row in the xIPTraceValues[] table contains a pointer to a function that updates the value for that row. Rows that simply increment an event count point to this function. */ ( void ) ulCount; ( *pulCurrentValue )++; } /*-----------------------------------------------------------*/ static void prvStoreLowest( uint32_t *pulCurrentValue, uint32_t ulCount ) { /* Each row in the xIPTraceValues[] table contains a pointer to a function that updates the value for that row. Rows that latch the lowest value point to this function (for example, this function can be used to latch the lowest number of network buffers that were available during the execution of the stack). */ if( ulCount < *pulCurrentValue ) { *pulCurrentValue = ulCount; } } /*-----------------------------------------------------------*/ #endif /* configINCLUDE_DEMO_DEBUG_STATS == 1 */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/shadow/src/aws_iot_shadow_static_memory.c
<reponame>MicroEJ/FreeRTOS /* * AWS IoT Shadow V2.1.0 * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_shadow_static_memory.c * @brief Implementation of Shadow static memory functions. */ /* The config header is always included first. */ #include "iot_config.h" /* This file should only be compiled if dynamic memory allocation is forbidden. */ #if IOT_STATIC_MEMORY_ONLY == 1 /* Standard includes. */ #include <stdbool.h> #include <stddef.h> #include <string.h> /* Static memory include. */ #include "iot_static_memory.h" /* Shadow internal include. */ #include "private/aws_iot_shadow_internal.h" /*-----------------------------------------------------------*/ /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Provide default values for undefined configuration constants. */ #ifndef AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS #define AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS ( 10 ) #endif #ifndef AWS_IOT_SHADOW_SUBSCRIPTIONS #define AWS_IOT_SHADOW_SUBSCRIPTIONS ( 2 ) #endif /** @endcond */ /* Validate static memory configuration settings. */ #if AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS <= 0 #error "AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS cannot be 0 or negative." #endif #if AWS_IOT_SHADOW_SUBSCRIPTIONS <= 0 #error "AWS_IOT_SHADOW_SUBSCRIPTIONS cannot be 0 or negative." #endif /** * @brief The size of a static memory Shadow subscription. * * Since the pThingName member of #_shadowSubscription_t is variable-length, * the constant `AWS_IOT_MAX_THING_NAME_LENGTH` is used for the length of * #_shadowSubscription_t.pThingName. */ #define SHADOW_SUBSCRIPTION_SIZE ( sizeof( _shadowSubscription_t ) + AWS_IOT_MAX_THING_NAME_LENGTH ) /*-----------------------------------------------------------*/ /* * Static memory buffers and flags, allocated and zeroed at compile-time. */ static uint32_t _pInUseShadowOperations[ AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS ] = { 0U }; /**< @brief Shadow operation in-use flags. */ static _shadowOperation_t _pShadowOperations[ AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS ] = { { .link = { 0 } } }; /**< @brief Shadow operations. */ static uint32_t _pInUseShadowSubscriptions[ AWS_IOT_SHADOW_SUBSCRIPTIONS ] = { 0U }; /**< @brief Shadow subscription in-use flags. */ static char _pShadowSubscriptions[ AWS_IOT_SHADOW_SUBSCRIPTIONS ][ SHADOW_SUBSCRIPTION_SIZE ] = { { 0 } }; /**< @brief Shadow subscriptions. */ /*-----------------------------------------------------------*/ void * AwsIotShadow_MallocOperation( size_t size ) { int32_t freeIndex = -1; void * pNewOperation = NULL; /* Check size argument. */ if( size == sizeof( _shadowOperation_t ) ) { /* Find a free Shadow operation. */ freeIndex = IotStaticMemory_FindFree( _pInUseShadowOperations, AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS ); if( freeIndex != -1 ) { pNewOperation = &( _pShadowOperations[ freeIndex ] ); } } return pNewOperation; } /*-----------------------------------------------------------*/ void AwsIotShadow_FreeOperation( void * ptr ) { /* Return the in-use Shadow operation. */ IotStaticMemory_ReturnInUse( ptr, _pShadowOperations, _pInUseShadowOperations, AWS_IOT_SHADOW_MAX_IN_PROGRESS_OPERATIONS, sizeof( _shadowOperation_t ) ); } /*-----------------------------------------------------------*/ void * AwsIotShadow_MallocSubscription( size_t size ) { int32_t freeIndex = -1; void * pNewSubscription = NULL; if( size <= SHADOW_SUBSCRIPTION_SIZE ) { /* Get the index of a free Shadow subscription. */ freeIndex = IotStaticMemory_FindFree( _pInUseShadowSubscriptions, AWS_IOT_SHADOW_SUBSCRIPTIONS ); if( freeIndex != -1 ) { pNewSubscription = &( _pShadowSubscriptions[ freeIndex ][ 0 ] ); } } return pNewSubscription; } /*-----------------------------------------------------------*/ void AwsIotShadow_FreeSubscription( void * ptr ) { /* Return the in-use Shadow subscription. */ IotStaticMemory_ReturnInUse( ptr, _pShadowSubscriptions, _pInUseShadowSubscriptions, AWS_IOT_SHADOW_SUBSCRIPTIONS, SHADOW_SUBSCRIPTION_SIZE ); } /*-----------------------------------------------------------*/ #endif
MicroEJ/FreeRTOS
FreeRTOS/Demo/CORTEX_LM3S811_GCC/microej/src/LLMJVM_stub.c
/* * C * * Copyright 2020 MicroEJ Corp. All rights reserved. * Use of this source code is governed by a BSD-style license that can be found with this software. */ #include "LLMJVM_impl.h" int32_t LLMJVM_IMPL_initialize() { return LLMJVM_OK; } int32_t LLMJVM_IMPL_vmTaskStarted() { return LLMJVM_OK; } int32_t LLMJVM_IMPL_scheduleRequest(int64_t absoluteTime) { return LLMJVM_OK; } int32_t LLMJVM_IMPL_idleVM() { return LLMJVM_OK; } int32_t LLMJVM_IMPL_wakeupVM() { return LLMJVM_OK; } int32_t LLMJVM_IMPL_ackWakeup() { return LLMJVM_OK; } int32_t LLMJVM_IMPL_getCurrentTaskID() { return (int32_t) 123456; } void LLMJVM_IMPL_setApplicationTime(int64_t t) { } int64_t LLMJVM_IMPL_getCurrentTime(uint8_t system) { return 0; } int64_t LLMJVM_IMPL_getTimeNanos() { return 0; } int32_t LLMJVM_IMPL_shutdown(void) { return LLMJVM_OK; }
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_Plus_TCP_and_FAT_Windows_Simulator/DemoTasks/SimpleTCPEchoServer.c
<filename>FreeRTOS-Labs/Demo/FreeRTOS_Plus_TCP_and_FAT_Windows_Simulator/DemoTasks/SimpleTCPEchoServer.c /* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from <NAME>, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* * FreeRTOS tasks are used with FreeRTOS+TCP to create a TCP echo server. Echo * clients are also created, but the echo clients use Windows threads (as * opposed to FreeRTOS tasks) and use the Windows TCP library (Winsocks). This * creates a communication between the FreeRTOS+TCP TCP/IP stack and the Windows * TCP/IP stack. * * See the following web page for essential demo usage and configuration * details: * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/examples_FreeRTOS_simulator.html */ /* Standard includes. */ #include <stdint.h> #include <stdio.h> #include <WinSock2.h> #include <Mswsock.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" /* Remove the whole file if FreeRTOSIPConfig.h is set to exclude TCP. */ #if( ipconfigUSE_TCP == 1 ) /* This example uses Winsocks clients to talk to a FreeRTOS+TCP server. */ #pragma comment( lib, "ws2_32.lib" ) /* The number of Winsock clients that communicate with the FreeRTOS+TCP server. */ #define tcpechoNUMBER_OF_CLIENTS 1 /* Specifies the size of the data sent to the server in MSS units. */ #define tcpechoBUFFER_SIZE_MULTIPLIER 3 /* Delay between cycles so as not to flood the network. */ #define tcpechoLOOP_DELAY ( ( TickType_t ) 750 / portTICK_PERIOD_MS ) /* The maximum time to wait for a closing socket to close. */ #define tcpechoSHUTDOWN_DELAY ( pdMS_TO_TICKS( 5000 ) ) /* The time to wait between reads of a Winsock socket when shutting the socket down. */ #define tcpechoWINSOCK_SHUTDOWN_DELAY ( 5 ) /* The standard echo port number. */ #define tcpechoPORT_NUMBER 7 /* The size of the Rx and Tx buffers. */ #define tcpechoBUFFER_SIZE ( ipconfigTCP_MSS * tcpechoBUFFER_SIZE_MULTIPLIER ) /*-----------------------------------------------------------*/ /* * Uses Winsocks from Windows threads to send data from the real IP and MAC * addresses to the IP and MAC addresses spoofed by FreeRTOS+TCP. Multiple * instances of this task are created. */ DWORD WINAPI prvSimpleWinsockTCPClientTask( void *pvParameters ); /* * Uses FreeRTOS+TCP to listen for incoming echo connections, creating a task * to handle each connection. */ static void prvConnectionListeningTask( void *pvParameters ); /* * Created by the connection listening task to handle a single connection. */ static void prvServerConnectionInstance( void *pvParameters ); /* * Create a string to transmit of pseudo random length. */ static BaseType_t prvCreateTxData( char *cBuffer, uint32_t ulBufferLength ); /* * Create the Windows threads that use the Windows TCP/IP stack to talk to the * FreeRTOS task that is using the FreeRTOS+TCP TCP/IP stack. */ static void prvCreateWindowsThreadClients( void ); /*-----------------------------------------------------------*/ /* Stores the stack size passed into vStartSimpleTCPServerTasks() so it can be reused when the server listening task creates tasks to handle connections. */ static uint16_t usUsedStackSize = 0; /* Used for error reporting. */ static uint32_t ulConnectionCount = 0, ulClientCycles = 0, ulClientTransmitErrors = 0, ulIncorrectDataReceived; static uint32_t ulClientSocketsClosedDuringReceive = 0, ulClientReceiveErrors = 0; /* The buffers used to hold the string to Tx and the received string. */ static char cTxBuffers[ tcpechoNUMBER_OF_CLIENTS ][ tcpechoBUFFER_SIZE ], cRxBuffers[ tcpechoNUMBER_OF_CLIENTS ][ tcpechoBUFFER_SIZE ]; /*-----------------------------------------------------------*/ void vStartSimpleTCPServerTasks( uint16_t usStackSize, UBaseType_t uxPriority ) { WORD wVersionRequested; WSADATA xWSAData; /* The clients use Winsock sockets and must therefore run at the idle priority. */ configASSERT( uxPriority == tskIDLE_PRIORITY ); /* Create the TCP echo server. The echo server uses FreeRTOS+TCP through the spoofed IP and MAC address. The WinSock client tasks are created from inside the listening task. */ xTaskCreate( prvConnectionListeningTask, "ServerListener", usStackSize, NULL, uxPriority + 1, NULL ); /* Prepare to use WinSock library. */ wVersionRequested = MAKEWORD( 2, 2 ); configASSERT( WSAStartup( wVersionRequested, &xWSAData ) == ( WORD ) 0 ); /* Remember the requested stack size so it can be re-used by the server listening task when it creates tasks to handle connections. */ usUsedStackSize = usStackSize; } /*-----------------------------------------------------------*/ static void prvCreateWindowsThreadClients( void ) { BaseType_t xClientTask; HANDLE xWinHandle; /* Create a set of (Windows thread) clients, all of which talk to the same (FreeRTOS task) server. The clients use Winsocks through the real IP and MAC address. */ for( xClientTask = 0; xClientTask < tcpechoNUMBER_OF_CLIENTS; xClientTask++ ) { xWinHandle = CreateThread( NULL, /* Pointer to thread security attributes. */ 0, /* Initial thread stack size, in bytes. */ prvSimpleWinsockTCPClientTask, /* Pointer to thread function. */ ( void * ) xClientTask, /* Argument for new thread. */ 0, /* Creation flags. */ NULL ); /* Set the priority and the cores used of the Windows threads such that they do no interfere with the FreeRTOS simulator. */ SetThreadPriority( xWinHandle, THREAD_PRIORITY_IDLE ); SetThreadPriorityBoost( xWinHandle, TRUE ); SetThreadAffinityMask( xWinHandle, ~0x01u ); } } /*-----------------------------------------------------------*/ static void prvConnectionListeningTask( void *pvParameters ) { struct freertos_sockaddr xClient, xBindAddress; Socket_t xListeningSocket, xConnectedSocket; socklen_t xSize = sizeof( xClient ); static const TickType_t xReceiveTimeOut = portMAX_DELAY; const BaseType_t xBacklog = 20; WinProperties_t xWinProps; /* Just to prevent compiler warnings. */ ( void ) pvParameters; /* Attempt to open the socket. */ xListeningSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP ); configASSERT( xListeningSocket != FREERTOS_INVALID_SOCKET ); /* Set a time out so accept() will just wait for a connection. */ FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) ); /* Fill in the buffer and window sizes that will be used by the socket. */ xWinProps.lTxBufSize = 6 * ipconfigTCP_MSS; xWinProps.lTxWinSize = 3; xWinProps.lRxBufSize = 6 * ipconfigTCP_MSS; xWinProps.lRxWinSize = 3; /* Set the window and buffer sizes. */ FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &xWinProps, sizeof( xWinProps ) ); /* Bind the socket to the port that the client task will send to, then listen for incoming connections. */ xBindAddress.sin_port = tcpechoPORT_NUMBER; xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port ); FreeRTOS_bind( xListeningSocket, &xBindAddress, sizeof( xBindAddress ) ); FreeRTOS_listen( xListeningSocket, xBacklog ); /* Create the clients that will connect to the listening socket. */ prvCreateWindowsThreadClients(); for( ;; ) { /* Wait for a client to connect. */ xConnectedSocket = FreeRTOS_accept( xListeningSocket, &xClient, &xSize ); configASSERT( xConnectedSocket != FREERTOS_INVALID_SOCKET ); /* Spawn a task to handle the connection. */ xTaskCreate( prvServerConnectionInstance, "EchoServer", usUsedStackSize, ( void * ) xConnectedSocket, tskIDLE_PRIORITY, NULL ); } } /*-----------------------------------------------------------*/ static void prvServerConnectionInstance( void *pvParameters ) { int32_t lBytes, lSent, lTotalSent; uint8_t cReceivedString[ ipconfigTCP_MSS ]; Socket_t xConnectedSocket; static const TickType_t xReceiveTimeOut = pdMS_TO_TICKS( 5000 ); static const TickType_t xSendTimeOut = pdMS_TO_TICKS( 5000 ); TickType_t xTimeOnShutdown; ulConnectionCount++; xConnectedSocket = ( Socket_t ) pvParameters; FreeRTOS_setsockopt( xConnectedSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) ); FreeRTOS_setsockopt( xConnectedSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xReceiveTimeOut ) ); for( ;; ) { /* Zero out the receive array so there is NULL at the end of the string when it is printed out. */ memset( cReceivedString, 0x00, sizeof( cReceivedString ) ); /* Receive data on the socket. */ lBytes = FreeRTOS_recv( xConnectedSocket, cReceivedString, sizeof( cReceivedString ), 0 ); /* If data was received, echo it back. */ if( lBytes >= 0 ) { lSent = 0; lTotalSent = 0; /* Call send() until all the data has been sent. */ while( ( lSent >= 0 ) && ( lTotalSent < lBytes ) ) { lSent = FreeRTOS_send( xConnectedSocket, cReceivedString, lBytes - lTotalSent, 0 ); lTotalSent += lSent; } if( lSent < 0 ) { /* Socket closed? */ break; } } else { /* Socket closed? */ break; } } /* Initiate a shutdown in case it has not already been initiated. */ FreeRTOS_shutdown( xConnectedSocket, FREERTOS_SHUT_RDWR ); /* Wait for the shutdown to take effect, indicated by FreeRTOS_recv() returning an error. */ xTimeOnShutdown = xTaskGetTickCount(); do { if( FreeRTOS_recv( xConnectedSocket, cReceivedString, ipconfigTCP_MSS, 0 ) < 0 ) { break; } } while( ( xTaskGetTickCount() - xTimeOnShutdown ) < tcpechoSHUTDOWN_DELAY ); /* Finished with the socket and the task. */ FreeRTOS_closesocket( xConnectedSocket ); vTaskDelete( NULL ); } /*-----------------------------------------------------------*/ static BaseType_t prvCreateTxData( char *cBuffer, uint32_t ulBufferLength ) { BaseType_t lCharactersToAdd, lCharacter; char cChar = '0'; /* Randomise the number of characters that will be sent. */ do { lCharactersToAdd = ipconfigRAND32() % ( ulBufferLength - 20UL ); } while ( lCharactersToAdd == 0 ); /* Fill the buffer. */ for( lCharacter = 0; lCharacter < lCharactersToAdd; lCharacter++ ) { cBuffer[ lCharacter ] = cChar; cChar++; if( cChar > '~' ) { cChar = '0'; } } return lCharactersToAdd; } /*-----------------------------------------------------------*/ BaseType_t xAreTCPEchoServersStillRunning( void ) { static uint32_t ulLastConnectionCount = 0, ulLastClientCycles = 0; BaseType_t xReturn = pdPASS; if( ulConnectionCount == ulLastConnectionCount ) { xReturn = pdFAIL; } else { ulLastConnectionCount = ulConnectionCount; } if( ulClientCycles == ulLastClientCycles ) { xReturn = pdFAIL; } else { ulLastClientCycles = ulClientCycles; } return xReturn; } /*-----------------------------------------------------------*/ DWORD WINAPI prvSimpleWinsockTCPClientTask( void *pvParameters ) { char *pcTransmittedString, *pcReceivedString; BaseType_t lReceived, lTransmitted = 0, lStringLength, lReturned = 0, lInstance; uint32_t ulCount = 0UL, ulMaxCount, ulIPAddress; const uint32_t ulMaxLoopsPerSocket = 100UL; struct sockaddr_in xConnection; SOCKET xClientSocket; int iReturned; TickType_t xTimeOnShutdown; /* Multiple instances of this task are created. The instance is passed in as the parameter. */ lInstance = ( BaseType_t ) pvParameters; /* Locate the buffers for this instance of this task. */ pcTransmittedString = &( cTxBuffers[ lInstance ][ 0 ] ); pcReceivedString = &( cRxBuffers[ lInstance ][ 0 ] ); /* It is assumed that this task is not created until the network is up, so the IP address of the server (which is the FreeRTOS+TCP side of the connection) can be obtained immediately. Store the IP address being used in ulIPAddress. */ FreeRTOS_GetAddressConfiguration( &ulIPAddress, NULL, NULL, NULL ); /* Set family and port for client socket. */ memset( ( void * ) &xConnection, 0x00, sizeof( struct sockaddr_in ) ); xConnection.sin_family = AF_INET; xConnection.sin_addr.s_addr = ulIPAddress; xConnection.sin_port = htons( tcpechoPORT_NUMBER ); for( ;; ) { /* Create the socket then connect it to the FreeRTOS+TCP server. */ xClientSocket = socket( AF_INET, SOCK_STREAM, 0 ); configASSERT( xClientSocket != INVALID_SOCKET ); do { iReturned = connect( xClientSocket, (const struct sockaddr*) &xConnection, sizeof( xConnection ) ); } while( iReturned != 0 ); ulMaxCount = ipconfigRAND32() % ulMaxLoopsPerSocket; for( ulCount = 0; ulCount < ulMaxCount; ulCount++ ) { /* Create a string then send it to the server. */ lStringLength = prvCreateTxData( pcTransmittedString, tcpechoBUFFER_SIZE ); lTransmitted = send( xClientSocket, pcTransmittedString, lStringLength, 0 ); configASSERT( lTransmitted != SOCKET_ERROR ); configASSERT( lTransmitted == lStringLength ); if( lTransmitted == lStringLength ) { memset( ( void * ) pcReceivedString, 0x00, tcpechoBUFFER_SIZE ); lReceived = 0; /* Wait for the echoed string. */ while( lReceived < lTransmitted ) { lReturned = recv( xClientSocket, ( char * ) &( pcReceivedString[ lReceived ] ), lTransmitted - lReceived, 0 ); if( lReturned >= 0 ) { /* Data was received. */ lReceived += lReturned; } else { /* Error was returned. */ ulClientReceiveErrors++; break; } } /* If the socket was not closed, check the number of bytes received. */ if( lReceived == lTransmitted ) { /* Were the expected characters received? */ configASSERT( memcmp( pcTransmittedString, pcReceivedString, lTransmitted ) == 0x00 ); if( memcmp( pcTransmittedString, pcReceivedString, lReceived ) != 0x00 ) { ulIncorrectDataReceived++; break; } else { /* Received expected string, increment the count of successful cycles. */ ulClientCycles++; } } else { /* Socket is being closed or an error occurred. Don't try using the same socket again. */ break; } } else { ulClientTransmitErrors++; break; } } shutdown( xClientSocket, SD_BOTH ); xTimeOnShutdown = xTaskGetTickCount(); do { Sleep( tcpechoWINSOCK_SHUTDOWN_DELAY ); lReturned = recv( xClientSocket, pcReceivedString, lTransmitted, 0 ); if( lReturned < 0 ) { break; } } while( ( xTaskGetTickCount() - xTimeOnShutdown ) < tcpechoSHUTDOWN_DELAY ); configASSERT( closesocket( xClientSocket ) == 0 ); Sleep( tcpechoLOOP_DELAY ); } } /*-----------------------------------------------------------*/ /* The whole file is excluded if TCP is not compiled in. */ #endif /* ipconfigUSE_TCP */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/abstractions/platform/freertos/private/iot_taskpool_internal_freertos.h
<filename>FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/abstractions/platform/freertos/private/iot_taskpool_internal_freertos.h<gh_stars>1-10 /* * IoT Common V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file iot_taskpool_internal.h * @brief Internal header of task pool library. This header should not be included in * typical application code. */ #ifndef IOT_TASKPOOL_INTERNAL_H_ #define IOT_TASKPOOL_INTERNAL_H_ /* The config header is always included first. */ #include "iot_config.h" /* Task pool include. */ #include "iot_error.h" #include "iot_taskpool_freertos.h" /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "semphr.h" #include "timers.h" /* Configure logs for TASKPOOL functions. */ #ifdef IOT_LOG_LEVEL_TASKPOOL #define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_TASKPOOL #else #ifdef IOT_LOG_LEVEL_GLOBAL #define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL #else #define LIBRARY_LOG_LEVEL IOT_LOG_NONE #endif #endif #define LIBRARY_LOG_NAME ( "TASKPOOL" ) #include "iot_logging_setup.h" /* ---------------------------------------------------------------------------------------------- */ /** * @brief The task pool data structure keeps track of the internal state and the signals for the dispatcher threads. * The task pool is a thread safe data structure. * * @warning This is a system-level data type that should not be modified or used directly in any application. * @warning This is a system-level data type that can and will change across different versions of the platform, with no regards for backward compatibility. * */ typedef struct _taskPool { IotDeQueue_t dispatchQueue; /**< @brief The queue for the jobs waiting to be executed. */ IotListDouble_t timerEventsList; /**< @brief The timeouts queue for all deferred jobs waiting to be executed. */ SemaphoreHandle_t dispatchSignal; /**< @brief The synchronization object on which threads are waiting for incoming jobs. */ StaticSemaphore_t dispatchSignalBuffer; /**< @brief The semaphore buffer. */ SemaphoreHandle_t xTimerEventMutex; /**< @brief The mutex for guarding the Timer Event Queue. */ StaticSemaphore_t xTimerEventMutexBuffer; /**< @brief The buffer for statically allocating the mutex. */ TimerHandle_t timer; /**< @brief The timer for deferred jobs. */ StaticTimer_t timerBuffer; /**< @brief The timer buffer. */ bool running; /**< @brief A flag to track whether the task pool is operational or should shut down. */ } _taskPool_t; /** * @brief Represents an operation that is subject to a timer. * * These events are queued per MQTT connection. They are sorted by their * expiration time. */ typedef struct _taskPoolTimerEvent { IotLink_t link; /**< @brief List link member. */ TickType_t expirationTime; /**< @brief When this event should be processed. */ } _taskPoolTimerEvent_t; /** * @brief The job data structure keeps track of the user callback and context, as well as the status of the job. * * @warning This is a system-level data type that should not be modified or used directly in any application. * @warning This is a system-level data type that can and will change across different versions of the platform, with no regards for backward compatibility. * */ typedef struct _taskPoolJob { IotLink_t link; /**< @brief The link to insert the job in the dispatch queue. */ IotTaskPoolRoutine_t userCallback; /**< @brief The user provided callback. */ void * pUserContext; /**< @brief The user provided context. */ IotTaskPoolJobStatus_t status; /**< @brief The status for the job. */ _taskPoolTimerEvent_t timer; /**< @brief The timer for scheduling this job deferred. */ } _taskPoolJob_t; #endif /* ifndef IOT_TASKPOOL_INTERNAL_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/mbedtls/include/mbedtls/x509.h
/** * \file x509.h * * \brief X.509 generic defines and structures */ /* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_X509_H #define MBEDTLS_X509_H #if !defined(MBEDTLS_CONFIG_FILE) #include "config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "asn1.h" #include "pk.h" #if defined(MBEDTLS_RSA_C) #include "rsa.h" #endif /** * \addtogroup x509_module * \{ */ #if !defined(MBEDTLS_X509_MAX_INTERMEDIATE_CA) /** * Maximum number of intermediate CAs in a verification chain. * That is, maximum length of the chain, excluding the end-entity certificate * and the trusted root certificate. * * Set this to a low value to prevent an adversary from making you waste * resources verifying an overlong certificate chain. */ #define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 #endif /** * \name X509 Error codes * \{ */ #define MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE -0x2080 /**< Unavailable feature, e.g. RSA hashing/encryption combination. */ #define MBEDTLS_ERR_X509_UNKNOWN_OID -0x2100 /**< Requested OID is unknown. */ #define MBEDTLS_ERR_X509_INVALID_FORMAT -0x2180 /**< The CRT/CRL/CSR format is invalid, e.g. different type expected. */ #define MBEDTLS_ERR_X509_INVALID_VERSION -0x2200 /**< The CRT/CRL/CSR version element is invalid. */ #define MBEDTLS_ERR_X509_INVALID_SERIAL -0x2280 /**< The serial tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_ALG -0x2300 /**< The algorithm tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_NAME -0x2380 /**< The name tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_DATE -0x2400 /**< The date tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_SIGNATURE -0x2480 /**< The signature tag or value invalid. */ #define MBEDTLS_ERR_X509_INVALID_EXTENSIONS -0x2500 /**< The extension tag or value is invalid. */ #define MBEDTLS_ERR_X509_UNKNOWN_VERSION -0x2580 /**< CRT/CRL/CSR has an unsupported version number. */ #define MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG -0x2600 /**< Signature algorithm (oid) is unsupported. */ #define MBEDTLS_ERR_X509_SIG_MISMATCH -0x2680 /**< Signature algorithms do not match. (see \c ::mbedtls_x509_crt sig_oid) */ #define MBEDTLS_ERR_X509_CERT_VERIFY_FAILED -0x2700 /**< Certificate verification failed, e.g. CRL, CA or signature check failed. */ #define MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT -0x2780 /**< Format not recognized as DER or PEM. */ #define MBEDTLS_ERR_X509_BAD_INPUT_DATA -0x2800 /**< Input invalid. */ #define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */ #define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */ #define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */ #define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000 /**< A fatal error occurred, eg the chain is too long or the vrfy callback failed. */ /* \} name */ /** * \name X509 Verify codes * \{ */ /* Reminder: update x509_crt_verify_strings[] in library/x509_crt.c */ #define MBEDTLS_X509_BADCERT_EXPIRED 0x01 /**< The certificate validity has expired. */ #define MBEDTLS_X509_BADCERT_REVOKED 0x02 /**< The certificate has been revoked (is on a CRL). */ #define MBEDTLS_X509_BADCERT_CN_MISMATCH 0x04 /**< The certificate Common Name (CN) does not match with the expected CN. */ #define MBEDTLS_X509_BADCERT_NOT_TRUSTED 0x08 /**< The certificate is not correctly signed by the trusted CA. */ #define MBEDTLS_X509_BADCRL_NOT_TRUSTED 0x10 /**< The CRL is not correctly signed by the trusted CA. */ #define MBEDTLS_X509_BADCRL_EXPIRED 0x20 /**< The CRL is expired. */ #define MBEDTLS_X509_BADCERT_MISSING 0x40 /**< Certificate was missing. */ #define MBEDTLS_X509_BADCERT_SKIP_VERIFY 0x80 /**< Certificate verification was skipped. */ #define MBEDTLS_X509_BADCERT_OTHER 0x0100 /**< Other reason (can be used by verify callback) */ #define MBEDTLS_X509_BADCERT_FUTURE 0x0200 /**< The certificate validity starts in the future. */ #define MBEDTLS_X509_BADCRL_FUTURE 0x0400 /**< The CRL is from the future */ #define MBEDTLS_X509_BADCERT_KEY_USAGE 0x0800 /**< Usage does not match the keyUsage extension. */ #define MBEDTLS_X509_BADCERT_EXT_KEY_USAGE 0x1000 /**< Usage does not match the extendedKeyUsage extension. */ #define MBEDTLS_X509_BADCERT_NS_CERT_TYPE 0x2000 /**< Usage does not match the nsCertType extension. */ #define MBEDTLS_X509_BADCERT_BAD_MD 0x4000 /**< The certificate is signed with an unacceptable hash. */ #define MBEDTLS_X509_BADCERT_BAD_PK 0x8000 /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */ #define MBEDTLS_X509_BADCERT_BAD_KEY 0x010000 /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */ #define MBEDTLS_X509_BADCRL_BAD_MD 0x020000 /**< The CRL is signed with an unacceptable hash. */ #define MBEDTLS_X509_BADCRL_BAD_PK 0x040000 /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */ #define MBEDTLS_X509_BADCRL_BAD_KEY 0x080000 /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */ /* \} name */ /* \} addtogroup x509_module */ /* * X.509 v3 Subject Alternative Name types. * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER */ #define MBEDTLS_X509_SAN_OTHER_NAME 0 #define MBEDTLS_X509_SAN_RFC822_NAME 1 #define MBEDTLS_X509_SAN_DNS_NAME 2 #define MBEDTLS_X509_SAN_X400_ADDRESS_NAME 3 #define MBEDTLS_X509_SAN_DIRECTORY_NAME 4 #define MBEDTLS_X509_SAN_EDI_PARTY_NAME 5 #define MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER 6 #define MBEDTLS_X509_SAN_IP_ADDRESS 7 #define MBEDTLS_X509_SAN_REGISTERED_ID 8 /* * X.509 v3 Key Usage Extension flags * Reminder: update x509_info_key_usage() when adding new flags. */ #define MBEDTLS_X509_KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */ #define MBEDTLS_X509_KU_NON_REPUDIATION (0x40) /* bit 1 */ #define MBEDTLS_X509_KU_KEY_ENCIPHERMENT (0x20) /* bit 2 */ #define MBEDTLS_X509_KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */ #define MBEDTLS_X509_KU_KEY_AGREEMENT (0x08) /* bit 4 */ #define MBEDTLS_X509_KU_KEY_CERT_SIGN (0x04) /* bit 5 */ #define MBEDTLS_X509_KU_CRL_SIGN (0x02) /* bit 6 */ #define MBEDTLS_X509_KU_ENCIPHER_ONLY (0x01) /* bit 7 */ #define MBEDTLS_X509_KU_DECIPHER_ONLY (0x8000) /* bit 8 */ /* * Netscape certificate types * (http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn3.html) */ #define MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT (0x80) /* bit 0 */ #define MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER (0x40) /* bit 1 */ #define MBEDTLS_X509_NS_CERT_TYPE_EMAIL (0x20) /* bit 2 */ #define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING (0x10) /* bit 3 */ #define MBEDTLS_X509_NS_CERT_TYPE_RESERVED (0x08) /* bit 4 */ #define MBEDTLS_X509_NS_CERT_TYPE_SSL_CA (0x04) /* bit 5 */ #define MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA (0x02) /* bit 6 */ #define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA (0x01) /* bit 7 */ /* * X.509 extension types * * Comments refer to the status for using certificates. Status can be * different for writing certificates or reading CRLs or CSRs. * * Those are defined in oid.h as oid.c needs them in a data structure. Since * these were previously defined here, let's have aliases for compatibility. */ #define MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER #define MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER #define MBEDTLS_X509_EXT_KEY_USAGE MBEDTLS_OID_X509_EXT_KEY_USAGE #define MBEDTLS_X509_EXT_CERTIFICATE_POLICIES MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES #define MBEDTLS_X509_EXT_POLICY_MAPPINGS MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS #define MBEDTLS_X509_EXT_SUBJECT_ALT_NAME MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME /* Supported (DNS) */ #define MBEDTLS_X509_EXT_ISSUER_ALT_NAME MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME #define MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS #define MBEDTLS_X509_EXT_BASIC_CONSTRAINTS MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS /* Supported */ #define MBEDTLS_X509_EXT_NAME_CONSTRAINTS MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS #define MBEDTLS_X509_EXT_POLICY_CONSTRAINTS MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS #define MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE #define MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS #define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY #define MBEDTLS_X509_EXT_FRESHEST_CRL MBEDTLS_OID_X509_EXT_FRESHEST_CRL #define MBEDTLS_X509_EXT_NS_CERT_TYPE MBEDTLS_OID_X509_EXT_NS_CERT_TYPE /* * Storage format identifiers * Recognized formats: PEM and DER */ #define MBEDTLS_X509_FORMAT_DER 1 #define MBEDTLS_X509_FORMAT_PEM 2 #define MBEDTLS_X509_MAX_DN_NAME_SIZE 256 /**< Maximum value size of a DN entry */ #ifdef __cplusplus extern "C" { #endif /** * \addtogroup x509_module * \{ */ /** * \name Structures for parsing X.509 certificates, CRLs and CSRs * \{ */ /** * Type-length-value structure that allows for ASN1 using DER. */ typedef mbedtls_asn1_buf mbedtls_x509_buf; /** * Container for ASN1 bit strings. */ typedef mbedtls_asn1_bitstring mbedtls_x509_bitstring; /** * Container for ASN1 named information objects. * It allows for Relative Distinguished Names (e.g. cn=localhost,ou=code,etc.). */ typedef mbedtls_asn1_named_data mbedtls_x509_name; /** * Container for a sequence of ASN.1 items */ typedef mbedtls_asn1_sequence mbedtls_x509_sequence; /** Container for date and time (precision in seconds). */ typedef struct mbedtls_x509_time { int year, mon, day; /**< Date. */ int hour, min, sec; /**< Time. */ } mbedtls_x509_time; /** \} name Structures for parsing X.509 certificates, CRLs and CSRs */ /** \} addtogroup x509_module */ /** * \brief Store the certificate DN in printable form into buf; * no more than size characters will be written. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param dn The X509 name to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn ); /** * \brief Store the certificate serial in printable form into buf; * no more than size characters will be written. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param serial The X509 serial to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial ); /** * \brief Check a given mbedtls_x509_time against the system time * and tell if it's in the past. * * \note Intended usage is "if( is_past( valid_to ) ) ERROR". * Hence the return value of 1 if on internal errors. * * \param to mbedtls_x509_time to check * * \return 1 if the given time is in the past or an error occurred, * 0 otherwise. */ int mbedtls_x509_time_is_past( const mbedtls_x509_time *to ); /** * \brief Check a given mbedtls_x509_time against the system time * and tell if it's in the future. * * \note Intended usage is "if( is_future( valid_from ) ) ERROR". * Hence the return value of 1 if on internal errors. * * \param from mbedtls_x509_time to check * * \return 1 if the given time is in the future or an error occurred, * 0 otherwise. */ int mbedtls_x509_time_is_future( const mbedtls_x509_time *from ); #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_x509_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ /* * Internal module functions. You probably do not want to use these unless you * know you do. */ int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end, mbedtls_x509_name *cur ); int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg ); int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg, mbedtls_x509_buf *params ); #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params, mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md, int *salt_len ); #endif int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig ); int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg, void **sig_opts ); int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, mbedtls_x509_time *t ); int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *serial ); int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *ext, int tag ); int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid, mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, const void *sig_opts ); int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name ); int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name ); int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len, int critical, const unsigned char *val, size_t val_len ); int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ); int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ); int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start, const char *oid, size_t oid_len, unsigned char *sig, size_t size ); #define MBEDTLS_X509_SAFE_SNPRINTF \ do { \ if( ret < 0 || (size_t) ret >= n ) \ return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); \ \ n -= (size_t) ret; \ p += (size_t) ret; \ } while( 0 ) #ifdef __cplusplus } #endif #endif /* x509.h */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/Common/FreeRTOS_Plus_CLI_Demos/TCPCommandConsole.c
<reponame>MicroEJ/FreeRTOS<gh_stars>1-10 /* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from <NAME>, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* Standard includes. */ #include <stdint.h> #include <stdio.h> #include <stdarg.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* FreeRTOS+CLI includes. */ #include "FreeRTOS_CLI.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" /* Demo app includes. */ #include "TCPCommandConsole.h" /* Dimensions the buffer into which input characters are placed. */ #define cmdMAX_INPUT_SIZE 60 /* Dimensions the buffer into which string outputs can be placed. */ #define cmdMAX_OUTPUT_SIZE 1024 /* Dimensions the buffer passed to the recv() call. */ #define cmdSOCKET_INPUT_BUFFER_SIZE 60 /* DEL acts as a backspace. */ #define cmdASCII_DEL ( 0x7F ) /* The maximum time to wait for a closing socket to close. */ #define cmdSHUTDOWN_DELAY ( pdMS_TO_TICKS( 5000 ) ) /* * The task that runs FreeRTOS+CLI. */ static void prvTCPCommandInterpreterTask( void *pvParameters ); /* * Open and configure the TCP socket. */ static Socket_t prvOpenTCPServerSocket( uint16_t usPort ); /* * A connected socket is being closed. Ensure the socket is closed at both ends * properly. */ static void prvGracefulShutdown( Socket_t xSocket ); /*-----------------------------------------------------------*/ /* * Various buffers used by the command lin interpreter. */ static char cOutputString[ cmdMAX_OUTPUT_SIZE ], cLocalBuffer[ cmdSOCKET_INPUT_BUFFER_SIZE ]; static char cInputString[ cmdMAX_INPUT_SIZE ], cLastInputString[ cmdMAX_INPUT_SIZE ]; /* Const messages output by the command console. */ static const char * const pcWelcomeMessage = "FreeRTOS command server.\r\nType help to view a list of registered commands.\r\nType quit to end a session.\r\n\r\n>"; static const char * const pcEndOfOutputMessage = "\r\n[Press ENTER to execute the previous command again]\r\n>"; static const char * const pcNewLine = "\r\n"; /*-----------------------------------------------------------*/ void vStartTCPCommandInterpreterTask( uint16_t usStackSize, uint32_t ulPort, UBaseType_t uxPriority ) { xTaskCreate( prvTCPCommandInterpreterTask, "TCP CLI", usStackSize, ( void * ) ulPort, uxPriority, NULL ); } /*-----------------------------------------------------------*/ void prvTCPCommandInterpreterTask( void *pvParameters ) { int32_t lBytes, lByte, lSent; char cRxedChar, cInputIndex = 0; BaseType_t xMoreDataToFollow; struct freertos_sockaddr xClient; Socket_t xListeningSocket, xConnectedSocket; socklen_t xSize = sizeof( xClient ); memset( cInputString, 0x00, cmdMAX_INPUT_SIZE ); for( ;; ) { /* Attempt to open the socket. The port number is passed in the task parameter. The strange casting is to remove compiler warnings on 32-bit machines. NOTE: The FREERTOS_SO_REUSE_LISTEN_SOCKET option is used, so the listening and connecting socket are the same - meaning only one connection will be accepted at a time, and that xListeningSocket must be created on each iteration. */ xListeningSocket = prvOpenTCPServerSocket( ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL ); /* Nothing for this task to do if the socket cannot be created. */ if( xListeningSocket == FREERTOS_INVALID_SOCKET ) { vTaskDelete( NULL ); } /* Wait for an incoming connection. */ xConnectedSocket = FreeRTOS_accept( xListeningSocket, &xClient, &xSize ); /* The FREERTOS_SO_REUSE_LISTEN_SOCKET option is set, so the connected and listening socket should be the same socket. */ configASSERT( xConnectedSocket == xListeningSocket ); /* Send the welcome message. */ lSent = FreeRTOS_send( xConnectedSocket, ( void * ) pcWelcomeMessage, strlen( pcWelcomeMessage ), 0 ); /* Process the socket as long as it remains connected. */ while( lSent >= 0 ) { /* Receive data on the socket. */ lBytes = FreeRTOS_recv( xConnectedSocket, cLocalBuffer, sizeof( cLocalBuffer ), 0 ); if( lBytes >= 0 ) { /* Process each received byte in turn. */ lByte = 0; while( lByte < lBytes ) { /* The next character in the input buffer. */ cRxedChar = cLocalBuffer[ lByte ]; lByte++; /* Newline characters are taken as the end of the command string. */ if( cRxedChar == '\n' ) { /* Just to space the output from the input. */ FreeRTOS_send( xConnectedSocket, pcNewLine, strlen( pcNewLine ), 0 ); /* See if the command is empty, indicating that the last command is to be executed again. */ if( cInputIndex == 0 ) { /* Copy the last command back into the input string. */ strcpy( cInputString, cLastInputString ); } /* If the command was "quit" then close the console. */ if( strcasecmp( cInputString, "quit" ) == 0 ) { /* Fake an error code so the outer loop exits on the assumption there was an error on the socket. The socket will then be shut down gracefully. */ lSent = -1; break; } /* Process the input string received prior to the newline. */ do { /* Pass the string to FreeRTOS+CLI. */ cOutputString[ 0 ] = 0x00; xMoreDataToFollow = FreeRTOS_CLIProcessCommand( cInputString, cOutputString, cmdMAX_OUTPUT_SIZE ); /* Send the output generated by the command's implementation. */ lSent = FreeRTOS_send( xConnectedSocket, cOutputString, strlen( ( const char * ) cOutputString ), 0 ); /* Until the command does not generate any more output. */ } while( ( xMoreDataToFollow != pdFALSE ) && ( lSent >= 0 ) ); if( lSent >= 0 ) { /* All the strings generated by the command processing have been sent. Clear the input string ready to receive the next command. Remember the previous command so it can be executed again by pressing [ENTER]. */ strcpy( cLastInputString, cInputString ); cInputIndex = 0; memset( cInputString, 0x00, cmdMAX_INPUT_SIZE ); /* Transmit a spacer to make the console easier to read. */ lSent = FreeRTOS_send( xConnectedSocket, ( void * ) pcEndOfOutputMessage, strlen( pcEndOfOutputMessage ), 0 ); } if( lSent < 0 ) { /* Socket closed? */ break; } } else { if( cRxedChar == '\r' ) { /* Ignore the character. Newlines are used to detect the end of the input string. */ } else if( ( cRxedChar == '\b' ) || ( cRxedChar == cmdASCII_DEL ) ) { /* Backspace was pressed. Erase the last character in the string - if any. */ if( cInputIndex > 0 ) { cInputIndex--; cInputString[ ( int ) cInputIndex ] = '\0'; } } else { /* A character was entered. Add it to the string entered so far. When a \n is entered the complete string will be passed to the command interpreter. */ if( cInputIndex < cmdMAX_INPUT_SIZE ) { if( ( cRxedChar >= ' ' ) && ( cRxedChar <= '~' ) ) { cInputString[ ( int ) cInputIndex ] = cRxedChar; cInputIndex++; } } } } } } else { /* Socket closed? */ break; } } /* Close the socket correctly. */ prvGracefulShutdown( xListeningSocket ); } } /*-----------------------------------------------------------*/ static void prvGracefulShutdown( Socket_t xSocket ) { TickType_t xTimeOnShutdown; /* Initiate a shutdown in case it has not already been initiated. */ FreeRTOS_shutdown( xSocket, FREERTOS_SHUT_RDWR ); /* Wait for the shutdown to take effect, indicated by FreeRTOS_recv() returning an error. */ xTimeOnShutdown = xTaskGetTickCount(); do { if( FreeRTOS_recv( xSocket, cInputString, ipconfigTCP_MSS, 0 ) < 0 ) { break; } } while( ( xTaskGetTickCount() - xTimeOnShutdown ) < cmdSHUTDOWN_DELAY ); /* Finished with the socket and the task. */ FreeRTOS_closesocket( xSocket ); } /*-----------------------------------------------------------*/ static Socket_t prvOpenTCPServerSocket( uint16_t usPort ) { struct freertos_sockaddr xBindAddress; Socket_t xSocket; static const TickType_t xReceiveTimeOut = portMAX_DELAY; const BaseType_t xBacklog = 20; BaseType_t xReuseSocket = pdTRUE; /* Attempt to open the socket. */ xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP ); configASSERT( xSocket != FREERTOS_INVALID_SOCKET ); /* Set a time out so accept() will just wait for a connection. */ FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) ); /* Only one connection will be used at a time, so re-use the listening socket as the connected socket. See SimpleTCPEchoServer.c for an example that accepts multiple connections. */ FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_REUSE_LISTEN_SOCKET, &xReuseSocket, sizeof( xReuseSocket ) ); /* NOTE: The CLI is a low bandwidth interface (typing characters is slow), so the TCP window properties are left at their default. See SimpleTCPEchoServer.c for an example of a higher throughput TCP server that uses are larger RX and TX buffer. */ /* Bind the socket to the port that the client task will send to, then listen for incoming connections. */ xBindAddress.sin_port = usPort; xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port ); FreeRTOS_bind( xSocket, &xBindAddress, sizeof( xBindAddress ) ); FreeRTOS_listen( xSocket, xBacklog ); return xSocket; } /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/common/include/aws_iot.h
<gh_stars>1-10 /* * AWS IoT Common V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot.h * @brief Provides routines and constants that are common to AWS IoT libraries. * This header should not be included in typical application code. */ #ifndef AWS_IOT_H_ #define AWS_IOT_H_ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <stdbool.h> #include <stdint.h> /* Platform types include. */ #include "types/iot_platform_types.h" /* MQTT types include. */ #include "types/iot_mqtt_types.h" /** * @brief The longest Thing Name accepted by AWS IoT, per the [AWS IoT * Service Limits](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_iot). */ #define AWS_IOT_MAX_THING_NAME_LENGTH ( 128 ) /** * @brief The common prefix of all AWS IoT MQTT topics. */ #define AWS_IOT_TOPIC_PREFIX "$aws/things/" /** * @brief The length of #AWS_IOT_TOPIC_PREFIX. */ #define AWS_IOT_TOPIC_PREFIX_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_TOPIC_PREFIX ) - 1 ) ) /** * @brief The suffix for an AWS IoT operation "accepted" topic. */ #define AWS_IOT_ACCEPTED_SUFFIX "/accepted" /** * @brief The length of #AWS_IOT_ACCEPTED_SUFFIX. */ #define AWS_IOT_ACCEPTED_SUFFIX_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_ACCEPTED_SUFFIX ) - 1 ) ) /** * @brief The suffix for an AWS IoT operation "rejected" topic. */ #define AWS_IOT_REJECTED_SUFFIX "/rejected" /** * @brief The length of #AWS_IOT_REJECTED_SUFFIX. */ #define AWS_IOT_REJECTED_SUFFIX_LENGTH ( ( uint16_t ) ( sizeof( AWS_IOT_REJECTED_SUFFIX ) - 1 ) ) /** * @brief The JSON key used to represent client tokens for AWS IoT. */ #define AWS_IOT_CLIENT_TOKEN_KEY "clientToken" /** * @brief The length of #AWS_IOT_CLIENT_TOKEN_KEY. */ #define AWS_IOT_CLIENT_TOKEN_KEY_LENGTH ( sizeof( AWS_IOT_CLIENT_TOKEN_KEY ) - 1 ) /** * @brief The length of the longest client token allowed by AWS IoT. */ #define AWS_IOT_CLIENT_TOKEN_MAX_LENGTH ( 64 ) /** * @brief A flag to represent persistent subscriptions in a subscriptions * object. * * Its value is negative to distinguish it from valid subscription counts, which * are 0 or positive. */ #define AWS_IOT_PERSISTENT_SUBSCRIPTION ( -1 ) /** * @brief Function pointer representing an MQTT blocking operation. * * Currently, this is used to represent @ref mqtt_function_subscribesync or * @ref mqtt_function_unsubscribesync. * * @param[in] mqttConnection The MQTT connection to use for the subscription. * @param[in] pSubscriptionList Pointer to the first element in the array of * subscriptions. * @param[in] subscriptionCount The number of elements in pSubscriptionList. * @param[in] flags Flags which modify the behavior of this function. See @ref mqtt_constants_flags. * Currently, flags are ignored by this function; this parameter is for * future-compatibility. * @param[in] timeoutMs If the MQTT server does not acknowledge the subscriptions within * this timeout in milliseconds, this function returns #IOT_MQTT_TIMEOUT. * * @return One of the following: * - #IOT_MQTT_SUCCESS * - #IOT_MQTT_NOT_INITIALIZED * - #IOT_MQTT_BAD_PARAMETER * - #IOT_MQTT_NO_MEMORY * - #IOT_MQTT_NETWORK_ERROR * - #IOT_MQTT_SCHEDULING_ERROR * - #IOT_MQTT_BAD_RESPONSE * - #IOT_MQTT_TIMEOUT * - #IOT_MQTT_SERVER_REFUSED */ typedef IotMqttError_t ( * AwsIotMqttFunction_t )( IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, uint32_t timeoutMs ); /** * @brief Function pointer representing an MQTT library callback function. * * @param[in] pArgument Ignored. * @param[in] pMessage The received DELTA document (as an MQTT PUBLISH message). */ typedef void ( * AwsIotMqttCallbackFunction_t )( void * pArgument, IotMqttCallbackParam_t * pMessage ); /** * @brief Enumerations representing each of the statuses that may be parsed * from a topic. */ typedef enum AwsIotStatus { AWS_IOT_ACCEPTED = 0, /**< Operation accepted. */ AWS_IOT_REJECTED = 1, /**< Operation rejected. */ AWS_IOT_UNKNOWN = 2 /**< Unknown status (neither accepted nor rejected). */ } AwsIotStatus_t; /** * @brief Information required to generate a topic for AWS IoT. */ typedef struct AwsIotTopicInfo { const char * pThingName; /**< @brief The Thing Name associated with the operation. */ size_t thingNameLength; /**< @brief The length of `pThingName`. */ const char * pOperationName; /**< @brief The operation name to place in the topic. */ uint16_t operationNameLength; /**< @brief The length of `pOperationName`. */ uint16_t longestSuffixLength; /**< @brief The length of longest suffix that will be placed at the end of the topic. */ void * ( *mallocString )( size_t size ); /**< @brief Function used to allocate a string, if needed. */ } AwsIotTopicInfo_t; /** * @brief Information needed to modify AWS IoT subscription topics. * * @warning The buffer passed as `pTopicFilterBase` must be large enough to * accommodate the "/accepted" and "/rejected" suffixes. */ typedef struct AwsIotSubscriptionInfo_t { IotMqttConnection_t mqttConnection; /**< @brief The MQTT connection to use. */ AwsIotMqttCallbackFunction_t callbackFunction; /**< @brief Callback function for MQTT subscribe. */ uint32_t timeout; /**< @brief Timeout for MQTT function. */ /* Topic filter. */ char * pTopicFilterBase; /**< @brief Contains the base topic filter, without "/accepted" or "/rejected". */ uint16_t topicFilterBaseLength; /**< @brief Length of the base topic filter. */ } AwsIotSubscriptionInfo_t; /** * @brief Thing Name and length, used to match subscriptions. */ typedef struct AwsIotThingName { const char * pThingName; /**< @brief Thing Name to compare. */ size_t thingNameLength; /**< @brief Length of `pThingName`. */ } AwsIotThingName_t; /** * @brief Initializes the lists used by AWS IoT operations. * * @param[in] pPendingOperationsList The list that holds pending operations for * a library. * @param[in] pSubscriptionsList The list that holds subscriptions for a library. * @param[in] pPendingOperationsMutex The mutex that guards the pending operations * list. * @param[in] pSubscriptionsMutex The mutex that guards the subscriptions list. * * @return `true` if all initialization succeeded; `false` otherwise. */ bool AwsIot_InitLists( IotListDouble_t * pPendingOperationsList, IotListDouble_t * pSubscriptionsList, IotMutex_t * pPendingOperationsMutex, IotMutex_t * pSubscriptionsMutex ); /** * @brief Checks that a Thing Name is valid for AWS IoT. * * @param[in] pThingName Thing Name to validate. * @param[in] thingNameLength Length of `pThingName`. * * @return `true` if `pThingName` is valid; `false` otherwise. */ bool AwsIot_ValidateThingName( const char * pThingName, size_t thingNameLength ); /** * @brief Extracts the client token from a JSON document. * * The client token is used to differentiate AWS IoT operations. It is unique per * operation. * * @param[in] pJsonDocument The JSON document to parse. * @param[in] jsonDocumentLength The length of `pJsonDocument`. * @param[out] pClientToken Set to point to the client token in `pJsonDocument`. * @param[out] pClientTokenLength Set to the length of the client token. * * @return `true` if the client token was found; `false` otherwise. The output * parameters are only valid if this function returns `true`. */ bool AwsIot_GetClientToken( const char * pJsonDocument, size_t jsonDocumentLength, const char ** pClientToken, size_t * pClientTokenLength ); /** * @brief Parse the Thing Name from an MQTT topic. * * @param[in] pTopicName The topic to parse. * @param[in] topicNameLength The length of `pTopicName`. * @param[out] pThingName Set to point to the Thing Name. * @param[out] pThingNameLength Set to the length of the Thing Name. * * @return `true` if a Thing Name was successfully parsed; `false` otherwise. The output * parameters are only valid if this function returns `true`. */ bool AwsIot_ParseThingName( const char * pTopicName, uint16_t topicNameLength, const char ** pThingName, size_t * pThingNameLength ); /** * @brief Parse the operation status (accepted or rejected) from an MQTT topic. * * @param[in] pTopicName The topic to parse. * @param[in] topicNameLength The length of `pTopicName`. * * @return Any #AwsIotStatus_t. */ AwsIotStatus_t AwsIot_ParseStatus( const char * pTopicName, uint16_t topicNameLength ); /** * @brief Generate a topic to use for an AWS IoT operation. * * @param[in] pTopicInfo Information needed to generate an AWS IoT topic. * @param[in,out] pTopicBuffer Where to place the generated topic. An existing * buffer may be passed in. If `NULL`, this function will attempt to allocate a * new buffer. * @param[out] pOperationTopicLength Set to the length of the generated topic. * * @warning This function does not check the length of `pTopicBuffer`! Any provided * buffer must be long enough to accommodate the Thing Name, operation name, and * any other suffixes. * * @return `true` if the topic was successfully generated; `false` otherwise. * This function will always succeed when an input buffer is provided. */ bool AwsIot_GenerateOperationTopic( const AwsIotTopicInfo_t * pTopicInfo, char ** pTopicBuffer, uint16_t * pOperationTopicLength ); /** * @brief Add or remove subscriptions for AWS IoT operations. * * @param[in] mqttOperation Either @ref mqtt_function_subscribesync or * @ref mqtt_function_unsubscribesync. * @param[in] pSubscriptionInfo Information needed to process an MQTT * operation. * * @return See the return values of @ref mqtt_function_subscribesync or * @ref mqtt_function_unsubscribesync. */ IotMqttError_t AwsIot_ModifySubscriptions( AwsIotMqttFunction_t mqttOperation, const AwsIotSubscriptionInfo_t * pSubscriptionInfo ); #endif /* ifndef AWS_IOT_H_ */
MicroEJ/FreeRTOS
FreeRTOS/Demo/CORTEX_MPU_M33F_NXP_LPC55S69_MCUXpresso/NXP_Code/drivers/fsl_usart.h
/* * Copyright (c) 2016, Freescale Semiconductor, Inc. * Copyright 2016-2018 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _FSL_USART_H_ #define _FSL_USART_H_ #include "fsl_common.h" /*! * @addtogroup usart_driver * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @name Driver version */ /*@{*/ /*! @brief USART driver version 2.0.3. */ #define FSL_USART_DRIVER_VERSION (MAKE_VERSION(2, 0, 3)) /*@}*/ #define USART_FIFOTRIG_TXLVL_GET(base) (((base)->FIFOTRIG & USART_FIFOTRIG_TXLVL_MASK) >> USART_FIFOTRIG_TXLVL_SHIFT) #define USART_FIFOTRIG_RXLVL_GET(base) (((base)->FIFOTRIG & USART_FIFOTRIG_RXLVL_MASK) >> USART_FIFOTRIG_RXLVL_SHIFT) /*! @brief Error codes for the USART driver. */ enum _usart_status { kStatus_USART_TxBusy = MAKE_STATUS(kStatusGroup_LPC_USART, 0), /*!< Transmitter is busy. */ kStatus_USART_RxBusy = MAKE_STATUS(kStatusGroup_LPC_USART, 1), /*!< Receiver is busy. */ kStatus_USART_TxIdle = MAKE_STATUS(kStatusGroup_LPC_USART, 2), /*!< USART transmitter is idle. */ kStatus_USART_RxIdle = MAKE_STATUS(kStatusGroup_LPC_USART, 3), /*!< USART receiver is idle. */ kStatus_USART_TxError = MAKE_STATUS(kStatusGroup_LPC_USART, 7), /*!< Error happens on txFIFO. */ kStatus_USART_RxError = MAKE_STATUS(kStatusGroup_LPC_USART, 9), /*!< Error happens on rxFIFO. */ kStatus_USART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_LPC_USART, 8), /*!< Error happens on rx ring buffer */ kStatus_USART_NoiseError = MAKE_STATUS(kStatusGroup_LPC_USART, 10), /*!< USART noise error. */ kStatus_USART_FramingError = MAKE_STATUS(kStatusGroup_LPC_USART, 11), /*!< USART framing error. */ kStatus_USART_ParityError = MAKE_STATUS(kStatusGroup_LPC_USART, 12), /*!< USART parity error. */ kStatus_USART_BaudrateNotSupport = MAKE_STATUS(kStatusGroup_LPC_USART, 13), /*!< Baudrate is not support in current clock source */ }; /*! @brief USART parity mode. */ typedef enum _usart_parity_mode { kUSART_ParityDisabled = 0x0U, /*!< Parity disabled */ kUSART_ParityEven = 0x2U, /*!< Parity enabled, type even, bit setting: PE|PT = 10 */ kUSART_ParityOdd = 0x3U, /*!< Parity enabled, type odd, bit setting: PE|PT = 11 */ } usart_parity_mode_t; /*! @brief USART stop bit count. */ typedef enum _usart_stop_bit_count { kUSART_OneStopBit = 0U, /*!< One stop bit */ kUSART_TwoStopBit = 1U, /*!< Two stop bits */ } usart_stop_bit_count_t; /*! @brief USART data size. */ typedef enum _usart_data_len { kUSART_7BitsPerChar = 0U, /*!< Seven bit mode */ kUSART_8BitsPerChar = 1U, /*!< Eight bit mode */ } usart_data_len_t; /*! @brief txFIFO watermark values */ typedef enum _usart_txfifo_watermark { kUSART_TxFifo0 = 0, /*!< USART tx watermark is empty */ kUSART_TxFifo1 = 1, /*!< USART tx watermark at 1 item */ kUSART_TxFifo2 = 2, /*!< USART tx watermark at 2 items */ kUSART_TxFifo3 = 3, /*!< USART tx watermark at 3 items */ kUSART_TxFifo4 = 4, /*!< USART tx watermark at 4 items */ kUSART_TxFifo5 = 5, /*!< USART tx watermark at 5 items */ kUSART_TxFifo6 = 6, /*!< USART tx watermark at 6 items */ kUSART_TxFifo7 = 7, /*!< USART tx watermark at 7 items */ } usart_txfifo_watermark_t; /*! @brief rxFIFO watermark values */ typedef enum _usart_rxfifo_watermark { kUSART_RxFifo1 = 0, /*!< USART rx watermark at 1 item */ kUSART_RxFifo2 = 1, /*!< USART rx watermark at 2 items */ kUSART_RxFifo3 = 2, /*!< USART rx watermark at 3 items */ kUSART_RxFifo4 = 3, /*!< USART rx watermark at 4 items */ kUSART_RxFifo5 = 4, /*!< USART rx watermark at 5 items */ kUSART_RxFifo6 = 5, /*!< USART rx watermark at 6 items */ kUSART_RxFifo7 = 6, /*!< USART rx watermark at 7 items */ kUSART_RxFifo8 = 7, /*!< USART rx watermark at 8 items */ } usart_rxfifo_watermark_t; /*! * @brief USART interrupt configuration structure, default settings all disabled. */ enum _usart_interrupt_enable { kUSART_TxErrorInterruptEnable = (USART_FIFOINTENSET_TXERR_MASK), kUSART_RxErrorInterruptEnable = (USART_FIFOINTENSET_RXERR_MASK), kUSART_TxLevelInterruptEnable = (USART_FIFOINTENSET_TXLVL_MASK), kUSART_RxLevelInterruptEnable = (USART_FIFOINTENSET_RXLVL_MASK), }; /*! * @brief USART status flags. * * This provides constants for the USART status flags for use in the USART functions. */ enum _usart_flags { kUSART_TxError = (USART_FIFOSTAT_TXERR_MASK), /*!< TEERR bit, sets if TX buffer is error */ kUSART_RxError = (USART_FIFOSTAT_RXERR_MASK), /*!< RXERR bit, sets if RX buffer is error */ kUSART_TxFifoEmptyFlag = (USART_FIFOSTAT_TXEMPTY_MASK), /*!< TXEMPTY bit, sets if TX buffer is empty */ kUSART_TxFifoNotFullFlag = (USART_FIFOSTAT_TXNOTFULL_MASK), /*!< TXNOTFULL bit, sets if TX buffer is not full */ kUSART_RxFifoNotEmptyFlag = (USART_FIFOSTAT_RXNOTEMPTY_MASK), /*!< RXNOEMPTY bit, sets if RX buffer is not empty */ kUSART_RxFifoFullFlag = (USART_FIFOSTAT_RXFULL_MASK), /*!< RXFULL bit, sets if RX buffer is full */ }; /*! @brief USART configuration structure. */ typedef struct _usart_config { uint32_t baudRate_Bps; /*!< USART baud rate */ usart_parity_mode_t parityMode; /*!< Parity mode, disabled (default), even, odd */ usart_stop_bit_count_t stopBitCount; /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits */ usart_data_len_t bitCountPerChar; /*!< Data length - 7 bit, 8 bit */ bool loopback; /*!< Enable peripheral loopback */ bool enableRx; /*!< Enable RX */ bool enableTx; /*!< Enable TX */ usart_txfifo_watermark_t txWatermark; /*!< txFIFO watermark */ usart_rxfifo_watermark_t rxWatermark; /*!< rxFIFO watermark */ } usart_config_t; /*! @brief USART transfer structure. */ typedef struct _usart_transfer { uint8_t *data; /*!< The buffer of data to be transfer.*/ size_t dataSize; /*!< The byte count to be transfer. */ } usart_transfer_t; /* Forward declaration of the handle typedef. */ typedef struct _usart_handle usart_handle_t; /*! @brief USART transfer callback function. */ typedef void (*usart_transfer_callback_t)(USART_Type *base, usart_handle_t *handle, status_t status, void *userData); /*! @brief USART handle structure. */ struct _usart_handle { uint8_t *volatile txData; /*!< Address of remaining data to send. */ volatile size_t txDataSize; /*!< Size of the remaining data to send. */ size_t txDataSizeAll; /*!< Size of the data to send out. */ uint8_t *volatile rxData; /*!< Address of remaining data to receive. */ volatile size_t rxDataSize; /*!< Size of the remaining data to receive. */ size_t rxDataSizeAll; /*!< Size of the data to receive. */ uint8_t *rxRingBuffer; /*!< Start address of the receiver ring buffer. */ size_t rxRingBufferSize; /*!< Size of the ring buffer. */ volatile uint16_t rxRingBufferHead; /*!< Index for the driver to store received data into ring buffer. */ volatile uint16_t rxRingBufferTail; /*!< Index for the user to get data from the ring buffer. */ usart_transfer_callback_t callback; /*!< Callback function. */ void *userData; /*!< USART callback function parameter.*/ volatile uint8_t txState; /*!< TX transfer state. */ volatile uint8_t rxState; /*!< RX transfer state */ usart_txfifo_watermark_t txWatermark; /*!< txFIFO watermark */ usart_rxfifo_watermark_t rxWatermark; /*!< rxFIFO watermark */ }; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /* _cplusplus */ /*! @brief Returns instance number for USART peripheral base address. */ uint32_t USART_GetInstance(USART_Type *base); /*! * @name Initialization and deinitialization * @{ */ /*! * @brief Initializes a USART instance with user configuration structure and peripheral clock. * * This function configures the USART module with the user-defined settings. The user can configure the configuration * structure and also get the default configuration by using the USART_GetDefaultConfig() function. * Example below shows how to use this API to configure USART. * @code * usart_config_t usartConfig; * usartConfig.baudRate_Bps = 115200U; * usartConfig.parityMode = kUSART_ParityDisabled; * usartConfig.stopBitCount = kUSART_OneStopBit; * USART_Init(USART1, &usartConfig, 20000000U); * @endcode * * @param base USART peripheral base address. * @param config Pointer to user-defined configuration structure. * @param srcClock_Hz USART clock source frequency in HZ. * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source. * @retval kStatus_InvalidArgument USART base address is not valid * @retval kStatus_Success Status USART initialize succeed */ status_t USART_Init(USART_Type *base, const usart_config_t *config, uint32_t srcClock_Hz); /*! * @brief Deinitializes a USART instance. * * This function waits for TX complete, disables TX and RX, and disables the USART clock. * * @param base USART peripheral base address. */ void USART_Deinit(USART_Type *base); /*! * @brief Gets the default configuration structure. * * This function initializes the USART configuration structure to a default value. The default * values are: * usartConfig->baudRate_Bps = 115200U; * usartConfig->parityMode = kUSART_ParityDisabled; * usartConfig->stopBitCount = kUSART_OneStopBit; * usartConfig->bitCountPerChar = kUSART_8BitsPerChar; * usartConfig->loopback = false; * usartConfig->enableTx = false; * usartConfig->enableRx = false; * * @param config Pointer to configuration structure. */ void USART_GetDefaultConfig(usart_config_t *config); /*! * @brief Sets the USART instance baud rate. * * This function configures the USART module baud rate. This function is used to update * the USART module baud rate after the USART module is initialized by the USART_Init. * @code * USART_SetBaudRate(USART1, 115200U, 20000000U); * @endcode * * @param base USART peripheral base address. * @param baudrate_Bps USART baudrate to be set. * @param srcClock_Hz USART clock source freqency in HZ. * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source. * @retval kStatus_Success Set baudrate succeed. * @retval kStatus_InvalidArgument One or more arguments are invalid. */ status_t USART_SetBaudRate(USART_Type *base, uint32_t baudrate_Bps, uint32_t srcClock_Hz); /* @} */ /*! * @name Status * @{ */ /*! * @brief Get USART status flags. * * This function get all USART status flags, the flags are returned as the logical * OR value of the enumerators @ref _usart_flags. To check a specific status, * compare the return value with enumerators in @ref _usart_flags. * For example, to check whether the TX is empty: * @code * if (kUSART_TxFifoNotFullFlag & USART_GetStatusFlags(USART1)) * { * ... * } * @endcode * * @param base USART peripheral base address. * @return USART status flags which are ORed by the enumerators in the _usart_flags. */ static inline uint32_t USART_GetStatusFlags(USART_Type *base) { return base->FIFOSTAT; } /*! * @brief Clear USART status flags. * * This function clear supported USART status flags * Flags that can be cleared or set are: * kUSART_TxError * kUSART_RxError * For example: * @code * USART_ClearStatusFlags(USART1, kUSART_TxError | kUSART_RxError) * @endcode * * @param base USART peripheral base address. * @param mask status flags to be cleared. */ static inline void USART_ClearStatusFlags(USART_Type *base, uint32_t mask) { /* Only TXERR, RXERR fields support write. Remaining fields should be set to zero */ base->FIFOSTAT = mask & (USART_FIFOSTAT_TXERR_MASK | USART_FIFOSTAT_RXERR_MASK); } /* @} */ /*! * @name Interrupts * @{ */ /*! * @brief Enables USART interrupts according to the provided mask. * * This function enables the USART interrupts according to the provided mask. The mask * is a logical OR of enumeration members. See @ref _usart_interrupt_enable. * For example, to enable TX empty interrupt and RX full interrupt: * @code * USART_EnableInterrupts(USART1, kUSART_TxLevelInterruptEnable | kUSART_RxLevelInterruptEnable); * @endcode * * @param base USART peripheral base address. * @param mask The interrupts to enable. Logical OR of @ref _usart_interrupt_enable. */ static inline void USART_EnableInterrupts(USART_Type *base, uint32_t mask) { base->FIFOINTENSET = mask & 0xF; } /*! * @brief Disables USART interrupts according to a provided mask. * * This function disables the USART interrupts according to a provided mask. The mask * is a logical OR of enumeration members. See @ref _usart_interrupt_enable. * This example shows how to disable the TX empty interrupt and RX full interrupt: * @code * USART_DisableInterrupts(USART1, kUSART_TxLevelInterruptEnable | kUSART_RxLevelInterruptEnable); * @endcode * * @param base USART peripheral base address. * @param mask The interrupts to disable. Logical OR of @ref _usart_interrupt_enable. */ static inline void USART_DisableInterrupts(USART_Type *base, uint32_t mask) { base->FIFOINTENCLR = mask & 0xF; } /*! * @brief Returns enabled USART interrupts. * * This function returns the enabled USART interrupts. * * @param base USART peripheral base address. */ static inline uint32_t USART_GetEnabledInterrupts(USART_Type *base) { return base->FIFOINTENSET; } /*! * @brief Enable DMA for Tx */ static inline void USART_EnableTxDMA(USART_Type *base, bool enable) { if (enable) { base->FIFOCFG |= USART_FIFOCFG_DMATX_MASK; } else { base->FIFOCFG &= ~(USART_FIFOCFG_DMATX_MASK); } } /*! * @brief Enable DMA for Rx */ static inline void USART_EnableRxDMA(USART_Type *base, bool enable) { if (enable) { base->FIFOCFG |= USART_FIFOCFG_DMARX_MASK; } else { base->FIFOCFG &= ~(USART_FIFOCFG_DMARX_MASK); } } /*! * @brief Enable CTS. * This function will determine whether CTS is used for flow control. * * @param base USART peripheral base address. * @param enable Enable CTS or not, true for enable and false for disable. */ static inline void USART_EnableCTS(USART_Type *base, bool enable) { if (enable) { base->CFG |= USART_CFG_CTSEN_MASK; } else { base->CFG &= ~USART_CFG_CTSEN_MASK; } } /* @} */ /*! * @name Bus Operations * @{ */ /*! * @brief Writes to the FIFOWR register. * * This function writes data to the txFIFO directly. The upper layer must ensure * that txFIFO has space for data to write before calling this function. * * @param base USART peripheral base address. * @param data The byte to write. */ static inline void USART_WriteByte(USART_Type *base, uint8_t data) { base->FIFOWR = data; } /*! * @brief Reads the FIFORD register directly. * * This function reads data from the rxFIFO directly. The upper layer must * ensure that the rxFIFO is not empty before calling this function. * * @param base USART peripheral base address. * @return The byte read from USART data register. */ static inline uint8_t USART_ReadByte(USART_Type *base) { return base->FIFORD; } /*! * @brief Writes to the TX register using a blocking method. * * This function polls the TX register, waits for the TX register to be empty or for the TX FIFO * to have room and writes data to the TX buffer. * * @param base USART peripheral base address. * @param data Start address of the data to write. * @param length Size of the data to write. */ void USART_WriteBlocking(USART_Type *base, const uint8_t *data, size_t length); /*! * @brief Read RX data register using a blocking method. * * This function polls the RX register, waits for the RX register to be full or for RX FIFO to * have data and read data from the TX register. * * @param base USART peripheral base address. * @param data Start address of the buffer to store the received data. * @param length Size of the buffer. * @retval kStatus_USART_FramingError Receiver overrun happened while receiving data. * @retval kStatus_USART_ParityError Noise error happened while receiving data. * @retval kStatus_USART_NoiseError Framing error happened while receiving data. * @retval kStatus_USART_RxError Overflow or underflow rxFIFO happened. * @retval kStatus_Success Successfully received all data. */ status_t USART_ReadBlocking(USART_Type *base, uint8_t *data, size_t length); /* @} */ /*! * @name Transactional * @{ */ /*! * @brief Initializes the USART handle. * * This function initializes the USART handle which can be used for other USART * transactional APIs. Usually, for a specified USART instance, * call this API once to get the initialized handle. * * @param base USART peripheral base address. * @param handle USART handle pointer. * @param callback The callback function. * @param userData The parameter of the callback function. */ status_t USART_TransferCreateHandle(USART_Type *base, usart_handle_t *handle, usart_transfer_callback_t callback, void *userData); /*! * @brief Transmits a buffer of data using the interrupt method. * * This function sends data using an interrupt method. This is a non-blocking function, which * returns directly without waiting for all data to be written to the TX register. When * all data is written to the TX register in the IRQ handler, the USART driver calls the callback * function and passes the @ref kStatus_USART_TxIdle as status parameter. * * @note The kStatus_USART_TxIdle is passed to the upper layer when all data is written * to the TX register. However it does not ensure that all data are sent out. Before disabling the TX, * check the kUSART_TransmissionCompleteFlag to ensure that the TX is finished. * * @param base USART peripheral base address. * @param handle USART handle pointer. * @param xfer USART transfer structure. See #usart_transfer_t. * @retval kStatus_Success Successfully start the data transmission. * @retval kStatus_USART_TxBusy Previous transmission still not finished, data not all written to TX register yet. * @retval kStatus_InvalidArgument Invalid argument. */ status_t USART_TransferSendNonBlocking(USART_Type *base, usart_handle_t *handle, usart_transfer_t *xfer); /*! * @brief Sets up the RX ring buffer. * * This function sets up the RX ring buffer to a specific USART handle. * * When the RX ring buffer is used, data received are stored into the ring buffer even when the * user doesn't call the USART_TransferReceiveNonBlocking() API. If there is already data received * in the ring buffer, the user can get the received data from the ring buffer directly. * * @note When using the RX ring buffer, one byte is reserved for internal use. In other * words, if @p ringBufferSize is 32, then only 31 bytes are used for saving data. * * @param base USART peripheral base address. * @param handle USART handle pointer. * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer. * @param ringBufferSize size of the ring buffer. */ void USART_TransferStartRingBuffer(USART_Type *base, usart_handle_t *handle, uint8_t *ringBuffer, size_t ringBufferSize); /*! * @brief Aborts the background transfer and uninstalls the ring buffer. * * This function aborts the background transfer and uninstalls the ring buffer. * * @param base USART peripheral base address. * @param handle USART handle pointer. */ void USART_TransferStopRingBuffer(USART_Type *base, usart_handle_t *handle); /*! * @brief Get the length of received data in RX ring buffer. * * @param handle USART handle pointer. * @return Length of received data in RX ring buffer. */ size_t USART_TransferGetRxRingBufferLength(usart_handle_t *handle); /*! * @brief Aborts the interrupt-driven data transmit. * * This function aborts the interrupt driven data sending. The user can get the remainBtyes to find out * how many bytes are still not sent out. * * @param base USART peripheral base address. * @param handle USART handle pointer. */ void USART_TransferAbortSend(USART_Type *base, usart_handle_t *handle); /*! * @brief Get the number of bytes that have been written to USART TX register. * * This function gets the number of bytes that have been written to USART TX * register by interrupt method. * * @param base USART peripheral base address. * @param handle USART handle pointer. * @param count Send bytes count. * @retval kStatus_NoTransferInProgress No send in progress. * @retval kStatus_InvalidArgument Parameter is invalid. * @retval kStatus_Success Get successfully through the parameter \p count; */ status_t USART_TransferGetSendCount(USART_Type *base, usart_handle_t *handle, uint32_t *count); /*! * @brief Receives a buffer of data using an interrupt method. * * This function receives data using an interrupt method. This is a non-blocking function, which * returns without waiting for all data to be received. * If the RX ring buffer is used and not empty, the data in the ring buffer is copied and * the parameter @p receivedBytes shows how many bytes are copied from the ring buffer. * After copying, if the data in the ring buffer is not enough to read, the receive * request is saved by the USART driver. When the new data arrives, the receive request * is serviced first. When all data is received, the USART driver notifies the upper layer * through a callback function and passes the status parameter @ref kStatus_USART_RxIdle. * For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer. * The 5 bytes are copied to the xfer->data and this function returns with the * parameter @p receivedBytes set to 5. For the left 5 bytes, newly arrived data is * saved from the xfer->data[5]. When 5 bytes are received, the USART driver notifies the upper layer. * If the RX ring buffer is not enabled, this function enables the RX and RX interrupt * to receive data to the xfer->data. When all data is received, the upper layer is notified. * * @param base USART peripheral base address. * @param handle USART handle pointer. * @param xfer USART transfer structure, see #usart_transfer_t. * @param receivedBytes Bytes received from the ring buffer directly. * @retval kStatus_Success Successfully queue the transfer into transmit queue. * @retval kStatus_USART_RxBusy Previous receive request is not finished. * @retval kStatus_InvalidArgument Invalid argument. */ status_t USART_TransferReceiveNonBlocking(USART_Type *base, usart_handle_t *handle, usart_transfer_t *xfer, size_t *receivedBytes); /*! * @brief Aborts the interrupt-driven data receiving. * * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to find out * how many bytes not received yet. * * @param base USART peripheral base address. * @param handle USART handle pointer. */ void USART_TransferAbortReceive(USART_Type *base, usart_handle_t *handle); /*! * @brief Get the number of bytes that have been received. * * This function gets the number of bytes that have been received. * * @param base USART peripheral base address. * @param handle USART handle pointer. * @param count Receive bytes count. * @retval kStatus_NoTransferInProgress No receive in progress. * @retval kStatus_InvalidArgument Parameter is invalid. * @retval kStatus_Success Get successfully through the parameter \p count; */ status_t USART_TransferGetReceiveCount(USART_Type *base, usart_handle_t *handle, uint32_t *count); /*! * @brief USART IRQ handle function. * * This function handles the USART transmit and receive IRQ request. * * @param base USART peripheral base address. * @param handle USART handle pointer. */ void USART_TransferHandleIRQ(USART_Type *base, usart_handle_t *handle); /* @} */ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* _FSL_USART_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/ff_stdio.c
<reponame>MicroEJ/FreeRTOS<filename>FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/ff_stdio.c /* * FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab! * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Authors include <NAME>, <NAME> and <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * */ /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "portable.h" /* FreeRTOS+FAT includes. */ #include "ff_headers.h" #include "ff_stdio.h" #if( ffconfigTIME_SUPPORT != 0 ) #include <time.h> #endif #ifndef SIZE_MAX #define SIZE_MAX ( ( size_t ) -1 ) #endif /* The number of bytes to write at a time when extending the length of a file in a call to ff_truncate(). */ #define stdioTRUNCATE_WRITE_LENGTH 512 /* Bits set to indicate whether ".." should be included as well as ".". */ #define stdioDIR_ENTRY_DOT_1 ( 1U & 0x03U ) #define stdioDIR_ENTRY_DOT_2 ( 2U & 0x03U ) /* The directory entries '.' and '..' will show a file size of 1 KB. */ #define stdioDOT_ENTRY_FILE_SIZE 1024 /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) /* FreeRTOS+FAT requires two thread local storage pointers. One for errno and one for the CWD structure. */ #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS < 2 ) #error FreeRTOS+FAT requires two thread local storage pointers so configNUM_THREAD_LOCAL_STORAGE_POINTERS must be at least 2 in FreeRTOSConfig.h #endif /* Each task has its own Current Working Directory (CWD). The CWD is used to extend relative paths to absolute paths. */ typedef struct WORKING_DIR { char pcCWD[ ffconfigMAX_FILENAME ]; /* The current working directory. */ char pcFileName[ ffconfigMAX_FILENAME ]; /* The created absolute path. */ } WorkingDirectory_t; /* * Add the CWD to the beginning of a relative path, and copy the resultant * absolute path into a thread local non const buffer. */ /*static*/ const char *prvABSPath( const char *pcPath ); /* * Lookup the CWD of the current task. */ static WorkingDirectory_t *pxFindCWD( void ); /* * Convert a string which may contain a relative path into a string that * will only contain an absolute path. */ static const char *prvProcessRelativePaths( const char *pcPath ); #else /* ffconfigHAS_CWD */ /* FreeRTOS+FAT requires one thread local storage pointers for errno. */ #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS < 2 ) #error FreeRTOS+FAT requires one thread local storage pointers so configNUM_THREAD_LOCAL_STORAGE_POINTERS must be at least 1 in FreeRTOSConfig.h #endif /* Only absolute paths are supported so define away the prvABSPath() function. */ /*static*/ const char *prvABSPath( const char *pcPath ) { return pcPath; } #endif /* ffconfigHAS_CWD */ #if( ffconfigUSE_DELTREE != 0 ) /* * Remove all files and directories starting from a certain path. * This function uses recursion - which breaches the coding standard. USE * WITH CARE. */ static int ff_deltree_recurse( char *pcPath ); #endif /* * Translate a +FAT error to a value compatible with errno.h * If the value represents an error, it is negative * The return value of this function will always be positive */ int prvFFErrorToErrno( FF_Error_t xError ); /* * Generate a time stamp for the file. */ #if( ffconfigTIME_SUPPORT == 1 ) static uint32_t prvFileTime( FF_SystemTime_t *pxTime ); #endif /*-----------------------------------------------------------*/ FF_FILE *ff_fopen( const char *pcFile, const char *pcMode ) { FF_FILE *pxStream = NULL; FF_DirHandler_t xHandler; FF_Error_t xError; uint8_t ucMode; /* Insert the current working directory in front of relative paths. */ pcFile = prvABSPath( pcFile ); /* Look-up the I/O manager for the file system. */ if( FF_FS_Find( pcFile, &xHandler ) == pdFALSE ) { stdioSET_ERRNO( pdFREERTOS_ERRNO_ENXIO ); /* No such device or address. */ } else { /* Now 'xHandler.pcPath' contains an absolute path within the file system. Translate a type string "r|w|a[+]" to +FAT's mode bits. */ ucMode = FF_GetModeBits( pcMode ); pxStream = FF_Open( xHandler.pxManager, xHandler.pcPath, ucMode, &xError ); stdioSET_ERRNO( prvFFErrorToErrno( xError ) ); #if( ffconfigUSE_NOTIFY != 0 ) { if( ( pxStream != NULL ) && ( ( ucMode & ( FF_MODE_WRITE | FF_MODE_APPEND ) ) != 0 ) ) { /*_RB_ Function name needs updating. */ callFileEvents( pcFile, eFileCreate ); } } #endif /* ffconfigUSE_NOTIFY */ #if( ffconfigDEV_SUPPORT != 0 ) { if( pxStream != NULL ) { FF_Device_Open( pcFile, pxStream ); } } #endif /* ffconfigDEV_SUPPORT */ } return pxStream; } /*-----------------------------------------------------------*/ int ff_fclose( FF_FILE *pxStream ) { FF_Error_t xError; int iReturn, ff_errno; #if( ffconfigDEV_SUPPORT != 0 ) { /* Currently device support is in an experimental state. It will allow to create virtual files. The I/O data to those files will be redirected to their connected "drivers". */ if( pxStream != NULL ) { FF_Device_Close( pxStream ); } } #endif xError = FF_Close( pxStream ); ff_errno = prvFFErrorToErrno( xError ); if( ff_errno == 0 ) { iReturn = 0; } else { /* Return -1 for error as per normal fclose() semantics. */ iReturn = -1; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iReturn; } /*-----------------------------------------------------------*/ int ff_fseek( FF_FILE *pxStream, long lOffset, int iWhence ) { FF_Error_t xError; int iReturn, ff_errno; #if( ffconfigDEV_SUPPORT != 0 ) if( pxStream->pxDevNode != NULL ) { xError = FF_Device_Seek( pxStream, lOffset, iWhence ); } else #endif { xError = FF_Seek( pxStream, lOffset, iWhence ); } ff_errno = prvFFErrorToErrno( xError ); if( ff_errno == 0 ) { iReturn = 0; } else { if( xError == FF_ERR_FILE_SEEK_INVALID_POSITION ) { /* Illegal position, outside the file's space */ ff_errno = pdFREERTOS_ERRNO_ESPIPE; } else if( xError == FF_ERR_FILE_SEEK_INVALID_ORIGIN ) { /* Illegal parameter value for iWhence: SET,CUR,END. */ ff_errno = pdFREERTOS_ERRNO_EINVAL; } /* Return -1 for error as per normal fseek() semantics. */ iReturn = -1; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iReturn; } /*-----------------------------------------------------------*/ void ff_rewind( FF_FILE *pxStream ) { ff_fseek( pxStream, 0, FF_SEEK_SET ); /* Rewind is supposed to reset errno unconditionally. Store the errno to thread local storage. */ stdioSET_ERRNO( 0 ); } /*-----------------------------------------------------------*/ long ff_ftell( FF_FILE *pxStream ) { long lResult; if( pxStream == NULL ) { /* Store the errno to thread local storage. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_EBADF ); /* Return -1 for error as per normal ftell() semantics. */ lResult = -1; } else { lResult = ( long ) pxStream->ulFilePointer; } return lResult; } /*-----------------------------------------------------------*/ int ff_feof( FF_FILE *pxStream ) { int iResult; FF_Error_t xError; xError = FF_CheckValid( pxStream ); if( FF_isERR( xError ) == pdFALSE ) { /* Store the errno to thread local storage. */ stdioSET_ERRNO( 0 ); if( pxStream->ulFilePointer >= pxStream->ulFileSize ) { iResult = pdTRUE; } else { iResult = pdFALSE; } } else { /* Store the errno to thread local storage. */ stdioSET_ERRNO( prvFFErrorToErrno( xError ) ); /* The file was invalid so a non-zero value cannot be returned. */ iResult = pdFALSE; } return iResult; } /*-----------------------------------------------------------*/ size_t ff_fread( void *pvBuffer, size_t xSize, size_t xItems, FF_FILE * pxStream ) { int32_t iReturned; size_t xReturn; int ff_errno; #if( ffconfigDEV_SUPPORT != 0 ) if( pxStream->pxDevNode != NULL ) { iReturned = FF_Device_Read( pvBuffer, xSize, xItems, pxStream ); } else #endif { iReturned = FF_Read( pxStream, xSize, xItems, (uint8_t *)pvBuffer ); } ff_errno = prvFFErrorToErrno( iReturned ); if( ff_errno == pdFREERTOS_ERRNO_NONE ) { /* As per the standard fread() semantics, the return value is the number of complete items read, which will only equal the number of bytes transferred when the item size is 1. */ xReturn = ( size_t ) iReturned; } else { xReturn = 0; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return xReturn; } /*-----------------------------------------------------------*/ size_t ff_fwrite( const void *pvBuffer, size_t xSize, size_t xItems, FF_FILE * pxStream ) { int32_t iReturned; size_t xReturn; int ff_errno; #if( ffconfigDEV_SUPPORT != 0 ) if( pxStream->pxDevNode != NULL ) { iReturned = FF_Device_Write( pvBuffer, xSize, xItems, pxStream ); } else #endif { iReturned = FF_Write( pxStream, xSize, xItems, (uint8_t *)pvBuffer ); } ff_errno = prvFFErrorToErrno( iReturned ); if( ff_errno == pdFREERTOS_ERRNO_NONE ) { /* As per the standard fwrite() semantics, the return value is the number of complete items read, which will only equal the number of bytes transferred when the item size is 1. */ xReturn = ( size_t ) iReturned; } else { xReturn = 0; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return xReturn; } /*-----------------------------------------------------------*/ int ff_fgetc( FF_FILE * pxStream ) { int32_t iResult; int ff_errno; iResult = FF_GetC( pxStream ); ff_errno = prvFFErrorToErrno( iResult ); if( ff_errno != 0 ) { iResult = FF_EOF; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iResult; } /*-----------------------------------------------------------*/ int ff_fputc( int iChar, FF_FILE *pxStream ) { int iResult, ff_errno; iResult = FF_PutC( pxStream, ( uint8_t ) iChar ); ff_errno = prvFFErrorToErrno( iResult ); if( ff_errno != 0 ) { iResult = FF_EOF; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iResult; } /*-----------------------------------------------------------*/ #if( ffconfigFPRINTF_SUPPORT == 1 ) int ff_fprintf( FF_FILE * pxStream, const char *pcFormat, ... ) { int iCount; size_t xResult; char *pcBuffer; va_list xArgs; pcBuffer = ( char * ) ffconfigMALLOC( ffconfigFPRINTF_BUFFER_LENGTH ); if( pcBuffer == NULL ) { /* Store the errno to thread local storage. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_ENOMEM ); iCount = -1; } else { va_start( xArgs, pcFormat ); iCount = vsnprintf( pcBuffer, ffconfigFPRINTF_BUFFER_LENGTH, pcFormat, xArgs ); va_end( xArgs ); /* ff_fwrite() will set ff_errno. */ if( iCount > 0 ) { xResult = ff_fwrite( pcBuffer, ( size_t ) 1, ( size_t ) iCount, pxStream ); if( xResult < ( size_t ) iCount ) { iCount = -1; } } ffconfigFREE( pcBuffer ); } return iCount; } #endif /*-----------------------------------------------------------*/ /*_RB_ to comply with the norm, the second parameter should be an int, but size_t is more appropriate. */ char *ff_fgets( char *pcBuffer, size_t xCount, FF_FILE *pxStream ) { int32_t xResult; int ff_errno; xResult = FF_GetLine( pxStream, ( char * ) pcBuffer, xCount ); /* This call seems to result in errno being incorrectly set to FF_ERR_IOMAN_NO_MOUNTABLE_PARTITION when an EOF is encountered. */ ff_errno = prvFFErrorToErrno( xResult ); if( ff_errno != 0 ) { pcBuffer = NULL; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return pcBuffer; } /*-----------------------------------------------------------*/ int ff_seteof( FF_FILE *pxStream ) { FF_Error_t iResult; int iReturn, ff_errno; iResult = FF_SetEof( pxStream ); ff_errno = prvFFErrorToErrno( iResult ); if( ff_errno == 0 ) { iReturn = 0; } else { iReturn = FF_EOF; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iReturn; } /*-----------------------------------------------------------*/ /*_RB_ The norm would be to return an int, but in either case it is not clear what state the file is left in (open/closed). */ FF_FILE *ff_truncate( const char * pcFileName, long lTruncateSize ) { FF_Error_t xResult = 0; FF_FILE *pxStream; size_t xReturned; uint32_t ulLength, ulBytesLeftToAdd, ulBytesToWrite; char *pcBufferToWrite; pxStream = ff_fopen( pcFileName, "a+"); if( pxStream != NULL ) { ulLength = pxStream->ulFileSize; } else { ulLength = 0; } if( pxStream == NULL ) { /* Store the errno to thread local storage. */ stdioSET_ERRNO( prvFFErrorToErrno( xResult ) ); } else if( ulLength > ( uint32_t ) lTruncateSize ) { /* Seek the desired position */ xResult = FF_Seek( pxStream, lTruncateSize, FF_SEEK_SET ); /* Make the current position equal to its length */ if( FF_isERR( xResult ) == pdFALSE ) { xResult = FF_SetEof( pxStream ); } if( FF_isERR( xResult ) != pdFALSE ) { ff_fclose( pxStream ); pxStream = NULL; } /* Store the errno to thread local storage. */ stdioSET_ERRNO( prvFFErrorToErrno( xResult ) ); } else if( ulLength == ( uint32_t ) lTruncateSize ) { /* Nothing to do, the file has the desired size and the open handle will be returned. */ } else { /* lTruncateSize > ulLength. The user wants to open this file with a larger size than it currently has. Fill it with zeros. */ pcBufferToWrite = ( char * ) ffconfigMALLOC( stdioTRUNCATE_WRITE_LENGTH ); if( pcBufferToWrite == NULL ) { ff_fclose( pxStream ); pxStream = NULL; /* Store the errno to thread local storage. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_ENOMEM ); } else { /* File has to grow */ ulBytesLeftToAdd = ( ( uint32_t ) lTruncateSize ) - ulLength; /* Zeros must be written. */ memset( pcBufferToWrite, '\0', stdioTRUNCATE_WRITE_LENGTH ); while( ulBytesLeftToAdd > 0UL ) { if( ( pxStream->ulFileSize % stdioTRUNCATE_WRITE_LENGTH ) != 0 ) { /* Although +FAT's FF_Write() can handle any size at any offset, the driver puts data more efficiently if blocks are written at block boundaries. */ ulBytesToWrite = stdioTRUNCATE_WRITE_LENGTH - ( pxStream->ulFileSize % stdioTRUNCATE_WRITE_LENGTH ); if( ulBytesToWrite > ulBytesLeftToAdd ) { ulBytesToWrite = ulBytesLeftToAdd; } } else { ulBytesToWrite = ulBytesLeftToAdd; if( ulBytesToWrite > stdioTRUNCATE_WRITE_LENGTH ) { ulBytesToWrite = stdioTRUNCATE_WRITE_LENGTH; } } xReturned = ff_fwrite( pcBufferToWrite, sizeof( char ), ulBytesToWrite, pxStream ); if( xReturned != ( size_t ) ulBytesToWrite ) { /* Write error. Close the stream and set the proper . errno. */ ff_fclose( pxStream ); pxStream = NULL; /* Not setting ff_errno because it has been set by other functions from this ff_stdio. */ break; } ulBytesLeftToAdd -= ulBytesToWrite; } ffconfigFREE( pcBufferToWrite ); } } return pxStream; } /*-----------------------------------------------------------*/ #if( ffconfigMKDIR_RECURSIVE == 0 ) /* The normal mkdir() : if assumes that the directories leading to the last element of pcDirectory already exists. For instance: mkdir( "/a/b/c" ) will succeed if the path "/a/b" already exists. */ int ff_mkdir( const char *pcDirectory ) { int iResult, ff_errno; FF_DirHandler_t xHandler; /* In case a CWD is used, get the absolute path. */ pcDirectory = prvABSPath( pcDirectory ); /* Find the i/o manager for this path */ if( FF_FS_Find( pcDirectory, &xHandler ) == pdFALSE ) { /* No such device or address. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_ENXIO ); /* Return -1 for error as per normal mkdir() semantics. */ iResult = -1; } else { /* A simple non-recursive make of a directory. */ iResult = FF_MkDir( xHandler.pxManager, xHandler.pcPath ); if( FF_GETERROR( iResult ) == FF_ERR_DIR_OBJECT_EXISTS ) { /* No error if the target directory already exists. */ iResult = FF_ERR_NONE; } ff_errno = prvFFErrorToErrno( iResult ); /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); if( ff_errno == pdFREERTOS_ERRNO_NONE ) { iResult = 0; } else { /* Return -1 for error as per normal mkdir() semantics. */ iResult = -1; } } return iResult; } #else /* ffconfigMKDIR_RECURSIVE */ #warning This path is not yet included in the regression tests. /* The 'recursive mkdir() : if the parameter 'xRecursive' is non-zero, the function will try to create the complete path. */ int ff_mkdir( const char *pcDirectory, int xRecursive ) { int32_t lResult; FF_DirHandler_t xHandler; /* In case a CWD is used, get the absolute path. */ pcDirectory = prvABSPath( pcDirectory ); /* Find the i/o manager for this path */ if( FF_FS_Find( pcDirectory, &xHandler ) == pdFALSE ) { /* No such device or address. Store the errno to thread local storage. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_ENXIO ); /* Return -1 for error as per normal mkdir() semantics. */ lResult = -1; } else { if( xRecursive == pdFALSE ) { /* A simple non-recursive make of a directory. */ lResult = FF_MkDir( xHandler.pxManager, xHandler.pcPath ); if( FF_GETERROR( lResult ) == FF_ERR_DIR_OBJECT_EXISTS ) { /* No error if the target directory already exists. */ lResult = 0; } } else { /* The recursive option is used. */ char pcTempPath[ffconfigMAX_FILENAME]; FF_Error_t errCode; int iLength = snprintf( pcTempPath, sizeof( pcTempPath ), "%s", xHandler.pcPath ); char *pcPtr = pcTempPath + 1, *pcPrev; const char *pcLast = pcTempPath + iLength; lResult = FF_ERR_NONE; for( ; ; ) { for ( pcPrev = pcPtr; pcPtr < pcLast; pcPtr++ ) { if( *pcPtr == '/' ) { *pcPtr = '\0'; break; } } if( pcPrev == pcPtr ) { break; } errCode = FF_MkDir( xHandler.pxManager, pcTempPath ); if( FF_isERR( errCode ) && FF_GETERROR( errCode ) != FF_ERR_DIR_OBJECT_EXISTS ) { lResult = errCode; break; } if( pcPtr >= ( pcLast - 1 ) ) { break; } *( pcPtr++ ) = '/'; } } /* Store the errno to thread local storage. */ stdioSET_ERRNO( prvFFErrorToErrno( lResult ) ); } return lResult; } #endif /* ffconfigMKDIR_RECURSIVE */ /*-----------------------------------------------------------*/ int ff_rmdir( const char *pcDirectory ) { int32_t lResult; int iReturn, ff_errno; FF_DirHandler_t xHandler; /* In case a CWD is used, get the absolute path */ pcDirectory = prvABSPath( pcDirectory ); /* Find the i/o manager which can handle this path. */ if( FF_FS_Find( pcDirectory, &xHandler ) == pdFALSE ) { ff_errno = pdFREERTOS_ERRNO_ENXIO; /* No such device or address */ /* Return -1 for error as per normal rmdir() semantics. */ iReturn = -1; } else { lResult = FF_RmDir( xHandler.pxManager, xHandler.pcPath ); ff_errno = prvFFErrorToErrno( lResult ); if( ff_errno == 0 ) { iReturn = 0; } else { /* Return -1 for error as per normal rmdir() semantics. */ iReturn = -1; } } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iReturn; } /*-----------------------------------------------------------*/ int ff_remove( const char *pcPath ) { FF_DirHandler_t xHandler; FF_Error_t xError; int iReturn, ff_errno; /* In case a CWD is used, get the absolute path */ pcPath = prvABSPath( pcPath ); /* Find the i/o manager which can handle this path. */ if( FF_FS_Find( pcPath, &xHandler ) == pdFALSE ) { /* No such device or address */ ff_errno = pdFREERTOS_ERRNO_ENXIO; /* Return -1 for error as per normal remove() semantics. */ iReturn = -1; } else { xError = FF_RmFile( xHandler.pxManager, xHandler.pcPath ); ff_errno = prvFFErrorToErrno( xError ); #if ffconfigUSE_NOTIFY { if( FF_isERR( xError ) == pdFALSE ) { callFileEvents( pcPath, eFileRemove ); } } #endif if( ff_errno == 0 ) { iReturn = 0; } else { /* Return -1 for error as per normal remove() semantics. */ iReturn = -1; } } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); return iReturn; } /*-----------------------------------------------------------*/ /*_RB_ Last parameter not documented. */ int ff_rename( const char *pcOldName, const char *pcNewName, int bDeleteIfExists ) { FF_DirHandler_t xHandlers[ 2 ]; FF_Error_t xError = FF_ERR_NONE; int ff_errno = 0, iReturn; #if( ffconfigHAS_CWD != 0 ) char *pcOldCopy; size_t xSize; #endif /* In case a CWD is used, get the absolute path */ pcOldName = prvABSPath( pcOldName ); /* Find the i/o manager which can handle this path */ if( FF_FS_Find( pcOldName, &xHandlers[ 0 ] ) == pdFALSE ) { xError = ( int32_t ) ( FF_ERR_NULL_POINTER | FF_MOVE ); ff_errno = pdFREERTOS_ERRNO_ENXIO; /* No such device or address */ } else { #if( ffconfigHAS_CWD != 0 ) { xSize = strlen( xHandlers[0].pcPath ) + 1; pcOldCopy = ( char *)ffconfigMALLOC( xSize ); if( pcOldCopy == NULL ) { /* Could not allocate space to store a file name. */ ff_errno = pdFREERTOS_ERRNO_ENOMEM; xError = ( int32_t ) ( FF_ERR_NOT_ENOUGH_MEMORY | FF_MOVE ); } else { /* The function prvABSPath() returns a pointer to the task storage space. Rename needs to call it twice and therefore the path must be stored before it gets overwritten. */ memcpy( pcOldCopy, xHandlers[0].pcPath, xSize ); xHandlers[0].pcPath = pcOldCopy; } } #endif /* ffconfigHAS_CWD != 0 */ #if( ffconfigHAS_CWD != 0 ) if( pcOldCopy != NULL ) #endif /* ffconfigHAS_CWD != 0 */ { pcNewName = prvABSPath( pcNewName ); /* Find the i/o manager which can handle this path */ if( FF_FS_Find( pcNewName, &( xHandlers[ 1 ] ) ) == pdFALSE ) { xError = ( int32_t ) ( FF_ERR_NULL_POINTER | FF_MOVE ); ff_errno = pdFREERTOS_ERRNO_ENXIO; /* No such device or address */ } else if( xHandlers[ 0 ].pxManager != xHandlers[ 1 ].pxManager ) { xError = ( int32_t ) ( FF_ERR_NULL_POINTER | FF_MOVE ); /* Cross-device link, which can not be done. */ ff_errno = pdFREERTOS_ERRNO_EXDEV; } else { xError = FF_Move( xHandlers[ 0 ].pxManager, xHandlers[ 0 ].pcPath, xHandlers[ 1 ].pcPath, bDeleteIfExists ); ff_errno = prvFFErrorToErrno( xError ); #if ffconfigUSE_NOTIFY { if( FF_isERR( xError ) == pdFALSE ) { callFileEvents( pcNewName, eFileChange ); } } #endif } #if( ffconfigHAS_CWD != 0 ) { ffconfigFREE( pcOldCopy ); } #endif } } /* Store the errno to thread local storage. */ stdioSET_ERRNO( ff_errno ); if( ff_errno == 0 ) { iReturn = 0; } else { /* Return -1 for error as per normal rmdir() semantics. */ iReturn = -1; } return iReturn; } /*-----------------------------------------------------------*/ int ff_stat( const char *pcName, FF_Stat_t *pxStatBuffer ) { FF_DirEnt_t xDirEntry; uint32_t ulFileCluster; FF_Error_t xError; int iResult; FF_DirHandler_t xHandler; BaseType_t xIndex; FF_FindParams_t xFindParams; #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) const FF_T_WCHAR *pcFileName = NULL; #else /* Initialised to prevent MSVC incorrectly claiming the variable is used without being initialised. */ const char *pcFileName = NULL; #endif memset( &xFindParams, '\0', sizeof( xFindParams ) ); /* Insert the current working directory in front of relative paths. */ pcName = prvABSPath( pcName ); /* Look-up the I/O manager for the file system. */ if( FF_FS_Find( pcName, &xHandler ) == pdFALSE ) { /* No such device or address. */ xError = ( FF_Error_t ) ( pdFREERTOS_ERRNO_ENXIO | FF_STAT_FUNC ); } else { xError = FF_ERR_NONE; pcName = xHandler.pcPath; /* Let xIndex point to the last occurrence of '/' or '\', to separate the path from the file name. */ xIndex = ( BaseType_t ) STRLEN( pcName ); while( xIndex != 0 ) { if( ( pcName[ xIndex ] == '\\' ) || ( pcName[ xIndex ] == '/' ) ) { break; } xIndex--; } /* Copy the file name, i.e. the string that comes after the last separator. */ pcFileName = pcName + xIndex + 1; if( xIndex == 0 ) { /* Only for the root, the slash is part of the directory name. 'xIndex' now equals to the length of the path name. */ xIndex = 1; } /* FF_CreateShortName() might set flags FIND_FLAG_FITS_SHORT and FIND_FLAG_SIZE_OK. */ FF_CreateShortName( &xFindParams, pcFileName ); /* Lookup the path and find the cluster pointing to the directory: */ xFindParams.ulDirCluster = FF_FindDir( xHandler.pxManager, pcName, xIndex, &xError ); } if( FF_isERR( xError ) == pdFALSE ) { /* See if the file does exist within the given directory. */ ulFileCluster = FF_FindEntryInDir( xHandler.pxManager, &xFindParams, pcFileName, 0x00, &xDirEntry, &xError ); if( ulFileCluster == 0ul ) { /* If cluster 0 was returned, it might be because the file has no allocated cluster, i.e. only a directory entry and no stored data. */ if( STRLEN( pcFileName ) == STRLEN( xDirEntry.pcFileName ) ) { if( ( xDirEntry.ulFileSize == 0 ) && ( FF_strmatch( pcFileName, xDirEntry.pcFileName, ( BaseType_t ) STRLEN( pcFileName ) ) == pdTRUE ) ) { /* It is the file, give it a pseudo cluster number '1'. */ ulFileCluster = 1; /* And reset any error. */ xError = FF_ERR_NONE; } } } /* Test 'ulFileCluster' again, it might have been changed. */ if( ulFileCluster == 0ul ) { xError = FF_ERR_FILE_NOT_FOUND | FF_STAT_FUNC; } } if( ( pxStatBuffer != NULL ) && ( FF_isERR( xError ) == pdFALSE ) ) { if( ( xDirEntry.ucAttrib & FF_FAT_ATTR_DIR ) != 0 ) { pxStatBuffer->st_mode = ( unsigned short ) FF_IFDIR; } else { pxStatBuffer->st_mode = ( unsigned short ) FF_IFREG; } #if( ffconfigDEV_SUPPORT != 0 ) { BaseType_t bIsDeviceDir = xCheckDevicePath( pcFileName ); if( bIsDeviceDir != pdFALSE ) { FF_Device_GetDirEnt( xHandler.pcPath, &( xDirEntry ) ); } } #endif /* Despite the warning output by MSVC - it is not possible to get here if xDirEntry has not been initialised. */ pxStatBuffer->st_size = xDirEntry.ulFileSize; pxStatBuffer->st_ino = xDirEntry.ulObjectCluster; pxStatBuffer->st_dev = ( short ) xHandler.xFSIndex; #if( ffconfigTIME_SUPPORT == 1 ) { pxStatBuffer->st_atime = ( unsigned long ) prvFileTime( &( xDirEntry.xAccessedTime ) ); pxStatBuffer->st_mtime = ( unsigned long ) prvFileTime( &( xDirEntry.xModifiedTime ) ); pxStatBuffer->st_ctime = ( unsigned long ) prvFileTime( &( xDirEntry.xCreateTime ) ); } #endif } stdioSET_ERRNO( prvFFErrorToErrno( xError ) ); if( FF_isERR( xError ) == pdFALSE ) { iResult = 0; } else { iResult = -1; } return iResult; } /* ff_stat() */ /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) int ff_chdir( const char *pcDirectoryName ) { int iResult, iLength, iValid = pdFALSE; WorkingDirectory_t *pxDir = NULL; /* Not all paths set an errno. */ stdioSET_ERRNO( 0 ); /* Is there a file system mounted? */ if( FF_FS_Count() != 0 ) { /* In case a CWD is used, get the absolute path. */ pcDirectoryName = prvABSPath( pcDirectoryName ); pxDir = pxFindCWD(); if( pxDir == NULL ) { /* Store the errno to thread local storage. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_ENOMEM ); /* Return -1 for error as per normal chdir() semantics. */ iResult = -1; } else { /* The CWD will be stored without a trailing '/'. If "/" happens to be the CWD, it will be stored as an empty string. */ iLength = strlen( pcDirectoryName ); /* Knock off the trailing / if one exits - being careful not to remove the trailing slash if this is the root directory. */ if( ( iLength > 1 ) && ( pxDir->pcFileName[ iLength - 1 ] == '/' ) ) { pxDir->pcFileName[ iLength - 1 ] = '\0'; } stdioSET_ERRNO( pdFREERTOS_ERRNO_ENOENT ); /* Does the directory exist? */ if( strcmp( pcDirectoryName, "/" ) == 0 ) { /* Moving to the root - which exists. */ iValid = pdTRUE; } else if( ff_finddir( pxDir->pcFileName ) != pdFALSE ) { iValid = pdTRUE; } } } if( iValid == pdTRUE ) { /* The generated name becomes the CWD. No need to test for overflow as pcPath and pcFileName are the same size. */ strcpy( pxDir->pcCWD, pxDir->pcFileName ); /* chdir returns 0 for success. */ iResult = FF_ERR_NONE; } else { /* Return -1 for error as per normal chdir() semantics. */ iResult = -1; } return iResult; } #endif /* ffconfigHAS_CWD == 1 */ /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) char *ff_getcwd( char *pcBuffer, size_t xBufferLength ) { WorkingDirectory_t *pxDir = pxFindCWD(); stdioSET_ERRNO( 0 ); if( ( pxDir == NULL ) || ( pxDir->pcCWD[0] == '\0' ) ) { if( xBufferLength > strlen( "/" ) ) { strncpy( pcBuffer, "/", xBufferLength ); } else { pcBuffer = NULL; } } else { if( strlen( pxDir->pcCWD ) < xBufferLength ) { strncpy( pcBuffer, pxDir->pcCWD, xBufferLength ); } else { pcBuffer = NULL; } } return pcBuffer; } #endif /* ffconfigHAS_CWD */ /*-----------------------------------------------------------*/ int ff_findfirst( const char *pcPath, FF_FindData_t *pxFindData ) { int iIsRootDir, iReturn; const char *pcDirectory; iReturn = 0; memset( pxFindData, '\0', sizeof( *pxFindData ) ); pxFindData->pcFileName = pxFindData->xDirectoryEntry.pcFileName; /* In case a CWD is used, get the absolute path. */ pcDirectory = prvABSPath( pcPath ); if( ( pcDirectory[ 0 ] == '/' ) && ( pcDirectory[ 1 ] == 0x00 ) ) { iIsRootDir = pdTRUE; } else { iIsRootDir = pdFALSE; } /* Find the i/o manager that can handle this path. */ if( FF_FS_Find( pcDirectory, &( pxFindData->xDirectoryHandler ) ) == pdFALSE ) { if( ( iIsRootDir == pdFALSE ) || ( FF_FS_Count() == 0 ) ) { stdioSET_ERRNO( prvFFErrorToErrno( ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_FINDFIRST ) ) ); iReturn = -1; } } /* Check no errors before continuing. */ if( iReturn == 0 ) { #if( ffconfigDEV_SUPPORT != 0 ) { pxFindData->bIsDeviceDir = xCheckDevicePath( pcDirectory ); } #endif if( iIsRootDir != pdFALSE ) { /* A listing of the root directory will include pseudo entries such as /ram /nand. */ pxFindData->xDirectoryHandler.xFSIndex = FF_FS_Count(); /* Only add '.' */ pxFindData->xDirectoryHandler.u.bits.bAddDotEntries = stdioDIR_ENTRY_DOT_1; } else { /* This is the root of a sub file system, add "." and ".." */ pxFindData->xDirectoryHandler.u.bits.bAddDotEntries = stdioDIR_ENTRY_DOT_1 | stdioDIR_ENTRY_DOT_2; } pxFindData->xDirectoryHandler.u.bits.bIsValid = pdTRUE; iReturn = ff_findnext( pxFindData ); } else { /* errno has already been set. */ } return iReturn; } /*-----------------------------------------------------------*/ int ff_findnext( FF_FindData_t *pxFindData ) { FF_Error_t xError; #if( ffconfigTIME_SUPPORT != 0 ) BaseType_t xSetTime = 0; #endif /* ffconfigTIME_SUPPORT */ if( pxFindData->xDirectoryHandler.u.bits.bIsValid == pdFALSE ) { xError = ( FF_Error_t ) ( FF_ERR_DIR_INVALID_PARAMETER | FF_FINDNEXT ); FF_PRINTF("ff_findnext: xDirectoryHandler not valid\n" ); } else { xError = ( FF_Error_t ) ( FF_ERR_DIR_END_OF_DIR | FF_FINDNEXT ); if( pxFindData->xDirectoryHandler.pxManager != NULL ) { if( pxFindData->xDirectoryHandler.u.bits.bFirstCalled == pdFALSE ) { pxFindData->xDirectoryHandler.u.bits.bFirstCalled = pdTRUE; xError = FF_FindFirst( pxFindData->xDirectoryHandler.pxManager, &( pxFindData->xDirectoryEntry ), pxFindData->xDirectoryHandler.pcPath ); } else if( pxFindData->xDirectoryHandler.u.bits.bEndOfDir == pdFALSE ) { xError = FF_FindNext( pxFindData->xDirectoryHandler.pxManager, &( pxFindData->xDirectoryEntry ) ); } if( FF_GETERROR( xError ) == FF_ERR_DIR_END_OF_DIR ) { /* Stop further calls to FF_FindNext(). */ pxFindData->xDirectoryHandler.u.bits.bEndOfDir = pdTRUE; } #if( ffconfigDEV_SUPPORT != 0 ) { if( pxFindData->bIsDeviceDir != pdFALSE ) { FF_Device_GetDirEnt( pxFindData->xDirectoryHandler.pcPath, &( pxFindData->xDirectoryEntry ) ); } } #endif } if( FF_isERR( xError ) == pdFALSE ) { /* If an entry is found, see if it is a dot-entry. Dot-entries ("." and "..") need a time-stamp. */ if( pxFindData->xDirectoryEntry.pcFileName[ 0 ] == '.' ) { if( ( pxFindData->xDirectoryEntry.pcFileName[ 1 ] == '.' ) && ( pxFindData->xDirectoryEntry.pcFileName[ 2 ] == '\0' ) ) { /* This is a directory "..". Clear the flag for DOT_2. */ pxFindData->xDirectoryHandler.u.bits.bAddDotEntries &= stdioDIR_ENTRY_DOT_1; #if( ffconfigTIME_SUPPORT != 0 ) { /* The dot-entries do not have a proper time stamp, add it here. */ xSetTime = pdTRUE; } #endif /* ffconfigTIME_SUPPORT */ } else if( pxFindData->xDirectoryEntry.pcFileName[ 1 ] == '\0' ) { /* This is a directory ".". Clear the flag for DOT_1. */ pxFindData->xDirectoryHandler.u.bits.bAddDotEntries &= stdioDIR_ENTRY_DOT_2; #if( ffconfigTIME_SUPPORT != 0 ) { xSetTime = pdTRUE; } #endif /* ffconfigTIME_SUPPORT */ } } } if( FF_GETERROR( xError ) == FF_ERR_DIR_END_OF_DIR ) { /* No more physical entries were found. Now see if there are FS entries or dot-entries to be added: */ while( ( pxFindData->xDirectoryHandler.xFSIndex > 0 ) || ( pxFindData->xDirectoryHandler.u.bits.bAddDotEntries != 0 ) ) { if( pxFindData->xDirectoryHandler.xFSIndex > 0 ) { FF_SubSystem_t xSubSystem; int found; pxFindData->xDirectoryHandler.xFSIndex--; found = FF_FS_Get( pxFindData->xDirectoryHandler.xFSIndex, &xSubSystem ); if( ( found == pdFALSE ) || ( xSubSystem.pcPath[ 1 ] == '\0' ) ) { continue; } snprintf( pxFindData->xDirectoryEntry.pcFileName, sizeof( pxFindData->xDirectoryEntry.pcFileName ), "%s", xSubSystem.pcPath + 1 ); if( xSubSystem.pxManager != NULL ) { pxFindData->xDirectoryEntry.ulObjectCluster = xSubSystem.pxManager->xPartition.ulRootDirCluster; } else { pxFindData->xDirectoryEntry.ulObjectCluster = 0; } } else if( ( pxFindData->xDirectoryHandler.u.bits.bAddDotEntries & stdioDIR_ENTRY_DOT_2 ) != 0 ) { strcpy( pxFindData->xDirectoryEntry.pcFileName, ".."); /* Clear DOT_2 (keep DOT_1). */ pxFindData->xDirectoryHandler.u.bits.bAddDotEntries &= stdioDIR_ENTRY_DOT_1; } else { strcpy( pxFindData->xDirectoryEntry.pcFileName, "."); pxFindData->xDirectoryHandler.u.bits.bAddDotEntries = 0; } pxFindData->xDirectoryEntry.ucAttrib = FF_FAT_ATTR_READONLY | FF_FAT_ATTR_DIR; pxFindData->xDirectoryEntry.ulFileSize = stdioDOT_ENTRY_FILE_SIZE; #if( ffconfigTIME_SUPPORT != 0 ) { xSetTime = pdTRUE; } #endif /* ffconfigTIME_SUPPORT */ xError = FF_ERR_NONE; break; } } #if( ffconfigTIME_SUPPORT != 0 ) { if( xSetTime != pdFALSE ) { FF_TimeStruct_t xTimeStruct; time_t xSeconds; xSeconds = FreeRTOS_time( NULL ); FreeRTOS_gmtime_r( &xSeconds, &xTimeStruct ); pxFindData->xDirectoryEntry.xCreateTime.Year = ( uint16_t ) ( xTimeStruct.tm_year + 1900 ); /* Year (e.g. 2009). */ pxFindData->xDirectoryEntry.xCreateTime.Month = ( uint16_t ) ( xTimeStruct.tm_mon + 1 ); /* Month (e.g. 1 = Jan, 12 = Dec). */ pxFindData->xDirectoryEntry.xCreateTime.Day = ( uint16_t ) xTimeStruct.tm_mday; /* Day (1 - 31). */ pxFindData->xDirectoryEntry.xCreateTime.Hour = ( uint16_t ) xTimeStruct.tm_hour; /* Hour (0 - 23). */ pxFindData->xDirectoryEntry.xCreateTime.Minute = ( uint16_t ) xTimeStruct.tm_min; /* Min (0 - 59). */ pxFindData->xDirectoryEntry.xCreateTime.Second = ( uint16_t ) xTimeStruct.tm_sec; /* Second (0 - 59). */ pxFindData->xDirectoryEntry.xModifiedTime = pxFindData->xDirectoryEntry.xCreateTime; /* Date and Time Modified. */ pxFindData->xDirectoryEntry.xAccessedTime = pxFindData->xDirectoryEntry.xCreateTime; /* Date of Last Access. */ } } #endif /* ffconfigTIME_SUPPORT */ if( FF_GETERROR( xError ) == FF_ERR_DIR_END_OF_DIR ) { /* FF_ERR_DIR_END_OF_DIR will be returned. */ pxFindData->xDirectoryHandler.u.bits.bIsValid = 0; } pxFindData->ucAttributes = pxFindData->xDirectoryEntry.ucAttrib; pxFindData->ulFileSize = pxFindData->xDirectoryEntry.ulFileSize; } stdioSET_ERRNO( prvFFErrorToErrno( xError ) ); return xError; } /*-----------------------------------------------------------*/ /*----------------------------------------------------------- * ff_isdirempty() returns 1 if a given directory is empty * (has no entries) *-----------------------------------------------------------*/ int ff_isdirempty(const char *pcPath ) { FF_DirHandler_t xHandler; int iResult; /* In case a CWD is used, get the absolute path */ pcPath = prvABSPath( pcPath ); /* Find the i/o manager which can handle this path */ if( FF_FS_Find( pcPath, &xHandler ) == pdFALSE ) { iResult = ( int ) ( FF_ERR_NULL_POINTER | FF_ISDIREMPTY ); } else { iResult = FF_isDirEmpty( xHandler.pxManager, xHandler.pcPath ); } /* Store the errno to thread local storage. */ stdioSET_ERRNO( prvFFErrorToErrno( iResult ) ); return iResult; } /*-----------------------------------------------------------*/ #if (ffconfig64_NUM_SUPPORT != 0 ) int64_t ff_diskfree(const char *pcPath, uint32_t *pxSectorCount ) #else int32_t ff_diskfree(const char *pcPath, uint32_t *pxSectorCount ) #endif { FF_DirHandler_t xHandler; FF_Error_t xError; #if (ffconfig64_NUM_SUPPORT != 0 ) #define DISKFREE_RETURN_TYPE int64_t int64_t lReturn; #else #define DISKFREE_RETURN_TYPE int32_t int32_t lReturn; #endif if( FF_FS_Find( pcPath, &xHandler ) == pdFALSE ) { /* Return cluster 0 for error. */ lReturn = 0ul; /* Store the errno to thread local storage. */ stdioSET_ERRNO( pdFREERTOS_ERRNO_ENXIO ); /* No such device or address */ } else { if (pxSectorCount != NULL ) { *pxSectorCount = xHandler.pxManager->xPartition.ulDataSectors; } lReturn = ( DISKFREE_RETURN_TYPE ) FF_GetFreeSize( xHandler.pxManager, &xError ) / 512; /* Store the errno to thread local storage. */ stdioSET_ERRNO( prvFFErrorToErrno( xError ) ); } return lReturn; } /*-----------------------------------------------------------*/ int ff_finddir(const char *pcPath ) { int iResult; FF_DirHandler_t xHandler; FF_Error_t errCode; if( FF_FS_Find( pcPath, &xHandler ) == pdFALSE ) { /* Return cluster 0 for error. */ iResult = 0; } else { iResult = ( int ) FF_FindDir( xHandler.pxManager, xHandler.pcPath, ( uint16_t ) strlen( xHandler.pcPath ), &errCode ); } return iResult; } /*-----------------------------------------------------------*/ size_t ff_filelength( FF_FILE *pxStream ) { FF_Error_t xReturned; uint32_t ulLength; xReturned = FF_GetFileSize( pxStream, &( ulLength ) ); if( FF_isERR( xReturned ) != pdFALSE ) { /* An error. */ ulLength = ( uint32_t ) 0u; stdioSET_ERRNO( prvFFErrorToErrno( xReturned ) ); } else { stdioSET_ERRNO( pdFREERTOS_ERRNO_NONE ); } return ( size_t ) ulLength; } /*-----------------------------------------------------------*/ /*----------------------------------------------------------- * Delete a directory and, recursively, all of its contents *-----------------------------------------------------------*/ #if( ffconfigUSE_DELTREE != 0 ) int ff_deltree( const char *pcDirectory ) { int iResult; char *pcPath; pcPath = ( char * ) ffconfigMALLOC( ffconfigMAX_FILENAME ); if( pcPath != NULL ) { /* In case a CWD is used, get the absolute path */ pcDirectory = prvABSPath( pcDirectory ); snprintf (pcPath, ffconfigMAX_FILENAME, "%s", pcDirectory); /* This recursive function will do all the work */ iResult = ff_deltree_recurse (pcPath); if( iResult >= 0 ) { iResult = ff_rmdir( pcPath ); if( iResult ) { FF_PRINTF("ff_deltree(%s): %s\n", pcPath, strerror( stdioGET_ERRNO( ) ) ); } } ffconfigFREE( pcPath ); } else { iResult = -1; stdioSET_ERRNO( pdFREERTOS_ERRNO_ENOMEM ); } return iResult; } #endif /* ffconfigUSE_DELTREE */ /*-----------------------------------------------------------*/ #if( ffconfigUSE_DELTREE != 0 ) static int ff_deltree_recurse( char *pcPath ) { FF_FindData_t *pxFindData; BaseType_t xIsDir, xIsDotDir; FF_Error_t xError; int iResult, iNext, iNameLength, pass, iCount = 0; pxFindData = ( FF_FindData_t * ) ffconfigMALLOC( sizeof( *pxFindData ) ); if( pxFindData != NULL ) { iNameLength = ( int ) strlen( pcPath ); /* The directory will be scanned 2 times. First the sub-directories will be entered and their contents deleted. In the second pass the files in the current directory will be removed. In this way 'pcPath' can be constantly used and reused recursively which is cheaper than allocating 'ffconfigMAX_FILENAME' bytes within each recursion. */ for( pass = 0; pass < 2; pass++ ) { for( iResult = ff_findfirst( pcPath, pxFindData ); iResult == 0; iResult = iNext ) { xIsDir = ( pxFindData->xDirectoryEntry.ucAttrib & FF_FAT_ATTR_DIR ) != 0; if( ( pass == 0 ) && ( xIsDir != pdFALSE ) ) { /* This entry is a directory. Don't traverse '.' or '..' */ xIsDotDir = 0; if( pxFindData->pcFileName[ 0 ] == '.' ) { if( ( pxFindData->pcFileName[ 1 ] == '.' ) && ( pxFindData->pcFileName[ 2 ] == '\0' ) ) { xIsDotDir = 2; } else if( pxFindData->pcFileName[ 1 ] == '\0' ) { xIsDotDir = 1; } } if( xIsDotDir == 0 ) { snprintf( pcPath + iNameLength, ( size_t ) ( ffconfigMAX_FILENAME - iNameLength ) , "%s%s", pcPath[ iNameLength - 1 ] == '/' ? "" : "/", pxFindData->pcFileName ); /* Let pxFindData point to the next element before the current will get removed. */ iNext = ff_findnext( pxFindData ); /* Remove the contents of this directory. */ iResult = ff_deltree_recurse( pcPath ); if( iResult < 0 ) { iCount = -1; break; } iCount += iResult; /* remove the directory itself */ xError = ff_rmdir( pcPath ); if( xError != 0 ) { FF_PRINTF( "ff_rmdir( %s ): errno %d\n", pcPath, stdioGET_ERRNO() ); } else { iCount++; } } else { iNext = ff_findnext( pxFindData ); } } else if( ( pass == 1 ) && ( xIsDir == pdFALSE ) ) { snprintf( pcPath + iNameLength, ( size_t ) ( ffconfigMAX_FILENAME - iNameLength ), "%s%s", pcPath[ iNameLength - 1 ] == '/' ? "" : "/", pxFindData->pcFileName ); /* Let pxFindData point to the next element before the current will get removed. */ iNext = ff_findnext( pxFindData ); /* Remove a plain file. */ xError = ff_remove( pcPath ); if( xError != 0 ) { FF_PRINTF( "ff_remove( %s ): errno %d\n", pcPath, stdioGET_ERRNO() ); } else { iCount++; } } else { iNext = ff_findnext( pxFindData ); } pcPath[ iNameLength ] = '\0'; } if( FF_GETERROR( iResult ) == FF_ERR_DIR_INVALID_PATH ) { break; } if( ( FF_GETERROR( iResult ) != FF_ERR_DIR_END_OF_DIR ) && ( FF_GETERROR( iResult ) != FF_ERR_FILE_INVALID_PATH ) ) { FF_PRINTF( "ff_deltree_recurse[%s]: %s\n", pcPath, ( const char * ) FF_GetErrMessage( iResult ) ); } } ffconfigFREE( pxFindData ); } else { iCount = -1; stdioSET_ERRNO( pdFREERTOS_ERRNO_ENOMEM ); } return iCount; } #endif /* ffconfigUSE_DELTREE */ /*-----------------------------------------------------------*/ int prvFFErrorToErrno( FF_Error_t xError ) { if( FF_isERR( xError ) == pdFALSE ) { return 0; } /* Store the last +FAT error code received. */ stdioSET_FF_ERROR( xError ); switch( FF_GETERROR( xError ) ) { /* Global Error Codes. */ case FF_ERR_NONE: return 0; /* No Error. */ case FF_ERR_NULL_POINTER: return pdFREERTOS_ERRNO_EBADF; /* pxIOManager was NULL. */ case FF_ERR_NOT_ENOUGH_MEMORY: return pdFREERTOS_ERRNO_ENOMEM; /* malloc() failed! - Could not allocate handle memory. */ case FF_ERR_DEVICE_DRIVER_FAILED: return pdFREERTOS_ERRNO_EIO; /* The Block Device driver reported a FATAL error, cannot continue. */ /* User return codes for Rd/Wr functions:. */ case FF_ERR_IOMAN_DRIVER_BUSY: return pdFREERTOS_ERRNO_EBUSY; /* 10. */ case FF_ERR_IOMAN_DRIVER_FATAL_ERROR: return pdFREERTOS_ERRNO_EUNATCH; /* Protocol driver not attached. */ /* IOMAN Error Codes. */ case FF_ERR_IOMAN_BAD_BLKSIZE: return pdFREERTOS_ERRNO_EINVAL; /* The provided blocksize was not a multiple of 512. */ case FF_ERR_IOMAN_BAD_MEMSIZE: return pdFREERTOS_ERRNO_EINVAL; /* The memory size was not a multiple of the blocksize. */ case FF_ERR_IOMAN_DEV_ALREADY_REGD: return pdFREERTOS_ERRNO_EADDRINUSE; /* Device was already registered. Use FF_UnRegister() to re-use this IOMAN with another device. */ case FF_ERR_IOMAN_NO_MOUNTABLE_PARTITION: return pdFREERTOS_ERRNO_ENOMEDIUM; /* A mountable partition could not be found on the device. */ case FF_ERR_IOMAN_INVALID_FORMAT: return pdFREERTOS_ERRNO_EFTYPE; /* The. */ case FF_ERR_IOMAN_INVALID_PARTITION_NUM: return pdFREERTOS_ERRNO_EINVAL; /* The partition number provided was out of range. */ case FF_ERR_IOMAN_NOT_FAT_FORMATTED: return pdFREERTOS_ERRNO_EFTYPE; /* The partition did not look like a FAT partition. */ case FF_ERR_IOMAN_DEV_INVALID_BLKSIZE: return pdFREERTOS_ERRNO_EINVAL; /* IOMAN object BlkSize is not compatible with the blocksize of this device driver. */ case FF_ERR_IOMAN_PARTITION_MOUNTED: return pdFREERTOS_ERRNO_EADDRINUSE; /* Device is in use by an actively mounted partition. Unmount the partition first. */ case FF_ERR_IOMAN_ACTIVE_HANDLES: return pdFREERTOS_ERRNO_EBUSY; /* The partition cannot be unmounted until all active file handles are closed. (There may also be active handles on the cache). */ case FF_ERR_IOMAN_GPT_HEADER_CORRUPT: return pdFREERTOS_ERRNO_EBADE; /* The GPT partition table appears to be corrupt, refusing to mount. */ case FF_ERR_IOMAN_NOT_ENOUGH_FREE_SPACE: return pdFREERTOS_ERRNO_ENOSPC; /* 22. */ case FF_ERR_IOMAN_OUT_OF_BOUNDS_READ: return pdFREERTOS_ERRNO_ESPIPE; /* 23, return 'Illegal seek'. */ case FF_ERR_IOMAN_OUT_OF_BOUNDS_WRITE: return pdFREERTOS_ERRNO_ESPIPE; /* 24. */ case FF_ERR_IOMAN_DRIVER_NOMEDIUM: return pdFREERTOS_ERRNO_ENOMEDIUM; /* The medium (e.g. SD-card) has been extracted. */ /* File Error Codes 30 +. */ case FF_ERR_FILE_ALREADY_OPEN: return pdFREERTOS_ERRNO_EALREADY; /* File is in use. */ case FF_ERR_FILE_NOT_FOUND: return pdFREERTOS_ERRNO_ENOENT; /* File was not found. */ case FF_ERR_FILE_OBJECT_IS_A_DIR: return pdFREERTOS_ERRNO_EISDIR; /* Tried to FF_Open() a Directory. */ case FF_ERR_FILE_IS_READ_ONLY: return pdFREERTOS_ERRNO_EROFS; /* Tried to FF_Open() a file marked read only. */ case FF_ERR_FILE_INVALID_PATH: return pdFREERTOS_ERRNO_ENOTDIR; /* The path of the file was not found. */ case FF_ERR_FILE_NOT_OPENED_IN_WRITE_MODE: return pdFREERTOS_ERRNO_EACCES; /* 35. */ case FF_ERR_FILE_NOT_OPENED_IN_READ_MODE: return pdFREERTOS_ERRNO_EACCES; /* 36. */ case FF_ERR_FILE_EXTEND_FAILED: return pdFREERTOS_ERRNO_ENOSPC; /* Could not extend the file. */ case FF_ERR_FILE_DESTINATION_EXISTS: return pdFREERTOS_ERRNO_EEXIST; /* 38. */ case FF_ERR_FILE_SOURCE_NOT_FOUND: return pdFREERTOS_ERRNO_ENOENT; /* 39. */ case FF_ERR_FILE_DIR_NOT_FOUND: return pdFREERTOS_ERRNO_ENOENT; /* 40. */ case FF_ERR_FILE_COULD_NOT_CREATE_DIRENT: return pdFREERTOS_ERRNO_EIO; /* 41. */ case FF_ERR_FILE_BAD_HANDLE: return pdFREERTOS_ERRNO_EBADF; /* A file handle was invalid. */ case FF_ERR_FILE_MEDIA_REMOVED: return pdFREERTOS_ERRNO_ENODEV; /* File handle got invalid because media was removed. */ case FF_ERR_FILE_SEEK_INVALID_POSITION: return pdFREERTOS_ERRNO_ESPIPE; /* Illegal position, outside the file's space */ case FF_ERR_FILE_SEEK_INVALID_ORIGIN: return pdFREERTOS_ERRNO_EINVAL; /* Seeking beyond end of file. */ /* Directory Error Codes 50 +. */ case FF_ERR_DIR_OBJECT_EXISTS: return pdFREERTOS_ERRNO_EEXIST; /* A file or folder of the same name already exists in the current directory. */ case FF_ERR_DIR_DIRECTORY_FULL: return pdFREERTOS_ERRNO_ENOSPC; /* No more items could be added to the directory. */ case FF_ERR_DIR_END_OF_DIR: return pdFREERTOS_ERRNO_ENMFILE; /*/. */ case FF_ERR_DIR_NOT_EMPTY: return pdFREERTOS_ERRNO_ENOTEMPTY; /* Cannot delete a directory that contains files or folders. */ case FF_ERR_DIR_INVALID_PATH: return pdFREERTOS_ERRNO_EINVAL; /* Could not find the directory specified by the path. */ case FF_ERR_DIR_CANT_EXTEND_ROOT_DIR: return pdFREERTOS_ERRNO_ENOSPC; /* Can't extend the root dir. */ case FF_ERR_DIR_EXTEND_FAILED: return pdFREERTOS_ERRNO_ENOSPC; /* Not enough space to extend the directory. */ case FF_ERR_DIR_NAME_TOO_LONG: return pdFREERTOS_ERRNO_ENAMETOOLONG;/* Name exceeds the number of allowed characters for a filename. */ /* Fat Error Codes 70 +. */ case FF_ERR_FAT_NO_FREE_CLUSTERS: return pdFREERTOS_ERRNO_ENOSPC; /* No more free space is available on the disk. */ /* UNICODE Error Codes 100 +. */ case FF_ERR_UNICODE_INVALID_CODE: return pdFREERTOS_ERRNO_EBADE; /* An invalid Unicode character was provided!. */ case FF_ERR_UNICODE_DEST_TOO_SMALL: return pdFREERTOS_ERRNO_ENOBUFS; /* Not enough space in the UTF-16 buffer to encode the entire sequence as UTF-16. */ case FF_ERR_UNICODE_INVALID_SEQUENCE: return pdFREERTOS_ERRNO_EILSEQ; /* An invalid UTF-16 sequence was encountered. */ case FF_ERR_UNICODE_CONVERSION_EXCEEDED: return pdFREERTOS_ERRNO_ENAMETOOLONG;/* Filename exceeds MAX long-filename length when converted to UTF-16. */ } return pdFREERTOS_ERRNO_EFAULT; } /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) void ff_free_CWD_space( void ) { WorkingDirectory_t *pxSpace; /* Obtain the CWD used by the current task. */ pxSpace = ( WorkingDirectory_t * ) pvTaskGetThreadLocalStoragePointer( NULL, stdioCWD_THREAD_LOCAL_OFFSET ); if( pxSpace != NULL ) { vTaskSetThreadLocalStoragePointer( NULL, stdioCWD_THREAD_LOCAL_OFFSET, ( void * ) NULL ); ffconfigFREE( pxSpace ); } } #endif /* ffconfigHAS_CWD */ /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) static WorkingDirectory_t *pxFindCWD( void ) { WorkingDirectory_t *pxReturn; /* Obtain the CWD used by the current task. */ pxReturn = ( WorkingDirectory_t * ) pvTaskGetThreadLocalStoragePointer( NULL, stdioCWD_THREAD_LOCAL_OFFSET ); if( pxReturn == NULL ) { /* This task does not yet have a WorkingDirectory_t structure - create and initialise one now. */ pxReturn = ( WorkingDirectory_t * ) ffconfigMALLOC( sizeof( WorkingDirectory_t ) ); if( pxReturn != NULL ) { pxReturn->pcCWD[ 0 ] = '\0'; vTaskSetThreadLocalStoragePointer( NULL, stdioCWD_THREAD_LOCAL_OFFSET, ( void * ) pxReturn ); } } return pxReturn; } #endif /* ffconfigHAS_CWD */ /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) static const char *prvProcessRelativePaths( const char *pcPath ) { const char *pcReturn; char *pcChar, *pcTokenStart = NULL, *pcFollowingToken, cPreviousChar = 0x00; BaseType_t xByte; /* Scan the string looking for a relative path. */ pcReturn = pcPath; pcChar = ( char * ) pcReturn; configASSERT( pcPath ); while( *pcChar != 0x00 ) { if( *pcChar == '.' ) { /* A potential relative path was found. Is this a "." or a "..". */ if( *( pcChar + 1 ) == '.' ) { /* Nothing can be done if this is at the start of the string. */ if( pcTokenStart != NULL ) { /* A ".." was found. Where does the next token start? */ pcFollowingToken = pcChar + 2; if( *pcFollowingToken == '/' ) { /* The next token starts after the "../" */ pcFollowingToken += sizeof( char ); } /* Remove the ".." and the previous token. */ xByte = 0; while( pcFollowingToken[ xByte ] != 0x00 ) { pcTokenStart[ xByte ] = pcFollowingToken[ xByte ]; xByte++; } /* Terminate. */ pcTokenStart[ xByte ] = 0x00; /* The pointer to the previous token will now be wrong if there are multiple if "../.." appears in the string. So reset the variables to continue scanning. */ pcChar = ( char * ) pcReturn; cPreviousChar = 0x00; pcTokenStart = NULL; continue; } } else { /* A "." was found. Remove it. */ } } if( cPreviousChar == '/' ) { /* This is the start of a new token. */ pcTokenStart = pcChar; } cPreviousChar = *pcChar; pcChar++; } /* Make sure there is no / on the end of the string, being careful not to remove the / at the beginning of the string. */ if( *( pcChar - 1 ) == '/' ) { if( ( pcChar - 1 ) != pcReturn ) { *( pcChar - 1 ) = 0x00; } } return pcReturn; } #endif /* ffconfigHAS_CWD */ /*-----------------------------------------------------------*/ #if( ffconfigHAS_CWD == 1 ) /*static*/ const char *prvABSPath( const char *pcPath ) { char *pcReturn; WorkingDirectory_t *pxWorkingDirectory = pxFindCWD(); configASSERT( pxWorkingDirectory ); if( ( pcPath[ 0 ] ) == '/' ) { /* If the path starts with a slash it does not start with a relative path. Copy the string into a thread local buffer so it can be manipulated without risk of attempting to write to read only memory. */ snprintf( pxWorkingDirectory->pcFileName, sizeof( pxWorkingDirectory->pcFileName ), "%s", pcPath ); pcReturn = pxWorkingDirectory->pcFileName; } else { /* Insert the working directory into the front of the path. */ if( pxWorkingDirectory->pcCWD[ 1 ] == 0x00 ) { /* In the root, so don't add a '/' between the CWD and the file name. */ snprintf( pxWorkingDirectory->pcFileName, sizeof( pxWorkingDirectory->pcFileName ), "/%s", pcPath ); } else { snprintf( pxWorkingDirectory->pcFileName, sizeof( pxWorkingDirectory->pcFileName ), "%s/%s", pxWorkingDirectory->pcCWD, pcPath ); } pcReturn = pxWorkingDirectory->pcFileName; } /* Make any adjustments necessitated by relative paths. */ prvProcessRelativePaths( pcReturn ); return pcReturn; } #endif /* ffconfigHAS_CWD */ #if( ffconfigTIME_SUPPORT == 1 ) static uint32_t prvFileTime( FF_SystemTime_t *pxTime ) { FF_TimeStruct_t xTime; time_t xReturn; xTime.tm_sec = pxTime->Second; xTime.tm_min = pxTime->Minute; xTime.tm_hour = pxTime->Hour; xTime.tm_mday = pxTime->Day; xTime.tm_mon = pxTime->Month - 1; xTime.tm_year = pxTime->Year - 1900; xReturn = FreeRTOS_mktime( &xTime ); return xReturn; } #endif /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/shadow/include/aws_iot_shadow.h
/* * AWS IoT Shadow V2.1.0 * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_shadow.h * @brief User-facing functions of the Shadow library. */ #ifndef AWS_IOT_SHADOW_H_ #define AWS_IOT_SHADOW_H_ /* The config header is always included first. */ #include "iot_config.h" /* Shadow types include. */ #include "types/aws_iot_shadow_types.h" /*------------------------ Shadow library functions -------------------------*/ /** * @functionspage{shadow,Shadow library} * - @functionname{shadow_function_init} * - @functionname{shadow_function_cleanup} * - @functionname{shadow_function_deleteasync} * - @functionname{shadow_function_deletesync} * - @functionname{shadow_function_getasync} * - @functionname{shadow_function_getsync} * - @functionname{shadow_function_updateasync} * - @functionname{shadow_function_updatesync} * - @functionname{shadow_function_wait} * - @functionname{shadow_function_setdeltacallback} * - @functionname{shadow_function_setupdatedcallback} * - @functionname{shadow_function_removepersistentsubscriptions} * - @functionname{shadow_function_strerror} */ /** * @functionpage{AwsIotShadow_Init,shadow,init} * @functionpage{AwsIotShadow_Cleanup,shadow,cleanup} * @functionpage{AwsIotShadow_DeleteAsync,shadow,deleteasync} * @functionpage{AwsIotShadow_DeleteSync,shadow,deletesync} * @functionpage{AwsIotShadow_GetAsync,shadow,getasync} * @functionpage{AwsIotShadow_GetSync,shadow,getsync} * @functionpage{AwsIotShadow_UpdateAsync,shadow,updateasync} * @functionpage{AwsIotShadow_UpdateSync,shadow,updatesync} * @functionpage{AwsIotShadow_Wait,shadow,wait} * @functionpage{AwsIotShadow_SetDeltaCallback,shadow,setdeltacallback} * @functionpage{AwsIotShadow_SetUpdatedCallback,shadow,setupdatedcallback} * @functionpage{AwsIotShadow_RemovePersistentSubscriptions,shadow,removepersistentsubscriptions} * @functionpage{AwsIotShadow_strerror,shadow,strerror} */ /** * @brief One-time initialization function for the Shadow library. * * This function performs internal setup of the Shadow library. <b>It must be * called once (and only once) before calling any other Shadow function.</b> * Calling this function more than once without first calling @ref * shadow_function_cleanup may result in a crash. * * @param[in] mqttTimeout The amount of time (in milliseconds) that the Shadow * library will wait for MQTT operations. Optional; set this to `0` to use * @ref AWS_IOT_SHADOW_DEFAULT_MQTT_TIMEOUT_MS. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_INIT_FAILED * * @warning No thread-safety guarantees are provided for this function. * * @see @ref shadow_function_cleanup */ /* @[declare_shadow_init] */ AwsIotShadowError_t AwsIotShadow_Init( uint32_t mqttTimeout ); /* @[declare_shadow_init] */ /** * @brief One-time deinitialization function for the Shadow library. * * This function frees resources taken in @ref shadow_function_init and deletes * any [persistent subscriptions.](@ref AWS_IOT_SHADOW_FLAG_KEEP_SUBSCRIPTIONS) * It should be called to clean up the Shadow library. After this function returns, * @ref shadow_function_init must be called again before calling any other Shadow * function. * * @warning No thread-safety guarantees are provided for this function. * * @see @ref shadow_function_init */ /* @[declare_shadow_cleanup] */ void AwsIotShadow_Cleanup( void ); /* @[declare_shadow_cleanup] */ /** * @brief Delete a Thing Shadow and receive an asynchronous notification when * the Delete completes. * * This function deletes any existing Shadow document for the given Thing Name. * If the given Thing has no Shadow and this function is called, the result will * be #AWS_IOT_SHADOW_NOT_FOUND. * * Deleting a Shadow involves sending an MQTT message to AWS IoT and waiting on * a response. This message will always be sent at [MQTT QoS 0](@ref #IOT_MQTT_QOS_0). * * @param[in] mqttConnection The MQTT connection to use for Shadow delete. * @param[in] pThingName The Thing Name associated with the Shadow to delete. * @param[in] thingNameLength The length of `pThingName`. * @param[in] flags Flags which modify the behavior of this function. See @ref shadow_constants_flags. * @param[in] pCallbackInfo Asynchronous notification of this function's completion. * @param[out] pDeleteOperation Set to a handle by which this operation may be referenced * after this function returns. This reference is invalidated once the Shadow delete * completes. * * @return This function will return #AWS_IOT_SHADOW_STATUS_PENDING upon successfully * queuing a Shadow delete. * @return If this function fails before queuing a Shadow delete, it will return one of: * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * @return Upon successful completion of the Shadow delete (either through an #AwsIotShadowCallbackInfo_t * or #AwsIotShadow_Wait), the status will be #AWS_IOT_SHADOW_SUCCESS. * @return Should the Shadow delete fail, the status will be one of: * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_BAD_RESPONSE * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) * * @see @ref shadow_function_deletesync for a blocking variant of this function. * * <b>Example</b> * @code{c} * #define THING_NAME "Test_device" * #define THING_NAME_LENGTH ( sizeof( THING_NAME ) - 1 ) * * // Shadow operation handle. * AwsIotShadowOperation_t deleteOperation = AWS_IOT_SHADOW_OPERATION_INITIALIZER; * * // Queue a Shadow delete. * AwsIotShadowError_t deleteResult = AwsIotShadow_DeleteAsync( mqttConnection, * THING_NAME, * THING_NAME_LENGTH, * AWS_IOT_SHADOW_FLAG_WAITABLE, * NULL, * &deleteOperation ); * * // Shadow delete should return AWS_IOT_SHADOW_STATUS_PENDING upon success. * if( deleteResult == AWS_IOT_SHADOW_STATUS_PENDING ) * { * // Wait for the Shadow delete to complete. * deleteResult = AwsIotShadow_Wait( deleteOperation, 5000 ); * * // Delete result should be AWS_IOT_SHADOW_SUCCESS upon successfully * // deleting an existing Shadow. * } * @endcode */ /* @[declare_shadow_deleteasync] */ AwsIotShadowError_t AwsIotShadow_DeleteAsync( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags, const AwsIotShadowCallbackInfo_t * pCallbackInfo, AwsIotShadowOperation_t * const pDeleteOperation ); /* @[declare_shadow_deleteasync] */ /** * @brief Delete a Thing Shadow with a timeout. * * This function queues a Shadow delete, then waits for the result. Internally, this * function is a call to @ref shadow_function_deleteasync followed by @ref shadow_function_wait. * See @ref shadow_function_deleteasync for more information on the Shadow delete operation. * * @param[in] mqttConnection The MQTT connection to use for Shadow delete. * @param[in] pThingName The Thing Name associated with the Shadow to delete. * @param[in] thingNameLength The length of `pThingName`. * @param[in] flags Flags which modify the behavior of this function. See @ref shadow_constants_flags. * @param[in] timeoutMs If the Shadow service does not respond to the Shadow delete * within this timeout, this function returns #AWS_IOT_SHADOW_TIMEOUT. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_BAD_RESPONSE * - #AWS_IOT_SHADOW_TIMEOUT * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) */ /* @[declare_shadow_deletesync] */ AwsIotShadowError_t AwsIotShadow_DeleteSync( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags, uint32_t timeoutMs ); /* @[declare_shadow_deletesync] */ /** * @brief Retrieve a Thing Shadow and receive an asynchronous notification when * the Shadow document is received. * * This function retrieves the Thing Shadow document currently stored by the * Shadow service. If a given Thing has no Shadow and this function is called, * the result will be #AWS_IOT_SHADOW_NOT_FOUND. * * Shadow documents may be large, and their size is not known beforehand. * Therefore, this function works best when memory is dynamically allocated. * Because the Shadow document is retrieved in an MQTT PUBLISH packet, the MQTT * library will allocate a buffer for the Shadow document using #IotMqtt_MallocMessage. * * The MQTT library may free the buffer for a retrieved Shadow document as soon * as the [Shadow completion callback](@ref AwsIotShadowCallbackInfo_t) returns. * Therefore, any data needed later must be copied from the Shadow document. * Similarly, if the flag #AWS_IOT_SHADOW_FLAG_WAITABLE is given to this function * (which indicates that the Shadow document will be needed after the Shadow * operation completes), #AwsIotShadowDocumentInfo_t.mallocDocument must be * provided to allocate a longer-lasting buffer. * * @note Because of the potentially large size of complete Shadow documents, it is more * memory-efficient for most applications to use [delta callbacks] * (@ref shadow_function_setdeltacallback) to retrieve Shadows from * the Shadow service. * * @param[in] mqttConnection The MQTT connection to use for Shadow get. * @param[in] pGetInfo Shadow document parameters. * @param[in] flags Flags which modify the behavior of this function. See @ref shadow_constants_flags. * @param[in] pCallbackInfo Asynchronous notification of this function's completion. * @param[out] pGetOperation Set to a handle by which this operation may be referenced * after this function returns. This reference is invalidated once the Shadow get * completes. * * @return This function will return #AWS_IOT_SHADOW_STATUS_PENDING upon successfully * queuing a Shadow get. * @return If this function fails before queuing a Shadow get, it will return one of: * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * @return Upon successful completion of the Shadow get (either through an #AwsIotShadowCallbackInfo_t * or #AwsIotShadow_Wait), the status will be #AWS_IOT_SHADOW_SUCCESS. * @return Should the Shadow get fail, the status will be one of: * - #AWS_IOT_SHADOW_NO_MEMORY (Memory could not be allocated for incoming document) * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_BAD_RESPONSE * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) * * @see @ref shadow_function_getsync for a blocking variant of this function. * * <b>Example</b> * @code{c} * // Shadow get completion callback. The retrieved document will be in * // pCallbackParam. Any data in the retrieved document needed after this * // function returns must be copied. * void _processRetrievedDocument( void * pCallbackContext, * AwsIotShadowCallbackParam_t * pCallbackParam ); * * // Parameters and return value of Shadow get. * AwsIotShadowError_t result = AWS_IOT_SHADOW_STATUS_PENDING; * AwsIotShadowDocumentInfo_t getInfo = { ... }; * uint32_t timeout = 5000; // 5 seconds * * // Callback for get completion. * AwsIotShadowCallbackInfo_t getCallback = AWS_IOT_SHADOW_CALLBACK_INFO_INITIALIZER; * getCallback.function = _processRetrievedDocument; * * // Shadow get operation. * result = AwsIotShadow_GetAsync( mqttConnection, * &getInfo, * 0, * &getCallback, * NULL ); * * // Get should have returned AWS_IOT_SHADOW_STATUS_PENDING. The function * // _processRetrievedDocument will be invoked once the Shadow get completes. * @endcode * * See @ref shadow_function_wait <b>Example 2</b> for an example of using this * function with #AWS_IOT_SHADOW_FLAG_WAITABLE and @ref shadow_function_wait. */ /* @[declare_shadow_getasync] */ AwsIotShadowError_t AwsIotShadow_GetAsync( IotMqttConnection_t mqttConnection, const AwsIotShadowDocumentInfo_t * pGetInfo, uint32_t flags, const AwsIotShadowCallbackInfo_t * pCallbackInfo, AwsIotShadowOperation_t * const pGetOperation ); /* @[declare_shadow_getasync] */ /** * @brief Retrieve a Thing Shadow with a timeout. * * This function queues a Shadow get, then waits for the result. Internally, this * function is a call to @ref shadow_function_getasync followed by @ref shadow_function_wait. * See @ref shadow_function_getasync for more information on the Shadow get operation. * * @param[in] mqttConnection The MQTT connection to use for Shadow get. * @param[in] pGetInfo Shadow document parameters. * @param[in] flags Flags which modify the behavior of this function. See @ref shadow_constants_flags. * @param[in] timeoutMs If the Shadow service does not respond to the Shadow get * within this timeout, this function returns #AWS_IOT_SHADOW_TIMEOUT. * @param[out] pShadowDocument A pointer to a buffer containing the Shadow document * retrieved by a Shadow get is placed here. The buffer was allocated with the function * `pGetInfo->get.mallocDocument`. This output parameter is only valid if this function * returns #AWS_IOT_SHADOW_SUCCESS. * @param[out] pShadowDocumentLength The length of the Shadow document in * `pShadowDocument` is placed here. This output parameter is only valid if this function * returns #AWS_IOT_SHADOW_SUCCESS. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_BAD_RESPONSE * - #AWS_IOT_SHADOW_TIMEOUT * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) */ /* @[declare_shadow_getsync] */ AwsIotShadowError_t AwsIotShadow_GetSync( IotMqttConnection_t mqttConnection, const AwsIotShadowDocumentInfo_t * pGetInfo, uint32_t flags, uint32_t timeoutMs, const char ** const pShadowDocument, size_t * const pShadowDocumentLength ); /* @[declare_shadow_getsync] */ /** * @brief Send a Thing Shadow update and receive an asynchronous notification when * the Shadow Update completes. * * This function modifies the Thing Shadow document stored by the Shadow service. * If a given Thing has no Shadow and this function is called, then a new Shadow * is created. * * New JSON keys in the Shadow document will be appended. For example, if the Shadow service * currently has a document containing key `example1` and this function sends a document * only containing key `example2`, then the resulting document in the Shadow service * will contain both `example1` and `example2`. * * Existing JSON keys in the Shadow document will be replaced. For example, if the Shadow * service currently has a document containing `"example1": [0,1,2]` and this function sends * a document containing key `"example1": [1,2,3]`, then the resulting document in the Shadow * service will contain `"example1": [1,2,3]`. * * Successful Shadow updates will trigger the [Shadow updated callback] * (@ref shadow_function_setupdatedcallback). If the resulting Shadow document contains * different `desired` and `reported` keys, then the [Shadow delta callback] * (@ref shadow_function_setdeltacallback) will be triggered as well. * * @attention All documents passed to this function must contain a `clientToken`. * The [client token] * (https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-document.html#client-token) * is a string used to distinguish between Shadow updates. They are limited to 64 * characters; attempting to use a client token longer than 64 characters will * cause the Shadow update to fail. They must be unique at any given time, i.e. * they may be reused <i>as long as no two Shadow updates are using the same * client token at the same time</i>. * * @param[in] mqttConnection The MQTT connection to use for Shadow update. * @param[in] pUpdateInfo Shadow document parameters. * @param[in] flags Flags which modify the behavior of this function. See @ref shadow_constants_flags. * @param[in] pCallbackInfo Asynchronous notification of this function's completion. * @param[out] pUpdateOperation Set to a handle by which this operation may be referenced * after this function returns. This reference is invalidated once the Shadow update * completes. * * @return This function will return #AWS_IOT_SHADOW_STATUS_PENDING upon successfully * queuing a Shadow update. * @return If this function fails before queuing a Shadow update, it will return one of: * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * @return Upon successful completion of the Shadow update (either through an #AwsIotShadowCallbackInfo_t * or #AwsIotShadow_Wait), the status will be #AWS_IOT_SHADOW_SUCCESS. * @return Should the Shadow update fail, the status will be one of: * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_BAD_RESPONSE * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) * * @see @ref shadow_function_updatesync for a blocking variant of this function. * * <b>Example</b> * @code{c} * // Shadow update completion callback. * void _updateComplete( void * pCallbackContext, * AwsIotShadowCallbackParam_t * pCallbackParam ); * * // Parameters and return value of Shadow update. * AwsIotShadowError_t result = AWS_IOT_SHADOW_STATUS_PENDING; * AwsIotShadowDocumentInfo_t updateInfo = { ... }; * uint32_t timeout = 5000; // 5 seconds * * // Set Shadow document to send. * updateInfo.update.pUpdateDocument = "{...}"; // Must contain clientToken * updateInfo.update.updateDocumentLength = strlen( updateInfo.update.pUpdateDocument ); * * // Callback for update completion. * AwsIotShadowCallbackInfo_t updateCallback = AWS_IOT_SHADOW_CALLBACK_INFO_INITIALIZER; * updateCallback.function = _updateComplete; * * // Shadow update operation. * result = AwsIotShadow_UpdateAsync( mqttConnection, * &updateInfo, * 0, * &updateCallback, * NULL ); * * // Update should have returned AWS_IOT_SHADOW_STATUS_PENDING. The function * // _updateComplete will be invoked once the Shadow update completes. * @endcode * * See @ref shadow_function_wait <b>Example 1</b> for an example of using this * function with #AWS_IOT_SHADOW_FLAG_WAITABLE and @ref shadow_function_wait. */ /* @[declare_shadow_updateasync] */ AwsIotShadowError_t AwsIotShadow_UpdateAsync( IotMqttConnection_t mqttConnection, const AwsIotShadowDocumentInfo_t * pUpdateInfo, uint32_t flags, const AwsIotShadowCallbackInfo_t * pCallbackInfo, AwsIotShadowOperation_t * const pUpdateOperation ); /* @[declare_shadow_updateasync] */ /** * @brief Send a Thing Shadow update with a timeout. * * This function queues a Shadow update, then waits for the result. Internally, this * function is a call to @ref shadow_function_updateasync followed by @ref shadow_function_wait. * See @ref shadow_function_updateasync for more information on the Shadow update operation. * * @param[in] mqttConnection The MQTT connection to use for Shadow update. * @param[in] pUpdateInfo Shadow document parameters. * @param[in] flags Flags which modify the behavior of this function. See @ref shadow_constants_flags. * @param[in] timeoutMs If the Shadow service does not respond to the Shadow update * within this timeout, this function returns #AWS_IOT_SHADOW_TIMEOUT. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_BAD_RESPONSE * - #AWS_IOT_SHADOW_TIMEOUT * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) */ /* @[declare_shadow_updatesync] */ AwsIotShadowError_t AwsIotShadow_UpdateSync( IotMqttConnection_t mqttConnection, const AwsIotShadowDocumentInfo_t * pUpdateInfo, uint32_t flags, uint32_t timeoutMs ); /* @[declare_shadow_updatesync] */ /** * @brief Wait for a Shadow operation to complete. * * This function blocks to wait for a [delete](@ref shadow_function_deleteasync), * [get](@ref shadow_function_getasync), or [update](@ref shadow_function_updateasync) to * complete. These operations are by default asynchronous; the function calls * queue an operation for processing, and a callback is invoked once the operation * is complete. * * To use this function, the flag #AWS_IOT_SHADOW_FLAG_WAITABLE must have been * set in the operation's function call. Additionally, this function must always * be called with any waitable operation to clean up resources. * * Regardless of its return value, this function always clean up resources used * by the waitable operation. This means `operation` is invalidated as soon as * this function returns, even if it returns #AWS_IOT_SHADOW_TIMEOUT or another * error. * * @param[in] operation Reference to the Shadow operation to wait for. The flag * #AWS_IOT_SHADOW_FLAG_WAITABLE must have been set for this operation. * @param[in] timeoutMs How long to wait before returning #AWS_IOT_SHADOW_TIMEOUT. * @param[out] pShadowDocument A pointer to a buffer containing the Shadow document * retrieved by a [Shadow get](@ref shadow_function_getasync) is placed here. The buffer * was allocated with the function #AwsIotShadowDocumentInfo_t.mallocDocument passed * to @ref shadow_function_getasync. This parameter is only valid for a [Shadow get] * (@ref shadow_function_getasync) and ignored for other Shadow operations. This output * parameter is only valid if this function returns #AWS_IOT_SHADOW_SUCCESS. * @param[out] pShadowDocumentLength The length of the Shadow document in * `pShadowDocument` is placed here. This parameter is only valid for a [Shadow get] * (@ref shadow_function_getasync) and ignored for other Shadow operations. This output * parameter is only valid if this function returns #AWS_IOT_SHADOW_SUCCESS. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_BAD_RESPONSE * - #AWS_IOT_SHADOW_TIMEOUT * - A Shadow service rejection reason between 400 (#AWS_IOT_SHADOW_BAD_REQUEST) * and 500 (#AWS_IOT_SHADOW_SERVER_ERROR) * * <b>Example 1 (Shadow Update)</b> * @code{c} * AwsIotShadowError_t result = AWS_IOT_SHADOW_STATUS_PENDING; * AwsIotShadowDocumentInfo_t updateInfo = { ... }; * * // Reference and timeout. * AwsIotShadowOperation_t updateOperation = AWS_IOT_SHADOW_OPERATION_INITIALIZER; * uint32_t timeout = 5000; // 5 seconds * * // Shadow update operation. * result = AwsIotShadow_UpdateAsync( mqttConnection, * &updateInfo, * AWS_IOT_SHADOW_FLAG_WAITABLE, * NULL, * &updateOperation ); * * // Update should have returned AWS_IOT_SHADOW_STATUS_PENDING. The call to wait * // returns once the result of the update is available or the timeout expires. * if( result == AWS_IOT_SHADOW_STATUS_PENDING ) * { * // The last two parameters are ignored for a Shadow update. * result = AwsIotShadow_Wait( updateOperation, timeout, NULL, NULL ); * * // After the call to wait, the result of the update is known * // (not AWS_IOT_SHADOW_STATUS_PENDING). * assert( result != AWS_IOT_SHADOW_STATUS_PENDING ); * } * @endcode * * <b>Example 2 (Shadow Get)</b> * @code{c} * AwsIotShadowError_t result = AWS_IOT_SHADOW_STATUS_PENDING; * AwsIotShadowDocumentInfo_t getInfo = { ... }; * * // Reference and timeout. * AwsIotShadowOperation_t getOperation = AWS_IOT_SHADOW_OPERATION_INITIALIZER; * uint32_t timeout = 5000; // 5 seconds * * // Buffer pointer and size for retrieved Shadow document. * const char * pShadowDocument = NULL; * size_t documentLength = 0; * * // Buffer allocation function must be set for a waitable Shadow get. * getInfo.get.mallocDocument = malloc; * * // Shadow get operation. * result = AwsIotShadow_GetAsync( mqttConnection, * &getInfo, * AWS_IOT_SHADOW_FLAG_WAITABLE, * NULL, * &getOperation ); * * // Get should have returned AWS_IOT_SHADOW_STATUS_PENDING. The call to wait * // returns once the result of the get is available or the timeout expires. * if( result == AWS_IOT_SHADOW_STATUS_PENDING ) * { * // The last two parameters must be set for a Shadow get. * result = AwsIotShadow_Wait( getOperation, timeout, &pShadowDocument, &documentLength ); * * // After the call to wait, the result of the get is known * // (not AWS_IOT_SHADOW_STATUS_PENDING). * assert( result != AWS_IOT_SHADOW_STATUS_PENDING ); * * // The retrieved Shadow document is only valid for a successful Shadow get. * if( result == AWS_IOT_SHADOW_SUCCESS ) * { * // Do something with the Shadow document... * * // Free the Shadow document when finished. * free( pShadowDocument ); * } * } * @endcode */ /* @[declare_shadow_wait] */ AwsIotShadowError_t AwsIotShadow_Wait( AwsIotShadowOperation_t operation, uint32_t timeoutMs, const char ** const pShadowDocument, size_t * const pShadowDocumentLength ); /* @[declare_shadow_wait] */ /** * @brief Set a callback to be invoked when the Thing Shadow `desired` and `reported` * states differ. * * A Thing Shadow contains `reported` and `desired` states, meant to represent * the current device status and some desired status, respectively. When the * `reported` and `desired` states differ, the Thing Shadow service generates a * <i>delta document</i> and publishes it to the topic `update/delta`. Devices * with a subscription for this topic will receive the delta document and may act * based on the different `reported` and `desired` states. See [this page] * (https://docs.aws.amazon.com/iot/latest/developerguide/using-device-shadows.html#delta-state) * for more information about using delta documents. * * A <i>delta callback</i> may be invoked whenever a delta document is generated. * Each Thing may have a single delta callback set. This function modifies the delta * callback for a specific Thing depending on the `pDeltaCallback` parameter and * the presence of any existing delta callback: * - When no existing delta callback exists for a specific Thing, a new delta * callback is added. * - If there is an existing delta callback and `pDeltaCallback` is not `NULL`, then * the existing callback function and parameter are replaced with `pDeltaCallback`. * - If there is an existing subscription and `pDeltaCallback` is `NULL`, then the * delta callback is removed. * * This function is always blocking; it may block for up to the default MQTT * timeout. This timeout is set as a parameter to @ref shadow_function_init, * and defaults to @ref AWS_IOT_SHADOW_DEFAULT_MQTT_TIMEOUT_MS if not set. If * this function's underlying MQTT operations fail to complete within this * timeout, then this function returns #AWS_IOT_SHADOW_TIMEOUT. * * @param[in] mqttConnection The MQTT connection to use for the subscription to * `update/delta`. * @param[in] pThingName The subscription to `update/delta` will be added for * this Thing Name. * @param[in] thingNameLength The length of `pThingName`. * @param[in] flags This parameter is for future-compatibility. Currently, flags * are not supported for this function and this parameter is ignored. * @param[in] pDeltaCallback Callback function to invoke for incoming delta * documents. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_TIMEOUT * * @return This function always returns #AWS_IOT_SHADOW_SUCCESS when replacing or * removing existing delta callbacks. * * @see @ref shadow_function_setupdatedcallback for the function to register * callbacks for all Shadow updates. * * <b>Example</b> * @code{c} * #define THING_NAME "Test_device" * #define THING_NAME_LENGTH ( sizeof( THING_NAME ) - 1 ) * * AwsIotShadowError_t result = AWS_IOT_SHADOW_STATUS_PENDING; * AwsIotShadowCallbackInfo_t deltaCallback = AWS_IOT_SHADOW_CALLBACK_INFO_INITIALIZER; * * // _deltaCallbackFunction will be invoked when a delta document is received. * deltaCallback.function = _deltaCallbackFunction; * * // Set the delta callback for the Thing "Test_device". * result = AwsIotShadow_SetDeltaCallback( mqttConnection, * THING_NAME, * THING_NAME_LENGTH, * 0, * &deltaCallback ); * * // Check if callback was successfully set. * if( result == AWS_IOT_SHADOW_SUCCESS ) * { * AwsIotShadowDocumentInfo_t updateInfo = AWS_IOT_SHADOW_DOCUMENT_INFO_INITIALIZER; * * // Set the Thing Name for Shadow update. * updateInfo.pThingName = THING_NAME; * updateInfo.thingNameLength = THING_NAME_LENGTH; * * // Set the Shadow document to send. This document has different "reported" * // and "desired" states. It represents a scenario where a device is currently * // off, but is being ordered to turn on. * updateInfo.update.pUpdateDocument = * "{" * "\"state\": {" * "\"reported\": { \"deviceOn\": false }," * "\"desired\": { \"deviceOn\": true }" * "}" * "}"; * updateInfo.update.updateDocumentLength = strlen( updateInfo.update.pUpdateDocument ); * * // Send the Shadow document with different "reported" and desired states. * result = AwsIotShadow_UpdateSync( mqttConnection, * &updateInfo, * 0, * 0, * 5000 ); * * // After the update is successfully sent, the function _deltaCallbackFunction * // will be invoked once the Shadow service generates and sends a delta document. * // The delta document will contain the different "deviceOn" states, as well as * // metadata. * * // Once the delta callback is no longer needed, it may be removed by passing * // NULL as pDeltaCallback. * result = AwsIotShadow_SetDeltaCallback( mqttConnection, * THING_NAME, * THING_NAME_LENGTH, * 0, * NULL ); * * // The return value from removing a delta callback should always be success. * assert( result == AWS_IOT_SHADOW_SUCCESS ); * } * @endcode */ /* @[declare_shadow_setdeltacallback] */ AwsIotShadowError_t AwsIotShadow_SetDeltaCallback( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags, const AwsIotShadowCallbackInfo_t * pDeltaCallback ); /* @[declare_shadow_setdeltacallback] */ /** * @brief Set a callback to be invoked when a Thing Shadow changes. * * The Shadow service publishes a state document to the `update/documents` topic * whenever a Thing Shadow is successfully updated. This document reports the * complete previous and current Shadow documents in `previous` and `current` * sections, respectively. Therefore, the `update/documents` topic is useful * for monitoring Shadow updates. * * An <i>updated callback</i> may be invoked whenever a document is published to * `update/documents`. Each Thing may have a single updated callback set. This function * modifies the updated callback for a specific Thing depending on the `pUpdatedCallback` * parameter and the presence of any existing updated callback. * - When no existing updated callback exists for a specific Thing, a new updated * callback is added. * - If there is an existing updated callback and `pUpdatedCallback` is not `NULL`, * then the existing callback function and parameter are replaced with `pUpdatedCallback`. * - If there is an existing updated callback and `pUpdatedCallback` is `NULL`, * then the updated callback is removed. * * @param[in] mqttConnection The MQTT connection to use for the subscription to `update/documents`. * @param[in] pThingName The subscription to `update/documents` will be added for * this Thing Name. * @param[in] thingNameLength The length of `pThingName`. * @param[in] flags This parameter is for future-compatibility. Currently, flags are * not supported for this function and this parameter is ignored. * @param[in] pUpdatedCallback Callback function to invoke for incoming updated documents. * * @return One of the following: * - #AWS_IOT_SHADOW_SUCCESS * - #AWS_IOT_SHADOW_NOT_INITIALIZED * - #AWS_IOT_SHADOW_BAD_PARAMETER * - #AWS_IOT_SHADOW_NO_MEMORY * - #AWS_IOT_SHADOW_MQTT_ERROR * - #AWS_IOT_SHADOW_TIMEOUT * * @note Documents published to `update/documents` will be large, as they contain 2 * complete Shadow state documents. If an updated callback is used, ensure that the * device has sufficient memory for incoming documents. * * @see @ref shadow_function_setdeltacallback for the function to register callbacks * for delta documents. * * <b>Example</b> * @code{c} * #define THING_NAME "Test_device" * #define THING_NAME_LENGTH ( sizeof( THING_NAME ) - 1 ) * * AwsIotShadowError_t result = AWS_IOT_SHADOW_STATUS_PENDING; * AwsIotShadowCallbackInfo_t updatedCallback = AWS_IOT_SHADOW_CALLBACK_INFO_INITIALIZER; * * // _updatedCallbackFunction will be invoked when an updated document is received. * updatedCallback.function = _updatedCallbackFunction; * * // Set the updated callback for the Thing "Test_device". * result = AwsIotShadow_SetUpdatedCallback( mqttConnection, * THING_NAME, * THING_NAME_LENGTH, * 0, * &updatedCallback ); * * // Check if the callback was successfully set. * if( result == AWS_IOT_SHADOW_SUCCESS ) * { * AwsIotShadowDocumentInfo_t updateInfo = AWS_IOT_SHADOW_DOCUMENT_INFO_INITIALIZER; * * // Set the Thing Name for Shadow update. * updateInfo.pThingName = THING_NAME; * updateInfo.thingNameLength = THING_NAME_LENGTH; * * // Set the Shadow document to send. Any Shadow update will trigger the * // updated callback. * updateInfo.update.pUpdateDocument = * "{" * "\"state\": {" * "\"reported\": { \"deviceOn\": false }" * "}" * "}"; * updateInfo.update.updateDocumentLength = strlen( updateInfo.update.pUpdateDocument ); * * // Send the Shadow document. A successful update will trigger the updated callback. * result = AwsIotShadow_UpdateSync( mqttConnection, * &updateInfo, * 0, * 0, * 5000 ); * * // After a successful Shadow update, the updated callback will be invoked. * * // Once the updated callback is no longer needed, it may be removed by * // passing NULL as pUpdatedCallback. * result = AwsIotShadow_SetUpdatedCallback( mqttConnection, * THING_NAME, * THING_NAME_LENGTH, * NULL ); * * // The return value from removing an updated callback should always be * // success. * assert( result == AWS_IOT_SHADOW_SUCCESS ); * } * @endcode */ /* @[declare_shadow_setupdatedcallback] */ AwsIotShadowError_t AwsIotShadow_SetUpdatedCallback( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags, const AwsIotShadowCallbackInfo_t * pUpdatedCallback ); /* @[declare_shadow_setupdatedcallback] */ /** * @brief Remove persistent Thing Shadow operation topic subscriptions. * * Passing the flag @ref AWS_IOT_SHADOW_FLAG_KEEP_SUBSCRIPTIONS to @ref shadow_function_deleteasync, * @ref shadow_function_getasync, @ref shadow_function_updateasync, or their blocking versions. * causes the Shadow operation topic subscriptions to be maintained for future calls to the * same function. If a persistent subscription for a Shadow topic are no longer needed, * this function may be used to remove it. * * @param[in] mqttConnection The MQTT connection associated with the persistent subscription. * @param[in] pThingName The Thing Name associated with the persistent subscription. * @param[in] thingNameLength The length of `pThingName`. * @param[in] flags Flags that determine which subscriptions to remove. Valid values are * the bitwise OR of the following individual flags: * - @ref AWS_IOT_SHADOW_FLAG_REMOVE_DELETE_SUBSCRIPTIONS * - @ref AWS_IOT_SHADOW_FLAG_REMOVE_GET_SUBSCRIPTIONS * - @ref AWS_IOT_SHADOW_FLAG_REMOVE_UPDATE_SUBSCRIPTIONS * * @return On success: * - #AWS_IOT_SHADOW_SUCCESS * @return If an MQTT UNSUBSCRIBE packet cannot be sent, one of the following: * - #AWS_IOT_SHADOW_NO_MEMORY * - #AWS_IOT_SHADOW_MQTT_ERROR * * @note @ref shadow_function_cleanup removes all persistent subscriptions as well. * * @warning This function is not safe to call with any in-progress operations! * It also does not affect delta and updated callbacks registered with @ref * shadow_function_setdeltacallback and @ref shadow_function_setupdatedcallback, * respectively. (See documentation for those functions on how to remove their * callbacks). */ /* @[declare_shadow_removepersistentsubscriptions] */ AwsIotShadowError_t AwsIotShadow_RemovePersistentSubscriptions( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags ); /* @[declare_shadow_removepersistentsubscriptions] */ /*------------------------- Shadow helper functions -------------------------*/ /** * @brief Returns a string that describes an #AwsIotShadowError_t. * * Like POSIX's `strerror`, this function returns a string describing a return * code. In this case, the return code is a Shadow library error code, `status`. * * The string returned by this function <b>MUST</b> be treated as read-only: any * attempt to modify its contents may result in a crash. Therefore, this function * is limited to usage in logging. * * @param[in] status The status to describe. * * @return A read-only string that describes `status`. * * @warning The string returned by this function must never be modified. */ /* @[declare_shadow_strerror] */ const char * AwsIotShadow_strerror( AwsIotShadowError_t status ); /* @[declare_shadow_strerror] */ /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Backwards compatibility macros for previous function names. */ #define AwsIotShadow_Delete AwsIotShadow_DeleteAsync #define AwsIotShadow_TimedDelete AwsIotShadow_DeleteSync #define AwsIotShadow_Get AwsIotShadow_GetAsync #define AwsIotShadow_TimedGet AwsIotShadow_GetSync #define AwsIotShadow_Update AwsIotShadow_UpdateAsync #define AwsIotShadow_TimedUpdate AwsIotShadow_UpdateSync /** @endcond */ #endif /* ifndef AWS_IOT_SHADOW_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/standard/mqtt/include/types/iot_mqtt_types.h
<gh_stars>1-10 /* * IoT MQTT V2.1.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file iot_mqtt_types.h * @brief MQTT library types. */ #ifndef IOT_MQTT_TYPES_H_ #define IOT_MQTT_TYPES_H_ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <stdbool.h> #include <stdint.h> #include <stddef.h> /* Type includes. */ #include "types/iot_platform_types.h" #include "types/iot_taskpool_types_freertos.h" /* Platform network include. */ #include "platform/iot_network.h" /*---------------------------- MQTT handle types ----------------------------*/ /** * @handles{mqtt,MQTT library} */ /** * @ingroup mqtt_datatypes_handles * @brief Opaque handle of an MQTT connection. * * MQTT connection handle type. MQTT connection handles are created by * successful calls to @ref mqtt_function_connect and are used to refer to * the connection when calling MQTT library functions. * * A call to @ref mqtt_function_disconnect makes a connection handle invalid. Once * @ref mqtt_function_disconnect returns, the connection handle should no longer * be used. * * @initializer{IotMqttConnection_t,IOT_MQTT_CONNECTION_INITIALIZER} */ typedef struct _mqttConnection * IotMqttConnection_t; /** * @ingroup mqtt_datatypes_handles * @brief Opaque handle that references an in-progress MQTT operation. * * Set as an output parameter of @ref mqtt_function_publishasync, @ref mqtt_function_subscribeasync, * and @ref mqtt_function_unsubscribeasync. These functions queue an MQTT operation; the result * of the operation is unknown until a response from the MQTT server is received. Therefore, * this handle serves as a reference to MQTT operations awaiting MQTT server response. * * This reference will be valid from the successful return of @ref mqtt_function_publishasync, * @ref mqtt_function_subscribeasync, or @ref mqtt_function_unsubscribeasync. The reference becomes * invalid once the [completion callback](@ref IotMqttCallbackInfo_t) is invoked, or * @ref mqtt_function_wait returns. * * @initializer{IotMqttOperation_t,IOT_MQTT_OPERATION_INITIALIZER} * * @see @ref mqtt_function_wait and #IOT_MQTT_FLAG_WAITABLE for waiting on a reference. * #IotMqttCallbackInfo_t and #IotMqttCallbackParam_t for an asynchronous notification * of completion. */ typedef struct _mqttOperation * IotMqttOperation_t; /*-------------------------- MQTT enumerated types --------------------------*/ /** * @enums{mqtt,MQTT library} */ /** * @ingroup mqtt_datatypes_enums * @brief Return codes of [MQTT functions](@ref mqtt_functions). * * The function @ref mqtt_function_strerror can be used to get a return code's * description. */ typedef enum IotMqttError { /** * @brief MQTT operation completed successfully. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_publishasync with QoS 0 parameter * - @ref mqtt_function_wait * - @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishsync * * Will also be the value of an operation completion callback's * #IotMqttCallbackParam_t.result when successful. */ IOT_MQTT_SUCCESS = 0, /** * @brief MQTT operation queued, awaiting result. * * Functions that may return this value: * - @ref mqtt_function_subscribeasync * - @ref mqtt_function_unsubscribeasync * - @ref mqtt_function_publishasync with QoS 1 parameter */ IOT_MQTT_STATUS_PENDING = 1, /** * @brief Initialization failed. * * Functions that may return this value: * - @ref mqtt_function_init */ IOT_MQTT_INIT_FAILED = 2, /** * @brief At least one parameter is invalid. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_subscribeasync and @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribeasync and @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishasync and @ref mqtt_function_publishsync * - @ref mqtt_function_wait */ IOT_MQTT_BAD_PARAMETER = 3, /** * @brief MQTT operation failed because of memory allocation failure. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_subscribeasync and @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribeasync and @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishasync and @ref mqtt_function_publishsync */ IOT_MQTT_NO_MEMORY = 4, /** * @brief MQTT operation failed because the network was unusable. * * This return value may indicate that the network is disconnected. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_wait * - @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishsync * * May also be the value of an operation completion callback's * #IotMqttCallbackParam_t.result. */ IOT_MQTT_NETWORK_ERROR = 5, /** * @brief MQTT operation could not be scheduled, i.e. enqueued for sending. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_subscribeasync and @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribeasync and @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishasync and @ref mqtt_function_publishsync */ IOT_MQTT_SCHEDULING_ERROR = 6, /** * @brief MQTT response packet received from the network is malformed. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_wait * - @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishsync * * May also be the value of an operation completion callback's * #IotMqttCallbackParam_t.result. * * @note If this value is received, the network connection has been closed. */ IOT_MQTT_BAD_RESPONSE = 7, /** * @brief A blocking MQTT operation timed out. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_wait * - @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishsync */ IOT_MQTT_TIMEOUT = 8, /** * @brief A CONNECT or at least one subscription was refused by the server. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_wait, but only when its #IotMqttOperation_t parameter * is associated with a SUBSCRIBE operation. * - @ref mqtt_function_subscribesync * * May also be the value of an operation completion callback's * #IotMqttCallbackParam_t.result for a SUBSCRIBE. * * @note If this value is returned and multiple subscriptions were passed to * @ref mqtt_function_subscribeasync (or @ref mqtt_function_subscribesync), it's * still possible that some of the subscriptions succeeded. This value only * signifies that AT LEAST ONE subscription was rejected. The function @ref * mqtt_function_issubscribed can be used to determine which subscriptions * were accepted or rejected. */ IOT_MQTT_SERVER_REFUSED = 9, /** * @brief A QoS 1 PUBLISH received no response and [the retry limit] * (#IotMqttPublishInfo_t.retryLimit) was reached. * * Functions that may return this value: * - @ref mqtt_function_wait, but only when its #IotMqttOperation_t parameter * is associated with a QoS 1 PUBLISH operation * - @ref mqtt_function_publishsync * * May also be the value of an operation completion callback's * #IotMqttCallbackParam_t.result for a QoS 1 PUBLISH. */ IOT_MQTT_RETRY_NO_RESPONSE = 10, /** * @brief An API function was called before @ref mqtt_function_init. * * Functions that may return this value: * - @ref mqtt_function_connect * - @ref mqtt_function_subscribeasync * - @ref mqtt_function_subscribesync * - @ref mqtt_function_unsubscribeasync * - @ref mqtt_function_unsubscribesync * - @ref mqtt_function_publishasync * - @ref mqtt_function_publishsync * - @ref mqtt_function_wait */ IOT_MQTT_NOT_INITIALIZED = 11 } IotMqttError_t; /** * @ingroup mqtt_datatypes_enums * @brief Types of MQTT operations. * * The function @ref mqtt_function_operationtype can be used to get an operation * type's description. */ typedef enum IotMqttOperationType { IOT_MQTT_CONNECT, /**< Client-to-server CONNECT. */ IOT_MQTT_PUBLISH_TO_SERVER, /**< Client-to-server PUBLISH. */ IOT_MQTT_PUBACK, /**< Client-to-server PUBACK. */ IOT_MQTT_SUBSCRIBE, /**< Client-to-server SUBSCRIBE. */ IOT_MQTT_UNSUBSCRIBE, /**< Client-to-server UNSUBSCRIBE. */ IOT_MQTT_PINGREQ, /**< Client-to-server PINGREQ. */ IOT_MQTT_DISCONNECT /**< Client-to-server DISCONNECT. */ } IotMqttOperationType_t; /** * @ingroup mqtt_datatypes_enums * @brief Quality of service levels for MQTT PUBLISH messages. * * All MQTT PUBLISH messages, including Last Will and Testament and messages * received on subscription filters, have an associated <i>Quality of Service</i>, * which defines any delivery guarantees for that message. * - QoS 0 messages will be delivered at most once. This is a "best effort" * transmission with no retransmissions. * - QoS 1 messages will be delivered at least once. See #IotMqttPublishInfo_t * for the retransmission strategy this library uses to redeliver messages * assumed to be lost. * * @attention QoS 2 is not supported by this library and should not be used. */ typedef enum IotMqttQos { IOT_MQTT_QOS_0 = 0, /**< Delivery at most once. */ IOT_MQTT_QOS_1 = 1, /**< Delivery at least once. See #IotMqttPublishInfo_t for client-side retry strategy. */ IOT_MQTT_QOS_2 = 2 /**< Delivery exactly once. Unsupported, but enumerated for completeness. */ } IotMqttQos_t; /** * @ingroup mqtt_datatypes_enums * @brief The reason that an MQTT connection (and its associated network connection) * was disconnected. * * When an MQTT connection is closed, its associated [disconnect callback] * (@ref IotMqttNetworkInfo_t::disconnectCallback) will be invoked. This type * is passed inside of an #IotMqttCallbackParam_t to provide a reason for the * disconnect. */ typedef enum IotMqttDisconnectReason { IOT_MQTT_DISCONNECT_CALLED, /**< @ref mqtt_function_disconnect was invoked. */ IOT_MQTT_BAD_PACKET_RECEIVED, /**< An invalid packet was received from the network. */ IOT_MQTT_KEEP_ALIVE_TIMEOUT /**< Keep-alive response was not received within @ref IOT_MQTT_RESPONSE_WAIT_MS. */ } IotMqttDisconnectReason_t; /*------------------------- MQTT parameter structs --------------------------*/ /** * @paramstructs{mqtt,MQTT} */ /** * @ingroup mqtt_datatypes_paramstructs * @brief Information on a PUBLISH message. * * @paramfor @ref mqtt_function_connect, @ref mqtt_function_publishasync * * Passed to @ref mqtt_function_publishasync as the message to publish and @ref * mqtt_function_connect as the Last Will and Testament (LWT) message. * * @initializer{IotMqttPublishInfo_t,IOT_MQTT_PUBLISH_INFO_INITIALIZER} * * #IotMqttPublishInfo_t.retryMs and #IotMqttPublishInfo_t.retryLimit are only * relevant to QoS 1 PUBLISH messages. They are ignored for QoS 0 PUBLISH * messages and LWT messages. These members control retransmissions of QoS 1 * messages under the following rules: * - Retransmission is disabled when #IotMqttPublishInfo_t.retryLimit is 0. * After sending the PUBLISH, the library will wait indefinitely for a PUBACK. * - If #IotMqttPublishInfo_t.retryLimit is greater than 0, then QoS 1 publishes * that do not receive a PUBACK within #IotMqttPublishInfo_t.retryMs will be * retransmitted, up to #IotMqttPublishInfo_t.retryLimit times. * * Retransmission follows a truncated exponential backoff strategy. The constant * @ref IOT_MQTT_RETRY_MS_CEILING controls the maximum time between retransmissions. * * After #IotMqttPublishInfo_t.retryLimit retransmissions are sent, the MQTT * library will wait @ref IOT_MQTT_RESPONSE_WAIT_MS before a final check * for a PUBACK. If no PUBACK was received within this time, the QoS 1 PUBLISH * fails with the code #IOT_MQTT_RETRY_NO_RESPONSE. * * @note The lengths of the strings in this struct should not include the NULL * terminator. Strings in this struct do not need to be NULL-terminated. * * @note The AWS IoT MQTT broker does not support the DUP bit. More * information about connecting to AWS IoT via MQTT is available * [here](https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html). * * <b>Example</b> * * Consider a situation where * - @ref IOT_MQTT_RETRY_MS_CEILING is 60000 * - #IotMqttPublishInfo_t.retryMs is 2000 * - #IotMqttPublishInfo_t.retryLimit is 20 * * A PUBLISH message will be retransmitted at the following times after the initial * transmission if no PUBACK is received: * - 2000 ms (2000 ms after previous transmission) * - 6000 ms (4000 ms after previous transmission) * - 14000 ms (8000 ms after previous transmission) * - 30000 ms (16000 ms after previous transmission) * - 62000 ms (32000 ms after previous transmission) * - 122000 ms, 182000 ms, 242000 ms... (every 60000 ms until 20 transmissions have been sent) * * After the 20th retransmission, the MQTT library will wait * @ref IOT_MQTT_RESPONSE_WAIT_MS before checking a final time for a PUBACK. */ typedef struct IotMqttPublishInfo { IotMqttQos_t qos; /**< @brief QoS of message. Must be 0 or 1. */ bool retain; /**< @brief MQTT message retain flag. */ const char * pTopicName; /**< @brief Topic name of PUBLISH. */ uint16_t topicNameLength; /**< @brief Length of #IotMqttPublishInfo_t.pTopicName. */ const void * pPayload; /**< @brief Payload of PUBLISH. */ size_t payloadLength; /**< @brief Length of #IotMqttPublishInfo_t.pPayload. For LWT messages, this is limited to 65535. */ uint32_t retryMs; /**< @brief If no response is received within this time, the message is retransmitted. */ uint32_t retryLimit; /**< @brief How many times to attempt retransmission. */ } IotMqttPublishInfo_t; /** * @ingroup mqtt_datatypes_paramstructs * @brief Parameter to an MQTT callback function. * * @paramfor MQTT callback functions * * The MQTT library passes this struct to a registered callback whenever an * operation completes, a message is received on a topic filter, or an MQTT * connection is disconnected. * * The members of this struct are different based on the callback trigger. If the * callback function was triggered for completed operation, the `operation` * member is valid. Otherwise, if the callback was triggered because of a * server-to-client PUBLISH, the `message` member is valid. Finally, if the callback * was triggered because of a disconnect, the `disconnectReason` member is valid. * * For an incoming PUBLISH, the `message.pTopicFilter` parameter provides the * subscription topic filter that matched the topic name in the PUBLISH. Because * topic filters may use MQTT wildcards, the topic filter may be different from the * topic name. This pointer must be treated as read-only; the topic filter must not * be modified. Additionally, the topic filter may go out of scope as soon as the * callback function returns, so it must be copied if it is needed at a later time. * * @attention Any pointers in this callback parameter may be freed as soon as * the [callback function](@ref IotMqttCallbackInfo_t.function) returns. * Therefore, data must be copied if it is needed after the callback function * returns. * @attention The MQTT library may set strings that are not NULL-terminated. * * @see #IotMqttCallbackInfo_t for the signature of a callback function. */ typedef struct IotMqttCallbackParam { /** * @brief The MQTT connection associated with this completed operation, * incoming PUBLISH, or disconnect. * * [MQTT API functions](@ref mqtt_functions) are safe to call from a callback * for completed operations or incoming PUBLISH messages. However, blocking * function calls (including @ref mqtt_function_wait) are not recommended * (though still safe). Do not call any API functions from a disconnect * callback. */ IotMqttConnection_t mqttConnection; union { /* Valid for completed operations. */ struct { IotMqttOperationType_t type; /**< @brief Type of operation that completed. */ IotMqttOperation_t reference; /**< @brief Reference to the operation that completed. */ IotMqttError_t result; /**< @brief Result of operation, e.g. succeeded or failed. */ } operation; /* Valid for incoming PUBLISH messages. */ struct { const char * pTopicFilter; /**< @brief Topic filter that matched the message. */ uint16_t topicFilterLength; /**< @brief Length of `pTopicFilter`. */ IotMqttPublishInfo_t info; /**< @brief PUBLISH message received from the server. */ } message; /* Valid when a connection is disconnected. */ IotMqttDisconnectReason_t disconnectReason; /**< @brief Why the MQTT connection was disconnected. */ } u; /**< @brief Valid member depends on callback type. */ } IotMqttCallbackParam_t; /** * @ingroup mqtt_datatypes_paramstructs * @brief MQTT callback function and context. * * @paramfor @ref mqtt_function_subscribeasync, @ref mqtt_function_unsubscribeasync, * and @ref mqtt_function_publishasync. Cannot be used with #IOT_MQTT_FLAG_WAITABLE. * * Specifies a function to be invoked with optional context when an operation * completes or when a server-to-client PUBLISH is received. * * @initializer{IotMqttCallbackInfo_t,IOT_MQTT_CALLBACK_INFO_INITIALIZER} * * Below is an example for receiving an asynchronous notification on operation * completion. See @ref mqtt_function_subscribeasync for an example of using this struct * with for incoming PUBLISH messages. * * @code{c} * // Operation completion callback. * void operationComplete( void * pArgument, IotMqttCallbackParam_t * pOperation ); * * // Callback information. * IotMqttCallbackInfo_t callbackInfo = IOT_MQTT_CALLBACK_INFO_INITIALIZER; * callbackInfo.function = operationComplete; * * // Operation to wait for. * IotMqttError_t result = IotMqtt_PublishAsync( &mqttConnection, * &publishInfo, * 0, * &callbackInfo, * &reference ); * * // Publish should have returned IOT_MQTT_STATUS_PENDING. Once a response * // is received, operationComplete is executed with the actual status passed * // in pOperation. * @endcode */ typedef struct IotMqttCallbackInfo { void * pCallbackContext; /**< @brief The first parameter to pass to the callback function to provide context. */ /** * @brief User-provided callback function signature. * * @param[in] void * #IotMqttCallbackInfo_t.pCallbackContext * @param[in] IotMqttCallbackParam_t * Details on the outcome of the MQTT operation * or an incoming MQTT PUBLISH. * * @see #IotMqttCallbackParam_t for more information on the second parameter. */ void ( * function )( void *, IotMqttCallbackParam_t * ); } IotMqttCallbackInfo_t; /** * @ingroup mqtt_datatypes_paramstructs * @brief MQTT subscription. * * @paramfor @ref mqtt_function_subscribeasync, @ref mqtt_function_unsubscribeasync, * @ref mqtt_function_subscribesync, @ref mqtt_function_unsubscribesync * * An array of these is passed to @ref mqtt_function_subscribeasync and @ref * mqtt_function_unsubscribeasync. However, #IotMqttSubscription_t.callback and * and #IotMqttSubscription_t.qos are ignored by @ref mqtt_function_unsubscribeasync. * * @initializer{IotMqttSubscription_t,IOT_MQTT_SUBSCRIPTION_INITIALIZER} * * @note The lengths of the strings in this struct should not include the NULL * terminator. Strings in this struct do not need to be NULL-terminated. * @see #IotMqttCallbackInfo_t for details on setting a callback function. */ typedef struct IotMqttSubscription { /** * @brief QoS of messages delivered on subscription. * * Must be `0` or `1`. Ignored by @ref mqtt_function_unsubscribeasync. */ IotMqttQos_t qos; const char * pTopicFilter; /**< @brief Topic filter of subscription. */ uint16_t topicFilterLength; /**< @brief Length of #IotMqttSubscription_t.pTopicFilter. */ /** * @brief Callback to invoke when a message is received. * * See #IotMqttCallbackInfo_t. Ignored by @ref mqtt_function_unsubscribeasync. */ IotMqttCallbackInfo_t callback; } IotMqttSubscription_t; /** * @ingroup mqtt_datatypes_paramstructs * @brief MQTT connection details. * * @paramfor @ref mqtt_function_connect * * Passed as an argument to @ref mqtt_function_connect. Most members of this struct * correspond to the content of an [MQTT CONNECT packet.] * (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/csprd02/mqtt-v3.1.1-csprd02.html#_Toc385349764) * * @initializer{IotMqttConnectInfo_t,IOT_MQTT_CONNECT_INFO_INITIALIZER} * * @note The lengths of the strings in this struct should not include the NULL * terminator. Strings in this struct do not need to be NULL-terminated. */ typedef struct IotMqttConnectInfo { /** * @brief Specifies if this MQTT connection is to an AWS IoT MQTT server. * * Set this member to `true` when connecting to the AWS IoT MQTT broker or * `false` otherwise. Additional details about connecting to AWS IoT * via MQTT are available [here] * (https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.html) * * @attention This setting <b>MUST</b> be `true` when using the AWS IoT MQTT * server; it <b>MUST</b> be `false` otherwise. * @note Currently, @ref IOT_MQTT_CONNECT_INFO_INITIALIZER sets this * this member to `true`. */ bool awsIotMqttMode; /** * @brief Whether this connection is a clean session. * * MQTT servers can maintain and topic filter subscriptions and unacknowledged * PUBLISH messages. These form part of an <i>MQTT session</i>, which is identified by * the [client identifier](@ref IotMqttConnectInfo_t.pClientIdentifier). * * Setting this value to `true` establishes a <i>clean session</i>, which causes * the MQTT server to discard any previous session data for a client identifier. * When the client disconnects, the server discards all session data. If this * value is `true`, #IotMqttConnectInfo_t.pPreviousSubscriptions and * #IotMqttConnectInfo_t.previousSubscriptionCount are ignored. * * Setting this value to `false` does one of the following: * - If no previous session exists, the MQTT server will create a new * <i>persistent session</i>. The server may maintain subscriptions and * unacknowledged PUBLISH messages after a client disconnects, to be restored * once the same client identifier reconnects. * - If a previous session exists, the MQTT server restores all of the session's * subscriptions for the client identifier and may immediately transmit any * unacknowledged PUBLISH packets to the client. * * When a client with a persistent session disconnects, the MQTT server * continues to maintain all subscriptions and unacknowledged PUBLISH messages. * The client must also remember the session subscriptions to restore them * upon reconnecting. #IotMqttConnectInfo_t.pPreviousSubscriptions and * #IotMqttConnectInfo_t.previousSubscriptionCount are used to restore a * previous session's subscriptions client-side. */ bool cleanSession; /** * @brief An array of MQTT subscriptions present in a previous session, if any. * * Pointer to the start of an array of subscriptions present a previous session, * if any. These subscriptions will be immediately restored upon reconnecting. * * [Optional] The field can also be used to pass a list of subscriptions to be * stored locally without a SUBSCRIBE packet being sent to the broker. These subscriptions * are useful to invoke application level callbacks for messages received on unsolicited * topics from the broker. * * This member is ignored if it is `NULL`. If this member is not `NULL`, * #IotMqttConnectInfo_t.previousSubscriptionCount must be nonzero. */ const IotMqttSubscription_t * pPreviousSubscriptions; /** * @brief The number of MQTT subscriptions present in a previous session, if any. * * Number of subscriptions contained in the array * #IotMqttConnectInfo_t.pPreviousSubscriptions. * * This value is ignored if #IotMqttConnectInfo_t.pPreviousSubscriptions * is `NULL`. If #IotMqttConnectInfo_t.pPreviousSubscriptions is not `NULL`, * this value must be nonzero. */ size_t previousSubscriptionCount; /** * @brief A message to publish if the new MQTT connection is unexpectedly closed. * * A Last Will and Testament (LWT) message may be published if this connection is * closed without sending an MQTT DISCONNECT packet. This pointer should be set to * an #IotMqttPublishInfo_t representing any LWT message to publish. If an LWT * is not needed, this member must be set to `NULL`. * * Unlike other PUBLISH messages, an LWT message is limited to 65535 bytes in * length. Additionally, [pWillInfo->retryMs](@ref IotMqttPublishInfo_t.retryMs) * and [pWillInfo->retryLimit](@ref IotMqttPublishInfo_t.retryLimit) will * be ignored. */ const IotMqttPublishInfo_t * pWillInfo; uint16_t keepAliveSeconds; /**< @brief Period of keep-alive messages. Set to 0 to disable keep-alive. */ const char * pClientIdentifier; /**< @brief MQTT client identifier. */ uint16_t clientIdentifierLength; /**< @brief Length of #IotMqttConnectInfo_t.pClientIdentifier. */ /* These credentials are not used by AWS IoT and may be ignored if * awsIotMqttMode is true. */ const char * pUserName; /**< @brief Username for MQTT connection. */ uint16_t userNameLength; /**< @brief Length of #IotMqttConnectInfo_t.pUserName. */ const char * pPassword; /**< @brief Password for MQTT connection. */ uint16_t passwordLength; /**< @brief Length of #IotMqttConnectInfo_t.pPassword. */ } IotMqttConnectInfo_t; /** * @ingroup mqtt_datatypes_paramstructs * @brief MQTT packet details. * * @paramfor @ref mqtt_function_deserializeresponse @ref mqtt_function_deserializepublish * * Passed as an argument to public low level mqtt deserialize functions. * * @initializer{IotMqttPacketInfo_t,IOT_MQTT_PACKET_INFO_INITIALIZER} * * @note This structure should be only used while accessing low level MQTT deserialization API. * The low level serialization/ deserialization API should be only used for implementing * light weight single threaded mqtt client. */ typedef struct IotMqttPacketInfo { uint8_t * pRemainingData; /**< @brief (Input) The remaining data in MQTT packet. */ size_t remainingLength; /**< @brief (Input) Length of the remaining data in the MQTT packet. */ uint16_t packetIdentifier; /**< @brief (Output) MQTT packet identifier. */ uint8_t type; /**< @brief (Input) A value identifying the packet type. */ IotMqttPublishInfo_t pubInfo; /**< @brief (Output) Publish info in case of deserializing PUBLISH. */ } IotMqttPacketInfo_t; /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Forward declaration of the internal MQTT packet structure. */ struct _mqttPacket; /** @endcond */ /** * @brief Get the MQTT packet type from a stream of bytes off the network. * * @param[in] pNetworkConnection Reference to the network connection. * @param[in] pNetworkInterface Function pointers used to interact with the * network. */ typedef uint8_t ( * IotMqttGetPacketType_t )( void * pNetworkConnection, const IotNetworkInterface_t * pNetworkInterface ); /** * @brief Get the remaining length from a stream of bytes off the network. * * @param[in] pNetworkConnection Reference to the network connection. * @param[in] pNetworkInterface Function pointers used to interact with the * network. */ typedef size_t ( * IotMqttGetRemainingLength_t )( void * pNetworkConnection, const IotNetworkInterface_t * pNetworkInterface ); /** * @brief Free a packet generated by the serializer. * * This function pointer must be set if any other serializer override is set. * @param[in] uint8_t* The packet to free. */ typedef void ( * IotMqttFreePacket_t )( uint8_t * pPacket ); /** * @brief CONNECT packet serializer function. * @param[in] IotMqttConnectInfo_t* User-provided CONNECT information. * @param[out] uint8_t** Where the CONNECT packet is written. * @param[out] size_t* Size of the CONNECT packet. */ typedef IotMqttError_t ( * IotMqttSerializeConnect_t )( const IotMqttConnectInfo_t * pConnectInfo, uint8_t ** pConnectPacket, size_t * pPacketSize ); /** * @brief PINGREQ packet serializer function. * @param[out] uint8_t** Where the PINGREQ packet is written. * @param[out] size_t* Size of the PINGREQ packet. */ typedef IotMqttError_t ( * IotMqttSerializePingreq_t )( uint8_t ** pDisconnectPacket, size_t * pPacketSize ); /** * @brief PUBLISH packet serializer function. * @param[in] IotMqttPublishInfo_t* User-provided PUBLISH information. * @param[out] uint8_t** Where the PUBLISH packet is written. * @param[out] size_t* Size of the PUBLISH packet. * @param[out] uint16_t* The packet identifier generated for this PUBLISH. * @param[out] uint8_t** Where the high byte of the packet identifier * is written. */ typedef IotMqttError_t ( * IotMqtt_SerializePublish_t )( const IotMqttPublishInfo_t * pPublishInfo, uint8_t ** pPublishPacket, size_t * pPacketSize, uint16_t * pPacketIdentifier, uint8_t ** pPacketIdentifierHigh ); /** * @brief SUBSCRIBE/UNSUBSCRIBE packet serializer function. * @param[in] IotMqttSubscription_t* User-provided array of subscriptions. * @param[in] size_t Number of elements in the subscription array. * @param[out] uint8_t** Where the SUBSCRIBE packet is written. * @param[out] size_t* Size of the SUBSCRIBE packet. * @param[out] uint16_t* The packet identifier generated for this SUBSCRIBE. */ typedef IotMqttError_t ( * IotMqttSerializeSubscribe_t )( const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint8_t ** pSubscribePacket, size_t * pPacketSize, uint16_t * pPacketIdentifier ); /** * @brief DISCONNECT packet serializer function. * @param[out] uint8_t** Where the DISCONNECT packet is written. * @param[out] size_t* Size of the DISCONNECT packet. */ typedef IotMqttError_t ( * IotMqttSerializeDisconnect_t )( uint8_t ** ppDisconnectPacket, size_t * pPacketSize ); /** * @brief MQTT packet deserializer function. * @param[in,out] _mqttPacket* Pointer to an MQTT packet structure */ typedef IotMqttError_t ( * IotMqttDeserialize_t )( struct _mqttPacket * pMqttPacket ); /** * @brief PUBACK packet serializer function. * @param[in] uint16_t The packet identifier to place in PUBACK. * @param[out] uint8_t** Where the PUBACK packet is written. * @param[out] size_t* Size of the PUBACK packet. */ typedef IotMqttError_t ( * IotMqttSerializePuback_t )( uint16_t packetIdentifier, uint8_t ** pPubackPacket, size_t * pPacketSize ); /** * @brief Set the `DUP` bit in a QoS `1` PUBLISH packet. * @param[in] uint8_t* Pointer to the PUBLISH packet to modify. * @param[in] uint8_t* The high byte of any packet identifier to modify. * @param[out] uint16_t* New packet identifier (AWS IoT MQTT mode only). */ typedef void ( * IotMqttPublishSetDup_t )( uint8_t * pPublishPacket, uint8_t * pPacketIdentifierHigh, uint16_t * pNewPacketIdentifier ); /** * @brief Function pointer to read the next available byte on a network connection. * @param[in] pNetworkContext reference to network connection like socket. * @param[out] pNextByte Pointer to the byte read from the network. */ typedef IotMqttError_t (* IotMqttGetNextByte_t)( void * pNetworkContext, uint8_t * pNextByte ); #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 /** * @ingroup mqtt_datatypes_paramstructs * @brief Function pointers for MQTT packet serializer overrides. * * These function pointers allow the MQTT serialization and deserialization functions * to be overridden for an MQTT connection. The compile-time setting * @ref IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES must be `1` to enable this functionality. * See the #IotMqttSerializer_t::serialize and #IotMqttSerializer_t::deserialize * members for a list of functions that can be overridden. In addition, the functions * for freeing packets and determining the packet type can also be overridden. If * @ref IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES is `1`, the serializer initialization and * cleanup functions may be extended. See documentation of * @ref IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES for more information. * * If any function pointers that are `NULL`, then the default implementation of that * function will be used. */ typedef struct IotMqttSerializer { /** * @brief Get the MQTT packet type from a stream of bytes off the network. * <b>Default implementation:</b> #_IotMqtt_GetPacketType */ IotMqttGetPacketType_t getPacketType; /** * @brief Get the remaining length from a stream of bytes off the network. * <b>Default implementation:</b> #_IotMqtt_GetRemainingLength */ IotMqttGetRemainingLength_t getRemainingLength; /** * @brief Free a packet generated by the serializer. * * <b>Default implementation:</b> #_IotMqtt_FreePacket */ IotMqttFreePacket_t freePacket; struct { /** * @brief CONNECT packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializeConnect */ IotMqttSerializeConnect_t connect; /** * @brief PUBLISH packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializePublish */ IotMqtt_SerializePublish_t publish; /** * @brief Set the `DUP` bit in a QoS `1` PUBLISH packet. * * <b>Default implementation:</b> #_IotMqtt_PublishSetDup */ IotMqttPublishSetDup_t publishSetDup; /** * @brief PUBACK packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializePuback */ IotMqttSerializePuback_t puback; /** * @brief SUBSCRIBE packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializeSubscribe */ IotMqttSerializeSubscribe_t subscribe; /** * @brief UNSUBSCRIBE packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializeUnsubscribe */ IotMqttSerializeSubscribe_t unsubscribe; /** * @brief PINGREQ packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializePingreq */ IotMqttSerializePingreq_t pingreq; /** * @brief DISCONNECT packet serializer function. * * <b>Default implementation:</b> #_IotMqtt_SerializeDisconnect */ IotMqttSerializeDisconnect_t disconnect; } serialize; /**< @brief Overrides the packet serialization functions for a single connection. */ struct { /** * @brief CONNACK packet deserializer function. * * <b>Default implementation:</b> #_IotMqtt_DeserializeConnack */ IotMqttDeserialize_t connack; /** * @brief PUBLISH packet deserializer function. * * <b>Default implementation:</b> #_IotMqtt_DeserializePublish */ IotMqttDeserialize_t publish; /** * @brief PUBACK packet deserializer function. * * <b>Default implementation:</b> #_IotMqtt_DeserializePuback */ IotMqttDeserialize_t puback; /** * @brief SUBACK packet deserializer function. * * <b>Default implementation:</b> #_IotMqtt_DeserializeSuback */ IotMqttDeserialize_t suback; /** * @brief UNSUBACK packet deserializer function. * * <b>Default implementation:</b> #_IotMqtt_DeserializeUnsuback */ IotMqttDeserialize_t unsuback; /** * @brief PINGRESP packet deserializer function. * * <b>Default implementation:</b> #_IotMqtt_DeserializePingresp */ IotMqttDeserialize_t pingresp; } deserialize; /**< @brief Overrides the packet deserialization functions for a single connection. */ } IotMqttSerializer_t; #else /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */ /* When MQTT packet serializer overrides are disabled, this struct is an * incomplete type. */ typedef struct IotMqttSerializer IotMqttSerializer_t; #endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */ /** * @ingroup mqtt_datatypes_paramstructs * @brief MQTT network connection details. * * @paramfor @ref mqtt_function_connect * * The MQTT library needs to be able to send and receive data over a network. * This struct provides an interface for interacting with the network. * * @initializer{IotMqttNetworkInfo_t,IOT_MQTT_NETWORK_INFO_INITIALIZER} */ typedef struct IotMqttNetworkInfo { /** * @brief Whether a new network connection should be created. * * When this value is `true`, a new transport-layer network connection will * be created along with the MQTT connection. #IotMqttNetworkInfo_t::pNetworkServerInfo * and #IotMqttNetworkInfo_t::pNetworkCredentialInfo are valid when this value * is `true`. * * When this value is `false`, the MQTT connection will use a transport-layer * network connection that has already been established. The MQTT library will * still set the appropriate receive callback even if the network connection * has been established. * #IotMqttNetworkInfo_t::pNetworkConnection, which represents an established * network connection, is valid when this value is `false`. */ bool createNetworkConnection; union { struct { /** * @brief Information on the MQTT server, passed as `pServerInfo` to * #IotNetworkInterface_t::create. * * This member is opaque to the MQTT library. It is passed to the network * interface when creating a new network connection. It is only valid when * #IotMqttNetworkInfo_t::createNetworkConnection is `true`. */ IotNetworkServerInfo_t pNetworkServerInfo; /** * @brief Credentials for the MQTT server, passed as `pCredentialInfo` to * #IotNetworkInterface_t::create. * * This member is opaque to the MQTT library. It is passed to the network * interface when creating a new network connection. It is only valid when * #IotMqttNetworkInfo_t::createNetworkConnection is `true`. */ IotNetworkCredentials_t pNetworkCredentialInfo; } setup; /** * @brief An established transport-layer network connection. * * This member is opaque to the MQTT library. It is passed to the network * interface to reference an established network connection. It is only * valid when #IotMqttNetworkInfo_t::createNetworkConnection is `false`. */ IotNetworkConnection_t pNetworkConnection; } u /**< @brief Valid member depends of IotMqttNetworkInfo_t.createNetworkConnection. */; /** * @brief The network functions used by the new MQTT connection. * * @attention The function pointers of the network interface must remain valid * for the lifetime of the MQTT connection. */ const IotNetworkInterface_t * pNetworkInterface; /** * @brief A callback function to invoke when this MQTT connection is disconnected. */ IotMqttCallbackInfo_t disconnectCallback; #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 /** * @brief MQTT packet serializer overrides used by the new MQTT connection. * * @attention The function pointers of the MQTT serializer overrides must * remain valid for the lifetime of the MQTT connection. */ const IotMqttSerializer_t * pMqttSerializer; #endif } IotMqttNetworkInfo_t; /*------------------------- MQTT defined constants --------------------------*/ /** * @constantspage{mqtt,MQTT library} * * @section mqtt_constants_initializers MQTT Initializers * @brief Provides default values for the data types of the MQTT library. * * @snippet this define_mqtt_initializers * * All user-facing data types of the MQTT library should be initialized using * one of the following. * * @warning Failing to initialize an MQTT data type with the appropriate initializer * may result in undefined behavior! * @note The initializers may change at any time in future versions, but their * names will remain the same. * * <b>Example</b> * @code{c} * IotMqttNetworkInfo_t networkInfo = IOT_MQTT_NETWORK_INFO_INITIALIZER; * IotMqttSerializer_t serializer = IOT_MQTT_SERIALIZER_INITIALIZER; * IotMqttConnectInfo_t connectInfo = IOT_MQTT_CONNECT_INFO_INITIALIZER; * IotMqttPublishInfo_t publishInfo = IOT_MQTT_PUBLISH_INFO_INITIALIZER; * IotMqttSubscription_t subscription = IOT_MQTT_SUBSCRIPTION_INITIALIZER; * IotMqttCallbackInfo_t callbackInfo = IOT_MQTT_CALLBACK_INFO_INITIALIZER; * IotMqttConnection_t connection = IOT_MQTT_CONNECTION_INITIALIZER; * IotMqttOperation_t operation = IOT_MQTT_OPERATION_INITIALIZER; * @endcode * * @section mqtt_constants_flags MQTT Function Flags * @brief Flags that modify the behavior of MQTT library functions. * - #IOT_MQTT_FLAG_WAITABLE <br> * @copybrief IOT_MQTT_FLAG_WAITABLE * - #IOT_MQTT_FLAG_CLEANUP_ONLY <br> * @copybrief IOT_MQTT_FLAG_CLEANUP_ONLY * * Flags should be bitwise-ORed with each other to change the behavior of * @ref mqtt_function_subscribeasync, @ref mqtt_function_unsubscribeasync, * @ref mqtt_function_publishasync, their blocking versions; or @ref mqtt_function_disconnect. * * @note The values of the flags may change at any time in future versions, but * their names will remain the same. Additionally, flags that may be used together * will be bitwise-exclusive of each other. */ /* @[define_mqtt_initializers] */ /** @brief Initializer for #IotMqttNetworkInfo_t. */ #define IOT_MQTT_NETWORK_INFO_INITIALIZER { .createNetworkConnection = true } /** @brief Initializer for #IotMqttSerializer_t. */ #define IOT_MQTT_SERIALIZER_INITIALIZER { 0 } /** @brief Initializer for #IotMqttConnectInfo_t. */ #define IOT_MQTT_CONNECT_INFO_INITIALIZER { .cleanSession = true } /** @brief Initializer for #IotMqttPublishInfo_t. */ #define IOT_MQTT_PUBLISH_INFO_INITIALIZER { .qos = IOT_MQTT_QOS_0 } /** @brief Initializer for #IotMqttSubscription_t. */ #define IOT_MQTT_SUBSCRIPTION_INITIALIZER { .qos = IOT_MQTT_QOS_0 } /** @brief Initializer for #IotMqttCallbackInfo_t. */ #define IOT_MQTT_CALLBACK_INFO_INITIALIZER { 0 } /** @brief Initializer for #IotMqttConnection_t. */ #define IOT_MQTT_CONNECTION_INITIALIZER NULL /** @brief Initializer for #IotMqttOperation_t. */ #define IOT_MQTT_OPERATION_INITIALIZER NULL /** @brief Initializer for #IotMqttPacketInfo_t. */ #define IOT_MQTT_PACKET_INFO_INITIALIZER { .pRemainingData = NULL, remainingLength = 0, packetIdentifier = 0, .type = 0 } /* @[define_mqtt_initializers] */ /** * @brief Allows the use of @ref mqtt_function_wait for blocking until completion. * * This flag is always valid for @ref mqtt_function_subscribeasync and * @ref mqtt_function_unsubscribeasync. If passed to @ref mqtt_function_publishasync, * the parameter [pPublishInfo->qos](@ref IotMqttPublishInfo_t.qos) must not be `0`. * * An #IotMqttOperation_t <b>MUST</b> be provided if this flag is set. Additionally, an * #IotMqttCallbackInfo_t <b>MUST NOT</b> be provided. * * @note If this flag is set, @ref mqtt_function_wait <b>MUST</b> be called to clean up * resources. */ #define IOT_MQTT_FLAG_WAITABLE ( 0x00000001 ) /** * @brief Causes @ref mqtt_function_disconnect to only free memory and not send * an MQTT DISCONNECT packet. * * This flag is only valid for @ref mqtt_function_disconnect. It should be passed * to @ref mqtt_function_disconnect if the network goes offline or is otherwise * unusable. */ #define IOT_MQTT_FLAG_CLEANUP_ONLY ( 0x00000001 ) #endif /* ifndef IOT_MQTT_TYPES_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/mbedtls/include/mbedtls/certs.h
/** * \file certs.h * * \brief Sample certificates and DHM parameters for testing */ /* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_CERTS_H #define MBEDTLS_CERTS_H #if !defined(MBEDTLS_CONFIG_FILE) #include "config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #ifdef __cplusplus extern "C" { #endif #if defined(MBEDTLS_PEM_PARSE_C) /* Concatenation of all CA certificates in PEM format if available */ extern const char mbedtls_test_cas_pem[]; extern const size_t mbedtls_test_cas_pem_len; #endif /* List of all CA certificates, terminated by NULL */ extern const char * mbedtls_test_cas[]; extern const size_t mbedtls_test_cas_len[]; /* * Convenience for users who just want a certificate: * RSA by default, or ECDSA if RSA is not available */ extern const char * mbedtls_test_ca_crt; extern const size_t mbedtls_test_ca_crt_len; extern const char * mbedtls_test_ca_key; extern const size_t mbedtls_test_ca_key_len; extern const char * mbedtls_test_ca_pwd; extern const size_t mbedtls_test_ca_pwd_len; extern const char * mbedtls_test_srv_crt; extern const size_t mbedtls_test_srv_crt_len; extern const char * mbedtls_test_srv_key; extern const size_t mbedtls_test_srv_key_len; extern const char * mbedtls_test_cli_crt; extern const size_t mbedtls_test_cli_crt_len; extern const char * mbedtls_test_cli_key; extern const size_t mbedtls_test_cli_key_len; #if defined(MBEDTLS_ECDSA_C) extern const char mbedtls_test_ca_crt_ec[]; extern const size_t mbedtls_test_ca_crt_ec_len; extern const char mbedtls_test_ca_key_ec[]; extern const size_t mbedtls_test_ca_key_ec_len; extern const char mbedtls_test_ca_pwd_ec[]; extern const size_t mbedtls_test_ca_pwd_ec_len; extern const char mbedtls_test_srv_crt_ec[]; extern const size_t mbedtls_test_srv_crt_ec_len; extern const char mbedtls_test_srv_key_ec[]; extern const size_t mbedtls_test_srv_key_ec_len; extern const char mbedtls_test_cli_crt_ec[]; extern const size_t mbedtls_test_cli_crt_ec_len; extern const char mbedtls_test_cli_key_ec[]; extern const size_t mbedtls_test_cli_key_ec_len; #endif #if defined(MBEDTLS_RSA_C) extern const char mbedtls_test_ca_crt_rsa[]; extern const size_t mbedtls_test_ca_crt_rsa_len; extern const char mbedtls_test_ca_key_rsa[]; extern const size_t mbedtls_test_ca_key_rsa_len; extern const char mbedtls_test_ca_pwd_rsa[]; extern const size_t mbedtls_test_ca_pwd_rsa_len; extern const char mbedtls_test_srv_crt_rsa[]; extern const size_t mbedtls_test_srv_crt_rsa_len; extern const char mbedtls_test_srv_key_rsa[]; extern const size_t mbedtls_test_srv_key_rsa_len; extern const char mbedtls_test_cli_crt_rsa[]; extern const size_t mbedtls_test_cli_crt_rsa_len; extern const char mbedtls_test_cli_key_rsa[]; extern const size_t mbedtls_test_cli_key_rsa_len; #endif #ifdef __cplusplus } #endif #endif /* certs.h */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/jobs/src/aws_iot_jobs_api.c
/* * AWS IoT Jobs V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_jobs_api.c * @brief Implements the user-facing functions of the Jobs library. */ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <string.h> /* Platform threads include. */ #include "platform/iot_threads.h" /* Jobs internal include. */ #include "private/aws_iot_jobs_internal.h" /* Error handling include. */ #include "iot_error.h" /* MQTT include. */ #include "iot_mqtt.h" /* Validate Jobs configuration settings. */ #if AWS_IOT_JOBS_ENABLE_ASSERTS != 0 && AWS_IOT_JOBS_ENABLE_ASSERTS != 1 #error "AWS_IOT_JOBS_ENABLE_ASSERTS must be 0 or 1." #endif #if AWS_IOT_JOBS_DEFAULT_MQTT_TIMEOUT_MS <= 0 #error "AWS_IOT_JOBS_DEFAULT_MQTT_TIMEOUT_MS cannot be 0 or negative." #endif #if AWS_IOT_JOBS_NOTIFY_CALLBACKS <= 0 #error "AWS_IOT_JOBS_NOTIFY_CALLBACKS cannot be 0 or negative." #endif /** * @brief Returned by @ref _getCallbackIndex when there's no space in the callback array. */ #define NO_SPACE_FOR_CALLBACK ( -1 ) /** * @brief Returned by @ref _getCallbackIndex when a searching for an oldCallback that * does not exist. */ #define OLD_CALLBACK_NOT_FOUND ( -2 ) /*-----------------------------------------------------------*/ /** * @brief Check if the library is initialized. * * @return `true` if AwsIotJobs_Init was called; `false` otherwise. */ static bool _checkInit( void ); /** * @brief Validate the #AwsIotJobsRequestInfo_t passed to a Jobs API function. * * @param[in] type The Jobs API function type. * @param[in] pRequestInfo The request info passed to a Jobs API function. * @param[in] flags Flags used by the Jobs API function. * @param[in] pCallbackInfo The callback info passed with the request info. * @param[in] pOperation Operation reference pointer passed to a Jobs API function. * * @return #AWS_IOT_JOBS_SUCCESS or #AWS_IOT_JOBS_BAD_PARAMETER. */ static AwsIotJobsError_t _validateRequestInfo( _jobsOperationType_t type, const AwsIotJobsRequestInfo_t * pRequestInfo, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, const AwsIotJobsOperation_t * pOperation ); /** * @brief Validate the #AwsIotJobsUpdateInfo_t passed to a Jobs API function. * * @param[in] type The Jobs API function type. * @param[in] pUpdateInfo The update info passed to a Jobs API function. * * @return #AWS_IOT_JOBS_SUCCESS or #AWS_IOT_JOBS_BAD_PARAMETER. */ static AwsIotJobsError_t _validateUpdateInfo( _jobsOperationType_t type, const AwsIotJobsUpdateInfo_t * pUpdateInfo ); /** * @brief Gets an element of the callback array to modify. * * @param[in] type The type of callback to modify. * @param[in] pSubscription Subscription object that holds the callback array. * @param[in] pCallbackInfo User provided callback info. * * @return The index of the callback array to modify; on error: * - #NO_SPACE_FOR_CALLBACK if no free spaces are available * - #OLD_CALLBACK_NOT_FOUND if an old callback to remove was specified, but that function does not exist. * * @note This function should be called with the subscription list mutex locked. */ static int32_t _getCallbackIndex( _jobsCallbackType_t type, _jobsSubscription_t * pSubscription, const AwsIotJobsCallbackInfo_t * pCallbackInfo ); /** * @brief Common function for setting Jobs callbacks. * * @param[in] mqttConnection The MQTT connection to use. * @param[in] type Type of Jobs callback. * @param[in] pThingName Thing Name for Jobs callback. * @param[in] thingNameLength Length of `pThingName`. * @param[in] pCallbackInfo Callback information to set. * * @return #AWS_IOT_JOBS_SUCCESS, #AWS_IOT_JOBS_BAD_PARAMETER, * #AWS_IOT_JOBS_NO_MEMORY, or #AWS_IOT_JOBS_MQTT_ERROR. */ static AwsIotJobsError_t _setCallbackCommon( IotMqttConnection_t mqttConnection, _jobsCallbackType_t type, const char * pThingName, size_t thingNameLength, const AwsIotJobsCallbackInfo_t * pCallbackInfo ); /** * @brief Change the subscriptions for Jobs callbacks, either by subscribing * or unsubscribing. * * @param[in] mqttConnection The MQTT connection to use. * @param[in] type Type of Jobs callback. * @param[in] pSubscription Jobs subscriptions object for callback. * @param[in] mqttOperation Either @ref mqtt_function_subscribesync or * @ref mqtt_function_unsubscribesync. * * @return #AWS_IOT_JOBS_SUCCESS, #AWS_IOT_JOBS_NO_MEMORY, or * #AWS_IOT_JOBS_MQTT_ERROR. */ static AwsIotJobsError_t _modifyCallbackSubscriptions( IotMqttConnection_t mqttConnection, _jobsCallbackType_t type, _jobsSubscription_t * pSubscription, AwsIotMqttFunction_t mqttOperation ); /** * @brief Invoked when a document is received on the Jobs NOTIFY PENDING callback. * * @param[in] pArgument Ignored. * @param[in] pMessage The received Jobs document (as an MQTT PUBLISH message). */ static void _notifyPendingCallbackWrapper( void * pArgument, IotMqttCallbackParam_t * pMessage ); /** * @brief Invoked when a document is received on the Jobs NOTIFY NEXT callback. * * @param[in] pArgument Ignored. * @param[in] pMessage The received Jobs document (as an MQTT PUBLISH message). */ static void _notifyNextCallbackWrapper( void * pArgument, IotMqttCallbackParam_t * pMessage ); /** * @brief Common function for incoming Jobs callbacks. * * @param[in] type Jobs callback type. * @param[in] pMessage The received Jobs callback document (as an MQTT PUBLISH * message). */ static void _callbackWrapperCommon( _jobsCallbackType_t type, IotMqttCallbackParam_t * pMessage ); /*-----------------------------------------------------------*/ /** * @brief Tracks whether @ref jobs_function_init has been called. * * API functions will fail if @ref jobs_function_init was not called. */ static uint32_t _initCalled = 0; /** * @brief Timeout used for MQTT operations. */ uint32_t _AwsIotJobsMqttTimeoutMs = AWS_IOT_JOBS_DEFAULT_MQTT_TIMEOUT_MS; #if LIBRARY_LOG_LEVEL > IOT_LOG_NONE /** * @brief Printable names for the Jobs callbacks. */ const char * const _pAwsIotJobsCallbackNames[] = { "NOTIFY PENDING", "NOTIFY NEXT" }; #endif /*-----------------------------------------------------------*/ static bool _checkInit( void ) { bool status = true; if( _initCalled == 0 ) { IotLogError( "AwsIotJobs_Init was not called." ); status = false; } return status; } /*-----------------------------------------------------------*/ static AwsIotJobsError_t _validateRequestInfo( _jobsOperationType_t type, const AwsIotJobsRequestInfo_t * pRequestInfo, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, const AwsIotJobsOperation_t * pOperation ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_SUCCESS ); /* Check that the given MQTT connection is valid. */ if( pRequestInfo->mqttConnection == IOT_MQTT_CONNECTION_INITIALIZER ) { IotLogError( "MQTT connection is not initialized for Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* Check Thing Name. */ if( AwsIot_ValidateThingName( pRequestInfo->pThingName, pRequestInfo->thingNameLength ) == false ) { IotLogError( "Thing Name is not valid for Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* Checks for waitable operations. */ if( ( flags & AWS_IOT_JOBS_FLAG_WAITABLE ) == AWS_IOT_JOBS_FLAG_WAITABLE ) { if( pOperation == NULL ) { IotLogError( "Reference must be provided for a waitable Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( pRequestInfo->mallocResponse == NULL ) { IotLogError( "Memory allocation function must be set for waitable Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( pCallbackInfo != NULL ) { IotLogError( "Callback should not be set for a waitable Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } /* Check that a callback function is set. */ if( pCallbackInfo != NULL ) { if( pCallbackInfo->function == NULL ) { IotLogError( "Callback function must be set for Jobs %s callback.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } /* Check client token length. */ if( pRequestInfo->pClientToken != AWS_IOT_JOBS_CLIENT_TOKEN_AUTOGENERATE ) { if( pRequestInfo->clientTokenLength == 0 ) { IotLogError( "Client token length must be set for Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( pRequestInfo->clientTokenLength > AWS_IOT_CLIENT_TOKEN_MAX_LENGTH ) { IotLogError( "Client token for Jobs %s cannot be longer than %d.", _pAwsIotJobsOperationNames[ type ], AWS_IOT_CLIENT_TOKEN_MAX_LENGTH ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } /* Check Job ID for DESCRIBE and UPDATE. */ if( ( type == JOBS_DESCRIBE ) || ( type == JOBS_UPDATE ) ) { if( ( pRequestInfo->pJobId == NULL ) || ( pRequestInfo->jobIdLength == 0 ) ) { IotLogError( "Job ID must be set for Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( pRequestInfo->jobIdLength > JOBS_MAX_ID_LENGTH ) { IotLogError( "Job ID for Jobs %s cannot be longer than %d.", _pAwsIotJobsOperationNames[ type ], JOBS_MAX_ID_LENGTH ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } /* A Job ID (not $next job) must be specified for UPDATE. */ if( type == JOBS_UPDATE ) { if( ( pRequestInfo->jobIdLength == AWS_IOT_JOBS_NEXT_JOB_LENGTH ) && ( strncmp( AWS_IOT_JOBS_NEXT_JOB, pRequestInfo->pJobId, AWS_IOT_JOBS_NEXT_JOB_LENGTH ) == 0 ) ) { IotLogError( "Job ID $next is not valid for Jobs UPDATE." ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ static AwsIotJobsError_t _validateUpdateInfo( _jobsOperationType_t type, const AwsIotJobsUpdateInfo_t * pUpdateInfo ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_SUCCESS ); /* Only START NEXT and UPDATE operations need an update info. */ AwsIotJobs_Assert( ( type == JOBS_START_NEXT ) || ( type == JOBS_UPDATE ) ); /* Check that Job status to report is valid for Jobs UPDATE. */ if( type == JOBS_UPDATE ) { switch( pUpdateInfo->newStatus ) { case AWS_IOT_JOB_STATE_IN_PROGRESS: case AWS_IOT_JOB_STATE_FAILED: case AWS_IOT_JOB_STATE_SUCCEEDED: case AWS_IOT_JOB_STATE_REJECTED: break; default: IotLogError( "Job state %s is not valid for Jobs UPDATE.", AwsIotJobs_StateName( pUpdateInfo->newStatus ) ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } /* Check that step timeout is valid. */ if( ( pUpdateInfo->stepTimeoutInMinutes != AWS_IOT_JOBS_NO_TIMEOUT ) && ( pUpdateInfo->stepTimeoutInMinutes != AWS_IOT_JOBS_CANCEL_TIMEOUT ) ) { if( pUpdateInfo->stepTimeoutInMinutes < 1 ) { IotLogError( "Step timeout for Jobs %s must be at least 1.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } else if( pUpdateInfo->stepTimeoutInMinutes > JOBS_MAX_TIMEOUT ) { IotLogError( "Step timeout for Jobs %s cannot exceed %d.", _pAwsIotJobsOperationNames[ type ], JOBS_MAX_TIMEOUT ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } /* Check status details. */ if( pUpdateInfo->pStatusDetails != AWS_IOT_JOBS_NO_STATUS_DETAILS ) { if( pUpdateInfo->statusDetailsLength == 0 ) { IotLogError( "Status details length not set for Jobs %s.", _pAwsIotJobsOperationNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( pUpdateInfo->statusDetailsLength > JOBS_MAX_STATUS_DETAILS_LENGTH ) { IotLogError( "Status details length for Jobs %s cannot exceed %d.", _pAwsIotJobsOperationNames[ type ], JOBS_MAX_STATUS_DETAILS_LENGTH ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ static int32_t _getCallbackIndex( _jobsCallbackType_t type, _jobsSubscription_t * pSubscription, const AwsIotJobsCallbackInfo_t * pCallbackInfo ) { int32_t callbackIndex = 0; /* Find the matching oldFunction. */ if( pCallbackInfo->oldFunction != NULL ) { for( callbackIndex = 0; callbackIndex < AWS_IOT_JOBS_NOTIFY_CALLBACKS; callbackIndex++ ) { if( pSubscription->callbacks[ type ][ callbackIndex ].function == pCallbackInfo->oldFunction ) { /* oldFunction found. */ break; } } if( callbackIndex == AWS_IOT_JOBS_NOTIFY_CALLBACKS ) { /* oldFunction not found. */ callbackIndex = OLD_CALLBACK_NOT_FOUND; } } /* Find space for a new callback. */ else { for( callbackIndex = 0; callbackIndex < AWS_IOT_JOBS_NOTIFY_CALLBACKS; callbackIndex++ ) { if( pSubscription->callbacks[ type ][ callbackIndex ].function == NULL ) { break; } } if( callbackIndex == AWS_IOT_JOBS_NOTIFY_CALLBACKS ) { /* No memory for new callback. */ callbackIndex = NO_SPACE_FOR_CALLBACK; } } return callbackIndex; } /*-----------------------------------------------------------*/ static AwsIotJobsError_t _setCallbackCommon( IotMqttConnection_t mqttConnection, _jobsCallbackType_t type, const char * pThingName, size_t thingNameLength, const AwsIotJobsCallbackInfo_t * pCallbackInfo ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_SUCCESS ); bool subscriptionMutexLocked = false; _jobsSubscription_t * pSubscription = NULL; int32_t callbackIndex = 0; /* Check that AwsIotJobs_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NOT_INITIALIZED ); } /* Validate Thing Name. */ if( AwsIot_ValidateThingName( pThingName, thingNameLength ) == false ) { IotLogError( "Thing Name for Jobs %s callback is not valid.", _pAwsIotJobsCallbackNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* Check that a callback parameter is provided. */ if( pCallbackInfo == NULL ) { IotLogError( "Callback parameter must be provided for Jobs %s callback.", _pAwsIotJobsCallbackNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* The oldFunction member must be set when removing or replacing a callback. */ if( pCallbackInfo->function == NULL ) { if( pCallbackInfo->oldFunction == NULL ) { IotLogError( "Both oldFunction and function pointers cannot be NULL for Jobs %s callback.", _pAwsIotJobsCallbackNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } IotLogInfo( "(%.*s) Modifying Jobs %s callback.", thingNameLength, pThingName, _pAwsIotJobsCallbackNames[ type ] ); /* Lock the subscription list mutex to check for an existing subscription * object. */ IotMutex_Lock( &_AwsIotJobsSubscriptionsMutex ); subscriptionMutexLocked = true; /* Check for an existing subscription. This function will attempt to allocate * a new subscription if not found. */ pSubscription = _AwsIotJobs_FindSubscription( pThingName, thingNameLength, true ); if( pSubscription == NULL ) { /* No existing subscription was found, and no new subscription could be * allocated. */ IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NO_MEMORY ); } /* Get the index of the callback element to modify. */ callbackIndex = _getCallbackIndex( type, pSubscription, pCallbackInfo ); switch( callbackIndex ) { case NO_SPACE_FOR_CALLBACK: IotLogError( "No memory for a new Jobs %s callback.", _pAwsIotJobsCallbackNames[ type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NO_MEMORY ); case OLD_CALLBACK_NOT_FOUND: IotLogWarn( "Requested replacement function for Jobs %s callback not found.", _pAwsIotJobsCallbackNames[ type ] ); /* A subscription may have been allocated, but the callback operation can't * proceed. Check if the subscription should be removed. */ _AwsIotJobs_RemoveSubscription( pSubscription, NULL ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); default: break; } /* Check for an existing callback. */ if( pSubscription->callbacks[ type ][ callbackIndex ].function != NULL ) { /* Replace existing callback. */ if( pCallbackInfo->function != NULL ) { IotLogInfo( "(%.*s) Found existing %s callback. Replacing callback.", thingNameLength, pThingName, _pAwsIotJobsCallbackNames[ type ] ); pSubscription->callbacks[ type ][ callbackIndex ] = *pCallbackInfo; } /* Remove existing callback. */ else { IotLogInfo( "(%.*s) Removing existing %s callback.", thingNameLength, pThingName, _pAwsIotJobsCallbackNames[ type ] ); /* Clear the callback information and unsubscribe. */ ( void ) memset( &( pSubscription->callbacks[ type ][ callbackIndex ] ), 0x00, sizeof( AwsIotJobsCallbackInfo_t ) ); ( void ) _modifyCallbackSubscriptions( mqttConnection, type, pSubscription, IotMqtt_UnsubscribeSync ); /* Check if this subscription object can be removed. */ _AwsIotJobs_RemoveSubscription( pSubscription, NULL ); } } /* No existing callback. */ else { /* Add new callback. */ IotLogInfo( "(%.*s) Adding new %s callback.", thingNameLength, pThingName, _pAwsIotJobsCallbackNames[ type ] ); status = _modifyCallbackSubscriptions( mqttConnection, type, pSubscription, IotMqtt_SubscribeSync ); if( status == AWS_IOT_JOBS_SUCCESS ) { pSubscription->callbacks[ type ][ callbackIndex ] = *pCallbackInfo; } else { /* On failure, check if this subscription can be removed. */ _AwsIotJobs_RemoveSubscription( pSubscription, NULL ); } } IOT_FUNCTION_CLEANUP_BEGIN(); if( subscriptionMutexLocked == true ) { IotMutex_Unlock( &_AwsIotJobsSubscriptionsMutex ); } IotLogInfo( "(%.*s) Jobs %s callback operation complete with result %s.", thingNameLength, pThingName, _pAwsIotJobsCallbackNames[ type ], AwsIotJobs_strerror( status ) ); IOT_FUNCTION_CLEANUP_END(); } /*-----------------------------------------------------------*/ static AwsIotJobsError_t _modifyCallbackSubscriptions( IotMqttConnection_t mqttConnection, _jobsCallbackType_t type, _jobsSubscription_t * pSubscription, AwsIotMqttFunction_t mqttOperation ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_SUCCESS ); int32_t i = 0; IotMqttError_t mqttStatus = IOT_MQTT_STATUS_PENDING; IotMqttSubscription_t subscription = IOT_MQTT_SUBSCRIPTION_INITIALIZER; AwsIotTopicInfo_t topicInfo = { 0 }; char * pTopicFilter = NULL; uint16_t topicFilterLength = 0; /* Lookup table for Jobs callback suffixes. */ const char * const pCallbackSuffix[ JOBS_CALLBACK_COUNT ] = { JOBS_NOTIFY_PENDING_CALLBACK_STRING, /* Notify pending callback. */ JOBS_NOTIFY_NEXT_CALLBACK_STRING /* Notify next callback. */ }; /* Lookup table for Jobs callback suffix lengths. */ const uint16_t pCallbackSuffixLength[ JOBS_CALLBACK_COUNT ] = { JOBS_NOTIFY_PENDING_CALLBACK_STRING_LENGTH, /* Notify pending callback. */ JOBS_NOTIFY_NEXT_CALLBACK_STRING_LENGTH /* Notify next callback. */ }; /* Lookup table for Jobs callback function wrappers. */ const AwsIotMqttCallbackFunction_t pCallbackWrapper[ JOBS_CALLBACK_COUNT ] = { _notifyPendingCallbackWrapper, /* Notify pending callback. */ _notifyNextCallbackWrapper, /* Notify next callback. */ }; /* MQTT operation may only be subscribe or unsubscribe. */ AwsIotJobs_Assert( ( mqttOperation == IotMqtt_SubscribeSync ) || ( mqttOperation == IotMqtt_UnsubscribeSync ) ); /* Check if any subscriptions are currently registered for this type. */ for( i = 0; i < AWS_IOT_JOBS_NOTIFY_CALLBACKS; i++ ) { if( pSubscription->callbacks[ type ][ i ].function != NULL ) { /* No action is needed when another callback exists. */ IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_SUCCESS ); } } /* Use the subscription's topic buffer if available. */ if( pSubscription->pTopicBuffer != NULL ) { pTopicFilter = pSubscription->pTopicBuffer; } /* Generate the topic for the MQTT subscription. */ topicInfo.pThingName = pSubscription->pThingName; topicInfo.thingNameLength = pSubscription->thingNameLength; topicInfo.longestSuffixLength = JOBS_LONGEST_SUFFIX_LENGTH; topicInfo.mallocString = AwsIotJobs_MallocString; topicInfo.pOperationName = pCallbackSuffix[ type ]; topicInfo.operationNameLength = pCallbackSuffixLength[ type ]; if( AwsIot_GenerateOperationTopic( &topicInfo, &pTopicFilter, &topicFilterLength ) == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NO_MEMORY ); } IotLogDebug( "%s subscription for %.*s", mqttOperation == IotMqtt_SubscribeSync ? "Adding" : "Removing", topicFilterLength, pTopicFilter ); /* Set the members of the MQTT subscription. */ subscription.qos = IOT_MQTT_QOS_1; subscription.pTopicFilter = pTopicFilter; subscription.topicFilterLength = topicFilterLength; subscription.callback.pCallbackContext = NULL; subscription.callback.function = pCallbackWrapper[ type ]; /* Call the MQTT operation function. */ mqttStatus = mqttOperation( mqttConnection, &subscription, 1, 0, _AwsIotJobsMqttTimeoutMs ); /* Check the result of the MQTT operation. */ if( mqttStatus != IOT_MQTT_SUCCESS ) { IotLogError( "Failed to %s callback for %.*s %s callback, error %s.", mqttOperation == IotMqtt_SubscribeSync ? "subscribe to" : "unsubscribe from", pSubscription->thingNameLength, pSubscription->pThingName, _pAwsIotJobsCallbackNames[ type ], IotMqtt_strerror( mqttStatus ) ); /* Convert the MQTT "NO MEMORY" error to a Jobs "NO MEMORY" error. */ if( mqttStatus == IOT_MQTT_NO_MEMORY ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NO_MEMORY ); } else { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_MQTT_ERROR ); } } IotLogDebug( "Successfully %s %.*s Jobs %s callback.", mqttOperation == IotMqtt_SubscribeSync ? "subscribed to" : "unsubscribed from", pSubscription->thingNameLength, pSubscription->pThingName, _pAwsIotJobsCallbackNames[ type ] ); IOT_FUNCTION_CLEANUP_BEGIN(); /* MQTT subscribe should check the subscription topic buffer. */ if( mqttOperation == IotMqtt_SubscribeSync ) { /* If the current subscription has no topic buffer, assign it the current * topic buffer. */ if( pSubscription->pTopicBuffer == NULL ) { pSubscription->pTopicBuffer = pTopicFilter; } } IOT_FUNCTION_CLEANUP_END(); } /*-----------------------------------------------------------*/ static void _notifyPendingCallbackWrapper( void * pArgument, IotMqttCallbackParam_t * pMessage ) { /* Silence warnings about unused parameters. */ ( void ) pArgument; _callbackWrapperCommon( NOTIFY_PENDING_CALLBACK, pMessage ); } /*-----------------------------------------------------------*/ static void _notifyNextCallbackWrapper( void * pArgument, IotMqttCallbackParam_t * pMessage ) { /* Silence warnings about unused parameters. */ ( void ) pArgument; _callbackWrapperCommon( NOTIFY_NEXT_CALLBACK, pMessage ); } /*-----------------------------------------------------------*/ static void _callbackWrapperCommon( _jobsCallbackType_t type, IotMqttCallbackParam_t * pMessage ) { int32_t callbackIndex = 0; AwsIotJobsCallbackInfo_t callbackInfo = AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER; AwsIotJobsCallbackParam_t callbackParam = { .callbackType = ( AwsIotJobsCallbackType_t ) 0 }; _jobsSubscription_t * pSubscription = NULL; const char * pThingName = NULL; size_t thingNameLength = 0; /* Parse the Thing Name from the topic. */ if( AwsIot_ParseThingName( pMessage->u.message.info.pTopicName, pMessage->u.message.info.topicNameLength, &pThingName, &thingNameLength ) == false ) { IOT_GOTO_CLEANUP(); } /* Search for a matching subscription. */ IotMutex_Lock( &_AwsIotJobsSubscriptionsMutex ); pSubscription = _AwsIotJobs_FindSubscription( pThingName, thingNameLength, false ); if( pSubscription != NULL ) { /* Increment callback reference count to prevent the subscription object from being * freed while callbacks are running. */ pSubscription->callbackReferences++; } IotMutex_Unlock( &_AwsIotJobsSubscriptionsMutex ); if( pSubscription != NULL ) { /* Invoke all callbacks for this Thing. */ for( callbackIndex = 0; callbackIndex < AWS_IOT_JOBS_NOTIFY_CALLBACKS; callbackIndex++ ) { /* Copy the callback function and parameter, as it may be modified at any time. */ IotMutex_Lock( &_AwsIotJobsSubscriptionsMutex ); callbackInfo = pSubscription->callbacks[ type ][ callbackIndex ]; IotMutex_Unlock( &_AwsIotJobsSubscriptionsMutex ); if( callbackInfo.function != NULL ) { /* Set the callback type. Jobs callbacks are enumerated after the operations. */ callbackParam.callbackType = ( AwsIotJobsCallbackType_t ) ( type + JOBS_OPERATION_COUNT ); /* Set the remaining members of the callback param. */ callbackParam.mqttConnection = pMessage->mqttConnection; callbackParam.pThingName = pThingName; callbackParam.thingNameLength = thingNameLength; callbackParam.u.callback.pDocument = pMessage->u.message.info.pPayload; callbackParam.u.callback.documentLength = pMessage->u.message.info.payloadLength; /* Invoke the callback function. */ callbackInfo.function( callbackInfo.pCallbackContext, &callbackParam ); } } /* Callbacks are finished. Decrement reference count and check if subscription * object should be destroyed. */ IotMutex_Lock( &_AwsIotJobsSubscriptionsMutex ); pSubscription->callbackReferences--; AwsIotJobs_Assert( pSubscription->callbackReferences >= 0 ); _AwsIotJobs_RemoveSubscription( pSubscription, NULL ); IotMutex_Unlock( &_AwsIotJobsSubscriptionsMutex ); } /* This function uses cleanup sections to exit on error. */ IOT_FUNCTION_CLEANUP_BEGIN(); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_Init( uint32_t mqttTimeoutMs ) { AwsIotJobsError_t status = AWS_IOT_JOBS_SUCCESS; bool listInitStatus = false; if( _initCalled == 0 ) { listInitStatus = AwsIot_InitLists( &_AwsIotJobsPendingOperations, &_AwsIotJobsSubscriptions, &_AwsIotJobsPendingOperationsMutex, &_AwsIotJobsSubscriptionsMutex ); if( listInitStatus == false ) { IotLogInfo( "Failed to create Jobs lists." ); status = AWS_IOT_JOBS_INIT_FAILED; } else { /* Save the MQTT timeout option. */ if( mqttTimeoutMs != 0 ) { _AwsIotJobsMqttTimeoutMs = mqttTimeoutMs; } /* Set the flag that specifies initialization is complete. */ _initCalled = 1; IotLogInfo( "Jobs library successfully initialized." ); } } else { IotLogWarn( "AwsIotJobs_Init called with library already initialized." ); } return status; } /*-----------------------------------------------------------*/ void AwsIotJobs_Cleanup( void ) { if( _initCalled == 1 ) { _initCalled = 0; /* Remove and free all items in the Jobs pending operation list. */ IotMutex_Lock( &_AwsIotJobsPendingOperationsMutex ); IotListDouble_RemoveAll( &_AwsIotJobsPendingOperations, _AwsIotJobs_DestroyOperation, offsetof( _jobsOperation_t, link ) ); IotMutex_Unlock( &_AwsIotJobsPendingOperationsMutex ); /* Remove and free all items in the Jobs subscription list. */ IotMutex_Lock( &_AwsIotJobsSubscriptionsMutex ); IotListDouble_RemoveAll( &_AwsIotJobsSubscriptions, _AwsIotJobs_DestroySubscription, offsetof( _jobsSubscription_t, link ) ); IotMutex_Unlock( &_AwsIotJobsSubscriptionsMutex ); /* Restore the default MQTT timeout. */ _AwsIotJobsMqttTimeoutMs = AWS_IOT_JOBS_DEFAULT_MQTT_TIMEOUT_MS; /* Destroy Jobs library mutexes. */ IotMutex_Destroy( &_AwsIotJobsPendingOperationsMutex ); IotMutex_Destroy( &_AwsIotJobsSubscriptionsMutex ); IotLogInfo( "Jobs library cleanup done." ); } else { IotLogWarn( "AwsIotJobs_Init was not called before AwsIotShadow_Cleanup." ); } } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_GetPendingAsync( const AwsIotJobsRequestInfo_t * pRequestInfo, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, AwsIotJobsOperation_t * const pGetPendingOperation ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_STATUS_PENDING ); _jobsOperation_t * pOperation = NULL; /* Check that AwsIotJobs_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NOT_INITIALIZED ); } /* Check request info. */ status = _validateRequestInfo( JOBS_GET_PENDING, pRequestInfo, flags, pCallbackInfo, pGetPendingOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } /* Allocate a new Jobs operation. */ status = _AwsIotJobs_CreateOperation( JOBS_GET_PENDING, pRequestInfo, NULL, flags, pCallbackInfo, &pOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { /* No memory for Jobs operation. */ IOT_GOTO_CLEANUP(); } /* Set the reference if provided. This must be done before the Jobs operation * is processed. */ if( pGetPendingOperation != NULL ) { *pGetPendingOperation = pOperation; } /* Process the Jobs operation. This subscribes to any required topics and * sends the MQTT message for the Jobs operation. */ status = _AwsIotJobs_ProcessOperation( pRequestInfo, pOperation ); /* If the Jobs operation failed, clear the now invalid reference. */ if( ( status != AWS_IOT_JOBS_STATUS_PENDING ) && ( pGetPendingOperation != NULL ) ) { *pGetPendingOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_GetPendingSync( const AwsIotJobsRequestInfo_t * pRequestInfo, uint32_t flags, uint32_t timeoutMs, AwsIotJobsResponse_t * const pJobsResponse ) { AwsIotJobsError_t status = AWS_IOT_JOBS_STATUS_PENDING; AwsIotJobsOperation_t getPendingOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; /* Set the waitable flag. */ flags |= AWS_IOT_JOBS_FLAG_WAITABLE; /* Call the asynchronous Jobs Get Pending function. */ status = AwsIotJobs_GetPendingAsync( pRequestInfo, flags, NULL, &getPendingOperation ); /* Wait for the Jobs Get Pending operation to complete. */ if( status == AWS_IOT_JOBS_STATUS_PENDING ) { status = AwsIotJobs_Wait( getPendingOperation, timeoutMs, pJobsResponse ); } return status; } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_StartNextAsync( const AwsIotJobsRequestInfo_t * pRequestInfo, const AwsIotJobsUpdateInfo_t * pUpdateInfo, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, AwsIotJobsOperation_t * const pStartNextOperation ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_STATUS_PENDING ); _jobsOperation_t * pOperation = NULL; _jsonRequestContents_t requestContents = { 0 }; /* Check that AwsIotJobs_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NOT_INITIALIZED ); } /* Check request info. */ status = _validateRequestInfo( JOBS_START_NEXT, pRequestInfo, flags, pCallbackInfo, pStartNextOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } /* Check update info. */ status = _validateUpdateInfo( JOBS_START_NEXT, pUpdateInfo ); if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } /* Allocate a new Jobs operation. */ requestContents.pUpdateInfo = pUpdateInfo; status = _AwsIotJobs_CreateOperation( JOBS_START_NEXT, pRequestInfo, &requestContents, flags, pCallbackInfo, &pOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { /* No memory for Jobs operation. */ IOT_GOTO_CLEANUP(); } /* Set the reference if provided. This must be done before the Jobs operation * is processed. */ if( pStartNextOperation != NULL ) { *pStartNextOperation = pOperation; } /* Process the Jobs operation. This subscribes to any required topics and * sends the MQTT message for the Jobs operation. */ status = _AwsIotJobs_ProcessOperation( pRequestInfo, pOperation ); /* If the Jobs operation failed, clear the now invalid reference. */ if( ( status != AWS_IOT_JOBS_STATUS_PENDING ) && ( pStartNextOperation != NULL ) ) { *pStartNextOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_StartNextSync( const AwsIotJobsRequestInfo_t * pRequestInfo, const AwsIotJobsUpdateInfo_t * pUpdateInfo, uint32_t flags, uint32_t timeoutMs, AwsIotJobsResponse_t * const pJobsResponse ) { AwsIotJobsError_t status = AWS_IOT_JOBS_STATUS_PENDING; AwsIotJobsOperation_t startNextOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; /* Set the waitable flag. */ flags |= AWS_IOT_JOBS_FLAG_WAITABLE; /* Call the asynchronous Jobs Start Next function. */ status = AwsIotJobs_StartNextAsync( pRequestInfo, pUpdateInfo, flags, NULL, &startNextOperation ); /* Wait for the Jobs Start Next operation to complete. */ if( status == AWS_IOT_JOBS_STATUS_PENDING ) { status = AwsIotJobs_Wait( startNextOperation, timeoutMs, pJobsResponse ); } return status; } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_DescribeAsync( const AwsIotJobsRequestInfo_t * pRequestInfo, int32_t executionNumber, bool includeJobDocument, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, AwsIotJobsOperation_t * const pDescribeOperation ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_STATUS_PENDING ); _jobsOperation_t * pOperation = NULL; _jsonRequestContents_t requestContents = { 0 }; /* Check that AwsIotJobs_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NOT_INITIALIZED ); } /* Check request info. */ status = _validateRequestInfo( JOBS_DESCRIBE, pRequestInfo, flags, pCallbackInfo, pDescribeOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } /* Allocate a new Jobs operation. */ requestContents.describe.executionNumber = executionNumber; requestContents.describe.includeJobDocument = includeJobDocument; status = _AwsIotJobs_CreateOperation( JOBS_DESCRIBE, pRequestInfo, &requestContents, flags, pCallbackInfo, &pOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { /* No memory for Jobs operation. */ IOT_GOTO_CLEANUP(); } /* Set the reference if provided. This must be done before the Jobs operation * is processed. */ if( pDescribeOperation != NULL ) { *pDescribeOperation = pOperation; } /* Process the Jobs operation. This subscribes to any required topics and * sends the MQTT message for the Jobs operation. */ status = _AwsIotJobs_ProcessOperation( pRequestInfo, pOperation ); /* If the Jobs operation failed, clear the now invalid reference. */ if( ( status != AWS_IOT_JOBS_STATUS_PENDING ) && ( pDescribeOperation != NULL ) ) { *pDescribeOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_DescribeSync( const AwsIotJobsRequestInfo_t * pRequestInfo, int32_t executionNumber, bool includeJobDocument, uint32_t flags, uint32_t timeoutMs, AwsIotJobsResponse_t * const pJobsResponse ) { AwsIotJobsError_t status = AWS_IOT_JOBS_STATUS_PENDING; AwsIotJobsOperation_t describeOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; /* Set the waitable flag. */ flags |= AWS_IOT_JOBS_FLAG_WAITABLE; /* Call the asynchronous Jobs Describe function. */ status = AwsIotJobs_DescribeAsync( pRequestInfo, executionNumber, includeJobDocument, flags, NULL, &describeOperation ); /* Wait for the Jobs Describe operation to complete. */ if( status == AWS_IOT_JOBS_STATUS_PENDING ) { status = AwsIotJobs_Wait( describeOperation, timeoutMs, pJobsResponse ); } return status; } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_UpdateAsync( const AwsIotJobsRequestInfo_t * pRequestInfo, const AwsIotJobsUpdateInfo_t * pUpdateInfo, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, AwsIotJobsOperation_t * const pUpdateOperation ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_STATUS_PENDING ); _jobsOperation_t * pOperation = NULL; _jsonRequestContents_t requestContents = { 0 }; /* Check that AwsIotJobs_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NOT_INITIALIZED ); } /* Check request info. */ status = _validateRequestInfo( JOBS_UPDATE, pRequestInfo, flags, pCallbackInfo, pUpdateOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } /* Check update info. */ status = _validateUpdateInfo( JOBS_UPDATE, pUpdateInfo ); if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } /* Allocate a new Jobs operation. */ requestContents.pUpdateInfo = pUpdateInfo; status = _AwsIotJobs_CreateOperation( JOBS_UPDATE, pRequestInfo, &requestContents, flags, pCallbackInfo, &pOperation ); if( status != AWS_IOT_JOBS_SUCCESS ) { /* No memory for Jobs operation. */ IOT_GOTO_CLEANUP(); } /* Set the reference if provided. This must be done before the Jobs operation * is processed. */ if( pUpdateOperation != NULL ) { *pUpdateOperation = pOperation; } /* Process the Jobs operation. This subscribes to any required topics and * sends the MQTT message for the Jobs operation. */ status = _AwsIotJobs_ProcessOperation( pRequestInfo, pOperation ); /* If the Jobs operation failed, clear the now invalid reference. */ if( ( status != AWS_IOT_JOBS_STATUS_PENDING ) && ( pUpdateOperation != NULL ) ) { *pUpdateOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_UpdateSync( const AwsIotJobsRequestInfo_t * pRequestInfo, const AwsIotJobsUpdateInfo_t * pUpdateInfo, uint32_t flags, uint32_t timeoutMs, AwsIotJobsResponse_t * const pJobsResponse ) { AwsIotJobsError_t status = AWS_IOT_JOBS_STATUS_PENDING; AwsIotJobsOperation_t updateOperation = AWS_IOT_JOBS_OPERATION_INITIALIZER; /* Set the waitable flag. */ flags |= AWS_IOT_JOBS_FLAG_WAITABLE; /* Call the asynchronous Jobs Update function. */ status = AwsIotJobs_UpdateAsync( pRequestInfo, pUpdateInfo, flags, NULL, &updateOperation ); /* Wait for the Jobs Update operation to complete. */ if( status == AWS_IOT_JOBS_STATUS_PENDING ) { status = AwsIotJobs_Wait( updateOperation, timeoutMs, pJobsResponse ); } return status; } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_Wait( AwsIotJobsOperation_t operation, uint32_t timeoutMs, AwsIotJobsResponse_t * const pJobsResponse ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_STATUS_PENDING ); /* Check that AwsIotJobs_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_NOT_INITIALIZED ); } /* Check that reference is set. */ if( operation == NULL ) { IotLogError( "Operation reference cannot be NULL." ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* Check that reference is waitable. */ if( ( operation->flags & AWS_IOT_JOBS_FLAG_WAITABLE ) == 0 ) { IotLogError( "Operation is not waitable." ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* Check that output parameter is set. */ if( pJobsResponse == NULL ) { IotLogError( "Output Jobs response parameter must be set for Jobs %s.", _pAwsIotJobsOperationNames[ operation->type ] ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } /* Wait for a response to the Jobs operation. */ if( IotSemaphore_TimedWait( &( operation->notify.waitSemaphore ), timeoutMs ) == true ) { status = operation->status; } else { status = AWS_IOT_JOBS_TIMEOUT; } /* Remove the completed operation from the pending operation list. */ IotMutex_Lock( &( _AwsIotJobsPendingOperationsMutex ) ); IotListDouble_Remove( &( operation->link ) ); IotMutex_Unlock( &( _AwsIotJobsPendingOperationsMutex ) ); /* Decrement the reference count. This also removes subscriptions if the * count reaches 0. */ IotMutex_Lock( &_AwsIotJobsSubscriptionsMutex ); _AwsIotJobs_DecrementReferences( operation, operation->pSubscription->pTopicBuffer, NULL ); IotMutex_Unlock( &_AwsIotJobsSubscriptionsMutex ); /* Set the output parameters. Jobs responses are available on success or * when the Jobs service returns an error document. */ if( ( status == AWS_IOT_JOBS_SUCCESS ) || ( status > AWS_IOT_JOBS_INVALID_TOPIC ) ) { AwsIotJobs_Assert( operation->pJobsResponse != NULL ); AwsIotJobs_Assert( operation->jobsResponseLength > 0 ); pJobsResponse->pJobsResponse = operation->pJobsResponse; pJobsResponse->jobsResponseLength = operation->jobsResponseLength; } /* Destroy the Jobs operation. */ _AwsIotJobs_DestroyOperation( operation ); IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_SetNotifyPendingCallback( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags, const AwsIotJobsCallbackInfo_t * pNotifyPendingCallback ) { /* Flags are not currently used by this function. */ ( void ) flags; return _setCallbackCommon( mqttConnection, NOTIFY_PENDING_CALLBACK, pThingName, thingNameLength, pNotifyPendingCallback ); } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_SetNotifyNextCallback( IotMqttConnection_t mqttConnection, const char * pThingName, size_t thingNameLength, uint32_t flags, const AwsIotJobsCallbackInfo_t * pNotifyNextCallback ) { /* Flags are not currently used by this function. */ ( void ) flags; return _setCallbackCommon( mqttConnection, NOTIFY_NEXT_CALLBACK, pThingName, thingNameLength, pNotifyNextCallback ); } /*-----------------------------------------------------------*/ const char * AwsIotJobs_strerror( AwsIotJobsError_t status ) { const char * pMessage = NULL; switch( status ) { case AWS_IOT_JOBS_SUCCESS: pMessage = "SUCCESS"; break; case AWS_IOT_JOBS_STATUS_PENDING: pMessage = "STATUS PENDING"; break; case AWS_IOT_JOBS_INIT_FAILED: pMessage = "INIT FAILED"; break; case AWS_IOT_JOBS_BAD_PARAMETER: pMessage = "BAD PARAMETER"; break; case AWS_IOT_JOBS_NO_MEMORY: pMessage = "NO MEMORY"; break; case AWS_IOT_JOBS_MQTT_ERROR: pMessage = "MQTT ERROR"; break; case AWS_IOT_JOBS_BAD_RESPONSE: pMessage = "BAD RESPONSE"; break; case AWS_IOT_JOBS_TIMEOUT: pMessage = "TIMEOUT"; break; case AWS_IOT_JOBS_NOT_INITIALIZED: pMessage = "NOT INITIALIZED"; break; case AWS_IOT_JOBS_INVALID_TOPIC: pMessage = "FAILED: INVALID TOPIC"; break; case AWS_IOT_JOBS_INVALID_JSON: pMessage = "FAILED: INVALID JSON"; break; case AWS_IOT_JOBS_INVALID_REQUEST: pMessage = "FAILED: INVALID REQUEST"; break; case AWS_IOT_JOBS_INVALID_STATE: pMessage = "FAILED: INVALID STATE TRANSITION"; break; case AWS_IOT_JOBS_NOT_FOUND: pMessage = "FAILED: NOT FOUND"; break; case AWS_IOT_JOBS_VERSION_MISMATCH: pMessage = "FAILED: VERSION MISMATCH"; break; case AWS_IOT_JOBS_INTERNAL_ERROR: pMessage = "FAILED: INTERNAL ERROR"; break; case AWS_IOT_JOBS_THROTTLED: pMessage = "FAILED: THROTTLED"; break; case AWS_IOT_JOBS_TERMINAL_STATE: pMessage = "FAILED: TERMINAL STATE"; break; default: pMessage = "INVALID STATUS"; break; } return pMessage; } /*-----------------------------------------------------------*/ const char * AwsIotJobs_StateName( AwsIotJobState_t state ) { const char * pMessage = NULL; switch( state ) { case AWS_IOT_JOB_STATE_QUEUED: pMessage = "QUEUED"; break; case AWS_IOT_JOB_STATE_IN_PROGRESS: pMessage = "IN PROGRESS"; break; case AWS_IOT_JOB_STATE_FAILED: pMessage = "FAILED"; break; case AWS_IOT_JOB_STATE_SUCCEEDED: pMessage = "SUCCEEDED"; break; case AWS_IOT_JOB_STATE_CANCELED: pMessage = "CANCELED"; break; case AWS_IOT_JOB_STATE_TIMED_OUT: pMessage = "TIMED OUT"; break; case AWS_IOT_JOB_STATE_REJECTED: pMessage = "REJECTED"; break; case AWS_IOT_JOB_STATE_REMOVED: pMessage = "REMOVED"; break; default: pMessage = "INVALID STATE"; break; } return pMessage; } /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_Plus_TCP_and_FAT_Windows_Simulator/DemoTasks/TCPEchoSelectServer.c
<filename>FreeRTOS-Labs/Demo/FreeRTOS_Plus_TCP_and_FAT_Windows_Simulator/DemoTasks/TCPEchoSelectServer.c /* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from <NAME>, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* Standard includes. */ #include <stdint.h> #include <stdio.h> #include <WinSock2.h> #include <Mswsock.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" #include "FreeRTOS_char_buf.h" #include "SimpleTCPEchoServer.h" /* For prvSimpleTcpServerClientTask */ #define tcpechoNUMBER_OF_CLIENTS 0 void tcpWinShowEvent( BaseType_t aDoLog ); /* * Listens for incoming echo connections. Creates a task to handle each * connection. */ static void prvConnectionListeningTask( void *pvParameters ); /* Stores the stack size passed into vStartSimpleTCPServerTasks() so it can be reused when the server listening task creates tasks to handle connections. */ static unsigned short usUsedStackSize = 0; /*-----------------------------------------------------------*/ void vStartSelectTCPServerTasks( uint16_t usStackSize, uint32_t ulPort, UBaseType_t uxPriority ) { WORD wVersionRequested; WSADATA xWSAData; BaseType_t xClient; //extern void prvSimpleTCPClientTask( void *pvParameters ); /* The clients use non-blocking Winsock sockets and must therefore run at the idle priority. */ configASSERT( uxPriority == tskIDLE_PRIORITY ); /* Create the TCP echo server. The echo server uses FreeRTOS+TCP through the spoofed IP and MAC address. */ xTaskCreate( prvConnectionListeningTask, "ServerListener", usStackSize, ( void * ) ulPort, uxPriority + 1, NULL ); /* Prepare to use WinSock library. */ wVersionRequested = MAKEWORD( 2, 2 ); configASSERT( WSAStartup( wVersionRequested, &xWSAData ) == ( WORD ) 0 ); /* Remember the requested stack size so it can be re-used by the server listening task when it creates tasks to handle connections. */ usUsedStackSize = usStackSize; } #define SEND_BUFFER_SIZE ( 8 * ipconfigTCP_MSS ) typedef struct xTCP_SERVER { Socket_t xSocket; struct xTCP_SERVER *pxNext; SSimpleBuf *pxSendData; BaseType_t bHasSendRequest; } TCPServer_t; static uint8_t cReceivedString[ ipconfigTCP_MSS ]; static void prvTcpInit( TCPServer_t *pxTcpServer ) { struct freertos_sockaddr addr; BaseType_t xReceiveTimeOut = 0; BaseType_t xSendTimeOut = 0; pxTcpServer->pxSendData = ( SSimpleBuf * )pvPortMalloc( sizeof( *pxTcpServer->pxSendData ) - sizeof( pxTcpServer->pxSendData->array ) + SEND_BUFFER_SIZE + 1 ); configASSERT( pxTcpServer->pxSendData != NULL ); memset( pxTcpServer->pxSendData, '\0', sizeof( *pxTcpServer->pxSendData ) ); pxTcpServer->pxSendData->LENGTH = SEND_BUFFER_SIZE + 1; FreeRTOS_GetRemoteAddress( pxTcpServer->xSocket, &addr ); FreeRTOS_debug_printf( ( "prvTcpInit: serving %xip:%u\n", FreeRTOS_ntohl( addr.sin_addr ), addr.sin_port) ); FreeRTOS_setsockopt( pxTcpServer->xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) ); FreeRTOS_setsockopt( pxTcpServer->xSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendTimeOut, sizeof( xReceiveTimeOut ) ); } static void prvTcpClose( TCPServer_t *pxThisServer ) { FreeRTOS_closesocket( pxThisServer->xSocket ); vPortFree( pxThisServer->pxSendData ); vPortFree( pxThisServer ); } static BaseType_t prvTcpSend( TCPServer_t *pxTcpServer ) { BaseType_t lBytes, lReturned, xReturn = 0; lBytes = sbGet( pxTcpServer->pxSendData, 0, cReceivedString, sizeof( cReceivedString ), pdTRUE ); if( lBytes ) { /* Send as much as possible, non-blocking */ lReturned = FreeRTOS_send( pxTcpServer->xSocket, cReceivedString, lBytes, 0 ); if( lReturned > 0 ) { xReturn = sbGet( pxTcpServer->pxSendData, 0, NULL, lReturned, pdFALSE ); } } return xReturn; } static BaseType_t prvTcpHasSendData( TCPServer_t *pxTcpServer ) { return ( sbGetSize( pxTcpServer->pxSendData ) > 0 ) ? 1 : 0; } static BaseType_t prvTcpWork( TCPServer_t *pxTcpServer ) { BaseType_t lBytes, lReturned, lMayWrite; lMayWrite = FreeRTOS_maywrite( pxTcpServer->xSocket ); if( lMayWrite < 0 ) return lMayWrite; while( lMayWrite > 0 ) { lReturned = prvTcpSend( pxTcpServer ); if( lReturned < 0 ) return lReturned; if( lReturned == 0 ) break; lMayWrite = FreeRTOS_maywrite( pxTcpServer->xSocket ); if( lMayWrite < 0 ) return lMayWrite; } for( ; ; ) { /* Zero out the receive array so there is NULL at the end of the string when it is printed out. */ memset( cReceivedString, 0x00, sizeof( cReceivedString ) ); /* Receive data on the socket. */ lBytes = FreeRTOS_recv( pxTcpServer->xSocket, cReceivedString, sizeof( cReceivedString ), 0 ); if( lBytes <= 0 ) return lBytes; /* Return the received characters. */ if( lMayWrite > 0 && sbGetSize( pxTcpServer->pxSendData ) == 0 ) { /* The cirular buffer is empty, send the received data directly */ lReturned = FreeRTOS_send( pxTcpServer->xSocket, cReceivedString, lBytes, 0 ); if( lReturned < 0 ) { return -1; } if( lBytes > lReturned ) { /* Not all dta could be delivered, save them for later * FD_SET( eSELECT_WRITE ) will be called */ sbAdd( pxTcpServer->pxSendData, 0, cReceivedString + lReturned, lBytes - lReturned ); } lMayWrite = FreeRTOS_maywrite( pxTcpServer->xSocket ); if( lMayWrite < 0 ) return lMayWrite; } else { sbAdd( pxTcpServer->pxSendData, 0, cReceivedString, lBytes ); } } } static TickType_t lastTickTime; static BaseType_t xTaskCount = 0, xConfirmedCount = 0; static void prvConnectionListeningTask( void *pvParameters ) { struct freertos_sockaddr xClient, xBindAddress; Socket_t xListeningSocket; socklen_t xSize = sizeof( xClient ); static const TickType_t xReceiveTimeOut = 0; //portMAX_DELAY; const BaseType_t xBacklog = 10; SocketSet_t xSocketSet; struct xTCP_SERVER *pxServerList = NULL; struct xTCP_SERVER *pxIterator; WinProperties_t winProps; /* Just to prevent compiler warnings. */ ( void ) pvParameters; /* Attempt to open the socket. */ xListeningSocket = FreeRTOS_socket( PF_INET, SOCK_STREAM, IPPROTO_TCP ); configASSERT( xListeningSocket != FREERTOS_INVALID_SOCKET ); /* Set a time out so accept() will just wait for a connection. */ FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut, sizeof( xReceiveTimeOut ) ); memset(&winProps, '\0', sizeof( winProps ) ); // Size in units of MSS winProps.lTxBufSize = 1 * 1460;//1000; winProps.lTxWinSize = 2; winProps.lRxBufSize = 2 * 1460; winProps.lRxWinSize = 2; FreeRTOS_setsockopt( xListeningSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &winProps, sizeof( winProps ) ); /* The strange casting is to remove compiler errors. */ xBindAddress.sin_port = ( uint16_t ) ( ( uint32_t ) pvParameters ) & 0xffffUL; xBindAddress.sin_port = FreeRTOS_htons( xBindAddress.sin_port ); /* Bind the socket to the port that the client task will send to, then listen for incoming connections. */ while( FreeRTOS_bind( xListeningSocket, &xBindAddress, sizeof( xBindAddress ) ) != 0 ); FreeRTOS_listen( xListeningSocket, xBacklog ); lastTickTime = xTaskGetTickCount (); pxServerList = NULL; xSocketSet = FreeRTOS_createsocketset( ); configASSERT( xSocketSet != NULL ); FreeRTOS_FD_SET( xListeningSocket, xSocketSet, eSELECT_READ ); for( ;; ) { TickType_t xMask = FreeRTOS_select( xSocketSet, 3000 ); if( FreeRTOS_FD_ISSET( xListeningSocket, xSocketSet ) ) { Socket_t xNewSocket; xNewSocket = FreeRTOS_accept( xListeningSocket, &xClient, &xSize ); if ( xNewSocket && xNewSocket != FREERTOS_INVALID_SOCKET ) { TCPServer_t *pxServer; FreeRTOS_debug_printf( ( "prvConnectionListeningTask: new connection %xip:%u\n", FreeRTOS_ntohl( xClient.sin_addr ), FreeRTOS_ntohs( xClient.sin_port ) ) ); pxServer = (TCPServer_t *)pvPortMalloc( sizeof( *pxServer ) ); memset( pxServer, '\0', sizeof( *pxServer )); pxServer->xSocket = xNewSocket; FreeRTOS_FD_SET( xNewSocket, xSocketSet, eSELECT_READ | eSELECT_EXCEPT ); if( pxServerList == NULL ) { /* This is the first server */ pxServerList = pxServer; } else { /* Attach it to the end of the list */ for( pxIterator = pxServerList; pxIterator->pxNext != NULL; pxIterator = pxIterator->pxNext ) { } pxIterator->pxNext = pxServer; } prvTcpInit( pxServer ); } } { TCPServer_t *pxThisServer = NULL; for( pxIterator = pxServerList; pxIterator != NULL; ) { BaseType_t rc; pxThisServer = pxIterator; /* Move to the next one before the current gets deleted */ pxIterator = pxIterator->pxNext; if( FreeRTOS_FD_ISSET( pxThisServer->xSocket, xSocketSet ) == 0 ) { continue; } rc = prvTcpWork( pxThisServer ); if( rc < 0) { FreeRTOS_FD_CLR( pxThisServer->xSocket, xSocketSet, eSELECT_ALL ); if( pxServerList = pxThisServer ) { pxServerList = pxThisServer->pxNext; } else { struct xTCP_SERVER *pxOther; for( pxOther = pxServerList; pxOther->pxNext != NULL; pxOther = pxOther->pxNext ) { if( pxOther->pxNext == pxThisServer ) { pxOther->pxNext == pxThisServer->pxNext; break; } } } /* Close the socket and free the space */ prvTcpClose( pxThisServer ); } else { pxThisServer->bHasSendRequest = prvTcpHasSendData( pxThisServer ); if( pxThisServer->bHasSendRequest ) FreeRTOS_FD_SET( pxThisServer->xSocket, xSocketSet, eSELECT_WRITE ); else FreeRTOS_FD_CLR( pxThisServer->xSocket, xSocketSet, eSELECT_WRITE ); //FreeRTOS_debug_printf( ( "SET_FD WRITE %d\n", pxServerFound->bHasSendRequest != 0 ) ); } } } if( ( xTaskGetTickCount () - lastTickTime ) > 30000 ) { lastTickTime = xTaskGetTickCount (); //plusPrintf( "ListeningTask %ld,%ld tasks\n", xTaskCount, xConfirmedCount ); } } } /*-----------------------------------------------------------*/ static BaseType_t prvCreateTxData( uint8_t *ucBuffer, uint32_t ulBufferLength ) { BaseType_t lCharactersToAdd, lCharacter; uint8_t ucChar = '0'; /* Randomise the number of characters that will be sent. */ do { lCharactersToAdd = ipconfigRAND32() % ( ulBufferLength - 20UL ); } while ( lCharactersToAdd == 0 ); /* Fill the buffer. */ for( lCharacter = 0; lCharacter < lCharactersToAdd; lCharacter++ ) { ucBuffer[ lCharacter ] = ucChar; ucChar++; if( ucChar > '~' ) { ucChar = '0'; } } return lCharactersToAdd; } /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/mbedtls/include/mbedtls/hmac_drbg.h
<reponame>MicroEJ/FreeRTOS /** * \file hmac_drbg.h * * \brief HMAC_DRBG (NIST SP 800-90A) */ /* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_HMAC_DRBG_H #define MBEDTLS_HMAC_DRBG_H #if !defined(MBEDTLS_CONFIG_FILE) #include "config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "md.h" #if defined(MBEDTLS_THREADING_C) #include "threading.h" #endif /* * Error codes */ #define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG -0x0003 /**< Too many random requested in single call. */ #define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG -0x0005 /**< Input too large (Entropy + additional). */ #define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR -0x0007 /**< Read/write error in file. */ #define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED -0x0009 /**< The entropy source failed. */ /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in config.h or define them on the compiler command line. * \{ */ #if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL) #define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT) #define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST) #define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) #define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ #endif /* \} name SECTION: Module settings */ #define MBEDTLS_HMAC_DRBG_PR_OFF 0 /**< No prediction resistance */ #define MBEDTLS_HMAC_DRBG_PR_ON 1 /**< Prediction resistance enabled */ #ifdef __cplusplus extern "C" { #endif /** * HMAC_DRBG context. */ typedef struct mbedtls_hmac_drbg_context { /* Working state: the key K is not stored explicitly, * but is implied by the HMAC context */ mbedtls_md_context_t md_ctx; /*!< HMAC context (inc. K) */ unsigned char V[MBEDTLS_MD_MAX_SIZE]; /*!< V in the spec */ int reseed_counter; /*!< reseed counter */ /* Administrative state */ size_t entropy_len; /*!< entropy bytes grabbed on each (re)seed */ int prediction_resistance; /*!< enable prediction resistance (Automatic reseed before every random generation) */ int reseed_interval; /*!< reseed interval */ /* Callbacks */ int (*f_entropy)(void *, unsigned char *, size_t); /*!< entropy function */ void *p_entropy; /*!< context for the entropy function */ #if defined(MBEDTLS_THREADING_C) mbedtls_threading_mutex_t mutex; #endif } mbedtls_hmac_drbg_context; /** * \brief HMAC_DRBG context initialization * Makes the context ready for mbedtls_hmac_drbg_seed(), * mbedtls_hmac_drbg_seed_buf() or * mbedtls_hmac_drbg_free(). * * \param ctx HMAC_DRBG context to be initialized */ void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx ); /** * \brief HMAC_DRBG initial seeding * Seed and setup entropy source for future reseeds. * * \param ctx HMAC_DRBG context to be seeded * \param md_info MD algorithm to use for HMAC_DRBG * \param f_entropy Entropy callback (p_entropy, buffer to fill, buffer * length) * \param p_entropy Entropy context * \param custom Personalization data (Device specific identifiers) * (Can be NULL) * \param len Length of personalization data * * \note The "security strength" as defined by NIST is set to: * 128 bits if md_alg is SHA-1, * 192 bits if md_alg is SHA-224, * 256 bits if md_alg is SHA-256 or higher. * Note that SHA-256 is just as efficient as SHA-224. * * \return 0 if successful, or * MBEDTLS_ERR_MD_BAD_INPUT_DATA, or * MBEDTLS_ERR_MD_ALLOC_FAILED, or * MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED. */ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx, const mbedtls_md_info_t * md_info, int (*f_entropy)(void *, unsigned char *, size_t), void *p_entropy, const unsigned char *custom, size_t len ); /** * \brief Initilisation of simpified HMAC_DRBG (never reseeds). * (For use with deterministic ECDSA.) * * \param ctx HMAC_DRBG context to be initialised * \param md_info MD algorithm to use for HMAC_DRBG * \param data Concatenation of entropy string and additional data * \param data_len Length of data in bytes * * \return 0 if successful, or * MBEDTLS_ERR_MD_BAD_INPUT_DATA, or * MBEDTLS_ERR_MD_ALLOC_FAILED. */ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx, const mbedtls_md_info_t * md_info, const unsigned char *data, size_t data_len ); /** * \brief Enable / disable prediction resistance (Default: Off) * * Note: If enabled, entropy is used for ctx->entropy_len before each call! * Only use this if you have ample supply of good entropy! * * \param ctx HMAC_DRBG context * \param resistance MBEDTLS_HMAC_DRBG_PR_ON or MBEDTLS_HMAC_DRBG_PR_OFF */ void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx, int resistance ); /** * \brief Set the amount of entropy grabbed on each reseed * (Default: given by the security strength, which * depends on the hash used, see \c mbedtls_hmac_drbg_init() ) * * \param ctx HMAC_DRBG context * \param len Amount of entropy to grab, in bytes */ void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t len ); /** * \brief Set the reseed interval * (Default: MBEDTLS_HMAC_DRBG_RESEED_INTERVAL) * * \param ctx HMAC_DRBG context * \param interval Reseed interval */ void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, int interval ); /** * \brief HMAC_DRBG update state * * \param ctx HMAC_DRBG context * \param additional Additional data to update state with, or NULL * \param add_len Length of additional data, or 0 * * \return \c 0 on success, or an error from the underlying * hash calculation. * * \note Additional data is optional, pass NULL and 0 as second * third argument if no additional data is being used. */ int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t add_len ); /** * \brief HMAC_DRBG reseeding (extracts data from entropy source) * * \param ctx HMAC_DRBG context * \param additional Additional data to add to state (Can be NULL) * \param len Length of additional data * * \return 0 if successful, or * MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED */ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t len ); /** * \brief HMAC_DRBG generate random with additional update input * * Note: Automatically reseeds if reseed_counter is reached or PR is enabled. * * \param p_rng HMAC_DRBG context * \param output Buffer to fill * \param output_len Length of the buffer * \param additional Additional data to update with (can be NULL) * \param add_len Length of additional data (can be 0) * * \return 0 if successful, or * MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED, or * MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG, or * MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG. */ int mbedtls_hmac_drbg_random_with_add( void *p_rng, unsigned char *output, size_t output_len, const unsigned char *additional, size_t add_len ); /** * \brief HMAC_DRBG generate random * * Note: Automatically reseeds if reseed_counter is reached or PR is enabled. * * \param p_rng HMAC_DRBG context * \param output Buffer to fill * \param out_len Length of the buffer * * \return 0 if successful, or * MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED, or * MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG */ int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len ); /** * \brief Free an HMAC_DRBG context * * \param ctx HMAC_DRBG context to free. */ void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx ); #if ! defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief HMAC_DRBG update state * * \deprecated Superseded by mbedtls_hmac_drbg_update_ret() * in 2.16.0. * * \param ctx HMAC_DRBG context * \param additional Additional data to update state with, or NULL * \param add_len Length of additional data, or 0 * * \note Additional data is optional, pass NULL and 0 as second * third argument if no additional data is being used. */ MBEDTLS_DEPRECATED void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t add_len ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_FS_IO) /** * \brief Write a seed file * * \param ctx HMAC_DRBG context * \param path Name of the file * * \return 0 if successful, 1 on file error, or * MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED */ int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ); /** * \brief Read and update a seed file. Seed is added to this * instance * * \param ctx HMAC_DRBG context * \param path Name of the file * * \return 0 if successful, 1 on file error, * MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED or * MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG */ int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ); #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_hmac_drbg_self_test( int verbose ); #endif #ifdef __cplusplus } #endif #endif /* hmac_drbg.h */
MicroEJ/FreeRTOS
FreeRTOS/Demo/CORTEX_MPU_M33F_NXP_LPC55S69_MCUXpresso/NXP_Code/startup/boot_multicore_slave.c
<filename>FreeRTOS/Demo/CORTEX_MPU_M33F_NXP_LPC55S69_MCUXpresso/NXP_Code/startup/boot_multicore_slave.c //***************************************************************************** // boot_multicore_slave.c // // Provides functions to boot slave core in LPC55xx multicore system // // Version : 190215 // //***************************************************************************** // // Copyright(C) NXP Semiconductors, 2019 // All rights reserved. // // Software that is described herein is for illustrative purposes only // which provides customers with programming information regarding the // LPC products. This software is supplied "AS IS" without any warranties of // any kind, and NXP Semiconductors and its licensor disclaim any and // all warranties, express or implied, including all implied warranties of // merchantability, fitness for a particular purpose and non-infringement of // intellectual property rights. NXP Semiconductors assumes no responsibility // or liability for the use of the software, conveys no license or rights under any // patent, copyright, mask work right, or any other intellectual property rights in // or to any products. NXP Semiconductors reserves the right to make changes // in the software without notification. NXP Semiconductors also makes no // representation or warranty that such application will be suitable for the // specified use without further testing or modification. // // Permission to use, copy, modify, and distribute this software and its // documentation is hereby granted, under NXP Semiconductors' and its // licensor's relevant copyrights in the software, without fee, provided that it // is used in conjunction with NXP Semiconductors microcontrollers. This // copyright, permission, and disclaimer notice must appear in all copies of // this code. //***************************************************************************** #if defined (__MULTICORE_MASTER) #include <stdint.h> // ================================================================== // Define registers related to multicore CPU Control and setup // ================================================================== #define SYSCON_BASE ((uint32_t) 0x50000000) #define CPUCTRL (((volatile uint32_t *) (SYSCON_BASE + 0x800))) #define CPBOOT (((volatile uint32_t *) (SYSCON_BASE + 0x804))) #define CPSTACK (((volatile uint32_t *) (SYSCON_BASE + 0x808))) #define CPSTAT (((volatile uint32_t *) (SYSCON_BASE + 0x80C))) #define CPUCTRL_KEY ((uint32_t)(0x0000C0C4 << 16)) #define CORE1_CLK_ENA (1<<3) #define CORE1_RESET_ENA (1<<5) // ================================================================== // Function to boot the slave (core 1) // ================================================================== void slave_core1_boot(uint32_t *coentry, uint32_t *costackptr) { volatile uint32_t *u32REG, u32Val; // Load the slave's stack pointer value *CPSTACK = (uint32_t) costackptr; // Load address of the slave code in memory (for slave's VTOR) *CPBOOT = (uint32_t) coentry; // Read CPU control register and update to start slave execution u32REG = (uint32_t *) CPUCTRL; u32Val = *u32REG; // Enable slave clock and reset u32Val |= (CPUCTRL_KEY | ((CORE1_CLK_ENA | CORE1_RESET_ENA) & 0x7F)); *u32REG = u32Val; // Clear slave reset u32Val &= ~CORE1_RESET_ENA; *u32REG = u32Val; // Slave is now executing } // ================================================================== // Address of slave code in memory - provided by linker script extern uint8_t __core_m33slave_START__; // ================================================================== // ================================================================== // Top level function to boot the slave core // ================================================================== void boot_multicore_slave(void) { // Get the address of the slave code in memory uint32_t *slavevectortable_ptr = (uint32_t *)&__core_m33slave_START__; // Get initial address for slave's stack pointer volatile unsigned int spaddr; spaddr = *slavevectortable_ptr; // Boot the slave - passing address of code and stack pointer slave_core1_boot(slavevectortable_ptr, (uint32_t *)spaddr); } #endif //defined (__MULTICORE_MASTER)
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_Plus_POSIX_with_actor_Windows_Simulator/FreeRTOSConfig.h
<filename>FreeRTOS-Labs/Demo/FreeRTOS_Plus_POSIX_with_actor_Windows_Simulator/FreeRTOSConfig.h /* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifndef FREERTOS_CONFIG_H #define FREERTOS_CONFIG_H #include <stdint.h> /*----------------------------------------------------------- * Application specific definitions. * * These definitions should be adjusted for your particular hardware and * application requirements. * * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. * http://www.freertos.org/a00110.html *----------------------------------------------------------*/ #define configUSE_PREEMPTION 1 #define configTICK_RATE_HZ ( 1000 ) /* In this non-real time simulated environment the tick frequency has to be at least a multiple of the Win32 tick frequency, and therefore very slow. */ #define configMINIMAL_STACK_SIZE ( ( unsigned short ) 60 ) /* In this simulated case, the stack only has to hold one small structure as the real stack is part of the Win32 thread. */ #define configMAX_TASK_NAME_LEN ( 7 ) #define configUSE_TRACE_FACILITY 0 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 1 #define configUSE_CO_ROUTINES 0 #define configUSE_MUTEXES 1 #define configCHECK_FOR_STACK_OVERFLOW 0 /* Not applicable to the Win32 port. */ #define configUSE_RECURSIVE_MUTEXES 1 #define configQUEUE_REGISTRY_SIZE 0 #define configUSE_APPLICATION_TASK_TAG 1 #define configUSE_COUNTING_SEMAPHORES 1 #define configUSE_ALTERNATIVE_API 0 #define configUSE_TIMERS 1 #define configTIMER_TASK_PRIORITY 2 #define configTIMER_QUEUE_LENGTH 20 #define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE * 2 ) #define configMAX_PRIORITIES ( 7 ) #define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) /* Hook functions */ #define configUSE_IDLE_HOOK 0 #define configUSE_TICK_HOOK 0 #define configUSE_MALLOC_FAILED_HOOK 1 /* Co-routine definitions. */ #define configUSE_CO_ROUTINES 0 /* Set the following definitions to 1 to include the API function, or zero to exclude the API function. */ #define INCLUDE_vTaskPrioritySet 1 #define INCLUDE_uxTaskPriorityGet 1 #define INCLUDE_vTaskDelete 1 #define INCLUDE_vTaskCleanUpResources 0 #define INCLUDE_vTaskSuspend 1 #define INCLUDE_vTaskDelayUntil 1 #define INCLUDE_vTaskDelay 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 #define INCLUDE_xTaskGetSchedulerState 1 #define INCLUDE_xTimerGetTimerTaskHandle 0 #define INCLUDE_xTaskGetIdleTaskHandle 0 #define INCLUDE_xQueueGetMutexHolder 1 #define INCLUDE_eTaskGetState 1 #define INCLUDE_xEventGroupSetBitsFromISR 1 #define INCLUDE_xTimerPendFunctionCall 1 #define INCLUDE_xTaskGetCurrentTaskHandle 1 #define INCLUDE_xTaskAbortDelay 1 /* heap_4.c, */ #define configTOTAL_HEAP_SIZE ( ( size_t ) ( 2048U * 1024U ) ) /* Allow RTOS objects to be created using RAM provided by the application writer. */ #define configSUPPORT_STATIC_ALLOCATION 1 /* Create RTOS objects using dynamically allocated RAM */ #define configSUPPORT_DYNAMIC_ALLOCATION 1 /* This demo makes use of one or more example stats formatting functions. These format the raw data provided by the uxTaskGetSystemState() function in to human readable ASCII form. See the notes in the implementation of vTaskList() within FreeRTOS/Source/tasks.c for limitations. */ #define configUSE_STATS_FORMATTING_FUNCTIONS 1 /* Run time stats gathering definitions. */ #define configGENERATE_RUN_TIME_STATS 0 /* Assert call defined for debug builds. */ extern void vAssertCalled(const char * pcFile, uint32_t ulLine); #define configASSERT( x ) if( ( x ) == 0 ) vAssertCalled( __FILE__, __LINE__ ) #endif /* FREERTOS_CONFIG_H */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_Plus_TCP_and_FAT_Windows_Simulator/trcConfig.h
/******************************************************************************* * Tracealyzer v2.4.1 Recorder Library * Percepio AB, www.percepio.com * * trcConfig.h * * Configuration parameters for the trace recorder library. Before using the * trace recorder library, please check that the default settings are * appropriate for your system, and if necessary adjust these. Most likely, you * will need to adjust the NTask, NISR, NQueue, NMutex and NSemaphore values to * reflect the number of such objects in your system. These may be * over-approximated, although larger values values implies more RAM usage. * * Terms of Use * This software is copyright Percepio AB. The recorder library is free for * use together with Percepio products. You may distribute the recorder library * in its original form, including modifications in trcHardwarePort.c/.h * given that these modification are clearly marked as your own modifications * and documented in the initial comment section of these source files. * This software is the intellectual property of Percepio AB and may not be * sold or in other ways commercially redistributed without explicit written * permission by Percepio AB. * * Disclaimer * The trace tool and recorder library is being delivered to you AS IS and * Percepio AB makes no warranty as to its use or performance. Percepio AB does * not and cannot warrant the performance or results you may obtain by using the * software or documentation. Percepio AB make no warranties, express or * implied, as to noninfringement of third party rights, merchantability, or * fitness for any particular purpose. In no event will Percepio AB, its * technology partners, or distributors be liable to you for any consequential, * incidental or special damages, including any lost profits or lost savings, * even if a representative of Percepio AB has been advised of the possibility * of such damages, or for any claim by any third party. Some jurisdictions do * not allow the exclusion or limitation of incidental, consequential or special * damages, or the exclusion of implied warranties or limitations on how long an * implied warranty may last, so the above limitations may not apply to you. * * Copyright Percepio AB, 2013. * www.percepio.com ******************************************************************************/ #ifndef TRCCONFIG_H #define TRCCONFIG_H #include <stdint.h> /******************************************************************************* * CONFIGURATION RELATED TO CAPACITY AND ALLOCATION ******************************************************************************/ /******************************************************************************* * EVENT_BUFFER_SIZE * * Macro which should be defined as an integer value. * * This defines the capacity of the event buffer, i.e., the number of records * it may store. Each registered event typically use one record (4 byte), but * vTracePrintF may use multiple records depending on the number of data args. ******************************************************************************/ #define EVENT_BUFFER_SIZE 100000 /* Adjust wrt. to available RAM */ /******************************************************************************* * USE_LINKER_PRAGMA * * Macro which should be defined as an integer value, default is 0. * * If this is 1, the header file "recorderdata_linker_pragma.h" is included just * before the declaration of RecorderData (in trcBase.c), i.e., the trace data * structure. This allows the user to specify a pragma with linker options. * * Example (for IAR Embedded Workbench and NXP LPC17xx): * #pragma location="AHB_RAM_MEMORY" * * This example instructs the IAR linker to place RecorderData in another RAM * bank, the AHB RAM. This can also be used for other compilers with a similar * pragmas for linker options. * * Note that this only applies if using static allocation, see below. ******************************************************************************/ #define USE_LINKER_PRAGMA 0 /******************************************************************************* * SYMBOL_TABLE_SIZE * * Macro which should be defined as an integer value. * * This defines the capacity of the symbol table, in bytes. This symbol table * stores User Events labels and names of deleted tasks, queues, or other kernel * objects. Note that the names of active objects not stored here but in the * Object Table. Thus, if you don't use User Events or delete any kernel * objects you set this to zero (0) to minimize RAM usage. ******************************************************************************/ #define SYMBOL_TABLE_SIZE 5000 /******************************************************************************* * USE_SEPARATE_USER_EVENT_BUFFER * * Macro which should be defined as an integer value. * Default is zero (0). * * This enables and disables the use of the separate user event buffer. * * Note: When using the separate user event buffer, you may get an artificial * task instance named "Unknown actor". This is added as a placeholder when the * user event history is longer than the task scheduling history. ******************************************************************************/ #define USE_SEPARATE_USER_EVENT_BUFFER 0 /******************************************************************************* * USER_EVENT_BUFFER_SIZE * * Macro which should be defined as an integer value. * * This defines the capacity of the user event buffer, in number of slots. * A single user event can use between 1 and X slots, depending on the data. * * Only in use if USE_SEPARATE_USER_EVENT_BUFFER is set to 1. ******************************************************************************/ #define USER_EVENT_BUFFER_SIZE 500 /******************************************************************************* * USER_EVENT_CHANNELS * * Macro which should be defined as an integer value. * * This defines the number of allowed user event channels. * * Only in use if USE_SEPARATE_USER_EVENT_BUFFER is set to 1. ******************************************************************************/ #define CHANNEL_FORMAT_PAIRS 32 /******************************************************************************* * NTask, NISR, NQueue, NSemaphore, NMutex * * A group of Macros which should be defined as an integer value of zero (0) * or larger. * * This defines the capacity of the Object Property Table - the maximum number * of objects active at any given point within each object class. * * NOTE: In case objects are deleted and created during runtime, this setting * does not limit the total amount of objects, only the number of concurrently * active objects. * * Using too small values will give an error message through the vTraceError * routine, which makes the error message appear when opening the trace data * in Tracealyzer. If you are using the recorder status monitor task, * any error messages are displayed in console prints, assuming that the * print macro has been defined properly (vConsolePrintMessage). * * It can be wise to start with very large values for these constants, * unless you are very confident on these numbers. Then do a recording and * check the actual usage in Tracealyzer. This is shown by selecting * View -> Trace Details -> Resource Usage -> Object Table * * NOTE 2: Remember to account for all tasks created by the kernel, such as the * IDLE task, timer task, and any tasks created by other 3rd party * software components, such as communication stacks. The recorder also has an * optional monitor task to account for, if this is used. * Moreover, one task slot is used to indicate "(startup)", i.e., a fictive * task that represent the time before the scheduler starts. * NTask should thus be at least 2-3 slots larger than your application task count. * ******************************************************************************/ #define NTask 100 #define NISR 60 #define NQueue 60 #define NSemaphore 60 #define NMutex 60 /* Maximum object name length for each class (includes zero termination) */ #define NameLenTask 15 #define NameLenISR 15 #define NameLenQueue 15 #define NameLenSemaphore 15 #define NameLenMutex 15 /****************************************************************************** * TRACE_DESCRIPTION * * Macro which should be defined as a string. * * This string is stored in the trace and displayed in Tracealyzer. Can be * used to store, e.g., system version or build date. This is also used to store * internal error messages from the recorder, which if occurs overwrites the * value defined here. This may be maximum 256 chars. *****************************************************************************/ #define TRACE_DESCRIPTION "Tracealyzer Recorder Test Program" /****************************************************************************** * TRACE_DESCRIPTION_MAX_LENGTH * * The maximum length (including zero termination) for the TRACE_DESCRIPTION * string. Since this string also is used for internal error messages from the * recorder do not make it too short, as this may truncate the error messages. * Default is 80. * Maximum allowed length is 256 - the trace will fail to load if longer. *****************************************************************************/ #define TRACE_DESCRIPTION_MAX_LENGTH 80 /****************************************************************************** * TRACE_DATA_ALLOCATION * * This defines how to allocate the recorder data structure, i.e., using a * static declaration or using a dynamic allocation in runtime (malloc). * * Should be one of these two options: * - TRACE_DATA_ALLOCATION_STATIC (default) * - TRACE_DATA_ALLOCATION_DYNAMIC * * Using static allocation has the benefits of compile-time errors if the buffer * is too large (too large constants in trcConfig.h) and no need to call the * initialization routine (xTraceInitTraceData). * * Using dynamic allocation may give more flexibility in some cases. *****************************************************************************/ #define TRACE_DATA_ALLOCATION TRACE_DATA_ALLOCATION_STATIC /****************************************************************************** * CONFIGURATION REGARDING WHAT CODE/FEATURES TO INCLUDE *****************************************************************************/ /****************************************************************************** * USE_TRACE_ASSERT * * Macro which should be defined as either zero (0) or one (1). * Default is 0. * * If this is one (1), the TRACE_ASSERT macro will verify that a condition is * true. If the condition is false, vTraceError() will be called. *****************************************************************************/ #define USE_TRACE_ASSERT 1 /****************************************************************************** * INCLUDE_FLOAT_SUPPORT * * Macro which should be defined as either zero (0) or one (1). * Default is 1. * * If this is zero (0), all references to floating point values are removed, * in case floating point values are not supported by the platform used. * Floating point values are only used in vTracePrintF and its subroutines, to * store float (%f) or double (%lf) argments. * * Note: vTracePrintF can still be used with integer and string arguments in * either case. *****************************************************************************/ #define INCLUDE_FLOAT_SUPPORT 0 /****************************************************************************** * INCLUDE_USER_EVENTS * * Macro which should be defined as either zero (0) or one (1). * Default is 1. * * If this is zero (0) the code for creating User Events is excluded to * reduce code size. User Events are application-generated events, like * "printf" but for the trace log instead of console output. User Events are * much faster than a printf and can therefore be used in timing critical code. * See vTraceUserEvent() and vTracePrintF() in trcUser.h * * Note that Tracealyzer Standard Edition or Professional Edition is required * for User Events, they are not displayed in Tracealyzer Free Edition. *****************************************************************************/ #define INCLUDE_USER_EVENTS 1 /***************************************************************************** * INCLUDE_READY_EVENTS * * Macro which should be defined as either zero (0) or one (1). * Default is 1. * * If this is zero (0), the code for recording Ready events is * excluded. Note, this will make it impossible to calculate the correct * response times. *****************************************************************************/ #define INCLUDE_READY_EVENTS 1 /***************************************************************************** * INCLUDE_NEW_TIME_EVENTS * * Macro which should be defined as either zero (0) or one (1). * Default is 0. * * If this is zero (1), events will be generated whenever the os clock is * increased. *****************************************************************************/ #define INCLUDE_NEW_TIME_EVENTS 0 /***************************************************************************** * INCLUDE_ISR_TRACING * * Macro which should be defined as either zero (0) or one (1). * Default is 1. * * If this is zero (0), the code for recording Interrupt Service Routines is * excluded to reduce code size. * * Note, if the kernel has no central interrupt dispatcher, recording ISRs * require that you insert calls to vTraceStoreISRBegin and vTraceStoreISREnd * in your interrupt handlers. *****************************************************************************/ #define INCLUDE_ISR_TRACING 1 /****************************************************************************** * INCLUDE_OBJECT_DELETE * * Macro which should be defined as either zero (0) or one (1). * Default is 1. * * This must be enabled (1) if tasks, queues or other * traced kernel objects are deleted at runtime. If no deletes are made, this * can be set to 0 in order to exclude the delete-handling code. *****************************************************************************/ #define INCLUDE_OBJECT_DELETE 0 /****************************************************************************** * CONFIGURATION RELATED TO BEHAVIOR *****************************************************************************/ /****************************************************************************** * TRACE_RECORDER_STORE_MODE * * Macro which should be defined as one of: * - TRACE_STORE_MODE_RING_BUFFER * - TRACE_STORE_MODE_STOP_WHEN_FULL * Default is TRACE_STORE_MODE_RING_BUFFER. * * With TRACE_RECORDER_STORE_MODE set to TRACE_STORE_MODE_RING_BUFFER, the events are * stored in a ring buffer, i.e., where the oldest events are overwritten when * the buffer becomes full. This allows you to get the last events leading up * to an interesting state, e.g., an error, without having a large trace buffer * for string the whole run since startup. In this mode, the recorder can run * "forever" as the buffer never gets full, i.e., in the sense that it always * has room for more events. * * To fetch the trace in mode TRACE_STORE_MODE_RING_BUFFER, you need to first halt the * system using your debugger and then do a RAM dump, or to explicitly stop the * recorder using vTraceStop() and then store/upload the trace data using a * task that you need to provide yourself. The trace data is found in the struct * RecorderData, initialized in trcBase.c. * * Note that, if you upload the trace using a RAM dump, i.e., when the system is * halted on a breakpoint or by a debugger command, there is no need to stop the * recorder first. * * When TRACE_RECORDER_STORE_MODE is TRACE_STORE_MODE_STOP_WHEN_FULL, the recording is * stopped when the buffer becomes full. When the recorder stops itself this way * vTracePortEnd() is called which allows for custom actions, such as triggering * a task that stores the trace buffer, i.e., in case taking a RAM dump * using an on-chip debugger is not possible. In the Windows port, vTracePortEnd * saves the trace to file directly, but this is not recommended in a real-time * system since the scheduler is blocked during the processing of vTracePortEnd. *****************************************************************************/ #define TRACE_RECORDER_STORE_MODE TRACE_STORE_MODE_RING_BUFFER /****************************************************************************** * STOP_AFTER_N_EVENTS * * Macro which should be defined as an integer value, or not defined. * Default is -1 * * STOP_AFTER_N_EVENTS is intended for tests of the ring buffer mode (when * RECORDER_STORE_MODE is STORE_MODE_RING_BUFFER). It stops the recording when * the specified number of events has been observed. This value can be larger * than the buffer size, to allow for test of the "wrapping around" that occurs * in ring buffer mode . A negative value (or no definition of this macro) * disables this feature. *****************************************************************************/ #define STOP_AFTER_N_EVENTS -1 /****************************************************************************** * USE_IMPLICIT_IFE_RULES * * Macro which should be defined as either zero (0) or one (1). * Default is 1. * * ### Instance Finish Events (IFE) ### * * For tasks with "infinite" main loops (non-terminating tasks), the concept * of a task instance has no clear definition, it is an application-specific * thing. Tracealyzer allows you to define Instance Finish Events (IFEs), * which marks the point in a cyclic task when the "task instance" ends. * The IFE is a blocking kernel call, typically in the main loop of a task * which typically reads a message queue, waits for a semaphore or performs * an explicit delay. * * If USE_IMPLICIT_IFE_RULES is one (1), the kernel macros (trcKernelPort.h) * will define what kernel calls are considered by default to be IFEs. * * However, Implicit IFEs only applies to blocking kernel calls. If a * service reads a message without blocking, it does not create a new * instance since no blocking occurred. * * Moreover, the actual IFE might sometimes be another blocking call. We * therefore allow for user-defined Explicit IFEs by calling * * vTraceTaskInstanceIsFinished() * * right before the kernel call considered as IFE. This does not create an * additional event but instead stores the service code and object handle * of the IFE call as properties of the task. * * If using Explicit IFEs and the task also calls an Implicit IFE, this may * result in additional incorrect task instances. * This is solved by disabling the Implicit IFEs for the task, by adding * a call to * * vTraceTaskSkipDefaultInstanceFinishedEvents() * * in the very beginning of that task. This allows you to combine Explicit IFEs * for some tasks with Implicit IFEs for the rest of the tasks, if * USE_IMPLICIT_IFE_RULES is 1. * * By setting USE_IMPLICIT_IFE_RULES to zero (0), the implicit IFEs are disabled * for all tasks. Tasks will then be considered to have a single instance only, * covering all execution fragments, unless you define an explicit IFE in each * task by calling vTraceTaskInstanceIsFinished before the blocking call. *****************************************************************************/ #define USE_IMPLICIT_IFE_RULES 1 /****************************************************************************** * INCLUDE_SAVE_TO_FILE * * Macro which should be defined as either zero (0) or one (1). * Default is 0. * * If enabled (1), the recorder will include code for saving the trace * to a local file system. ******************************************************************************/ #ifdef WIN32 #define INCLUDE_SAVE_TO_FILE 1 #else #define INCLUDE_SAVE_TO_FILE 0 #endif /****************************************************************************** * TRACE_PROGRESS_MONITOR_TASK_PRIORITY * * Macro which sets the priority of the "recorder status monitor" task. * * This task, vTraceMonitorTask in trcUser.c, periodically writes * the recorder status using the vTraceConsoleMessage macro, which is to * be mapped to your console "printf" routine. The task is named TraceMon but * is intentionally excluded from the demo trace. * * Default is tskIDLE_PRIORITY + 1 * Note that if your system constantly has a high CPU load from high-priority * tasks, this might not be get a chance to execute. * * See vTraceMonitorTask in trcUser.c *****************************************************************************/ #define TRACE_PROGRESS_MONITOR_TASK_PRIORITY (tskIDLE_PRIORITY + 1) /****************************************************************************** * TRACE_PROGRESS_MONITOR_TASK_STACKSIZE * * Macro which sets the stack size of the "recorder status monitor" task. * * This task, vTraceMonitorTask in trcUser.c, periodically writes * the recorder status using the vTraceConsoleMessage macro, which is to * be mapped to your console "printf" routine. The task is intentionally * excluded from the demo trace. * * See vTraceMonitorTask in trcUser.c *****************************************************************************/ #define TRACE_PROGRESS_MONITOR_TASK_STACKSIZE 500 /****************************************************************************** * TRACE_PROGRESS_MONITOR_TASK_PERIOD * * Macro which sets the period of the "recorder status monitor" task. * * This task, vTraceMonitorTask in trcUser.c, periodically writes * the recorder status using the vTraceConsoleMessage macro, which is to * be mapped to your console "printf" routine. The task is named TraceMon but * is intentionally excluded from the demo trace. * * Default is 1000 ticks (typically 1 second). On the Windows port, a lower * value is suggested since the Windows port runs very slowly, often 20-40 * times slower than the simulated time. * * See vTraceMonitorTask in trcUser.c *****************************************************************************/ #ifdef WIN32 #define TRACE_PROGRESS_MONITOR_TASK_PERIOD 100 #else #define TRACE_PROGRESS_MONITOR_TASK_PERIOD 1000 #endif /****************************************************************************** * TEAM_LICENSE_CODE * * Macro which defines a string - the team license code. * If no team license is available, this should be an empty string "". * This should be maximum 32 chars, including zero-termination. *****************************************************************************/ #define TEAM_LICENSE_CODE "" #endif
MicroEJ/FreeRTOS
FreeRTOS/Demo/CORTEX_MPU_M33F_NXP_LPC55S69_MCUXpresso/NXP_Code/startup/startup_lpc55s69_cm33_core0.c
<filename>FreeRTOS/Demo/CORTEX_MPU_M33F_NXP_LPC55S69_MCUXpresso/NXP_Code/startup/startup_lpc55s69_cm33_core0.c //***************************************************************************** // LPC55S69_cm33_core0 startup code for use with MCUXpresso IDE // // Version : 220119 //***************************************************************************** // // Copyright 2016-2019 NXP // All rights reserved. // // SPDX-License-Identifier: BSD-3-Clause //***************************************************************************** #if defined (DEBUG) #pragma GCC push_options #pragma GCC optimize ("Og") #endif // (DEBUG) #if defined (__cplusplus) #ifdef __REDLIB__ #error Redlib does not support C++ #else //***************************************************************************** // // The entry point for the C++ library startup // //***************************************************************************** extern "C" { extern void __libc_init_array(void); } #endif #endif #define WEAK __attribute__ ((weak)) #define WEAK_AV __attribute__ ((weak, section(".after_vectors"))) #define ALIAS(f) __attribute__ ((weak, alias (#f))) //***************************************************************************** #if defined (__cplusplus) extern "C" { #endif //***************************************************************************** // Variable to store CRP value in. Will be placed automatically // by the linker when "Enable Code Read Protect" selected. // See crp.h header for more information //***************************************************************************** //***************************************************************************** // Declaration of external SystemInit function //***************************************************************************** #if defined (__USE_CMSIS) extern void SystemInit(void); #endif // (__USE_CMSIS) //***************************************************************************** // Forward declaration of the core exception handlers. // When the application defines a handler (with the same name), this will // automatically take precedence over these weak definitions. // If your application is a C++ one, then any interrupt handlers defined // in C++ files within in your main application will need to have C linkage // rather than C++ linkage. To do this, make sure that you are using extern "C" // { .... } around the interrupt handler within your main application code. //***************************************************************************** void ResetISR(void); WEAK void NMI_Handler(void); WEAK void HardFault_Handler(void); WEAK void MemManage_Handler(void); WEAK void BusFault_Handler(void); WEAK void UsageFault_Handler(void); WEAK void SVC_Handler(void); WEAK void DebugMon_Handler(void); WEAK void PendSV_Handler(void); WEAK void SysTick_Handler(void); WEAK void IntDefaultHandler(void); //***************************************************************************** // Forward declaration of the application IRQ handlers. When the application // defines a handler (with the same name), this will automatically take // precedence over weak definitions below //***************************************************************************** WEAK void WDT_BOD_IRQHandler(void); WEAK void DMA0_IRQHandler(void); WEAK void GINT0_IRQHandler(void); WEAK void GINT1_IRQHandler(void); WEAK void PIN_INT0_IRQHandler(void); WEAK void PIN_INT1_IRQHandler(void); WEAK void PIN_INT2_IRQHandler(void); WEAK void PIN_INT3_IRQHandler(void); WEAK void UTICK0_IRQHandler(void); WEAK void MRT0_IRQHandler(void); WEAK void CTIMER0_IRQHandler(void); WEAK void CTIMER1_IRQHandler(void); WEAK void SCT0_IRQHandler(void); WEAK void CTIMER3_IRQHandler(void); WEAK void FLEXCOMM0_IRQHandler(void); WEAK void FLEXCOMM1_IRQHandler(void); WEAK void FLEXCOMM2_IRQHandler(void); WEAK void FLEXCOMM3_IRQHandler(void); WEAK void FLEXCOMM4_IRQHandler(void); WEAK void FLEXCOMM5_IRQHandler(void); WEAK void FLEXCOMM6_IRQHandler(void); WEAK void FLEXCOMM7_IRQHandler(void); WEAK void ADC0_IRQHandler(void); WEAK void Reserved39_IRQHandler(void); WEAK void ACMP_IRQHandler(void); WEAK void Reserved41_IRQHandler(void); WEAK void Reserved42_IRQHandler(void); WEAK void USB0_NEEDCLK_IRQHandler(void); WEAK void USB0_IRQHandler(void); WEAK void RTC_IRQHandler(void); WEAK void Reserved46_IRQHandler(void); WEAK void MAILBOX_IRQHandler(void); WEAK void PIN_INT4_IRQHandler(void); WEAK void PIN_INT5_IRQHandler(void); WEAK void PIN_INT6_IRQHandler(void); WEAK void PIN_INT7_IRQHandler(void); WEAK void CTIMER2_IRQHandler(void); WEAK void CTIMER4_IRQHandler(void); WEAK void OS_EVENT_IRQHandler(void); WEAK void Reserved55_IRQHandler(void); WEAK void Reserved56_IRQHandler(void); WEAK void Reserved57_IRQHandler(void); WEAK void SDIO_IRQHandler(void); WEAK void Reserved59_IRQHandler(void); WEAK void Reserved60_IRQHandler(void); WEAK void Reserved61_IRQHandler(void); WEAK void USB1_UTMI_IRQHandler(void); WEAK void USB1_IRQHandler(void); WEAK void USB1_NEEDCLK_IRQHandler(void); WEAK void SEC_HYPERVISOR_CALL_IRQHandler(void); WEAK void SEC_GPIO_INT0_IRQ0_IRQHandler(void); WEAK void SEC_GPIO_INT0_IRQ1_IRQHandler(void); WEAK void PLU_IRQHandler(void); WEAK void SEC_VIO_IRQHandler(void); WEAK void HASHCRYPT_IRQHandler(void); WEAK void CASER_IRQHandler(void); WEAK void PUF_IRQHandler(void); WEAK void PQ_IRQHandler(void); WEAK void DMA1_IRQHandler(void); WEAK void LSPI_HS_IRQHandler(void); //***************************************************************************** // Forward declaration of the driver IRQ handlers. These are aliased // to the IntDefaultHandler, which is a 'forever' loop. When the driver // defines a handler (with the same name), this will automatically take // precedence over these weak definitions //***************************************************************************** void WDT_BOD_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void DMA0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void GINT0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void GINT1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT2_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT3_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void UTICK0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void MRT0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void CTIMER0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void CTIMER1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void SCT0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void CTIMER3_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM2_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM3_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM4_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM5_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM6_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void FLEXCOMM7_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void ADC0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved39_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void ACMP_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved41_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved42_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void USB0_NEEDCLK_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void USB0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void RTC_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved46_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void MAILBOX_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT4_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT5_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT6_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PIN_INT7_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void CTIMER2_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void CTIMER4_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void OS_EVENT_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved55_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved56_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved57_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void SDIO_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved59_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved60_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void Reserved61_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void USB1_UTMI_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void USB1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void USB1_NEEDCLK_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void SEC_HYPERVISOR_CALL_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void SEC_GPIO_INT0_IRQ0_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void SEC_GPIO_INT0_IRQ1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PLU_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void SEC_VIO_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void HASHCRYPT_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void CASER_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PUF_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void PQ_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void DMA1_DriverIRQHandler(void) ALIAS(IntDefaultHandler); void LSPI_HS_DriverIRQHandler(void) ALIAS(IntDefaultHandler); //***************************************************************************** // The entry point for the application. // __main() is the entry point for Redlib based applications // main() is the entry point for Newlib based applications //***************************************************************************** #if defined (__REDLIB__) extern void __main(void); #endif extern int main(void); //***************************************************************************** // External declaration for the pointer to the stack top from the Linker Script //***************************************************************************** extern void _vStackTop(void); //***************************************************************************** // External declaration for LPC MCU vector table checksum from Linker Script //***************************************************************************** WEAK extern void __valid_user_code_checksum(); //***************************************************************************** //***************************************************************************** #if defined (__cplusplus) } // extern "C" #endif //***************************************************************************** // The vector table. // This relies on the linker script to place at correct location in memory. //***************************************************************************** extern void (* const g_pfnVectors[])(void); extern void * __Vectors __attribute__ ((alias ("g_pfnVectors"))); __attribute__ ((used, section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { // Core Level - CM33 &_vStackTop, // The initial stack pointer ResetISR, // The reset handler NMI_Handler, // The NMI handler HardFault_Handler, // The hard fault handler MemManage_Handler, // The MPU fault handler BusFault_Handler, // The bus fault handler UsageFault_Handler, // The usage fault handler __valid_user_code_checksum, // LPC MCU checksum 0, // ECRP 0, // Reserved 0, // Reserved SVC_Handler, // SVCall handler DebugMon_Handler, // Debug monitor handler 0, // Reserved PendSV_Handler, // The PendSV handler SysTick_Handler, // The SysTick handler // Chip Level - LPC55S69_cm33_core0 WDT_BOD_IRQHandler, // 16: Windowed watchdog timer, Brownout detect, Flash interrupt DMA0_IRQHandler, // 17: DMA0 controller GINT0_IRQHandler, // 18: GPIO group 0 GINT1_IRQHandler, // 19: GPIO group 1 PIN_INT0_IRQHandler, // 20: Pin interrupt 0 or pattern match engine slice 0 PIN_INT1_IRQHandler, // 21: Pin interrupt 1or pattern match engine slice 1 PIN_INT2_IRQHandler, // 22: Pin interrupt 2 or pattern match engine slice 2 PIN_INT3_IRQHandler, // 23: Pin interrupt 3 or pattern match engine slice 3 UTICK0_IRQHandler, // 24: Micro-tick Timer MRT0_IRQHandler, // 25: Multi-rate timer CTIMER0_IRQHandler, // 26: Standard counter/timer CTIMER0 CTIMER1_IRQHandler, // 27: Standard counter/timer CTIMER1 SCT0_IRQHandler, // 28: SCTimer/PWM CTIMER3_IRQHandler, // 29: Standard counter/timer CTIMER3 FLEXCOMM0_IRQHandler, // 30: Flexcomm Interface 0 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM1_IRQHandler, // 31: Flexcomm Interface 1 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM2_IRQHandler, // 32: Flexcomm Interface 2 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM3_IRQHandler, // 33: Flexcomm Interface 3 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM4_IRQHandler, // 34: Flexcomm Interface 4 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM5_IRQHandler, // 35: Flexcomm Interface 5 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM6_IRQHandler, // 36: Flexcomm Interface 6 (USART, SPI, I2C, I2S, FLEXCOMM) FLEXCOMM7_IRQHandler, // 37: Flexcomm Interface 7 (USART, SPI, I2C, I2S, FLEXCOMM) ADC0_IRQHandler, // 38: ADC0 Reserved39_IRQHandler, // 39: Reserved interrupt ACMP_IRQHandler, // 40: ACMP interrupts Reserved41_IRQHandler, // 41: Reserved interrupt Reserved42_IRQHandler, // 42: Reserved interrupt USB0_NEEDCLK_IRQHandler, // 43: USB Activity Wake-up Interrupt USB0_IRQHandler, // 44: USB device RTC_IRQHandler, // 45: RTC alarm and wake-up interrupts Reserved46_IRQHandler, // 46: Reserved interrupt MAILBOX_IRQHandler, // 47: WAKEUP,Mailbox interrupt (present on selected devices) PIN_INT4_IRQHandler, // 48: Pin interrupt 4 or pattern match engine slice 4 int PIN_INT5_IRQHandler, // 49: Pin interrupt 5 or pattern match engine slice 5 int PIN_INT6_IRQHandler, // 50: Pin interrupt 6 or pattern match engine slice 6 int PIN_INT7_IRQHandler, // 51: Pin interrupt 7 or pattern match engine slice 7 int CTIMER2_IRQHandler, // 52: Standard counter/timer CTIMER2 CTIMER4_IRQHandler, // 53: Standard counter/timer CTIMER4 OS_EVENT_IRQHandler, // 54: OSEVTIMER0 and OSEVTIMER0_WAKEUP interrupts Reserved55_IRQHandler, // 55: Reserved interrupt Reserved56_IRQHandler, // 56: Reserved interrupt Reserved57_IRQHandler, // 57: Reserved interrupt SDIO_IRQHandler, // 58: SD/MMC Reserved59_IRQHandler, // 59: Reserved interrupt Reserved60_IRQHandler, // 60: Reserved interrupt Reserved61_IRQHandler, // 61: Reserved interrupt USB1_UTMI_IRQHandler, // 62: USB1_UTMI USB1_IRQHandler, // 63: USB1 interrupt USB1_NEEDCLK_IRQHandler, // 64: USB1 activity SEC_HYPERVISOR_CALL_IRQHandler, // 65: SEC_HYPERVISOR_CALL interrupt SEC_GPIO_INT0_IRQ0_IRQHandler, // 66: SEC_GPIO_INT0_IRQ0 interrupt SEC_GPIO_INT0_IRQ1_IRQHandler, // 67: SEC_GPIO_INT0_IRQ1 interrupt PLU_IRQHandler, // 68: PLU interrupt SEC_VIO_IRQHandler, // 69: SEC_VIO interrupt HASHCRYPT_IRQHandler, // 70: HASHCRYPT interrupt CASER_IRQHandler, // 71: CASPER interrupt PUF_IRQHandler, // 72: PUF interrupt PQ_IRQHandler, // 73: PQ interrupt DMA1_IRQHandler, // 74: DMA1 interrupt LSPI_HS_IRQHandler, // 75: Flexcomm Interface 8 (SPI, , FLEXCOMM) }; /* End of g_pfnVectors */ //***************************************************************************** // Functions to carry out the initialization of RW and BSS data sections. These // are written as separate functions rather than being inlined within the // ResetISR() function in order to cope with MCUs with multiple banks of // memory. //***************************************************************************** __attribute__ ((section(".after_vectors.init_data"))) void data_init(unsigned int romstart, unsigned int start, unsigned int len) { unsigned int *pulDest = (unsigned int*) start; unsigned int *pulSrc = (unsigned int*) romstart; unsigned int loop; for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = *pulSrc++; } __attribute__ ((section(".after_vectors.init_bss"))) void bss_init(unsigned int start, unsigned int len) { unsigned int *pulDest = (unsigned int*) start; unsigned int loop; for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = 0; } //***************************************************************************** // The following symbols are constructs generated by the linker, indicating // the location of various points in the "Global Section Table". This table is // created by the linker via the Code Red managed linker script mechanism. It // contains the load address, execution address and length of each RW data // section and the execution and length of each BSS (zero initialized) section. //***************************************************************************** extern unsigned int __data_section_table; extern unsigned int __data_section_table_end; extern unsigned int __bss_section_table; extern unsigned int __bss_section_table_end; //***************************************************************************** // Reset entry point for your code. // Sets up a simple runtime environment and initializes the C/C++ // library. //***************************************************************************** __attribute__ ((section(".after_vectors.reset"))) void ResetISR(void) { // Disable interrupts __asm volatile ("cpsid i"); #if defined (__USE_CMSIS) // If __USE_CMSIS defined, then call CMSIS SystemInit code SystemInit(); #endif // (__USE_CMSIS) // // Copy the data sections from flash to SRAM. // unsigned int LoadAddr, ExeAddr, SectionLen; unsigned int *SectionTableAddr; // Load base address of Global Section Table SectionTableAddr = &__data_section_table; // Copy the data sections from flash to SRAM. while (SectionTableAddr < &__data_section_table_end) { LoadAddr = *SectionTableAddr++; ExeAddr = *SectionTableAddr++; SectionLen = *SectionTableAddr++; data_init(LoadAddr, ExeAddr, SectionLen); } // At this point, SectionTableAddr = &__bss_section_table; // Zero fill the bss segment while (SectionTableAddr < &__bss_section_table_end) { ExeAddr = *SectionTableAddr++; SectionLen = *SectionTableAddr++; bss_init(ExeAddr, SectionLen); } #if !defined (__USE_CMSIS) // Assume that if __USE_CMSIS defined, then CMSIS SystemInit code // will setup the VTOR register // Check to see if we are running the code from a non-zero // address (eg RAM, external flash), in which case we need // to modify the VTOR register to tell the CPU that the // vector table is located at a non-0x0 address. unsigned int * pSCB_VTOR = (unsigned int *) 0xE000ED08; if ((unsigned int *)g_pfnVectors!=(unsigned int *) 0x00000000) { *pSCB_VTOR = (unsigned int)g_pfnVectors; } #endif // (__USE_CMSIS) #if defined (__cplusplus) // // Call C++ library initialisation // __libc_init_array(); #endif // Reenable interrupts __asm volatile ("cpsie i"); #if defined (__REDLIB__) // Call the Redlib library, which in turn calls main() __main(); #else main(); #endif // // main() shouldn't return, but if it does, we'll just enter an infinite loop // while (1) { ; } } //***************************************************************************** // Default core exception handlers. Override the ones here by defining your own // handler routines in your application code. //***************************************************************************** WEAK_AV void NMI_Handler(void) { while(1) {} } WEAK_AV void HardFault_Handler(void) { while(1) {} } WEAK_AV void MemManage_Handler(void) { while(1) {} } WEAK_AV void BusFault_Handler(void) { while(1) {} } WEAK_AV void UsageFault_Handler(void) { while(1) {} } WEAK_AV void SVC_Handler(void) { while(1) {} } WEAK_AV void DebugMon_Handler(void) { while(1) {} } WEAK_AV void PendSV_Handler(void) { while(1) {} } WEAK_AV void SysTick_Handler(void) { while(1) {} } //***************************************************************************** // Processor ends up here if an unexpected interrupt occurs or a specific // handler is not present in the application code. //***************************************************************************** WEAK_AV void IntDefaultHandler(void) { while(1) {} } //***************************************************************************** // Default application exception handlers. Override the ones here by defining // your own handler routines in your application code. These routines call // driver exception handlers or IntDefaultHandler() if no driver exception // handler is included. //***************************************************************************** WEAK void WDT_BOD_IRQHandler(void) { WDT_BOD_DriverIRQHandler(); } WEAK void DMA0_IRQHandler(void) { DMA0_DriverIRQHandler(); } WEAK void GINT0_IRQHandler(void) { GINT0_DriverIRQHandler(); } WEAK void GINT1_IRQHandler(void) { GINT1_DriverIRQHandler(); } WEAK void PIN_INT0_IRQHandler(void) { PIN_INT0_DriverIRQHandler(); } WEAK void PIN_INT1_IRQHandler(void) { PIN_INT1_DriverIRQHandler(); } WEAK void PIN_INT2_IRQHandler(void) { PIN_INT2_DriverIRQHandler(); } WEAK void PIN_INT3_IRQHandler(void) { PIN_INT3_DriverIRQHandler(); } WEAK void UTICK0_IRQHandler(void) { UTICK0_DriverIRQHandler(); } WEAK void MRT0_IRQHandler(void) { MRT0_DriverIRQHandler(); } WEAK void CTIMER0_IRQHandler(void) { CTIMER0_DriverIRQHandler(); } WEAK void CTIMER1_IRQHandler(void) { CTIMER1_DriverIRQHandler(); } WEAK void SCT0_IRQHandler(void) { SCT0_DriverIRQHandler(); } WEAK void CTIMER3_IRQHandler(void) { CTIMER3_DriverIRQHandler(); } WEAK void FLEXCOMM0_IRQHandler(void) { FLEXCOMM0_DriverIRQHandler(); } WEAK void FLEXCOMM1_IRQHandler(void) { FLEXCOMM1_DriverIRQHandler(); } WEAK void FLEXCOMM2_IRQHandler(void) { FLEXCOMM2_DriverIRQHandler(); } WEAK void FLEXCOMM3_IRQHandler(void) { FLEXCOMM3_DriverIRQHandler(); } WEAK void FLEXCOMM4_IRQHandler(void) { FLEXCOMM4_DriverIRQHandler(); } WEAK void FLEXCOMM5_IRQHandler(void) { FLEXCOMM5_DriverIRQHandler(); } WEAK void FLEXCOMM6_IRQHandler(void) { FLEXCOMM6_DriverIRQHandler(); } WEAK void FLEXCOMM7_IRQHandler(void) { FLEXCOMM7_DriverIRQHandler(); } WEAK void ADC0_IRQHandler(void) { ADC0_DriverIRQHandler(); } WEAK void Reserved39_IRQHandler(void) { Reserved39_DriverIRQHandler(); } WEAK void ACMP_IRQHandler(void) { ACMP_DriverIRQHandler(); } WEAK void Reserved41_IRQHandler(void) { Reserved41_DriverIRQHandler(); } WEAK void Reserved42_IRQHandler(void) { Reserved42_DriverIRQHandler(); } WEAK void USB0_NEEDCLK_IRQHandler(void) { USB0_NEEDCLK_DriverIRQHandler(); } WEAK void USB0_IRQHandler(void) { USB0_DriverIRQHandler(); } WEAK void RTC_IRQHandler(void) { RTC_DriverIRQHandler(); } WEAK void Reserved46_IRQHandler(void) { Reserved46_DriverIRQHandler(); } WEAK void MAILBOX_IRQHandler(void) { MAILBOX_DriverIRQHandler(); } WEAK void PIN_INT4_IRQHandler(void) { PIN_INT4_DriverIRQHandler(); } WEAK void PIN_INT5_IRQHandler(void) { PIN_INT5_DriverIRQHandler(); } WEAK void PIN_INT6_IRQHandler(void) { PIN_INT6_DriverIRQHandler(); } WEAK void PIN_INT7_IRQHandler(void) { PIN_INT7_DriverIRQHandler(); } WEAK void CTIMER2_IRQHandler(void) { CTIMER2_DriverIRQHandler(); } WEAK void CTIMER4_IRQHandler(void) { CTIMER4_DriverIRQHandler(); } WEAK void OS_EVENT_IRQHandler(void) { OS_EVENT_DriverIRQHandler(); } WEAK void Reserved55_IRQHandler(void) { Reserved55_DriverIRQHandler(); } WEAK void Reserved56_IRQHandler(void) { Reserved56_DriverIRQHandler(); } WEAK void Reserved57_IRQHandler(void) { Reserved57_DriverIRQHandler(); } WEAK void SDIO_IRQHandler(void) { SDIO_DriverIRQHandler(); } WEAK void Reserved59_IRQHandler(void) { Reserved59_DriverIRQHandler(); } WEAK void Reserved60_IRQHandler(void) { Reserved60_DriverIRQHandler(); } WEAK void Reserved61_IRQHandler(void) { Reserved61_DriverIRQHandler(); } WEAK void USB1_UTMI_IRQHandler(void) { USB1_UTMI_DriverIRQHandler(); } WEAK void USB1_IRQHandler(void) { USB1_DriverIRQHandler(); } WEAK void USB1_NEEDCLK_IRQHandler(void) { USB1_NEEDCLK_DriverIRQHandler(); } WEAK void SEC_HYPERVISOR_CALL_IRQHandler(void) { SEC_HYPERVISOR_CALL_DriverIRQHandler(); } WEAK void SEC_GPIO_INT0_IRQ0_IRQHandler(void) { SEC_GPIO_INT0_IRQ0_DriverIRQHandler(); } WEAK void SEC_GPIO_INT0_IRQ1_IRQHandler(void) { SEC_GPIO_INT0_IRQ1_DriverIRQHandler(); } WEAK void PLU_IRQHandler(void) { PLU_DriverIRQHandler(); } WEAK void SEC_VIO_IRQHandler(void) { SEC_VIO_DriverIRQHandler(); } WEAK void HASHCRYPT_IRQHandler(void) { HASHCRYPT_DriverIRQHandler(); } WEAK void CASER_IRQHandler(void) { CASER_DriverIRQHandler(); } WEAK void PUF_IRQHandler(void) { PUF_DriverIRQHandler(); } WEAK void PQ_IRQHandler(void) { PQ_DriverIRQHandler(); } WEAK void DMA1_IRQHandler(void) { DMA1_DriverIRQHandler(); } WEAK void LSPI_HS_IRQHandler(void) { LSPI_HS_DriverIRQHandler(); } //***************************************************************************** #if defined (DEBUG) #pragma GCC pop_options #endif // (DEBUG)
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/Common/FreeRTOS_Plus_TCP_Demos/include/DefaultWebPages.h
/* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from <NAME>, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* * This file defines some very basic web content that is used as default web * pages when the HTTP server is created. A FAT file is created in the * directory set by the configHTTP_ROOT constant (in FreeRTOSConfig.h) from each * file definition below. The files were converted to C structures using Hex * Edit (http://www.hexedit.com). */ /* A structure that defines a single file to be copied to the RAM disk. */ typedef struct FILE_TO_COPY { const char *pcFileName; /* The name of the file. */ size_t xFileSize; const uint8_t *pucFileData; /* The C structure that contains the file's data. */ } xFileToCopy_t; static const uint8_t pcFreeRTOS_HTML_Data[] = { 0x3C, 0x21, 0x44, 0x4F, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, 0x48, 0x54, 0x4D, 0x4C, 0x20, 0x50, 0x55, 0x42, 0x4C, 0x49, 0x43, 0x20, 0x22, 0x2D, 0x2F, 0x2F, 0x57, 0x33, 0x43, 0x2F, 0x2F, 0x44, 0x54, 0x44, 0x20, 0x48, 0x54, 0x4D, 0x4C, 0x20, 0x34, 0x2E, 0x30, 0x31, 0x20, 0x54, 0x72, 0x61, 0x6E, 0x73, 0x69, 0x74, 0x69, 0x6F, 0x6E, 0x61, 0x6C, 0x2F, 0x2F, 0x45, 0x4E, 0x22, 0x20, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x77, 0x33, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x54, 0x52, 0x2F, 0x68, 0x74, 0x6D, 0x6C, 0x34, 0x2F, 0x6C, 0x6F, 0x6F, 0x73, 0x65, 0x2E, 0x64, 0x74, 0x64, 0x22, 0x3E, 0x0D, 0x0A, 0x3C, 0x68, 0x74, 0x6D, 0x6C, 0x3E, 0x0D, 0x0A, 0x09, 0x3C, 0x68, 0x65, 0x61, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x3C, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x2B, 0x54, 0x43, 0x50, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x2B, 0x46, 0x41, 0x54, 0x20, 0x48, 0x54, 0x54, 0x50, 0x20, 0x57, 0x65, 0x62, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x20, 0x57, 0x65, 0x62, 0x20, 0x50, 0x61, 0x67, 0x65, 0x0D, 0x0A, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x3C, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x48, 0x31, 0x20, 0x7B, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x31, 0x61, 0x33, 0x30, 0x36, 0x35, 0x3B, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x32, 0x37, 0x70, 0x78, 0x3B, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x20, 0x33, 0x30, 0x70, 0x78, 0x3B, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x48, 0x31, 0x20, 0x73, 0x6D, 0x61, 0x6C, 0x6C, 0x20, 0x7B, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x31, 0x36, 0x70, 0x78, 0x3B, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x48, 0x32, 0x20, 0x7B, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x31, 0x61, 0x33, 0x30, 0x36, 0x35, 0x3B, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x32, 0x32, 0x70, 0x78, 0x3B, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x48, 0x33, 0x20, 0x7B, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x31, 0x61, 0x33, 0x30, 0x36, 0x35, 0x3B, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x31, 0x38, 0x70, 0x78, 0x3B, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x20, 0x6E, 0x6F, 0x72, 0x6D, 0x61, 0x6C, 0x3B, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x48, 0x33, 0x20, 0x73, 0x6D, 0x61, 0x6C, 0x6C, 0x20, 0x7B, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x31, 0x61, 0x33, 0x30, 0x36, 0x35, 0x3B, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x31, 0x35, 0x70, 0x78, 0x3B, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x48, 0x34, 0x20, 0x7B, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x31, 0x61, 0x33, 0x30, 0x36, 0x35, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x54, 0x41, 0x42, 0x4C, 0x45, 0x20, 0x7B, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x20, 0x31, 0x34, 0x70, 0x78, 0x3B, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x20, 0x31, 0x2E, 0x35, 0x65, 0x6D, 0x3B, 0x20, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x54, 0x41, 0x42, 0x4C, 0x45, 0x2E, 0x74, 0x65, 0x78, 0x74, 0x5F, 0x61, 0x64, 0x20, 0x7B, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x20, 0x6E, 0x6F, 0x72, 0x6D, 0x61, 0x6C, 0x3B, 0x20, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x41, 0x3A, 0x76, 0x69, 0x73, 0x69, 0x74, 0x65, 0x64, 0x20, 0x7B, 0x74, 0x65, 0x78, 0x74, 0x2D, 0x64, 0x65, 0x63, 0x6F, 0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3A, 0x20, 0x6E, 0x6F, 0x6E, 0x65, 0x3B, 0x20, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x30, 0x30, 0x30, 0x30, 0x65, 0x65, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x41, 0x3A, 0x68, 0x6F, 0x76, 0x65, 0x72, 0x20, 0x7B, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2D, 0x64, 0x65, 0x63, 0x6F, 0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3A, 0x20, 0x6E, 0x6F, 0x6E, 0x65, 0x3B, 0x20, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x61, 0x20, 0x7B, 0x74, 0x65, 0x78, 0x74, 0x2D, 0x64, 0x65, 0x63, 0x6F, 0x72, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x3A, 0x20, 0x6E, 0x6F, 0x6E, 0x65, 0x3B, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x42, 0x4F, 0x44, 0x59, 0x20, 0x7B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3A, 0x20, 0x23, 0x32, 0x30, 0x32, 0x30, 0x32, 0x30, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x66, 0x61, 0x6D, 0x69, 0x6C, 0x79, 0x3A, 0x20, 0x61, 0x72, 0x69, 0x61, 0x6C, 0x2C, 0x20, 0x68, 0x65, 0x6C, 0x76, 0x65, 0x74, 0x69, 0x63, 0x61, 0x2C, 0x20, 0x73, 0x65, 0x72, 0x69, 0x66, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x2D, 0x73, 0x69, 0x7A, 0x65, 0x3A, 0x20, 0x31, 0x34, 0x70, 0x78, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x20, 0x31, 0x2E, 0x35, 0x65, 0x6D, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x6D, 0x61, 0x72, 0x67, 0x69, 0x6E, 0x2D, 0x6C, 0x65, 0x66, 0x74, 0x3A, 0x20, 0x30, 0x70, 0x78, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x6D, 0x61, 0x72, 0x67, 0x69, 0x6E, 0x2D, 0x72, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x20, 0x30, 0x70, 0x78, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x6D, 0x61, 0x72, 0x67, 0x69, 0x6E, 0x2D, 0x74, 0x6F, 0x70, 0x3A, 0x30, 0x70, 0x78, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x20, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6B, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x3A, 0x20, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x7D, 0x0D, 0x0A, 0x09, 0x09, 0x3C, 0x2F, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x3C, 0x2F, 0x68, 0x65, 0x61, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x3C, 0x62, 0x6F, 0x64, 0x79, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x3C, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x31, 0x30, 0x30, 0x25, 0x3B, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3A, 0x31, 0x30, 0x30, 0x38, 0x70, 0x78, 0x3B, 0x20, 0x62, 0x61, 0x63, 0x6B, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x3A, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3B, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x2D, 0x72, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x73, 0x6F, 0x6C, 0x69, 0x64, 0x20, 0x31, 0x70, 0x78, 0x20, 0x23, 0x65, 0x36, 0x65, 0x36, 0x65, 0x36, 0x3B, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x2D, 0x6C, 0x65, 0x66, 0x74, 0x3A, 0x73, 0x6F, 0x6C, 0x69, 0x64, 0x20, 0x31, 0x70, 0x78, 0x20, 0x23, 0x65, 0x36, 0x65, 0x36, 0x65, 0x36, 0x3B, 0x22, 0x20, 0x63, 0x65, 0x6C, 0x6C, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6E, 0x67, 0x3D, 0x22, 0x35, 0x22, 0x20, 0x63, 0x65, 0x6C, 0x6C, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6E, 0x67, 0x3D, 0x22, 0x30, 0x22, 0x20, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x63, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x72, 0x20, 0x76, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x74, 0x6F, 0x70, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3A, 0x31, 0x30, 0x30, 0x25, 0x3B, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x31, 0x30, 0x30, 0x70, 0x78, 0x3B, 0x22, 0x3E, 0x20, 0x3C, 0x21, 0x2D, 0x2D, 0x20, 0x53, 0x70, 0x61, 0x6E, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6C, 0x65, 0x66, 0x74, 0x20, 0x6D, 0x65, 0x6E, 0x75, 0x2C, 0x20, 0x62, 0x6C, 0x61, 0x6E, 0x6B, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2C, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x6D, 0x61, 0x69, 0x6E, 0x20, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x63, 0x6F, 0x6C, 0x75, 0x6D, 0x6E, 0x73, 0x20, 0x6F, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6E, 0x65, 0x78, 0x74, 0x20, 0x72, 0x6F, 0x77, 0x2E, 0x20, 0x2D, 0x2D, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x66, 0x6F, 0x6E, 0x74, 0x20, 0x66, 0x61, 0x63, 0x65, 0x3D, 0x22, 0x41, 0x72, 0x69, 0x61, 0x6C, 0x2C, 0x20, 0x48, 0x65, 0x6C, 0x76, 0x65, 0x74, 0x69, 0x63, 0x61, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3A, 0x31, 0x30, 0x30, 0x25, 0x3B, 0x22, 0x20, 0x63, 0x65, 0x6C, 0x6C, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6E, 0x67, 0x3D, 0x22, 0x32, 0x22, 0x20, 0x63, 0x65, 0x6C, 0x6C, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6E, 0x67, 0x3D, 0x22, 0x30, 0x22, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x3D, 0x22, 0x30, 0x22, 0x3E, 0x20, 0x3C, 0x21, 0x2D, 0x2D, 0x20, 0x52, 0x6F, 0x77, 0x73, 0x20, 0x66, 0x6F, 0x72, 0x20, 0x6C, 0x6F, 0x67, 0x6F, 0x73, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x62, 0x61, 0x6E, 0x6E, 0x65, 0x72, 0x73, 0x2C, 0x20, 0x62, 0x6C, 0x75, 0x65, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x73, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x6D, 0x65, 0x6E, 0x75, 0x2E, 0x20, 0x2D, 0x2D, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x72, 0x20, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6E, 0x67, 0x3A, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x3B, 0x22, 0x3E, 0x20, 0x3C, 0x21, 0x2D, 0x2D, 0x20, 0x54, 0x6F, 0x70, 0x20, 0x72, 0x6F, 0x77, 0x2C, 0x20, 0x62, 0x61, 0x6E, 0x6E, 0x65, 0x72, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x6C, 0x6F, 0x67, 0x6F, 0x2E, 0x20, 0x2D, 0x2D, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3D, 0x22, 0x31, 0x30, 0x30, 0x25, 0x22, 0x20, 0x63, 0x65, 0x6C, 0x6C, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6E, 0x67, 0x3D, 0x22, 0x30, 0x22, 0x20, 0x63, 0x65, 0x6C, 0x6C, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6E, 0x67, 0x3D, 0x22, 0x35, 0x70, 0x78, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x6E, 0x6F, 0x72, 0x6D, 0x61, 0x6C, 0x3B, 0x22, 0x20, 0x76, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x6D, 0x69, 0x64, 0x64, 0x6C, 0x65, 0x22, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3D, 0x22, 0x31, 0x37, 0x34, 0x70, 0x78, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x64, 0x69, 0x76, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x66, 0x6C, 0x6F, 0x61, 0x74, 0x3A, 0x6C, 0x65, 0x66, 0x74, 0x3B, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x69, 0x6D, 0x67, 0x20, 0x73, 0x72, 0x63, 0x3D, 0x22, 0x6C, 0x6F, 0x67, 0x6F, 0x2E, 0x6A, 0x70, 0x67, 0x22, 0x20, 0x61, 0x6C, 0x74, 0x3D, 0x22, 0x46, 0x72, 0x65, 0x65, 0x20, 0x52, 0x54, 0x4F, 0x53, 0x20, 0x6C, 0x6F, 0x67, 0x6F, 0x22, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3D, 0x22, 0x31, 0x36, 0x34, 0x70, 0x78, 0x22, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x3D, 0x22, 0x30, 0x22, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6E, 0x67, 0x3A, 0x20, 0x30, 0x20, 0x30, 0x20, 0x30, 0x20, 0x35, 0x70, 0x78, 0x3B, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x64, 0x69, 0x76, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3A, 0x35, 0x70, 0x78, 0x3B, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x2D, 0x74, 0x6F, 0x70, 0x3A, 0x73, 0x6F, 0x6C, 0x69, 0x64, 0x20, 0x32, 0x70, 0x78, 0x20, 0x23, 0x65, 0x36, 0x65, 0x36, 0x65, 0x36, 0x3B, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x2D, 0x6C, 0x65, 0x66, 0x74, 0x3A, 0x73, 0x6F, 0x6C, 0x69, 0x64, 0x20, 0x32, 0x70, 0x78, 0x20, 0x23, 0x65, 0x36, 0x65, 0x36, 0x65, 0x36, 0x3B, 0x20, 0x62, 0x6F, 0x72, 0x64, 0x65, 0x72, 0x2D, 0x62, 0x6F, 0x74, 0x74, 0x6F, 0x6D, 0x3A, 0x73, 0x6F, 0x6C, 0x69, 0x64, 0x20, 0x32, 0x70, 0x78, 0x20, 0x23, 0x65, 0x36, 0x65, 0x36, 0x65, 0x36, 0x3B, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x26, 0x6E, 0x62, 0x73, 0x70, 0x3B, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x20, 0x76, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x6D, 0x69, 0x64, 0x64, 0x6C, 0x65, 0x22, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x6C, 0x69, 0x6E, 0x65, 0x2D, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x6E, 0x6F, 0x72, 0x6D, 0x61, 0x6C, 0x3B, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x68, 0x33, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x20, 0x57, 0x65, 0x62, 0x20, 0x50, 0x61, 0x67, 0x65, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x68, 0x33, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x72, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x35, 0x70, 0x78, 0x3B, 0x22, 0x20, 0x62, 0x67, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3D, 0x22, 0x23, 0x37, 0x30, 0x39, 0x35, 0x64, 0x33, 0x22, 0x3E, 0x20, 0x3C, 0x21, 0x2D, 0x2D, 0x20, 0x42, 0x6C, 0x61, 0x6E, 0x6B, 0x20, 0x6C, 0x69, 0x6E, 0x65, 0x2E, 0x20, 0x2D, 0x2D, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x72, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3A, 0x31, 0x39, 0x70, 0x78, 0x3B, 0x22, 0x20, 0x62, 0x67, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3D, 0x22, 0x23, 0x62, 0x36, 0x63, 0x66, 0x66, 0x65, 0x22, 0x3E, 0x20, 0x3C, 0x21, 0x2D, 0x2D, 0x20, 0x48, 0x6F, 0x72, 0x69, 0x7A, 0x6F, 0x6E, 0x74, 0x61, 0x6C, 0x20, 0x6D, 0x65, 0x6E, 0x75, 0x2E, 0x20, 0x2D, 0x2D, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x20, 0x76, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x6D, 0x69, 0x64, 0x64, 0x6C, 0x65, 0x22, 0x20, 0x62, 0x67, 0x63, 0x6F, 0x6C, 0x6F, 0x72, 0x3D, 0x22, 0x23, 0x62, 0x36, 0x63, 0x66, 0x66, 0x65, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x66, 0x6F, 0x6E, 0x74, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x72, 0x20, 0x76, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x74, 0x6F, 0x70, 0x22, 0x3E, 0x20, 0x3C, 0x21, 0x2D, 0x2D, 0x20, 0x4D, 0x61, 0x69, 0x6E, 0x20, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x72, 0x6F, 0x77, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x6D, 0x65, 0x6E, 0x75, 0x20, 0x61, 0x6E, 0x64, 0x20, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x61, 0x72, 0x65, 0x61, 0x20, 0x63, 0x6F, 0x6C, 0x75, 0x6D, 0x6E, 0x73, 0x2E, 0x20, 0x2D, 0x2D, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x74, 0x64, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6E, 0x67, 0x3A, 0x20, 0x32, 0x30, 0x70, 0x78, 0x20, 0x32, 0x30, 0x70, 0x78, 0x20, 0x32, 0x30, 0x70, 0x78, 0x20, 0x32, 0x30, 0x70, 0x78, 0x3B, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x64, 0x69, 0x76, 0x20, 0x73, 0x74, 0x79, 0x6C, 0x65, 0x3D, 0x22, 0x66, 0x6C, 0x6F, 0x61, 0x74, 0x3A, 0x72, 0x69, 0x67, 0x68, 0x74, 0x3B, 0x22, 0x20, 0x61, 0x6C, 0x69, 0x67, 0x6E, 0x3D, 0x22, 0x63, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x69, 0x6D, 0x67, 0x20, 0x73, 0x72, 0x63, 0x3D, 0x22, 0x66, 0x74, 0x70, 0x2E, 0x70, 0x6E, 0x67, 0x22, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x73, 0x6D, 0x61, 0x6C, 0x6C, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x62, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x62, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x46, 0x54, 0x50, 0x27, 0x69, 0x6E, 0x67, 0x20, 0x77, 0x65, 0x62, 0x20, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x69, 0x6E, 0x74, 0x6F, 0x20, 0x2F, 0x72, 0x61, 0x6D, 0x2F, 0x77, 0x65, 0x62, 0x73, 0x72, 0x63, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x62, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x73, 0x6D, 0x61, 0x6C, 0x6C, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x64, 0x69, 0x76, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x68, 0x31, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x2B, 0x54, 0x43, 0x50, 0x20, 0x57, 0x65, 0x62, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x68, 0x31, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x20, 0x70, 0x61, 0x67, 0x65, 0x20, 0x62, 0x65, 0x69, 0x6E, 0x67, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x2B, 0x54, 0x43, 0x50, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x77, 0x65, 0x62, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2C, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x20, 0x66, 0x72, 0x6F, 0x6D, 0x20, 0x61, 0x20, 0x64, 0x69, 0x73, 0x6B, 0x20, 0x69, 0x6D, 0x70, 0x6C, 0x65, 0x6D, 0x65, 0x6E, 0x74, 0x65, 0x64, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x75, 0x73, 0x69, 0x6E, 0x67, 0x20, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x2B, 0x46, 0x41, 0x54, 0x2E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x70, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x54, 0x68, 0x65, 0x20, 0x48, 0x54, 0x54, 0x50, 0x20, 0x72, 0x6F, 0x6F, 0x74, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x79, 0x20, 0x69, 0x73, 0x20, 0x73, 0x65, 0x74, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6F, 0x6E, 0x66, 0x69, 0x67, 0x48, 0x54, 0x54, 0x50, 0x5F, 0x52, 0x4F, 0x4F, 0x54, 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x69, 0x6E, 0x20, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x43, 0x6F, 0x6E, 0x66, 0x69, 0x67, 0x2E, 0x68, 0x2E, 0x20, 0x20, 0x54, 0x68, 0x65, 0x73, 0x65, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, 0x20, 0x77, 0x65, 0x62, 0x20, 0x70, 0x61, 0x67, 0x65, 0x73, 0x20, 0x63, 0x61, 0x6E, 0x20, 0x62, 0x65, 0x20, 0x72, 0x65, 0x70, 0x6C, 0x61, 0x63, 0x65, 0x64, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x77, 0x69, 0x74, 0x68, 0x20, 0x6E, 0x65, 0x77, 0x20, 0x77, 0x65, 0x62, 0x20, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x62, 0x79, 0x20, 0x46, 0x54, 0x50, 0x27, 0x69, 0x6E, 0x67, 0x20, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x20, 0x69, 0x6E, 0x74, 0x6F, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x79, 0x2E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x70, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x62, 0x3E, 0x4E, 0x4F, 0x54, 0x45, 0x3A, 0x3C, 0x2F, 0x62, 0x3E, 0x20, 0x50, 0x65, 0x72, 0x66, 0x6F, 0x72, 0x6D, 0x61, 0x6E, 0x63, 0x65, 0x20, 0x77, 0x69, 0x6C, 0x6C, 0x20, 0x62, 0x65, 0x20, 0x6C, 0x69, 0x6D, 0x69, 0x74, 0x65, 0x64, 0x20, 0x77, 0x68, 0x65, 0x6E, 0x20, 0x75, 0x73, 0x69, 0x6E, 0x67, 0x20, 0x74, 0x68, 0x65, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x09, 0x46, 0x72, 0x65, 0x65, 0x52, 0x54, 0x4F, 0x53, 0x20, 0x57, 0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20, 0x70, 0x6F, 0x72, 0x74, 0x2E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x64, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x72, 0x3E, 0x0D, 0x0A, 0x09, 0x09, 0x3C, 0x2F, 0x74, 0x61, 0x62, 0x6C, 0x65, 0x3E, 0x0D, 0x0A, 0x09, 0x3C, 0x2F, 0x62, 0x6F, 0x64, 0x79, 0x3E, 0x0D, 0x0A, 0x3C, 0x2F, 0x68, 0x74, 0x6D, 0x6C, 0x3E, 0x0D, 0x0A }; static const uint8_t pcLogo_JPG_Data[] = { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x03, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x05, 0x08, 0x05, 0x05, 0x04, 0x04, 0x05, 0x0A, 0x07, 0x07, 0x06, 0x08, 0x0C, 0x0A, 0x0C, 0x0C, 0x0B, 0x0A, 0x0B, 0x0B, 0x0D, 0x0E, 0x12, 0x10, 0x0D, 0x0E, 0x11, 0x0E, 0x0B, 0x0B, 0x10, 0x16, 0x10, 0x11, 0x13, 0x14, 0x15, 0x15, 0x15, 0x0C, 0x0F, 0x17, 0x18, 0x16, 0x14, 0x18, 0x12, 0x14, 0x15, 0x14, 0xFF, 0xDB, 0x00, 0x43, 0x01, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x09, 0x05, 0x05, 0x09, 0x14, 0x0D, 0x0B, 0x0D, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x3E, 0x00, 0xA4, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xC4, 0x00, 0x1F, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xD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xD4, 0xE4, 0xF3, 0x5A, 0x45, 0x56, 0xC6, 0x72, 0xFB, 0x58, 0xA8, 0xD9, 0xDF, 0x7B, 0xEC, 0x4C, 0x6A, 0x62, 0x73, 0x37, 0x1A, 0x75, 0x69, 0x72, 0x46, 0x2D, 0x36, 0xEE, 0x9D, 0xED, 0xAD, 0xB4, 0x3D, 0x58, 0x67, 0x14, 0x53, 0x82, 0xFB, 0xD1, 0x5E, 0xC1, 0xF5, 0x07, 0xFF, 0xD9 }; static const uint8_t pcFTP_PNG_Data[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x02, 0x07, 0x00, 0x00, 0x02, 0xAB, 0x08, 0x03, 0x00, 0x00, 0x00, 0x52, 0xA1, 0xDE, 0x9C, 0x00, 0x00, 0x03, 0x00, 0x50, 0x4C, 0x54, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x3A, 0x3A, 0x36, 0x00, 0x00, 0x36, 0x00, 0x35, 0x33, 0x32, 0x32, 0x00, 0x00, 0x51, 0x00, 0x00, 0x65, 0x10, 0x2D, 0x71, 0x30, 0x00, 0x51, 0x39, 0x00, 0x66, 0x30, 0x2E, 0x51, 0x2E, 0x30, 0x72, 0x11, 0x78, 0x10, 0x27, 0x79, 0x2E, 0x30, 0x54, 0x51, 0x36, 0x52, 0x7C, 0x39, 0x66, 0x66, 0x55, 0x00, 0x00, 0x55, 0x00, 0x2D, 0x55, 0x2E, 0x00, 0x50, 0x2F, 0x2B, 0x66, 0x00, 0x00, 0x66, 0x00, 0x39, 0x6E, 0x33, 0x00, 0x72, 0x31, 0x2F, 0x55, 0x00, 0x51, 0x4C, 0x31, 0x74, 0x66, 0x00, 0x66, 0x77, 0x2E, 0x51, 0x70, 0x33, 0x75, 0x56, 0x40, 0x36, 0x5A, 0x75, 0x30, 0x78, 0x55, 0x00, 0x66, 0x46, 0x38, 0x65, 0x64, 0x25, 0x40, 0x40, 0x40, 0x47, 0x5D, 0x7B, 0x4D, 0x7C, 0x49, 0x55, 0x75, 0x71, 0x6A, 0x58, 0x50, 0x6C, 0x67, 0x55, 0x6F, 0x6F, 0x72, 0x00, 0x06, 0x8F, 0x01, 0x13, 0xB0, 0x00, 0x39, 0x8F, 0x14, 0x2E, 0xA4, 0x39, 0x39, 0x8F, 0x26, 0x39, 0xA8, 0x04, 0x1C, 0xD2, 0x00, 0x54, 0x90, 0x10, 0x54, 0xB6, 0x00, 0x65, 0xB4, 0x32, 0x4E, 0x8C, 0x33, 0x53, 0xAE, 0x37, 0x6A, 0x8D, 0x30, 0x71, 0xB2, 0x1F, 0x5F, 0xC0, 0x0C, 0x75, 0xD0, 0x0E, 0x70, 0xF3, 0x35, 0x4E, 0xD4, 0x30, 0x6D, 0xCB, 0x34, 0x7B, 0xE3, 0x50, 0x3F, 0x80, 0x49, 0x36, 0xA8, 0x66, 0x39, 0x8F, 0x66, 0x3A, 0x90, 0x41, 0x5C, 0x98, 0x45, 0x63, 0x9C, 0x53, 0x72, 0xA9, 0x6C, 0x77, 0x81, 0x62, 0x76, 0xB4, 0x4A, 0x75, 0xCB, 0x68, 0x7C, 0xDC, 0x0F, 0x96, 0x0E, 0x13, 0xAF, 0x09, 0x0E, 0xB2, 0x21, 0x34, 0x93, 0x34, 0x25, 0xB6, 0x1B, 0x36, 0xAD, 0x35, 0x3A, 0xAA, 0x46, 0x18, 0xD1, 0x05, 0x14, 0xCB, 0x2B, 0x1E, 0xEC, 0x08, 0x18, 0xE2, 0x33, 0x25, 0xD3, 0x0E, 0x30, 0xCA, 0x33, 0x28, 0xF4, 0x06, 0x34, 0xFC, 0x28, 0x2D, 0xC2, 0x44, 0x5A, 0x86, 0x29, 0x4F, 0xAC, 0x39, 0x60, 0xB1, 0x3B, 0x52, 0x88, 0x4F, 0x5E, 0x97, 0x66, 0x49, 0xB5, 0x46, 0x6D, 0x8D, 0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xD5, 0x54, 0xC4, 0x8B, 0xC6, 0x8C, 0x16, 0x57, 0x5D, 0xF3, 0x7E, 0xB2, 0x15, 0xD8, 0x7D, 0x88, 0x1A, 0x3D, 0xC6, 0x9A, 0x00, 0xC6, 0x06, 0x88, 0x76, 0xAE, 0xD1, 0x10, 0xCB, 0x06, 0x14, 0xDB, 0xBE, 0xEE, 0x2C, 0x91, 0x12, 0xDC, 0x25, 0xA4, 0x78, 0xB5, 0x13, 0x66, 0x75, 0x19, 0x73, 0xCE, 0x8A, 0x72, 0xE5, 0x41, 0xD6, 0x1B, 0xEC, 0x39, 0xE8, 0x76, 0xB0, 0x18, 0xEC, 0xDD, 0x56, 0x9D, 0x0D, 0xDE, 0x61, 0x02, 0x41, 0xF2, 0x41, 0x37, 0x10, 0x65, 0x3D, 0x00, 0xE4, 0x82, 0xAE, 0x19, 0xE1, 0x9B, 0xDF, 0xEC, 0x32, 0x4A, 0x8F, 0xC2, 0x60, 0x03, 0x7E, 0x2F, 0xF9, 0x20, 0x6D, 0x78, 0x0A, 0x78, 0x8D, 0xD1, 0xC4, 0x06, 0xB2, 0x7F, 0xD0, 0x33, 0xE8, 0x51, 0xAB, 0x94, 0x1C, 0x29, 0xD7, 0xA8, 0xEC, 0x1F, 0x64, 0x1F, 0x85, 0xF1, 0x99, 0xC9, 0xF9, 0x03, 0x09, 0x82, 0x27, 0x0F, 0x4F, 0x62, 0x92, 0xE8, 0x79, 0x28, 0xCC, 0xC6, 0xB6, 0x44, 0x6F, 0xC7, 0xFF, 0x0F, 0xFF, 0x9B, 0xA5, 0xD3, 0x1C, 0xD5, 0x77, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 }; const xFileToCopy_t xHTTPFilesToCopy[] = { { "freertos.html", sizeof( pcFreeRTOS_HTML_Data ), pcFreeRTOS_HTML_Data }, { "logo.jpg", sizeof( pcLogo_JPG_Data ), pcLogo_JPG_Data }, { "ftp.png", sizeof( pcFTP_PNG_Data ), pcFTP_PNG_Data } };
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/abstractions/platform/freertos/iot_taskpool_freertos.c
<reponame>MicroEJ/FreeRTOS /* * FreeRTOS Task Pool v1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file iot_taskpool_freertos.c * @brief Implements the task pool functions in iot_taskpool.h for FreeRTOS. */ /* * The full IoT Task Pool Library has many use cases, including Linux development. * Typical FreeRTOS use cases do not require the full functionality so an optimized * implementation is provided specifically for use with FreeRTOS. The optimized * version has a fixed number of tasks in the pool, each of which uses statically * allocated memory to ensure creation of the pool is guaranteed (it does not run out * of heap space). The constant IOT_TASKPOOL_NUMBER_OF_WORKERS sets the number of * tasks in the pool. * * Unlike the full version, this optimized version: * + Only supports a single task pool (system task pool) at a time. * + Does not auto-scale by dynamically adding more tasks if the number of * tasks in the pool becomes exhausted. The number of tasks in the pool * are fixed at compile time. See the task pool configuration options for * more information. * + Cannot be shut down - it exists for the lifetime of the application. * * Users who are interested in the functionality of the full IoT Task Pool * library can us it in place of this optimized version. */ /* Kernel includes. */ #include "FreeRTOS.h" #include "semphr.h" /* IoT libraries includes. */ #include "iot_config.h" /* Standard includes. */ #include <stdbool.h> #include <stdio.h> #include <stddef.h> #include <stdint.h> #include <string.h> #if !defined( configSUPPORT_STATIC_ALLOCATION ) || ( configSUPPORT_STATIC_ALLOCATION != 1 ) #error configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h to build this file. #endif /* Task pool internal include. */ #include "private/iot_taskpool_internal_freertos.h" /** * @brief Maximum semaphore value for wait operations. */ #define TASKPOOL_MAX_SEM_VALUE ( ( UBaseType_t ) 0xFFFF ) /** * @brief Reschedule delay in milliseconds for deferred jobs. */ #define TASKPOOL_JOB_RESCHEDULE_DELAY_MS ( 10ULL ) /* ---------------------------------------------------------------------------------- */ /** * @brief Get the job associated with a timer. * * @warning This only works on a _taskPoolTimerEvent_t within a _taskPoolJob_t. */ #define GET_JOB_FROM_TIMER(t) ((_taskPoolJob_t *)((uint8_t*)(t) - offsetof(_taskPoolJob_t, timer))) /** * brief The maximum time to wait when attempting to obtain an internal semaphore. * Don't wait indefinitely to give the application a chance to recover in the case * of an error. */ #define MAX_SEMAPHORE_TAKE_WAIT_TIME_MS ( pdMS_TO_TICKS( 10000UL ) ) /* ---------------------------------------------------------------------------------- */ /** * Doxygen should ignore this section. * * @brief The system task pool handle for all libraries to use. * User application can use the system task pool as well knowing that the usage will be shared with * the system libraries as well. The system task pool needs to be initialized before any library is used or * before any code that posts jobs to the task pool runs. */ static _taskPool_t _IotSystemTaskPool = { 0 }; /* -------------- Convenience functions to create/recycle/destroy jobs -------------- */ /** * @brief Initialize a job. * * @param[in] pJob The job to initialize. * @param[in] userCallback The user callback for the job. * @param[in] pUserContext The context to be passed to the callback. */ static void _initializeJob( _taskPoolJob_t * const pJob, IotTaskPoolRoutine_t userCallback, void * pUserContext ); /* -------------- The worker thread procedure for a task pool thread -------------- */ /** * The procedure for a task pool worker thread. * * @param[in] pUserContext The user context. * */ static void _taskPoolWorker( void * pUserContext ); /* -------------- Convenience functions to handle timer events -------------- */ /** * Comparer for the time list. * * param[in] pTimerEventLink1 The link to the first timer event. * param[in] pTimerEventLink1 The link to the first timer event. */ static int32_t _timerEventCompare( const IotLink_t * const pTimerEventLink1, const IotLink_t * const pTimerEventLink2 ); /** * Reschedules the timer for handling deferred jobs to the next timeout. * * param[in] timer The timer to reschedule. * param[in] pFirstTimerEvent The timer event that carries the timeout and job information. */ static void _rescheduleDeferredJobsTimer( TimerHandle_t const timer, _taskPoolTimerEvent_t * const pFirstTimerEvent ); /** * The task pool timer procedure for scheduling deferred jobs. * * param[in] timer The timer to handle. */ static void _timerCallback( TimerHandle_t xTimer ); /* -------------- Convenience functions to create/initialize/destroy the task pool -------------- */ /** * Initializes a pre-allocated instance of a task pool. */ static void _initTaskPoolControlStructures( void ); /** * Initializes a pre-allocated instance of a task pool. * * @param[in] pInfo The initialization information for the task pool. * */ static IotTaskPoolError_t _createTaskPool( const IotTaskPoolInfo_t * const pInfo ); /** * Places a job in the dispatch queue. * * @param[in] pJob The job to schedule. * */ static void _scheduleInternal( _taskPoolJob_t * const pJob ); /** * Matches a deferred job in the timer queue with its timer event wrapper. * * @param[in] pLink A pointer to the timer event link in the timer queue. * @param[in] pMatch A pointer to the job to match. * */ static bool _matchJobByPointer( const IotLink_t * const pLink, void * pMatch ); /** * Tries to cancel a job. * * @param[in] pJob The job to cancel. * @param[out] pStatus The status of the job at the time of cancellation. * */ static IotTaskPoolError_t _tryCancelInternal( _taskPoolJob_t * const pJob, IotTaskPoolJobStatus_t * const pStatus ); /* ---------------------------------------------------------------------------------------------- */ IotTaskPoolError_t IotTaskPool_CreateSystemTaskPool( const IotTaskPoolInfo_t * const pInfo ) { IotTaskPoolError_t status; static BaseType_t isInitialized = pdFALSE; configASSERT( pInfo ); configASSERT( pInfo->minThreads >= 1UL ); /* This version of the task pool does not auto-scale so the specified minimum number of threads in the pool must match the specified maximum number of threads in the pool. */ configASSERT( pInfo->maxThreads == pInfo->minThreads ); /* Guard against multiple attempts to create the system task pool in case this function is called by more than one library initialization routine. */ taskENTER_CRITICAL(); { /* If the task pool has already been initialized then IOT_TASKPOOL_ILLEGAL_OPERATION will be returned - but that does not guarantee the initialization operation is complete as the task to which IOT_TASKPOOL_ILLEGAL_OPERATION is returned may have preempted the task that was performing the initialization before the initialization was complete - hence the assert to catch this occurrence during development and debug. */ configASSERT( isInitialized == pdFALSE ); if( isInitialized == pdFALSE ) { /* The task pool has not been initialized already so will be initialized now. */ status = IOT_TASKPOOL_SUCCESS; isInitialized = pdTRUE; } else { /* This function has already been called but executing this path does not guarantee the task pool has already been initialized as the task to which this error is returned may have preempted the task that was performing the initialization before the initialization was complete. */ status = IOT_TASKPOOL_ILLEGAL_OPERATION; } } taskEXIT_CRITICAL(); if( status == IOT_TASKPOOL_SUCCESS ) { /* Create the system task pool. Note in this version _createTaskPool() cannot fail because it is using statically allocated memory. Therefore the return value can be safely ignored and there is no need to consider resetting isInitialized in a failure case. */ ( void ) _createTaskPool( pInfo ); } return status; } /*-----------------------------------------------------------*/ IotTaskPoolError_t IotTaskPool_CreateJob( IotTaskPoolRoutine_t userCallback, void * pUserContext, IotTaskPoolJobStorage_t * const pJobStorage, IotTaskPoolJob_t * const ppJob ) { /* Parameter checking. */ configASSERT( userCallback != NULL ); configASSERT( pJobStorage != NULL ); configASSERT( ppJob != NULL ); /* Build a job around the user-provided storage. */ _initializeJob( ( _taskPoolJob_t * ) pJobStorage, userCallback, pUserContext ); *ppJob = ( IotTaskPoolJob_t ) pJobStorage; return IOT_TASKPOOL_SUCCESS; } /*-----------------------------------------------------------*/ IotTaskPoolError_t IotTaskPool_Schedule( IotTaskPool_t taskPoolHandle, IotTaskPoolJob_t pJob, uint32_t flags ) { IotTaskPoolError_t status = IOT_TASKPOOL_SUCCESS; /* Task pool must have been created. */ configASSERT( _IotSystemTaskPool.running != false ); /* This lean version of the task pool only supports the task pool created by this library (the system task pool). NULL means use the system task pool - no other values are allowed. Use the full implementation of this library if you want multiple task pools (there is more than one task in each pool. */ configASSERT( ( taskPoolHandle == NULL ) || ( taskPoolHandle == &_IotSystemTaskPool ) ); /* Avoid compiler warnings about unused parameters if configASSERT() is not defined. */ ( void ) taskPoolHandle; configASSERT( pJob != NULL ); configASSERT( ( flags == 0UL ) || ( flags == IOT_TASKPOOL_JOB_HIGH_PRIORITY ) ); /* Acquire the mutex for manipulating the job timer queue. */ if ( xSemaphoreTake( _IotSystemTaskPool.xTimerEventMutex, MAX_SEMAPHORE_TAKE_WAIT_TIME_MS ) == pdTRUE ) { _scheduleInternal( pJob ); if ( xSemaphoreGive( _IotSystemTaskPool.xTimerEventMutex ) == pdFALSE ) { /* This can only be reached if semaphores are configured incorrectly. */ status = IOT_TASKPOOL_GENERAL_FAILURE; } /* Signal a worker task that a job was queued. */ if ( xSemaphoreGive( _IotSystemTaskPool.dispatchSignal ) == pdFALSE ) { /* This can only be reached if semaphores are configured incorrectly. */ status = IOT_TASKPOOL_GENERAL_FAILURE; } } else { status = IOT_TASKPOOL_GENERAL_FAILURE; } return status; } /*-----------------------------------------------------------*/ IotTaskPoolError_t IotTaskPool_ScheduleDeferred( IotTaskPool_t taskPoolHandle, IotTaskPoolJob_t job, uint32_t timeMs ) { TickType_t now; IotTaskPoolError_t status = IOT_TASKPOOL_SUCCESS; /* This lean version of the task pool only supports the task pool created by this library (the system task pool). NULL means use the system task pool - no other values are allowed. Use the full implementation of this library if you want multiple task pools (there is more than one task in each pool. */ configASSERT( ( taskPoolHandle == NULL ) || ( taskPoolHandle == &_IotSystemTaskPool ) ); configASSERT( job != NULL ); /* If the timer period is zero, just immediately queue the job for execution. */ if( timeMs == 0UL ) { status = IotTaskPool_Schedule( &_IotSystemTaskPool, job, 0 ); } else { _taskPoolTimerEvent_t* pTimerEvent = &(job->timer); configASSERT( job->timer.link.pNext == NULL ); IotLink_t* pTimerEventLink; pTimerEvent->link.pNext = NULL; pTimerEvent->link.pPrevious = NULL; now = xTaskGetTickCount(); pTimerEvent->expirationTime = now + pdMS_TO_TICKS( timeMs ); if ( xSemaphoreTake( _IotSystemTaskPool.xTimerEventMutex, MAX_SEMAPHORE_TAKE_WAIT_TIME_MS ) == pdTRUE ) { /* Append the timer event to the timer list. */ IotListDouble_InsertSorted( &( _IotSystemTaskPool.timerEventsList ), &( pTimerEvent->link ), _timerEventCompare ); /* Update the job status to 'scheduled'. */ job->status = IOT_TASKPOOL_STATUS_DEFERRED; /* Peek the first event in the timer event list. There must be at least one, * since we just inserted it. */ pTimerEventLink = IotListDouble_PeekHead( &( _IotSystemTaskPool.timerEventsList ) ); configASSERT( pTimerEventLink != NULL ); /* If the event we inserted is at the front of the queue, then * we need to reschedule the underlying timer. */ if ( pTimerEventLink == &( pTimerEvent->link ) ) { pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pTimerEventLink, link ); _rescheduleDeferredJobsTimer( _IotSystemTaskPool.timer, pTimerEvent ); } if ( xSemaphoreGive( _IotSystemTaskPool.xTimerEventMutex ) == pdFALSE ) { /* This can only be reached if semaphores are configured incorrectly. */ status = IOT_TASKPOOL_GENERAL_FAILURE; } } else { status = IOT_TASKPOOL_GENERAL_FAILURE; } } return status; } /*-----------------------------------------------------------*/ IotTaskPoolError_t IotTaskPool_GetStatus( IotTaskPool_t taskPoolHandle, IotTaskPoolJob_t job, IotTaskPoolJobStatus_t * const pStatus ) { /* This lean version of the task pool only supports the task pool created by this library (the system task pool). NULL means use the system task pool - no other values are allowed. Use the full implementation of this library if you want multiple task pools (there is more than one task in each pool. */ configASSERT( ( taskPoolHandle == NULL ) || ( taskPoolHandle == &_IotSystemTaskPool ) ); /* Remove warning about unused parameter. */ ( void ) taskPoolHandle; /* Parameter checking. */ configASSERT( job != NULL ); configASSERT( pStatus != NULL ); taskENTER_CRITICAL(); { *pStatus = job->status; } taskEXIT_CRITICAL(); return IOT_TASKPOOL_SUCCESS; } /*-----------------------------------------------------------*/ IotTaskPoolError_t IotTaskPool_TryCancel( IotTaskPool_t taskPoolHandle, IotTaskPoolJob_t job, IotTaskPoolJobStatus_t * const pStatus ) { IotTaskPoolError_t status = IOT_TASKPOOL_SUCCESS; const TickType_t dontBlock = ( TickType_t ) 0; /* This lean version of the task pool only supports the task pool created by this library (the system task pool). NULL means use the system task pool - no other values are allowed. Use the full implementation of this library if you want multiple task pools (there is more than one task in each pool. */ configASSERT( ( taskPoolHandle == NULL ) || ( taskPoolHandle == &_IotSystemTaskPool ) ); if( job != NULL ) { if( pStatus != NULL ) { *pStatus = IOT_TASKPOOL_STATUS_UNDEFINED; } if ( xSemaphoreTake( _IotSystemTaskPool.xTimerEventMutex, dontBlock ) != pdFALSE ) { status = _tryCancelInternal( job, pStatus ); if ( xSemaphoreGive( _IotSystemTaskPool.xTimerEventMutex ) == pdFALSE ) { /* This can only be reached if semaphores are configured incorrectly. */ status = IOT_TASKPOOL_GENERAL_FAILURE; } } else { /* If we fail to take the semaphore, just abort the cancel. */ status = IOT_TASKPOOL_CANCEL_FAILED; } } else { status = IOT_TASKPOOL_BAD_PARAMETER; } return status; } /*-----------------------------------------------------------*/ IotTaskPoolJobStorage_t * IotTaskPool_GetJobStorageFromHandle( IotTaskPoolJob_t pJob ) { return ( IotTaskPoolJobStorage_t * ) pJob; } /*-----------------------------------------------------------*/ const char * IotTaskPool_strerror( IotTaskPoolError_t status ) { const char * pMessage = NULL; switch( status ) { case IOT_TASKPOOL_SUCCESS: pMessage = "SUCCESS"; break; case IOT_TASKPOOL_BAD_PARAMETER: pMessage = "BAD PARAMETER"; break; case IOT_TASKPOOL_ILLEGAL_OPERATION: pMessage = "ILLEGAL OPERATION"; break; case IOT_TASKPOOL_NO_MEMORY: pMessage = "NO MEMORY"; break; case IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS: pMessage = "SHUTDOWN IN PROGRESS"; break; case IOT_TASKPOOL_CANCEL_FAILED: pMessage = "CANCEL FAILED"; break; case IOT_TASKPOOL_GENERAL_FAILURE: pMessage = "GENERAL FAILURE"; break; default: pMessage = "INVALID STATUS"; break; } return pMessage; } /* ---------------------------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------------------------------- */ static void _initTaskPoolControlStructures( void ) { /* Initialize a job data structures that require no de-initialization. * All other data structures carry a value of 'NULL' before initialization. */ IotDeQueue_Create( &( _IotSystemTaskPool.dispatchQueue ) ); IotListDouble_Create( &( _IotSystemTaskPool.timerEventsList ) ); /* Initialize the semaphore for waiting for incoming work. Cannot fail as statically allocated. */ _IotSystemTaskPool.dispatchSignal = xSemaphoreCreateCountingStatic( TASKPOOL_MAX_SEM_VALUE, 0, &( _IotSystemTaskPool.dispatchSignalBuffer ) ); _IotSystemTaskPool.xTimerEventMutex = xSemaphoreCreateMutexStatic( &( _IotSystemTaskPool.xTimerEventMutexBuffer ) ); } static IotTaskPoolError_t _createTaskPool( const IotTaskPoolInfo_t * const pInfo ) { /* The taskpool will create a number of threads equal to the minThreads setting. The number of workers should be equal to avoid over/under allocation. */ configASSERT( IOT_TASKPOOL_NUMBER_OF_WORKERS == pInfo->minThreads ); /* Static TCB structures and arrays to be used by statically allocated worker tasks. */ static StaticTask_t workerTaskTCBs[ IOT_TASKPOOL_NUMBER_OF_WORKERS ]; static StackType_t workerTaskStacks[ IOT_TASKPOOL_NUMBER_OF_WORKERS ][ IOT_TASKPOOL_WORKER_STACK_SIZE_BYTES / sizeof( portSTACK_TYPE ) ]; /* Static structure to hold the software timer. */ static StaticTimer_t staticTimer; uint32_t threadsCreated = 0; /* Although initialized before use removing the initializer here results in compiler warnings. */ char taskName[ 10 ]; /* This assert is primarily to catch the function being called more than once, but will also ensure the C start up code has zeroed out the structure correctly. */ #if( configASSERT_DEFINED == 1 ) { size_t x; uint8_t *pucNextByte = ( uint8_t * ) &_IotSystemTaskPool; for( x = 0; x < sizeof( _taskPool_t ); x++ ) { configASSERT( pucNextByte[ x ] == ( uint8_t ) 0x00 ); } } #endif /* configASSERT_DEFINED */ /* Initialize all internal data structure prior to creating all threads. */ _initTaskPoolControlStructures(); /* Create the FreeRTOS timer for managing Task Pool timers. */ _IotSystemTaskPool.timer = xTimerCreateStatic( NULL, /* Text name for the timer, only used for debugging. */ portMAX_DELAY, /* Timer period in ticks. */ pdFALSE, /* pdFALSE means its a one-shot timer. */ ( void * ) &_IotSystemTaskPool, /* Parameter passed into callback. */ _timerCallback, /* Callback that executes when the timer expires. */ &staticTimer ); /* Static storage for the timer's data structure. */ /* The task pool will initialize the minimum number of threads requested by the user upon start. Note this tailored version of the task pool does not auto-scale, but fixes the number of tasks in the pool to the originally specified minimum, and the specified maximum value is ignored. */ /* Create the minimum number of threads specified by the user, and if one fails shutdown and return error. */ for( threadsCreated = 0; threadsCreated < pInfo->minThreads; ) { /* Generate a unique name for the task. */ snprintf( taskName, sizeof( taskName ), "pool%d", ( int ) threadsCreated ); xTaskCreateStatic( _taskPoolWorker, /* Function that implements the task. */ taskName, /* Text name for the task, used for debugging only. */ IOT_TASKPOOL_WORKER_STACK_SIZE_BYTES / sizeof( portSTACK_TYPE ), /* xTaskCreate() expects the stack size to be specified in words. */ &_IotSystemTaskPool, /* Parameter passed into the task. */ pInfo->priority, /* Priority at which the task starts running. */ &( workerTaskStacks[ threadsCreated ][ 0 ] ), /* Pointer to static storage for the task's stack. */ &( workerTaskTCBs[ threadsCreated ] ) ); /* Pointer to static storage for the task's TCB. */ ++threadsCreated; } _IotSystemTaskPool.running = true; /* This version of this function cannot fail as all the memory is allocated statically at compile time. */ return IOT_TASKPOOL_SUCCESS; } /* ---------------------------------------------------------------------------------------------- */ static void _taskPoolWorker( void * pUserContext ) { configASSERT( pUserContext != NULL ); IotTaskPoolRoutine_t userCallback = NULL; /* Extract pTaskPool pointer from context. */ _taskPool_t * pTaskPool = ( _taskPool_t * ) pUserContext; /* OUTER LOOP: it controls the lifetime of the worker thread. */ for( ; ; ) { IotLink_t * pFirst = NULL; _taskPoolJob_t * pJob = NULL; /* Wait on incoming notifications... */ configASSERT( pTaskPool->dispatchSignal ); /* If the semaphore for job dispatch expires without a job, a critical precondition of this task has not been met. See the xBlockTime parameter of xSemaphoreTake for details. */ configASSERT( xSemaphoreTake( pTaskPool->dispatchSignal, portMAX_DELAY ) ); /* Acquire the lock to check for incoming notifications. This call should not expire. See the xBlockTime parameter of xSemaphoreTake for details. */ configASSERT( xSemaphoreTake( pTaskPool->xTimerEventMutex, portMAX_DELAY ) ); /* Dequeue the first job in FIFO order. */ pFirst = IotDeQueue_DequeueHead( &pTaskPool->dispatchQueue ); /* If there is indeed a job, then update status under lock, and release the lock before processing the job. */ if( pFirst != NULL ) { /* Extract the job from its link. */ pJob = IotLink_Container( _taskPoolJob_t, pFirst, link ); /* Update status to 'completed' to indicate it is queued for execution. */ pJob->status = IOT_TASKPOOL_STATUS_COMPLETED; userCallback = pJob->userCallback; } /* Release the lock now that the job dispatch queue has been checked. This call should not expire. See the xBlockTime parameter of xSemaphoreTake for details. */ configASSERT( xSemaphoreGive( pTaskPool->xTimerEventMutex ) ); /* INNER LOOP: it controls the execution of jobs: the exit condition is the lack of a job to execute. */ while( pJob != NULL ) { /* Process the job by invoking the associated callback with the user context. * This task pool thread will not be available until the user callback returns. */ { configASSERT( IotLink_IsLinked( &pJob->link ) == false ); configASSERT( userCallback != NULL ); userCallback( pTaskPool, pJob, pJob->pUserContext ); /* This job is finished, clear its pointer. */ pJob = NULL; userCallback = NULL; } /* Acquire the lock to check for incoming notifications. This call should not expire. See the xBlockTime parameter of xSemaphoreTake for details. */ configASSERT( xSemaphoreTake( pTaskPool->xTimerEventMutex, portMAX_DELAY ) ); { /* Try and dequeue the next job in the dispatch queue. */ IotLink_t * pItem = NULL; /* Dequeue the next job from the dispatch queue. */ pItem = IotDeQueue_DequeueHead( &( pTaskPool->dispatchQueue ) ); /* If there is no job left in the dispatch queue, update the worker status and leave. */ if( pItem == NULL ) { /* Release the lock before exiting the loop. */ configASSERT( xSemaphoreGive( pTaskPool->xTimerEventMutex ) ); /* Abandon the INNER LOOP. Execution will transfer back to the OUTER LOOP condition. */ break; } else { pJob = IotLink_Container( _taskPoolJob_t, pItem, link ); userCallback = pJob->userCallback; } pJob->status = IOT_TASKPOOL_STATUS_COMPLETED; } /* Release the lock now that the job dispatch queue has been checked. */ configASSERT( xSemaphoreGive( pTaskPool->xTimerEventMutex ) ); } } } /* ---------------------------------------------------------------------------------------------- */ static void _initializeJob( _taskPoolJob_t * const pJob, IotTaskPoolRoutine_t userCallback, void * pUserContext ) { memset( ( void * ) pJob, 0x00, sizeof( _taskPoolJob_t ) ); pJob->userCallback = userCallback; pJob->pUserContext = pUserContext; pJob->status = IOT_TASKPOOL_STATUS_READY; } /* ---------------------------------------------------------------------------------------------- */ static void _scheduleInternal( _taskPoolJob_t * const pJob ) { /* Update the job status to 'scheduled'. */ pJob->status = IOT_TASKPOOL_STATUS_SCHEDULED; /* Append the job to the dispatch queue. */ IotDeQueue_EnqueueTail( &( _IotSystemTaskPool.dispatchQueue ), &( pJob->link ) ); /* NOTE: Every call to this function must be followed by giving the dispatchSignal semaphore - but do not give the semaphore directly in this function as giving the semaphore will result in the execution of a task pool worker task (depending on relative priorities) and we don't want the worker task to execute until all semaphores obtained before calling this function have been released. */ } /*-----------------------------------------------------------*/ static bool _matchJobByPointer( const IotLink_t * const pLink, void * pMatch ) { const _taskPoolJob_t * const pJob = ( _taskPoolJob_t * ) pMatch; const _taskPoolTimerEvent_t * const pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pLink, link ); if( pJob == GET_JOB_FROM_TIMER( pTimerEvent ) ) { return true; } return false; } /*-----------------------------------------------------------*/ static IotTaskPoolError_t _tryCancelInternal( _taskPoolJob_t * const pJob, IotTaskPoolJobStatus_t * const pStatus ) { IotTaskPoolError_t result = IOT_TASKPOOL_SUCCESS; bool cancelable = false; /* We can only cancel jobs that are either 'ready' (waiting to be scheduled). 'deferred', or 'scheduled'. */ IotTaskPoolJobStatus_t currentStatus = pJob->status; switch( currentStatus ) { case IOT_TASKPOOL_STATUS_READY: case IOT_TASKPOOL_STATUS_DEFERRED: case IOT_TASKPOOL_STATUS_SCHEDULED: case IOT_TASKPOOL_STATUS_CANCELED: cancelable = true; break; case IOT_TASKPOOL_STATUS_COMPLETED: /* Log message for debug purposes. */ IotLogWarn( "Attempt to cancel a job that is already executing, or canceled." ); break; default: /* Log message for debug purposes. */ IotLogError( "Attempt to cancel a job with an undefined state." ); break; } /* Update the returned status to the current status of the job. */ if( pStatus != NULL ) { *pStatus = currentStatus; } if( cancelable == false ) { result = IOT_TASKPOOL_CANCEL_FAILED; } else { /* Update the status of the job. */ pJob->status = IOT_TASKPOOL_STATUS_CANCELED; /* If the job is cancelable and its current status is 'scheduled' then unlink it from the dispatch * queue and signal any waiting threads. */ if( currentStatus == IOT_TASKPOOL_STATUS_SCHEDULED ) { /* A scheduled work items must be in the dispatch queue. */ configASSERT( IotLink_IsLinked( &pJob->link ) ); IotDeQueue_Remove( &pJob->link ); } /* If the job current status is 'deferred' then the job has to be pending * in the timeouts queue. */ else if( currentStatus == IOT_TASKPOOL_STATUS_DEFERRED ) { /* Find the timer event associated with the current job. There MUST be one, hence assert if not. */ IotLink_t * pTimerEventLink = IotListDouble_FindFirstMatch( &( _IotSystemTaskPool.timerEventsList ), NULL, _matchJobByPointer, pJob ); configASSERT( pTimerEventLink != NULL ); if( pTimerEventLink != NULL ) { bool shouldReschedule = false; /* If the job being canceled was at the head of the timeouts queue, then we need to reschedule the timer * with the next job timeout */ IotLink_t * pHeadLink = IotListDouble_PeekHead( &( _IotSystemTaskPool.timerEventsList ) ); if( pHeadLink == pTimerEventLink ) { shouldReschedule = true; } /* Remove the timer event associated with the canceled job and free the associated memory. */ IotListDouble_Remove( pTimerEventLink ); memset( IotLink_Container( _taskPoolTimerEvent_t, pTimerEventLink, link ), 0, sizeof( IotLink_t ) ); if( shouldReschedule ) { IotLink_t * pNextTimerEventLink = IotListDouble_PeekHead( &( _IotSystemTaskPool.timerEventsList ) ); if( pNextTimerEventLink != NULL ) { _rescheduleDeferredJobsTimer( _IotSystemTaskPool.timer, IotLink_Container( _taskPoolTimerEvent_t, pNextTimerEventLink, link ) ); } } } } else { /* A cancelable job status should be either 'scheduled' or 'deferred'. */ configASSERT( ( currentStatus == IOT_TASKPOOL_STATUS_READY ) || ( currentStatus == IOT_TASKPOOL_STATUS_CANCELED ) ); } } return result; } /*-----------------------------------------------------------*/ static int32_t _timerEventCompare( const IotLink_t * const pTimerEventLink1, const IotLink_t * const pTimerEventLink2 ) { const _taskPoolTimerEvent_t * const pTimerEvent1 = IotLink_Container( _taskPoolTimerEvent_t, pTimerEventLink1, link ); const _taskPoolTimerEvent_t * const pTimerEvent2 = IotLink_Container( _taskPoolTimerEvent_t, pTimerEventLink2, link ); if( pTimerEvent1->expirationTime < pTimerEvent2->expirationTime ) { return -1; } if( pTimerEvent1->expirationTime > pTimerEvent2->expirationTime ) { return 1; } return 0; } /*-----------------------------------------------------------*/ static void _rescheduleDeferredJobsTimer( TimerHandle_t const timer, _taskPoolTimerEvent_t * const pFirstTimerEvent ) { uint64_t delta = 0; TickType_t now = xTaskGetTickCount(); configASSERT( pFirstTimerEvent != NULL ); configASSERT( timer != NULL ); /* Determine how much time is left for the deferred job. */ if( pFirstTimerEvent->expirationTime > now ) { delta = pFirstTimerEvent->expirationTime - now; } /* If the job timer has exceeded it's period, schedule it to be executed shortly. */ if( delta < TASKPOOL_JOB_RESCHEDULE_DELAY_MS ) { delta = TASKPOOL_JOB_RESCHEDULE_DELAY_MS; /* The job will be late... */ } /* Change the period of the task pools timer to be the period of this timer. A precondition of this function is that this TimerEvent is the timer event with the shortest deadline. */ if( xTimerChangePeriod( timer, ( uint32_t ) delta, portMAX_DELAY ) == pdFAIL ) { IotLogWarn( "Failed to re-arm timer for task pool" ); } } /*-----------------------------------------------------------*/ static void _timerCallback( TimerHandle_t xTimer ) { _taskPool_t * pTaskPool = pvTimerGetTimerID( xTimer ); configASSERT( pTaskPool ); _taskPoolTimerEvent_t * pTimerEvent = NULL; BaseType_t numberOfSchedules = 0; IotLogDebug( "Timer thread started for task pool %p.", pTaskPool ); /* Attempt to lock the timer mutex. Return immediately if the mutex cannot be locked. * If this mutex cannot be locked it means that another thread is manipulating the * timeouts list, and will reset the timer to fire again, although it will be late. */ if ( xSemaphoreTake( pTaskPool->xTimerEventMutex, 0 ) == pdPASS ) { /* Dispatch all deferred job whose timer expired, then reset the timer for the next * job down the line. */ for( ; ; ) { /* Peek the first event in the timer event list. */ IotLink_t * pLink = IotListDouble_PeekHead( &pTaskPool->timerEventsList ); /* Check if the timer misfired for any reason. */ if( pLink != NULL ) { /* Record the current time. */ TickType_t now = xTaskGetTickCount(); /* Extract the job from its envelope. */ pTimerEvent = IotLink_Container( _taskPoolTimerEvent_t, pLink, link ); /* Check if the first event should be processed now. */ if( pTimerEvent->expirationTime <= now ) { /* Remove the timer event for immediate processing. */ IotListDouble_Remove( &( pTimerEvent->link ) ); } else { /* The first element in the timer queue shouldn't be processed yet. * Arm the timer for when it should be processed and leave altogether. */ _rescheduleDeferredJobsTimer( pTaskPool->timer, pTimerEvent ); break; } } /* If there are no timer events to process, terminate this thread. */ else { IotLogDebug( "Finished scheduling deferred jobs." ); break; } /* Queue the job associated with the received timer event. */ _scheduleInternal( GET_JOB_FROM_TIMER( pTimerEvent ) ); numberOfSchedules++; IotLogDebug( "Scheduled a job." ); /* Free the timer event. */ memset( &( pTimerEvent->link ), 0, sizeof( pTimerEvent->link ) ); } /* Release mutex guarding the timer list. */ configASSERT( xSemaphoreGive( pTaskPool->xTimerEventMutex ) == pdPASS ); for (; numberOfSchedules > 0; numberOfSchedules--) { /* Signal a worker task that a job was queued. */ configASSERT( xSemaphoreGive( pTaskPool->dispatchSignal ) ); } } }
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/Common/Demo_IP_Protocols/FTP/FreeRTOS_FTP_server.c
/* * FreeRTOS+TCP V2.0.3 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /* Standard includes. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "portmacro.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_TCP_IP.h" #include "FreeRTOS_Sockets.h" #include "FreeRTOS_Stream_Buffer.h" /* FreeRTOS Protocol includes. */ #include "FreeRTOS_FTP_commands.h" #include "FreeRTOS_TCP_server.h" #include "FreeRTOS_server_private.h" /* Remove the whole file if FTP is not supported. */ #if( ipconfigUSE_FTP == 1 ) #ifndef HTTP_SERVER_BACKLOG #define HTTP_SERVER_BACKLOG ( 12 ) #endif #if !defined( ARRAY_SIZE ) #define ARRAY_SIZE( x ) ( BaseType_t ) (sizeof( x ) / sizeof( x )[ 0 ] ) #endif #if defined(__WIN32__) && !defined(ipconfigFTP_FS_USES_BACKSLAH) #define ipconfigFTP_FS_USES_BACKSLAH 1 #endif /* Some defines to make the code more readbale */ #define pcCOMMAND_BUFFER pxClient->pxParent->pcCommandBuffer #define pcNEW_DIR pxClient->pxParent->pcNewDir #define pcFILE_BUFFER pxClient->pxParent->pcFileBuffer /* This FTP server will only do binary transfers */ #define TMODE_BINARY 1 #define TMODE_ASCII 2 #define TMODE_7BITS 3 #define TMODE_8BITS 4 /* Ascii character definitions. */ #define ftpASCII_CR 13 #define ftpASCII_LF 10 #if defined( FTP_WRITES_ALIGNED ) || defined( ipconfigFTP_WRITES_ALIGNED ) #error Name change : please rename the define to the new name 'ipconfigFTP_ZERO_COPY_ALIGNED_WRITES' #endif /* * ipconfigFTP_ZERO_COPY_ALIGNED_WRITES : experimental optimisation option. * If non-zero, receiving data will be done with the zero-copy method and also * writes to disk will be done with sector-alignment as much as possible. */ #ifndef ipconfigFTP_ZERO_COPY_ALIGNED_WRITES #define ipconfigFTP_ZERO_COPY_ALIGNED_WRITES 0 #endif /* * This module only has 2 public functions: */ BaseType_t xFTPClientWork( TCPClient_t *pxClient ); void vFTPClientDelete( TCPClient_t *pxClient ); /* * Process a single command. */ static BaseType_t prvProcessCommand( FTPClient_t *pxClient, BaseType_t xIndex, char *pcRestCommand ); /* * Create a socket for a data connection to the FTP client. */ static BaseType_t prvTransferConnect( FTPClient_t *pxClient, BaseType_t xDoListen ); /* * Either call listen() or connect() to start the transfer connection. */ static BaseType_t prvTransferStart( FTPClient_t *pxClient ); /* * See if the socket has got connected or disconnected. Close the socket if * necessary. */ static void prvTransferCheck( FTPClient_t *pxClient ); /* * Close the data socket and issue some informative logging. */ static void prvTransferCloseSocket( FTPClient_t *pxClient ); /* * Close the file handle (pxReadHandle or pxWriteHandle). */ static void prvTransferCloseFile( FTPClient_t *pxClient ); /* * Close a directory (-handle). */ static void prvTransferCloseDir( FTPClient_t *pxClient ); /* * Translate a string (indicating a transfer type) to a number. */ static BaseType_t prvGetTransferType( const char *pcType ); #if( ipconfigHAS_PRINTF != 0 ) /* * For nice logging: write an amount (number of bytes), e.g. 3512200 as * "3.45 MB" */ static const char *pcMkSize( uint32_t ulAmount, char *pcBuffer, BaseType_t xBufferSize ); #endif #if( ipconfigHAS_PRINTF != 0 ) /* * Calculate the average as bytes-per-second, when amount and milliseconds * are known. */ static uint32_t ulGetAverage( uint32_t ulAmount, TickType_t xDeltaMs ); #endif /* * A port command looks like: PORT h1,h2,h3,h4,p1,p2. Parse it and translate it * to an IP-address and a port number. */ static UBaseType_t prvParsePortData( const char *pcCommand, uint32_t *pulIPAddress ); /* * CWD: Change current working directory. */ static BaseType_t prvChangeDir( FTPClient_t *pxClient, char *pcDirectory ); /* * RNFR: Rename from ... */ static BaseType_t prvRenameFrom( FTPClient_t *pxClient, const char *pcFileName ); /* * RNTO: Rename to ... */ static BaseType_t prvRenameTo( FTPClient_t *pxClient, const char *pcFileName ); /* * SITE: Change file permissions. */ static BaseType_t prvSiteCmd( FTPClient_t *pxClient, char *pcRestCommand ); /* * DELE: Delete a file. */ static BaseType_t prvDeleteFile( FTPClient_t *pxClient, char *pcFileName ); /* * SIZE: get the size of a file (xSendDate = 0). * MDTM: get data and time properties (xSendDate = 1). */ static BaseType_t prvSizeDateFile( FTPClient_t *pxClient, char *pcFileName, BaseType_t xSendDate ); /* * MKD: Make / create a directory (xDoRemove = 0). * RMD: Remove a directory (xDoRemove = 1). */ static BaseType_t prvMakeRemoveDir( FTPClient_t *pxClient, const char *pcDirectory, BaseType_t xDoRemove ); /* * The next three commands: LIST, RETR and STOR all require a data socket. * The data connection is either started with a 'PORT' or a 'PASV' command. * Each of the commands has a prepare- (Prep) and a working- (Work) function. * The Work function should be called as long as the data socket is open, and * there is data to be transmitted. */ /* * LIST: Send a directory listing in Unix style. */ static BaseType_t prvListSendPrep( FTPClient_t *pxClient ); static BaseType_t prvListSendWork( FTPClient_t *pxClient ); /* * RETR: Send a file to the FTP client. */ static BaseType_t prvRetrieveFilePrep( FTPClient_t *pxClient, char *pcFileName ); static BaseType_t prvRetrieveFileWork( FTPClient_t *pxClient ); /* * STOR: Receive a file from the FTP client and store it. */ static BaseType_t prvStoreFilePrep( FTPClient_t *pxClient, char *pcFileName ); static BaseType_t prvStoreFileWork( FTPClient_t *pxClient ); /* * Print/format a single directory entry in Unix style. */ static BaseType_t prvGetFileInfoStat( FF_DirEnt_t *pxEntry, char *pcLine, BaseType_t xMaxLength ); /* * Send a reply to a socket, either the command- or the data-socket. */ static BaseType_t prvSendReply( Socket_t xSocket, const char *pcBuffer, BaseType_t xLength ); /* * Prepend the root directory (if any), plus the current working directory * (always), to get an absolute path. */ BaseType_t xMakeAbsolute( FTPClient_t *pxClient, char *pcBuffer, BaseType_t xBufferLength, const char *pcPath ); /* ####### ##### ###### # # ## # ## # # # # # # # # # # # # # # # # # # # # # # #### ### ## # # ##### # ##### # # # # # # # # # # # # # # # # # # # ## # #### # # # ## ## # # # # # # # # ## ## # # # # # #### #### #### ## ## #### #### ## ## * xFTPClientWork() * will be called by FreeRTOS_TCPServerWork(), after select has expired(). * FD_ISSET will not be used. This work function will always be called at * regular intervals, and also after a select() event has occurred. */ BaseType_t xFTPClientWork( TCPClient_t *pxTCPClient ) { FTPClient_t *pxClient = ( FTPClient_t * ) pxTCPClient; BaseType_t xRc; if( pxClient->bits.bHelloSent == pdFALSE_UNSIGNED ) { BaseType_t xLength; pxClient->bits.bHelloSent = pdTRUE_UNSIGNED; xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "220 Welcome to the FreeRTOS+TCP FTP server\r\n" ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); } /* Call recv() in a non-blocking way, to see if there is an FTP command sent to this server. */ xRc = FreeRTOS_recv( pxClient->xSocket, ( void * )pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), 0 ); if( xRc > 0 ) { BaseType_t xIndex; const FTPCommand_t *pxCommand; char *pcRestCommand; if( xRc < ( BaseType_t ) sizeof( pcCOMMAND_BUFFER ) ) { pcCOMMAND_BUFFER[ xRc ] = '\0'; } while( xRc && ( ( pcCOMMAND_BUFFER[ xRc - 1 ] == ftpASCII_CR ) || ( pcCOMMAND_BUFFER[ xRc - 1 ] == ftpASCII_LF ) ) ) { pcCOMMAND_BUFFER[ --xRc ] = '\0'; } /* Now iterate through a list of FTP commands, and look for a match. */ pxCommand = xFTPCommands; pcRestCommand = pcCOMMAND_BUFFER; for( xIndex = 0; xIndex < FTP_CMD_COUNT - 1; xIndex++, pxCommand++ ) { BaseType_t xLength; /* The length of each command is stored as well, just to be a bit quicker here. */ xLength = pxCommand->xCommandLength; if( ( xRc >= xLength ) && ( memcmp( ( const void * ) pxCommand->pcCommandName, ( const void * ) pcCOMMAND_BUFFER, xLength ) == 0 ) ) { /* A match with an existing command is found. Skip any whitespace to get the first parameter. */ pcRestCommand += xLength; while( ( *pcRestCommand == ' ' ) || ( *pcRestCommand == '\t' ) ) { pcRestCommand++; } break; } } /* If the command received was not recognised, xIndex will point to a fake entry called 'ECMD_UNKNOWN'. */ prvProcessCommand( pxClient, xIndex, pcRestCommand ); } else if( xRc < 0 ) { /* The connection will be closed and the client will be deleted. */ FreeRTOS_printf( ( "xFTPClientWork: xRc = %ld\n", xRc ) ); } /* Does it have an open data connection? */ if( pxClient->xTransferSocket != FREERTOS_NO_SOCKET ) { /* See if the connection has changed. */ prvTransferCheck( pxClient ); /* "pcConnectionAck" contains a string like: "Response: 150 Accepted data connection from 192.168.2.3:6789" The socket can only be used once this acknowledgement has been sent. */ if( ( pxClient->xTransferSocket != FREERTOS_NO_SOCKET ) && ( pxClient->pcConnectionAck[ 0 ] == '\0' ) ) { BaseType_t xClientRc = 0; if( pxClient->bits1.bDirHasEntry ) { /* Still listing a directory. */ xClientRc = prvListSendWork( pxClient ); } else if( pxClient->pxReadHandle != NULL ) { /* Sending a file. */ xClientRc = prvRetrieveFileWork( pxClient ); } else if( pxClient->pxWriteHandle != NULL ) { /* Receiving a file. */ xClientRc = prvStoreFileWork( pxClient ); } if( xClientRc < 0 ) { prvTransferCloseSocket( pxClient ); prvTransferCloseFile( pxClient ); } } } return xRc; } /*-----------------------------------------------------------*/ static void prvTransferCloseDir( FTPClient_t *pxClient ) { /* Nothing to close for +FAT. */ ( void ) pxClient; } /*-----------------------------------------------------------*/ void vFTPClientDelete( TCPClient_t *pxTCPClient ) { FTPClient_t *pxClient = ( FTPClient_t * ) pxTCPClient; /* Close any directory-listing-handles (not used by +FAT ). */ prvTransferCloseDir( pxClient ); /* Close the data-socket. */ prvTransferCloseSocket( pxClient ); /* Close any open file handle. */ prvTransferCloseFile( pxClient ); /* Close the FTP command socket */ if( pxClient->xSocket != FREERTOS_NO_SOCKET ) { FreeRTOS_FD_CLR( pxClient->xSocket, pxClient->pxParent->xSocketSet, eSELECT_ALL ); FreeRTOS_closesocket( pxClient->xSocket ); pxClient->xSocket = FREERTOS_NO_SOCKET; } } /*-----------------------------------------------------------*/ static BaseType_t prvProcessCommand( FTPClient_t *pxClient, BaseType_t xIndex, char *pcRestCommand ) { const FTPCommand_t *pxFTPCommand = &( xFTPCommands[ xIndex ] ); const char *pcMyReply = NULL; BaseType_t xResult = 0; if( ( pxFTPCommand->ucCommandType != ECMD_PASS ) && ( pxFTPCommand->ucCommandType != ECMD_PORT ) ) { FreeRTOS_printf( ( " %s %s\n", pxFTPCommand->pcCommandName, pcRestCommand ) ); } if( ( pxFTPCommand->checkLogin != pdFALSE ) && ( pxClient->bits.bLoggedIn == pdFALSE_UNSIGNED ) ) { pcMyReply = REPL_530; /* Please first log in. */ } else if( ( pxFTPCommand->checkNullArg != pdFALSE ) && ( ( pcRestCommand == NULL ) || ( pcRestCommand[ 0 ] == '\0' ) ) ) { pcMyReply = REPL_501; /* Command needs a parameter. */ } if( pcMyReply == NULL ) { switch( pxFTPCommand->ucCommandType ) { case ECMD_USER: /* User. */ /* User name has been entered, expect password. */ pxClient->bits.bStatusUser = pdTRUE_UNSIGNED; #if( ipconfigFTP_HAS_USER_PASSWORD_HOOK != 0 )/*_RB_ Needs defaulting and adding to the web documentation. */ { /* Save the user name in 'pcFileName'. */ snprintf( pxClient->pcFileName, sizeof( pxClient->pcFileName ), "%s", pcRestCommand ); /* The USER name is presented to the application. The function may return a const string like "331 Please enter your password\r\n". */ pcMyReply = pcApplicationFTPUserHook( pxClient->pcFileName ); if( pcMyReply == NULL ) { pcMyReply = REPL_331_ANON; } } #else { /* No password checks, any password will be accepted. */ pcMyReply = REPL_331_ANON; } #endif /* ipconfigFTP_HAS_USER_PASSWORD_HOOK != 0 */ #if( ipconfigFTP_HAS_USER_PROPERTIES_HOOK != 0 )/*_RB_ Needs defaulting and adding to the web documentation. */ { FTPUserProperties_t xProperties; xProperties.pcRootDir = pxClient->pcRootDir; xProperties.xReadOnly = pdFALSE; xProperties.usPortNumber = pxClient->usClientPort; vApplicationFTPUserPropertiesHook( pxClient->pcFileName, &( xProperties ) ); if( xProperties.pcRootDir != NULL ) { pxClient->pcRootDir = xProperties.pcRootDir; } pxClient->bits.bReadOnly = ( xProperties.xReadOnly != pdFALSE_UNSIGNED ); } #endif /* ipconfigFTP_HAS_USER_PROPERTIES_HOOK */ break; case ECMD_PASS: /* Password. */ pxClient->ulRestartOffset = 0; if( pxClient->bits.bStatusUser == pdFALSE_UNSIGNED ) { pcMyReply = REPL_503; /* "503 Bad sequence of commands.\r\n". */ } else { BaseType_t xAllow; pxClient->bits.bStatusUser = pdFALSE_UNSIGNED; #if( ipconfigFTP_HAS_USER_PASSWORD_HOOK != 0 ) { xAllow = xApplicationFTPPasswordHook( pxClient->pcFileName, pcRestCommand ); } #else { xAllow = 1; } #endif /* ipconfigFTP_HAS_USER_PASSWORD_HOOK */ if( xAllow > 0 ) { pxClient->bits.bLoggedIn = pdTRUE_UNSIGNED; /* Client has now logged in. */ pcMyReply = "230 OK. Current directory is /\r\n"; } else { pcMyReply = "530 Login incorrect\r\n"; /* 530 Login incorrect. */ } strcpy( pxClient->pcCurrentDir, ( const char * ) "/" ); } break; case ECMD_SYST: /* System. */ snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "215 UNIX Type: L8\r\n" ); pcMyReply = pcCOMMAND_BUFFER; break; case ECMD_PWD: /* Get working directory. */ xMakeRelative( pxClient, pcFILE_BUFFER, sizeof( pcFILE_BUFFER ), pxClient->pcCurrentDir ); snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), REPL_257_PWD, pcFILE_BUFFER ); pcMyReply = pcCOMMAND_BUFFER; break; case ECMD_REST: if( pxClient->bits.bReadOnly != pdFALSE_UNSIGNED ) { pcMyReply = REPL_553_READ_ONLY; } else { const char *pcPtr = pcRestCommand; while( *pcPtr == ' ' ) { pcPtr++; } if( ( *pcPtr >= '0' ) && ( *pcPtr <= '9' ) ) { sscanf( pcPtr, "%lu", &pxClient->ulRestartOffset ); snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "350 Restarting at %lu. Send STORE or RETRIEVE\r\n", pxClient->ulRestartOffset ); pcMyReply = pcCOMMAND_BUFFER; } else { pcMyReply = REPL_500; /* 500 Syntax error, command unrecognised. */ } } break; case ECMD_NOOP: /* NOP operation */ if( pxClient->xTransferSocket != FREERTOS_NO_SOCKET ) { pcMyReply = REPL_200_PROGRESS; } else { pcMyReply = REPL_200; } break; case ECMD_TYPE: /* Ask or set transfer type. */ { /* e.g. "TYPE I" for Images (binary). */ BaseType_t xType = prvGetTransferType( pcRestCommand ); if( xType < 0 ) { /* TYPE not recognised. */ pcMyReply = REPL_500; } else { pxClient->xTransType = xType; pcMyReply = REPL_200; } } break; case ECMD_PASV: /* Enter passive mode. */ /* Connect passive: Server will listen() and wait for a connection. Start up a new data connection with 'xDoListen' set to true. */ if( prvTransferConnect( pxClient, pdTRUE ) == pdFALSE ) { pcMyReply = REPL_502; } else { uint32_t ulIP; uint16_t ulPort; struct freertos_sockaddr xLocalAddress; struct freertos_sockaddr xRemoteAddress; FreeRTOS_GetLocalAddress( pxClient->xTransferSocket, &xLocalAddress ); FreeRTOS_GetRemoteAddress( pxClient->xSocket, &xRemoteAddress ); ulIP = FreeRTOS_ntohl( xLocalAddress.sin_addr ); pxClient->ulClientIP = FreeRTOS_ntohl( xRemoteAddress.sin_addr ); ulPort = FreeRTOS_ntohs( xLocalAddress.sin_port ); pxClient->usClientPort = FreeRTOS_ntohs( xRemoteAddress.sin_port ); /* REPL_227_D "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d). */ snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), REPL_227_D, ( unsigned )ulIP >> 24, ( unsigned )( ulIP >> 16 ) & 0xFF, ( unsigned )( ulIP >> 8 ) & 0xFF, ( unsigned )ulIP & 0xFF, ( unsigned )ulPort >> 8, ( unsigned )ulPort & 0xFF ); pcMyReply = pcCOMMAND_BUFFER; } break; case ECMD_PORT: /* Active connection to the client. */ /* The client uses this command to tell the server to what client-side port the server should contact; use of this command indicates an active data transfer. e.g. PORT 192,168,1,2,4,19. */ { uint32_t ulIPAddress = 0; UBaseType_t uxPort; uxPort = prvParsePortData( pcRestCommand, &ulIPAddress ); FreeRTOS_printf( (" PORT %lxip:%ld\n", ulIPAddress, uxPort ) ); if( uxPort == 0u ) { pcMyReply = REPL_501; } else if( prvTransferConnect( pxClient, pdFALSE ) == pdFALSE ) { /* Call prvTransferConnect() with 'xDoListen' = false for an active connect(). */ pcMyReply = REPL_501; } else { pxClient->usClientPort = ( uint16_t ) uxPort; pxClient->ulClientIP = ulIPAddress; FreeRTOS_printf( ("Client address %lxip:%lu\n", ulIPAddress, uxPort ) ); pcMyReply = REPL_200; } } break; case ECMD_CWD: /* Change current working directory. */ prvChangeDir( pxClient, pcRestCommand ); break; case ECMD_RNFR: if( pxClient->bits.bReadOnly != pdFALSE_UNSIGNED ) { pcMyReply = REPL_553_READ_ONLY; } else { prvRenameFrom( pxClient, pcRestCommand ); } break; case ECMD_RNTO: if( pxClient->bits.bInRename == pdFALSE_UNSIGNED ) { pcMyReply = REPL_503; /* "503 Bad sequence of commands. */ } else { prvRenameTo( pxClient, pcRestCommand ); } break; case ECMD_SITE: /* Set file permissions */ if( pxClient->bits.bReadOnly != pdFALSE_UNSIGNED ) { pcMyReply = REPL_553_READ_ONLY; } else if( prvSiteCmd( pxClient, pcRestCommand ) == pdFALSE ) { pcMyReply = REPL_202; } break; case ECMD_DELE: if( pxClient->bits.bReadOnly != pdFALSE_UNSIGNED ) { pcMyReply = REPL_553_READ_ONLY; } else { prvDeleteFile( pxClient, pcRestCommand ); } break; case ECMD_MDTM: prvSizeDateFile( pxClient, pcRestCommand, pdTRUE ); break; case ECMD_SIZE: if( pxClient->pxWriteHandle != NULL ) { /* This SIZE query is probably about a file which is now being received. If so, return the value of pxClient->ulRecvBytes, pcRestCommand points to 'pcCommandBuffer', make it free by copying it to pcNewDir. */ xMakeAbsolute( pxClient, pcNEW_DIR, sizeof( pcNEW_DIR ), pcRestCommand ); if( strcmp( pcNEW_DIR, pcRestCommand ) == 0 ) { BaseType_t xCount; for( xCount = 0; xCount < 3 && pxClient->pxWriteHandle; xCount++ ) { prvStoreFileWork( pxClient ); } if( pxClient->pxWriteHandle != NULL ) { /* File being queried is still open, return number of bytes received until now. */ snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "213 %lu\r\n", pxClient->ulRecvBytes ); pcMyReply = pcCOMMAND_BUFFER; } /* otherwise, do a normal stat(). */ } strcpy( pcRestCommand, pcNEW_DIR ); } if( pcMyReply == NULL ) { prvSizeDateFile( pxClient, pcRestCommand, pdFALSE ); } break; case ECMD_MKD: case ECMD_RMD: if( pxClient->bits.bReadOnly != pdFALSE_UNSIGNED ) { pcMyReply = REPL_553_READ_ONLY; } else { prvMakeRemoveDir( pxClient, pcRestCommand, pxFTPCommand->ucCommandType == ECMD_RMD ); } break; case ECMD_CDUP: prvChangeDir( pxClient, ".." ); break; case ECMD_QUIT: prvSendReply( pxClient->xSocket, REPL_221, 0 ); pxClient->bits.bLoggedIn = pdFALSE_UNSIGNED; break; case ECMD_LIST: case ECMD_RETR: case ECMD_STOR: if( ( pxClient->xTransferSocket == FREERTOS_NO_SOCKET ) && ( ( pxFTPCommand->ucCommandType != ECMD_STOR ) || ( pxClient->bits1.bEmptyFile == pdFALSE_UNSIGNED ) ) ) { /* Sending "425 Can't open data connection." : Before receiving any of these commands, there must have been a PORT or PASV command, which causes the creation of a data socket. */ /* There is one exception: a STOR command is received while the data connection has already been closed. This is tested with the 'bEmptyFile' flag. */ pcMyReply = REPL_425; } else { /* In case an empty file was received ( bits1.bEmptyFile ), the transfer socket never delivered any data. Check if the transfer socket is still open: */ if( pxClient->xTransferSocket != FREERTOS_NO_SOCKET ) { prvTransferCheck( pxClient ); } switch( pxFTPCommand->ucCommandType ) { case ECMD_LIST: prvListSendPrep( pxClient ); break; case ECMD_RETR: prvRetrieveFilePrep( pxClient, pcRestCommand ); break; case ECMD_STOR: if( pxClient->bits.bReadOnly != pdFALSE_UNSIGNED ) { pcMyReply = REPL_553_READ_ONLY; } else { prvStoreFilePrep( pxClient, pcRestCommand ); if( pxClient->bits1.bEmptyFile != pdFALSE_UNSIGNED ) { /* Although the 'xTransferSocket' is closed already, call this function just for the logging. */ prvTransferCloseSocket( pxClient ); /* Close an empty file. */ prvTransferCloseFile( pxClient ); } } break; } } break; case ECMD_FEAT: { static const char pcFeatAnswer[] = "211-Features:\x0a" /* The MDTM command is only allowed when there is support for date&time. */ #if( ffconfigTIME_SUPPORT != 0 ) " MDTM\x0a" #endif " REST STREAM\x0a" " SIZE\x0d\x0a" "211 End\x0d\x0a"; pcMyReply = pcFeatAnswer; } break; case ECMD_UNKNOWN: FreeRTOS_printf( ("ftp::processCmd: Cmd %s unknown\n", pcRestCommand ) ); pcMyReply = REPL_500; break; } } if( pxFTPCommand->ucCommandType != ECMD_RNFR ) { pxClient->bits.bInRename = pdFALSE_UNSIGNED; } if( pcMyReply != NULL ) { xResult = prvSendReply( pxClient->xSocket, pcMyReply, strlen( pcMyReply ) ); } return xResult; } /*-----------------------------------------------------------*/ static BaseType_t prvTransferConnect( FTPClient_t *pxClient, BaseType_t xDoListen ) { Socket_t xSocket; BaseType_t xResult; /* Open a socket for a data connection with the FTP client. Happens after a PORT or a PASV command. */ /* Make sure the previous socket is deleted and flags reset */ prvTransferCloseSocket( pxClient ); pxClient->bits1.bEmptyFile = pdFALSE_UNSIGNED; xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP ); if( ( xSocket != FREERTOS_NO_SOCKET ) && ( xSocket != FREERTOS_INVALID_SOCKET ) ) { BaseType_t xSmallTimeout = pdMS_TO_TICKS( 100 ); struct freertos_sockaddr xAddress; #if( ipconfigFTP_TX_BUFSIZE > 0 ) WinProperties_t xWinProps; #endif xAddress.sin_addr = FreeRTOS_GetIPAddress( ); /* Single NIC, currently not used */ xAddress.sin_port = FreeRTOS_htons( 0 ); /* Bind to any available port number */ FreeRTOS_bind( xSocket, &xAddress, sizeof( xAddress ) ); #if( ipconfigFTP_TX_BUFSIZE > 0 ) { /* Fill in the buffer and window sizes that will be used by the socket. */ xWinProps.lTxBufSize = ipconfigFTP_TX_BUFSIZE; xWinProps.lTxWinSize = ipconfigFTP_TX_WINSIZE; xWinProps.lRxBufSize = ipconfigFTP_RX_BUFSIZE; xWinProps.lRxWinSize = ipconfigFTP_RX_WINSIZE; /* Set the window and buffer sizes. */ FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_WIN_PROPERTIES, ( void * ) &xWinProps, sizeof( xWinProps ) ); } #endif FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xSmallTimeout, sizeof( BaseType_t ) ); FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xSmallTimeout, sizeof( BaseType_t ) ); /* The same instance of the socket will be used for the connection and data transport. */ if( xDoListen != pdFALSE ) { BaseType_t xTrueValue = pdTRUE; FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_REUSE_LISTEN_SOCKET, ( void * ) &xTrueValue, sizeof( xTrueValue ) ); } pxClient->bits1.bIsListen = xDoListen; pxClient->xTransferSocket = xSocket; if( xDoListen != pdFALSE ) { FreeRTOS_FD_SET( xSocket, pxClient->pxParent->xSocketSet, eSELECT_EXCEPT | eSELECT_READ ); /* Calling FreeRTOS_listen( ) */ xResult = prvTransferStart( pxClient ); if( xResult >= 0 ) { xResult = pdTRUE; } } else { FreeRTOS_FD_SET( xSocket, pxClient->pxParent->xSocketSet, eSELECT_EXCEPT | eSELECT_READ | eSELECT_WRITE ); xResult = pdTRUE; } } else { FreeRTOS_printf( ( "FreeRTOS_socket() failed\n" ) ); xResult = -pdFREERTOS_ERRNO_ENOMEM; } /* An active socket (PORT) should connect() later. */ return xResult; } /*-----------------------------------------------------------*/ static BaseType_t prvTransferStart( FTPClient_t *pxClient ) { BaseType_t xResult; /* A transfer socket has been opened, now either call listen() for 'PASV' or connect() for the 'PORT' command. */ if( pxClient->bits1.bIsListen != pdFALSE_UNSIGNED ) { xResult = FreeRTOS_listen( pxClient->xTransferSocket, 1 ); } else { struct freertos_sockaddr xAddress; xAddress.sin_addr = FreeRTOS_htonl( pxClient->ulClientIP ); xAddress.sin_port = FreeRTOS_htons( pxClient->usClientPort ); /* Start an active connection for this data socket */ xResult = FreeRTOS_connect( pxClient->xTransferSocket, &xAddress, sizeof( xAddress ) ); } return xResult; } /*-----------------------------------------------------------*/ static void prvTransferCheck( FTPClient_t *pxClient ) { BaseType_t xRxSize; /* A data transfer is busy. Check if there are changes in connectedness. */ xRxSize = FreeRTOS_rx_size( pxClient->xTransferSocket ); if( pxClient->bits1.bClientConnected == pdFALSE_UNSIGNED ) { /* The time to receive a small file can be so short, that we don't even see that the socket gets connected and disconnected. Therefore, check the sizeof of the RX buffer. */ { struct freertos_sockaddr xAddress; Socket_t xNexSocket; socklen_t xSocketLength = sizeof( xAddress ); if( pxClient->bits1.bIsListen != pdFALSE_UNSIGNED ) { xNexSocket = FreeRTOS_accept( pxClient->xTransferSocket, &xAddress, &xSocketLength); if( ( ( xNexSocket != FREERTOS_NO_SOCKET ) && ( xNexSocket != FREERTOS_INVALID_SOCKET ) ) || xRxSize > 0 ) { pxClient->bits1.bClientConnected = pdTRUE_UNSIGNED; } } else { if( FreeRTOS_issocketconnected( pxClient->xTransferSocket ) > 0 || xRxSize > 0 ) { pxClient->bits1.bClientConnected = pdTRUE_UNSIGNED; } } if( pxClient->bits1.bClientConnected != pdFALSE_UNSIGNED ) { pxClient->bits1.bEmptyFile = pdFALSE_UNSIGNED; #if( ipconfigHAS_PRINTF != 0 ) { struct freertos_sockaddr xRemoteAddress, xLocalAddress; FreeRTOS_GetRemoteAddress( pxClient->xTransferSocket, &xRemoteAddress ); FreeRTOS_GetLocalAddress( pxClient->xTransferSocket, &xLocalAddress ); FreeRTOS_printf( ( "%s Connected from %u to %u\n", pxClient->bits1.bIsListen != pdFALSE_UNSIGNED ? "PASV" : "PORT", ( unsigned ) FreeRTOS_ntohs( xLocalAddress.sin_port ), ( unsigned ) FreeRTOS_ntohs( xRemoteAddress.sin_port ) ) ); } #endif /* ipconfigHAS_PRINTF */ FreeRTOS_FD_CLR( pxClient->xTransferSocket, pxClient->pxParent->xSocketSet, eSELECT_WRITE ); FreeRTOS_FD_SET( pxClient->xTransferSocket, pxClient->pxParent->xSocketSet, eSELECT_READ|eSELECT_EXCEPT ); } } } if ( pxClient->bits1.bClientConnected != pdFALSE_UNSIGNED ) { if( pxClient->pcConnectionAck[ 0 ] != '\0' ) { BaseType_t xLength; BaseType_t xRemotePort; struct freertos_sockaddr xRemoteAddress; FreeRTOS_GetRemoteAddress( pxClient->xTransferSocket, &xRemoteAddress ); xRemotePort = FreeRTOS_ntohs( xRemoteAddress.sin_port ); /* Tell on the command port 21 we have a data connection */ xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), pxClient->pcConnectionAck, pxClient->ulClientIP, xRemotePort ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); pxClient->pcConnectionAck[ 0 ] = '\0'; } if( ( FreeRTOS_issocketconnected( pxClient->xTransferSocket ) == pdFALSE ) && FreeRTOS_rx_size( pxClient->xTransferSocket ) == 0 ) { prvTransferCloseSocket( pxClient ); prvTransferCloseFile( pxClient ); } } } /*-----------------------------------------------------------*/ static void prvTransferCloseSocket( FTPClient_t *pxClient ) { if( pxClient->xTransferSocket != FREERTOS_NO_SOCKET ) { /* DEBUGGING ONLY */ BaseType_t xRxSize = FreeRTOS_rx_size( pxClient->xTransferSocket ); if( xRxSize > 0 ) { BaseType_t xRxSize2; BaseType_t xStatus; prvStoreFileWork( pxClient ); xStatus = FreeRTOS_connstatus( pxClient->xTransferSocket ); xRxSize2 = FreeRTOS_rx_size( pxClient->xTransferSocket ); FreeRTOS_printf( ( "FTP: WARNING: %s: RX size = %ld -> %ld (%s)\n", FreeRTOS_GetTCPStateName( xStatus ), xRxSize, xRxSize2, pxClient->pcFileName ) ); if( xRxSize2 > 1 ) { return; } /* Remove compiler warnings in case FreeRTOS_printf() is not defined. */ ( void ) xStatus; } } if( ( pxClient->pxWriteHandle != NULL ) || ( pxClient->pxReadHandle != NULL ) ) { BaseType_t xLength; char pcStrBuf[ 32 ]; if( pxClient->bits1.bHadError == pdFALSE_UNSIGNED ) { xLength = snprintf( pxClient->pcClientAck, sizeof( pxClient->pcClientAck ), "226 Closing connection %d bytes transmitted\r\n", ( int ) pxClient->ulRecvBytes ); } else { xLength = snprintf( pxClient->pcClientAck, sizeof( pxClient->pcClientAck ), "451 Requested action aborted after %d bytes\r\n", ( int ) pxClient->ulRecvBytes ); } /* Tell on the command socket the data connection is now closed. */ prvSendReply( pxClient->xSocket, pxClient->pcClientAck, xLength ); #if( ipconfigHAS_PRINTF != 0 ) { TickType_t xDelta; uint32_t ulAverage; xDelta = xTaskGetTickCount( ) - pxClient->xStartTime; ulAverage = ulGetAverage( pxClient->ulRecvBytes, xDelta ); FreeRTOS_printf( ("FTP: %s: '%s' %lu Bytes (%s/sec)\n", pxClient->pxReadHandle ? "sent" : "recv", pxClient->pcFileName, pxClient->ulRecvBytes, pcMkSize( ulAverage, pcStrBuf, sizeof( pcStrBuf ) ) ) ); } #endif } if( pxClient->xTransferSocket != FREERTOS_NO_SOCKET ) { FreeRTOS_FD_CLR( pxClient->xTransferSocket, pxClient->pxParent->xSocketSet, eSELECT_ALL ); FreeRTOS_closesocket( pxClient->xTransferSocket ); pxClient->xTransferSocket = FREERTOS_NO_SOCKET; if( pxClient->ulRecvBytes == 0ul ) { /* Received zero bytes: an empty file */ pxClient->bits1.bEmptyFile = pdTRUE_UNSIGNED; } else { pxClient->bits1.bEmptyFile = pdFALSE_UNSIGNED; } } pxClient->bits1.bIsListen = pdFALSE_UNSIGNED; pxClient->bits1.bDirHasEntry = pdFALSE_UNSIGNED; pxClient->bits1.bClientConnected = pdFALSE_UNSIGNED; pxClient->bits1.bHadError = pdFALSE_UNSIGNED; } /*-----------------------------------------------------------*/ static void prvTransferCloseFile( FTPClient_t *pxClient ) { if( pxClient->pxWriteHandle != NULL ) { ff_fclose( pxClient->pxWriteHandle ); pxClient->pxWriteHandle = NULL; #if( ipconfigFTP_HAS_RECEIVED_HOOK != 0 ) { vApplicationFTPReceivedHook( pxClient->pcFileName, pxClient->ulRecvBytes, pxClient ); } #endif } if( pxClient->pxReadHandle != NULL ) { ff_fclose( pxClient->pxReadHandle ); pxClient->pxReadHandle = NULL; } /* These two field are only used for logging / file-statistics */ pxClient->ulRecvBytes = 0ul; pxClient->xStartTime = 0ul; } /*-----------------------------------------------------------*/ /** * Guess the transfer type, given the client requested type. * Actually in unix there is no difference between binary and * ascii mode when we work with file descriptors. * If #type is not recognized as a valid client request, -1 is returned. */ static BaseType_t prvGetTransferType( const char *pcType ) { BaseType_t xResult = -1; if( pcType != NULL ) { BaseType_t xLength = strlen( pcType ); if( xLength == 0 ) { return -1; } switch( pcType[ 0 ] ) { case 'I': xResult = TMODE_BINARY; break; case 'A': xResult = TMODE_ASCII; break; case 'L': if( xLength >= 3 ) { if( pcType[ 2 ] == '7' ) { xResult = TMODE_7BITS; } else if( pcType[ 2 ] == '8' ) { xResult = TMODE_7BITS; } } break; } } return xResult; } /*-----------------------------------------------------------*/ #if( ipconfigHAS_PRINTF != 0 ) #define SIZE_1_GB ( 1024ul * 1024ul * 1024ul ) #define SIZE_1_MB ( 1024ul * 1024ul ) #define SIZE_1_KB ( 1024ul ) static const char *pcMkSize( uint32_t ulAmount, char *pcBuffer, BaseType_t xBufferSize ) { uint32_t ulGB, ulMB, ulKB, ulByte; ulGB = ( ulAmount / SIZE_1_GB ); ulAmount -= ( ulGB * SIZE_1_GB ); ulMB = ( ulAmount / SIZE_1_MB ); ulAmount -= ( ulMB * SIZE_1_MB ); ulKB = ( ulAmount / SIZE_1_KB ); ulAmount -= ( ulKB * SIZE_1_KB ); ulByte = ( ulAmount ); if (ulGB != 0ul ) { snprintf( pcBuffer, xBufferSize, "%lu.%02lu GB", ulGB, (100 * ulMB) / SIZE_1_KB ); } else if( ulMB != 0ul ) { snprintf( pcBuffer, xBufferSize, "%lu.%02lu MB", ulMB, (100 * ulKB) / SIZE_1_KB ); } else if( ulKB != 0ul ) { snprintf(pcBuffer, xBufferSize, "%lu.%02lu KB", ulKB, (100 * ulByte) / SIZE_1_KB ); } else { snprintf( pcBuffer, xBufferSize, "%lu bytes", ulByte ); } return pcBuffer; } /*-----------------------------------------------------------*/ #endif /* ipconfigHAS_PRINTF != 0 */ #if( ipconfigHAS_PRINTF != 0 ) static uint32_t ulGetAverage( uint32_t ulAmount, TickType_t xDeltaMs ) { uint32_t ulAverage; /* Get the average amount of bytes per seconds. Ideally this is calculated by Multiplying with 1000 and dividing by milliseconds: ulAverage = ( 1000ul * ulAmount ) / xDeltaMs; Now get a maximum precision, while avoiding an arithmetic overflow: */ if( xDeltaMs == 0ul ) { /* Time is zero, there is no average */ ulAverage = 0ul; } else if( ulAmount >= ( ~0ul / 10ul ) ) { /* More than 409 MB has been transferred, do not multiply. */ ulAverage = ( ulAmount / ( xDeltaMs / 1000ul ) ); } else if( ulAmount >= ( ~0ul / 100ul ) ) { /* Between 409 and 41 MB has been transferred, can multiply by 10. */ ulAverage = ( ( ulAmount * 10ul ) / ( xDeltaMs / 100ul ) ); } else if( ulAmount >= ( ~0ul / 1000ul ) ) { /* Between 4.1 MB and 41 has been transferred, can multiply by 100. */ ulAverage = ( ( ulAmount * 100ul ) / ( xDeltaMs / 10ul ) ); } else { /* Less than 4.1 MB: can multiply by 1000. */ ulAverage = ( ( ulAmount * 1000ul ) / xDeltaMs ); } return ulAverage; } /*-----------------------------------------------------------*/ #endif /* ipconfigHAS_PRINTF != 0 */ static UBaseType_t prvParsePortData( const char *pcCommand, uint32_t *pulIPAddress ) { /*_HT_ Using 'unsigned' here because when sscanf() sees '%u', it expects a pointer to 'unsigned'. Not sure about the sscanf() format for UBaseType_t ? */ unsigned h1, h2, h3, h4, p1, p2; char sep; UBaseType_t uxResult; /* Expect PORT h1,h2,h3,h4,p1,p2 */ if (sscanf (pcCommand, "%u%c%u%c%u%c%u%c%u%c%u", &h1, &sep, &h2, &sep, &h3, &sep, &h4, &sep, &p1, &sep, &p2) != 11) { uxResult= 0u; } else { /* Put in network byte order. */ *pulIPAddress = ( ( uint32_t ) h1 << 24 ) | ( ( uint32_t ) h2 << 16 ) | ( ( uint32_t ) h3 << 8 ) | ( ( uint32_t ) h4 ); uxResult = ( p1 << 8 ) | p2; } return uxResult; } /*-----------------------------------------------------------*/ /* #### ####### # ### # # # # ## # # # # # # # # # ###### #### ### ## #### # # ### # #### ## # # # # # # # # ##### # # # # ## # # # ## # ###### # # # # ###### # # # # # # # # # # # # # # ## # # # # ## # # # # ## #### ## #### #### #### #### ##### ##### #### */ static BaseType_t prvStoreFilePrep( FTPClient_t *pxClient, char *pcFileName ) { BaseType_t xResult; FF_FILE *pxNewHandle; size_t uxFileSize = 0ul; int iErrorNo; /* Close previous handle (if any) and reset file transfer parameters. */ prvTransferCloseFile( pxClient ); xMakeAbsolute( pxClient, pxClient->pcFileName, sizeof( pxClient->pcFileName ), pcFileName ); pxNewHandle = NULL; if( pxClient->ulRestartOffset != 0 ) { size_t uxOffset = pxClient->ulRestartOffset; int32_t lRc; pxClient->ulRestartOffset = 0ul; /* Only use 1 time. */ pxNewHandle = ff_fopen( pxClient->pcFileName, "ab" ); if( pxNewHandle != NULL ) { uxFileSize = pxNewHandle->ulFileSize; if( uxOffset <= uxFileSize ) { lRc = ff_fseek( pxNewHandle, uxOffset, FF_SEEK_SET ); } else { /* Won't even try to seek after EOF */ lRc = -pdFREERTOS_ERRNO_EINVAL; } if( lRc != 0 ) { BaseType_t xLength; xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "450 Seek invalid %u length %u\r\n", ( unsigned ) uxOffset, ( unsigned ) uxFileSize ); /* "Requested file action not taken". */ prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); FreeRTOS_printf( ( "ftp::storeFile: create %s: Seek %u length %u\n", pxClient->pcFileName, ( unsigned ) uxOffset, ( unsigned ) uxFileSize ) ); ff_fclose( pxNewHandle ); pxNewHandle = NULL; } } } else { pxNewHandle = ff_fopen( pxClient->pcFileName, "wb" ); } if( pxNewHandle == NULL ) { iErrorNo = stdioGET_ERRNO(); if( iErrorNo == pdFREERTOS_ERRNO_ENOSPC ) { prvSendReply( pxClient->xSocket, REPL_552, 0 ); } else { /* "Requested file action not taken". */ prvSendReply( pxClient->xSocket, REPL_450, 0 ); } FreeRTOS_printf( ( "ftp::storeFile: create %s: %s (errno %d)\n", pxClient->pcFileName, ( const char* ) strerror( iErrorNo ), iErrorNo ) ); xResult = pdFALSE; } else { if( pxClient->bits1.bIsListen ) { /* True if PASV is used. */ snprintf( pxClient->pcConnectionAck, sizeof( pxClient->pcConnectionAck ), "150 Accepted data connection from %%xip:%%u\r\n" ); prvTransferCheck( pxClient ); } else { BaseType_t xLength; xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "150 Opening BIN connection to store file\r\n" ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); pxClient->pcConnectionAck[ 0 ] = '\0'; prvTransferStart( pxClient ); /* Now active connect. */ } pxClient->pxWriteHandle = pxNewHandle; /* To get some statistics about the performance. */ pxClient->xStartTime = xTaskGetTickCount( ); xResult = pdTRUE; } return xResult; } /*-----------------------------------------------------------*/ #if( ipconfigFTP_ZERO_COPY_ALIGNED_WRITES == 0 ) static BaseType_t prvStoreFileWork( FTPClient_t *pxClient ) { BaseType_t xRc, xWritten; /* Read from the data socket until all has been read or until a negative value is returned. */ for( ; ; ) { char *pcBuffer; /* The "zero-copy" method: */ xRc = FreeRTOS_recv( pxClient->xTransferSocket, ( void * ) &pcBuffer, 0x20000u, FREERTOS_ZERO_COPY | FREERTOS_MSG_DONTWAIT ); if( xRc <= 0 ) { break; } pxClient->ulRecvBytes += xRc; xWritten = ff_fwrite( pcBuffer, 1, xRc, pxClient->pxWriteHandle ); FreeRTOS_recv( pxClient->xTransferSocket, ( void * ) NULL, xRc, 0 ); if( xWritten != xRc ) { xRc = -1; /* bHadError: a transfer got aborted because of an error. */ pxClient->bits1.bHadError = pdTRUE_UNSIGNED; break; } } return xRc; } #else /* ipconfigFTP_ZERO_COPY_ALIGNED_WRITES != 0 */ #if !defined( ipconfigFTP_PREFERRED_WRITE_SIZE ) /* If you store data on flash, it may be profitable to give 'ipconfigFTP_PREFERRED_WRITE_SIZE' the same size as the size of the flash' erase blocks, e.g. 4KB */ #define ipconfigFTP_PREFERRED_WRITE_SIZE 512ul #endif static BaseType_t prvStoreFileWork( FTPClient_t *pxClient ) { BaseType_t xRc, xWritten; /* Read from the data socket until all has been read or until a negative value is returned. */ for( ; ; ) { char *pcBuffer; UBaseType_t xStatus; /* The "zero-copy" method: */ xRc = FreeRTOS_recv( pxClient->xTransferSocket, ( void * ) &pcBuffer, 0x20000u, FREERTOS_ZERO_COPY | FREERTOS_MSG_DONTWAIT ); if( xRc <= 0 ) { /* There are no data or the connection is closed. */ break; } xStatus = FreeRTOS_connstatus( pxClient->xTransferSocket ); if( xStatus != eESTABLISHED ) { /* The connection is not established (any more), therefore accept any amount of bytes, probably the last few bytes. */ } else { if( xRc >= ipconfigFTP_PREFERRED_WRITE_SIZE ) { /* More than a sector to write, round down to a multiple of PREFERRED_WRITE_SIZE bytes. */ xRc = ( xRc / ipconfigFTP_PREFERRED_WRITE_SIZE ) * ipconfigFTP_PREFERRED_WRITE_SIZE; } else { const StreamBuffer_t *pxBuffer = FreeRTOS_get_rx_buf( pxClient->xTransferSocket ); size_t uxSpace = pxBuffer->LENGTH - pxBuffer->uxTail; if( uxSpace >= ipconfigFTP_PREFERRED_WRITE_SIZE ) { /* At this moment there are les than PREFERRED_WRITE_SIZE bytes in the RX buffer, but there is space for more. Just return and wait for more. */ xRc = 0; } else { /* Now reading beyond the end of the circular buffer, use a normal read. */ pcBuffer = pcFILE_BUFFER; xRc = FreeRTOS_recvcount( pxClient->xTransferSocket ); xRc = ( xRc / ipconfigFTP_PREFERRED_WRITE_SIZE ) * ipconfigFTP_PREFERRED_WRITE_SIZE; if( xRc > 0 ) { xRc = FreeRTOS_recv( pxClient->xTransferSocket, ( void * ) pcBuffer, sizeof( pcFILE_BUFFER ), FREERTOS_MSG_DONTWAIT ); } } } } if( xRc == 0 ) { break; } pxClient->ulRecvBytes += xRc; xWritten = ff_fwrite( pcBuffer, 1, xRc, pxClient->pxWriteHandle ); if( pcBuffer != pcFILE_BUFFER ) { FreeRTOS_recv( pxClient->xTransferSocket, ( void * ) NULL, xRc, 0 ); } if( xWritten != xRc ) { xRc = -1; /* bHadError: a transfer got aborted because of an error. */ pxClient->bits1.bHadError = pdTRUE_UNSIGNED; break; } } return xRc; } #endif /* ipconfigFTP_ZERO_COPY_ALIGNED_WRITES */ /*-----------------------------------------------------------*/ /* ###### # ####### # ### # # # # # ## # # # # # # # # # # #### ###### ### ## ### #### # # #### # # ### # #### ###### # # # # # # # # # # # # # ##### # # # # # ## ###### # ## # # ###### # # ###### # # # # ###### # # # # # # # # # # # # # # # # # ## # ## # # # ## # # # ## # # # # ## ### ## #### ## #### ##### #### ## #### #### ##### ##### #### */ static BaseType_t prvRetrieveFilePrep( FTPClient_t *pxClient, char *pcFileName ) { BaseType_t xResult = pdTRUE; size_t uxFileSize; /* Close previous handle (if any) and reset file transfer parameters */ prvTransferCloseFile( pxClient ); xMakeAbsolute( pxClient, pxClient->pcFileName, sizeof( pxClient->pcFileName ), pcFileName ); pxClient->pxReadHandle = ff_fopen( pxClient->pcFileName, "rb" ); if( pxClient->pxReadHandle == NULL ) { int iErrno = stdioGET_ERRNO(); /* "Requested file action not taken". */ prvSendReply( pxClient->xSocket, REPL_450, 0 ); FreeRTOS_printf( ("prvRetrieveFilePrep: open '%s': errno %d: %s\n", pxClient->pcFileName, iErrno, ( const char * ) strerror( iErrno ) ) ); uxFileSize = 0ul; xResult = pdFALSE; } else { uxFileSize = pxClient->pxReadHandle->ulFileSize; pxClient->uxBytesLeft = uxFileSize; if( pxClient->ulRestartOffset != 0ul ) { size_t uxOffset = pxClient->ulRestartOffset; int32_t iRc; /* Only use 1 time. */ pxClient->ulRestartOffset = 0; if( uxOffset < uxFileSize ) { iRc = ff_fseek( pxClient->pxReadHandle, uxOffset, FF_SEEK_SET ); } else { iRc = -pdFREERTOS_ERRNO_EINVAL; } if( iRc != 0 ) { BaseType_t xLength; xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "450 Seek invalid %u length %u\r\n", ( unsigned ) uxOffset, ( unsigned ) uxFileSize ); /* "Requested file action not taken". */ prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); FreeRTOS_printf( ( "prvRetrieveFilePrep: create %s: Seek %u length %u\n", pxClient->pcFileName, ( unsigned ) uxOffset, ( unsigned ) uxFileSize ) ); ff_fclose( pxClient->pxReadHandle ); pxClient->pxReadHandle = NULL; xResult = pdFALSE; } else { pxClient->uxBytesLeft = uxFileSize - pxClient->ulRestartOffset; } } } if( xResult != pdFALSE ) { if( pxClient->bits1.bIsListen != pdFALSE_UNSIGNED ) { /* True if PASV is used. */ snprintf( pxClient->pcConnectionAck, sizeof( pxClient->pcConnectionAck ), "150%cAccepted data connection from %%xip:%%u\r\n%s", pxClient->xTransType == TMODE_ASCII ? '-' : ' ', pxClient->xTransType == TMODE_ASCII ? "150 NOTE: ASCII mode requested, but binary mode used\r\n" : "" ); } else { BaseType_t xLength; xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "150%cOpening data connection to %lxip:%u\r\n%s", pxClient->xTransType == TMODE_ASCII ? '-' : ' ', pxClient->ulClientIP, pxClient->usClientPort, pxClient->xTransType == TMODE_ASCII ? "150 NOTE: ASCII mode requested, but binary mode used\r\n" : "" ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); pxClient->pcConnectionAck[ 0 ] = '\0'; prvTransferStart( pxClient ); } /* Prepare the ACK which will be sent when all data has been sent. */ snprintf( pxClient->pcClientAck, sizeof( pxClient->pcClientAck ), "%s", REPL_226 ); /* To get some statistics about the performance. */ pxClient->xStartTime = xTaskGetTickCount( ); if( uxFileSize == 0ul ) { FreeRTOS_shutdown( pxClient->xTransferSocket, FREERTOS_SHUT_RDWR ); } } return xResult; } /*-----------------------------------------------------------*/ static BaseType_t prvRetrieveFileWork( FTPClient_t *pxClient ) { size_t uxSpace; size_t uxCount, uxItemsRead; BaseType_t xRc = 0; BaseType_t xSetEvent = pdFALSE; do { #if( ipconfigFTP_TX_ZERO_COPY != 0 ) char *pcBuffer; BaseType_t xBufferLength; #endif /* ipconfigFTP_TX_ZERO_COPY */ /* Take the lesser of the two: tx_space (number of bytes that can be queued for transmission) and uxBytesLeft (the number of bytes left to read from the file) */ uxSpace = FreeRTOS_tx_space( pxClient->xTransferSocket ); if( uxSpace == 0 ) { FreeRTOS_FD_SET( pxClient->xTransferSocket, pxClient->pxParent->xSocketSet, eSELECT_WRITE | eSELECT_EXCEPT ); xRc = FreeRTOS_select( pxClient->pxParent->xSocketSet, 200 ); uxSpace = FreeRTOS_tx_space( pxClient->xTransferSocket ); } uxCount = FreeRTOS_min_uint32( pxClient->uxBytesLeft, uxSpace ); if( uxCount == 0 ) { break; } #if( ipconfigFTP_TX_ZERO_COPY == 0 ) { if( uxCount > sizeof( pcFILE_BUFFER ) ) { uxCount = sizeof( pcFILE_BUFFER ); } uxItemsRead = ff_fread( pcFILE_BUFFER, 1, uxCount, pxClient->pxReadHandle ); if( uxItemsRead != uxCount ) { FreeRTOS_printf( ( "prvRetrieveFileWork: Got %u Expected %u\n", ( unsigned )uxItemsRead, ( unsigned ) uxCount ) ); xRc = FreeRTOS_shutdown( pxClient->xTransferSocket, FREERTOS_SHUT_RDWR ); pxClient->uxBytesLeft = 0u; break; } pxClient->uxBytesLeft -= uxCount; if( pxClient->uxBytesLeft == 0u ) { BaseType_t xTrueValue = 1; FreeRTOS_setsockopt( pxClient->xTransferSocket, 0, FREERTOS_SO_CLOSE_AFTER_SEND, ( void * ) &xTrueValue, sizeof( xTrueValue ) ); } xRc = FreeRTOS_send( pxClient->xTransferSocket, pcFILE_BUFFER, uxCount, 0 ); } #else /* ipconfigFTP_TX_ZERO_COPY != 0 */ { /* Use zero-copy transmission: FreeRTOS_get_tx_head() returns a direct pointer to the TX stream and set xBufferLength to know how much space there is left. */ pcBuffer = ( char * )FreeRTOS_get_tx_head( pxClient->xTransferSocket, &xBufferLength ); if( ( pcBuffer != NULL ) && ( xBufferLength >= 512 ) ) { /* Will read disk data directly to the TX stream of the socket. */ uxCount = FreeRTOS_min_uint32( uxCount, ( uint32_t )xBufferLength ); if( uxCount > ( size_t ) 0x40000u ) { uxCount = ( size_t ) 0x40000u; } } else { /* Use the normal file i/o buffer. */ pcBuffer = pcFILE_BUFFER; if( uxCount > sizeof( pcFILE_BUFFER ) ) { uxCount = sizeof( pcFILE_BUFFER ); } } if ( pxClient->uxBytesLeft >= 1024u ) { uxCount &= ~( ( size_t ) 512u - 1u ); } if( uxCount <= 0u ) { /* Nothing to send after rounding down to a multiple of a sector size. */ break; } uxItemsRead = ff_fread( pcBuffer, 1, uxCount, pxClient->pxReadHandle ); if( uxCount != uxItemsRead ) { FreeRTOS_printf( ( "prvRetrieveFileWork: Got %u Expected %u\n", ( unsigned )uxItemsRead, ( unsigned )uxCount ) ); xRc = FreeRTOS_shutdown( pxClient->xTransferSocket, FREERTOS_SHUT_RDWR ); pxClient->uxBytesLeft = 0u; break; } pxClient->uxBytesLeft -= uxCount; if( pxClient->uxBytesLeft == 0u ) { BaseType_t xTrueValue = 1; FreeRTOS_setsockopt( pxClient->xTransferSocket, 0, FREERTOS_SO_CLOSE_AFTER_SEND, ( void * ) &xTrueValue, sizeof( xTrueValue ) ); } if( pcBuffer != pcFILE_BUFFER ) { pcBuffer = NULL; } xRc = FreeRTOS_send( pxClient->xTransferSocket, pcBuffer, uxCount, 0 ); } #endif /* ipconfigFTP_TX_ZERO_COPY */ if( xRc < 0 ) { break; } pxClient->ulRecvBytes += xRc; if( pxClient->uxBytesLeft == 0u ) { break; } } while( uxCount > 0u ); if( xRc < 0 ) { FreeRTOS_printf( ( "prvRetrieveFileWork: already disconnected\n" ) ); } else if( pxClient->uxBytesLeft <= 0u ) { BaseType_t x; for( x = 0; x < 5; x++ ) { xRc = FreeRTOS_recv( pxClient->xTransferSocket, pcFILE_BUFFER, sizeof( pcFILE_BUFFER ), 0 ); if( xRc < 0 ) { break; } } // FreeRTOS_printf( ( "prvRetrieveFileWork: %s all sent: xRc %ld\n", pxClient->pcFileName, xRc ) ); } else { FreeRTOS_FD_SET( pxClient->xTransferSocket, pxClient->pxParent->xSocketSet, eSELECT_WRITE ); xSetEvent = pdTRUE; } if( xSetEvent == pdFALSE ) { FreeRTOS_FD_CLR( pxClient->xTransferSocket, pxClient->pxParent->xSocketSet, eSELECT_WRITE ); } return xRc; } /*-----------------------------------------------------------*/ /* ### ##### #### ##### # # # # # # # # # # # # # # # # # # ## # # # # ## # # # # # # # # # # # # # ####### ##### #### #### */ /* Prepare sending a directory LIST */ static BaseType_t prvListSendPrep( FTPClient_t *pxClient ) { BaseType_t xFindResult; int iErrorNo; if( pxClient->bits1.bIsListen != pdFALSE_UNSIGNED ) { /* True if PASV is used */ snprintf( pxClient->pcConnectionAck, sizeof( pxClient->pcConnectionAck ), "150 Accepted data connection from %%xip:%%u\r\n" ); } else { BaseType_t xLength; /* Here the FTP server is supposed to connect() */ xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "150 Opening ASCII mode data connection to for /bin/ls \r\n" ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); /* Clear the current connection acknowledge message */ pxClient->pcConnectionAck[ 0 ] = '\0'; prvTransferStart( pxClient ); } pxClient->xDirCount = 0; xMakeAbsolute( pxClient, pcNEW_DIR, sizeof( pcNEW_DIR ), pxClient->pcCurrentDir ); xFindResult = ff_findfirst( pcNEW_DIR, &pxClient->xFindData ); pxClient->bits1.bDirHasEntry = ( xFindResult >= 0 ); iErrorNo = stdioGET_ERRNO(); if( ( xFindResult < 0 ) && ( iErrorNo == pdFREERTOS_ERRNO_ENMFILE ) ) { FreeRTOS_printf( ("prvListSendPrep: Empty directory? (%s)\n", pxClient->pcCurrentDir ) ); prvSendReply( pxClient->xTransferSocket, "total 0\r\n", 0 ); pxClient->xDirCount++; } else if( xFindResult < 0 ) { FreeRTOS_printf( ( "prvListSendPrep: rc = %ld iErrorNo = %d\n", xFindResult, iErrorNo ) ); prvSendReply( pxClient->xSocket, REPL_451, 0 ); } pxClient->pcClientAck[ 0 ] = '\0'; return pxClient->xDirCount; } /*-----------------------------------------------------------*/ #define MAX_DIR_LIST_ENTRY_SIZE 256 static BaseType_t prvListSendWork( FTPClient_t *pxClient ) { BaseType_t xTxSpace; while( pxClient->bits1.bClientConnected != pdFALSE_UNSIGNED ) { char *pcWritePtr = pcCOMMAND_BUFFER; BaseType_t xWriteLength; xTxSpace = FreeRTOS_tx_space( pxClient->xTransferSocket ); if( xTxSpace > ( BaseType_t ) sizeof( pcCOMMAND_BUFFER ) ) { xTxSpace = sizeof( pcCOMMAND_BUFFER ); } while( ( xTxSpace >= MAX_DIR_LIST_ENTRY_SIZE ) && ( pxClient->bits1.bDirHasEntry != pdFALSE_UNSIGNED ) ) { BaseType_t xLength, xEndOfDir; int32_t iRc; int iErrorNo; xLength = prvGetFileInfoStat( &( pxClient->xFindData.xDirectoryEntry ), pcWritePtr, xTxSpace ); pxClient->xDirCount++; pcWritePtr += xLength; xTxSpace -= xLength; iRc = ff_findnext( &pxClient->xFindData ); iErrorNo = stdioGET_ERRNO(); xEndOfDir = ( iRc < 0 ) && ( iErrorNo == pdFREERTOS_ERRNO_ENMFILE ); pxClient->bits1.bDirHasEntry = ( xEndOfDir == pdFALSE ) && ( iRc >= 0 ); if( ( iRc < 0 ) && ( xEndOfDir == pdFALSE ) ) { FreeRTOS_printf( ("prvListSendWork: %s (rc %08x)\n", ( const char * ) strerror( iErrorNo ), ( unsigned )iRc ) ); } } xWriteLength = ( BaseType_t ) ( pcWritePtr - pcCOMMAND_BUFFER ); if( xWriteLength == 0 ) { break; } if( pxClient->bits1.bDirHasEntry == pdFALSE_UNSIGNED ) { uint32_t ulTotalCount; uint32_t ulFreeCount; uint32_t ulPercentage; ulTotalCount = 1; ulFreeCount = ff_diskfree( pxClient->pcCurrentDir, &ulTotalCount ); ulPercentage = ( uint32_t ) ( ( 100ULL * ulFreeCount + ulTotalCount / 2 ) / ulTotalCount ); /* Prepare the ACK which will be sent when all data has been sent. */ snprintf( pxClient->pcClientAck, sizeof( pxClient->pcClientAck ), "226-Options: -l\r\n" "226-%ld matches total\r\n" "226 Total %lu KB (%lu %% free)\r\n", pxClient->xDirCount, ulTotalCount /1024, ulPercentage ); } if( xWriteLength ) { if( pxClient->bits1.bDirHasEntry == pdFALSE_UNSIGNED ) { BaseType_t xTrueValue = 1; FreeRTOS_setsockopt( pxClient->xTransferSocket, 0, FREERTOS_SO_CLOSE_AFTER_SEND, ( void * ) &xTrueValue, sizeof( xTrueValue ) ); } prvSendReply( pxClient->xTransferSocket, pcCOMMAND_BUFFER, xWriteLength ); } if( pxClient->bits1.bDirHasEntry == pdFALSE_UNSIGNED ) { prvSendReply( pxClient->xSocket, pxClient->pcClientAck, 0 ); break; } } /* while( pxClient->bits1.bClientConnected ) */ return 0; } /*-----------------------------------------------------------*/ static const char *pcMonthAbbrev( BaseType_t xMonth ) { static const char pcMonthList[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; if( xMonth < 1 || xMonth > 12 ) xMonth = 12; return pcMonthList + 3 * ( xMonth - 1 ); }; /*-----------------------------------------------------------*/ static BaseType_t prvGetFileInfoStat( FF_DirEnt_t *pxEntry, char *pcLine, BaseType_t xMaxLength ) { char date[ 16 ]; char mode[ 11 ] = "----------"; BaseType_t st_nlink = 1; const char user[ 9 ] = "freertos"; const char group[ 8 ] = "plusfat"; /* * Creates a unix-style listing, understood by most FTP clients: * * -rw-rw-r-- 1 freertos FreeRTOS+FAT 10564588 Sep 01 00:17 03. Metaharmoniks - Star (Instrumental).mp3 * -rw-rw-r-- 1 freertos FreeRTOS+FAT 19087839 Sep 01 00:17 04. <NAME> - Dimitri (Wherever U Are) (Cosmos Mix).mp3 * -rw-rw-r-- 1 freertos FreeRTOS+FAT 11100621 Sep 01 00:16 05. D-Chill - Mistake (feat. Katy Blue).mp3 */ #if ( ffconfigTIME_SUPPORT == 1 ) const FF_SystemTime_t *pxCreateTime = &( pxEntry->xCreateTime ); #else #warning Do not use this. FF_SystemTime_t xCreateTime; const FF_SystemTime_t *pxCreateTime = &xCreateTime; #endif size_t ulSize = ( size_t )pxEntry->ulFileSize; const char *pcFileName = pxEntry->pcFileName; mode[ 0 ] = ( ( pxEntry->ucAttrib & FF_FAT_ATTR_DIR ) != 0 ) ? 'd' : '-'; #if( ffconfigDEV_SUPPORT != 0 ) { if( ( pxEntry->ucAttrib & FF_FAT_ATTR_DIR ) == 0 ) { switch( pxEntry->ucIsDeviceDir ) { case FF_DEV_CHAR_DEV: mode[ 0 ] = 'c'; break; case FF_DEV_BLOCK_DEV: mode[ 0 ] = 'b'; break; } } } #endif /* ffconfigDEV_SUPPORT != 0 */ mode[ 1 ] = 'r'; /* Owner. */ mode[ 2 ] = ( ( pxEntry->ucAttrib & FF_FAT_ATTR_READONLY ) != 0 ) ? '-' : 'w'; mode[ 3 ] = '-'; /* x for executable. */ mode[ 4 ] = 'r'; /* group. */ mode[ 5 ] = ( ( pxEntry->ucAttrib & FF_FAT_ATTR_READONLY ) != 0 ) ? '-' : 'w'; mode[ 6 ] = '-'; /* x for executable. */ mode[ 7 ] = 'r'; /* world. */ mode[ 8 ] = '-'; mode[ 9 ] = '-'; /* x for executable. */ if( pxCreateTime->Month && pxCreateTime->Day ) { snprintf( date, sizeof( date ), "%-3.3s %02d %02d:%02d", pcMonthAbbrev( pxCreateTime->Month ), pxCreateTime->Day, pxCreateTime->Hour, pxCreateTime->Minute ); } else { snprintf (date, sizeof( date ), "Jan 01 1970"); } return snprintf( pcLine, xMaxLength, "%s %3ld %-4s %-4s %8d %12s %s\r\n", mode, st_nlink, user, group, ( int ) ulSize, date, pcFileName ); } /*-----------------------------------------------------------*/ /* #### # # ##### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ## ## # # # # ## ## # # #### ## ## ##### */ static BaseType_t prvChangeDir( FTPClient_t *pxClient, char *pcDirectory ) { BaseType_t xResult; BaseType_t xIsRootDir, xLength, xValid; BaseType_t xIsDotDir = 0; if( pcDirectory[ 0 ] == '.' ) { if( ( pcDirectory[ 1 ] == '.' ) && ( pcDirectory[ 2 ] == '\0' ) ) { xIsDotDir = 2; } else if( pcDirectory[ 1 ] == '\0' ) { xIsDotDir = 1; } } if( xIsDotDir != 0 ) { strcpy( pcFILE_BUFFER, pxClient->pcCurrentDir ); if( pcDirectory[ 1 ] == '.' ) { char *p = strrchr( pcFILE_BUFFER, '/' ); if( p != NULL ) { if( p == pcFILE_BUFFER ) { p[ 1 ] = '\0'; } else { p[ 0 ] = '\0'; } } } } else { if(pcDirectory[ 0 ] != '/' ) { BaseType_t xCurLength; xCurLength = strlen( pxClient->pcCurrentDir ); snprintf( pcFILE_BUFFER, sizeof( pcFILE_BUFFER ), "%s%s%s", pxClient->pcCurrentDir, pxClient->pcCurrentDir[ xCurLength - 1 ] == '/' ? "" : "/", pcDirectory ); } else { snprintf( pcFILE_BUFFER, sizeof( pcFILE_BUFFER ), "%s", pcDirectory ); } } xIsRootDir = ( pcFILE_BUFFER[ 0 ] == '/' ) && ( pcFILE_BUFFER[ 1 ] == '\0' ); xMakeAbsolute( pxClient, pcNEW_DIR, sizeof( pcNEW_DIR ), pcFILE_BUFFER ); if( ( ( xIsRootDir == pdFALSE ) || ( FF_FS_Count() == 0 ) ) && ( ff_finddir( pcNEW_DIR ) == pdFALSE ) ) { xValid = pdFALSE; } else { xValid = pdTRUE; } if( xValid == pdFALSE ) { /* Get the directory cluster, if it exists. */ FreeRTOS_printf( ("FTP: chdir \"%s\": No such dir\n", pcNEW_DIR ) ); //#define REPL_550 "550 Requested action not taken.\r\n" //550 /home/hein/arch/h8300: No such file or directory xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "550 %s: No such file or directory\r\n", pcNEW_DIR ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); xResult = pdFALSE; } else { memcpy( pxClient->pcCurrentDir, pcNEW_DIR, sizeof( pxClient->pcCurrentDir ) ); xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "250 Changed to %s\r\n", pcNEW_DIR ); prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); xResult = pdTRUE; } return xResult; } /*-----------------------------------------------------------*/ /* ###### ## # ####### ###### # # ## # # ## # # # # ## # # # # # # # ### # # # # # ###### # ## # ##### ###### # ## # ## # # # # ## # # # ### # # # # # # ## # # # ### ## # ## #### ### ## */ static BaseType_t prvRenameFrom( FTPClient_t *pxClient, const char *pcFileName ) { const char *myReply; FF_FILE *fh; xMakeAbsolute( pxClient, pxClient->pcFileName, sizeof( pxClient->pcFileName ), pcFileName ); myReply = NULL; fh = ff_fopen( pxClient->pcFileName, "rb" ); if( fh != NULL ) { ff_fclose( fh ); /* REPL_350; "350 Requested file action pending further information." */ snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "350 Rename '%s' ...\r\n", pxClient->pcFileName ); myReply = pcCOMMAND_BUFFER; pxClient->bits.bInRename = pdTRUE_UNSIGNED; } else if( stdioGET_ERRNO() == pdFREERTOS_ERRNO_EISDIR ) { snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "350 Rename directory '%s' ...\r\n", pxClient->pcFileName ); myReply = pcCOMMAND_BUFFER; pxClient->bits.bInRename = pdTRUE_UNSIGNED; } else { FreeRTOS_printf( ("ftp::renameFrom[%s]\n%s\n", pxClient->pcFileName, strerror( stdioGET_ERRNO() ) ) ); myReply = REPL_451; /* "451 Requested action aborted. Local error in processing." */ } if( myReply ) { prvSendReply( pxClient->xSocket, myReply, 0 ); } return pdTRUE; } /*-----------------------------------------------------------*/ /* ###### ## # ##### ### # # ## # # # # ## ## # # ## # # ## ## # # ### # # # # ###### # ## # # # # # ## # ## # # # # # # # ### # ## ## # # # ## # ## ## ### ## # ## #### ### */ static BaseType_t prvRenameTo( FTPClient_t *pxClient, const char *pcFileName ) { const char *myReply = NULL; int iResult; xMakeAbsolute( pxClient, pcNEW_DIR, sizeof( pcNEW_DIR ), pcFileName ); /* FreeRTOS+FAT rename has an extra parameter: "remove target if already exists". */ iResult = ff_rename( pxClient->pcFileName, pcNEW_DIR, pdFALSE ); if( iResult < 0 ) { iResult = stdioGET_ERRNO(); } else { iResult = 0; } switch( iResult ) { case 0: FreeRTOS_printf( ( "ftp::renameTo[%s,%s]: Ok\n", pxClient->pcFileName, pcNEW_DIR ) ); snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "250 Rename successful to '%s'\r\n", pcNEW_DIR ); myReply = pcCOMMAND_BUFFER; break; case pdFREERTOS_ERRNO_EEXIST: /* the destination file already exists. "450 Requested file action not taken.\r\n"*/ snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "450 Already exists '%s'\r\n", pcNEW_DIR ); myReply = pcCOMMAND_BUFFER; break; case pdFREERTOS_ERRNO_EIO: /* FF_ERR_FILE_COULD_NOT_CREATE_DIRENT */ /* if dirent creation failed (fatal error!). "553 Requested action not taken.\r\n" */ FreeRTOS_printf( ("ftp::renameTo[%s,%s]: Error creating DirEnt\n", pxClient->pcFileName, pcNEW_DIR ) ); myReply = REPL_553; break; case pdFREERTOS_ERRNO_ENXIO: case pdFREERTOS_ERRNO_ENOENT: /* if the source file was not found. "450 Requested file action not taken.\r\n" */ snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "450 No such file '%s'\r\n", pxClient->pcFileName ); myReply = pcCOMMAND_BUFFER; break; default: FreeRTOS_printf( ("ftp::renameTo[%s,%s]: %s\n", pxClient->pcFileName, pcNEW_DIR, (const char*)strerror( stdioGET_ERRNO() ) ) ); myReply = REPL_451; /* "451 Requested action aborted. Local error in processing." */ break; } prvSendReply( pxClient->xSocket, myReply, 0 ); return pdTRUE; } /*-----------------------------------------------------------*/ /* #### # # # # # # # # # ### ###### #### ## # # # # ## # # ###### # # # # # # # # # ## # ## #### ##### ## #### */ static BaseType_t prvSiteCmd( FTPClient_t *pxClient, char *pcRestCommand ) { ( void ) pxClient; ( void ) pcRestCommand; return 0; } /*-----------------------------------------------------------*/ /* ##### ### # # # # # # # # # # #### # #### ###### #### # # # # # # # # # # # # ###### # ###### # ###### # # # # # # # # # # ## # # ## # ## # ## ##### #### ##### #### ## #### */ static BaseType_t prvDeleteFile( FTPClient_t *pxClient, char *pcFileName ) { BaseType_t xResult, xLength; int32_t iRc; int iErrorNo; /* DELE: Delete a file. */ xMakeAbsolute( pxClient, pxClient->pcFileName, sizeof( pxClient->pcFileName ), pcFileName ); iRc = ff_remove( pxClient->pcFileName ); if (iRc >= 0 ) { xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "250 File \"%s\" removed\r\n", pxClient->pcFileName ); xResult = pdTRUE; } else { const char *errMsg = "other error"; iErrorNo = stdioGET_ERRNO(); switch( iErrorNo ) { /*_RB_ What do these negative numbers relate to? */ case pdFREERTOS_ERRNO_ENOENT: errMsg = "No such file"; break; /* -31 File was not found. */ case pdFREERTOS_ERRNO_EALREADY: errMsg = "File still open"; break; /* -30 File is in use. */ case pdFREERTOS_ERRNO_EISDIR: errMsg = "Is a dir"; break; /* -32 Tried to FF_Open() a Directory. */ case pdFREERTOS_ERRNO_EROFS: errMsg = "Read-only"; break; /* -33 Tried to FF_Open() a file marked read only. */ case pdFREERTOS_ERRNO_ENOTDIR: errMsg = "Invalid path"; break; /* -34 The path of the file was not found. */ } FreeRTOS_printf( ( "ftp::delFile: '%s' because %s\n", pxClient->pcFileName, strerror( iErrorNo ) ) ); xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "521-\"%s\" %s;\r\n" "521 taking no action\r\n", pxClient->pcFileName, errMsg ); xResult = pdFALSE; } prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); return xResult; } /*-----------------------------------------------------------*/ /* #### # ##### # # # # # # # # # # # # ### ###### #### # # #### ###### #### ## # # # # # # # # # # # ## # # ###### # # ##### # ###### # # # # # # # # # # # # # # # # ## # # # # # ## # ## #### ##### ###### #### ##### ### ## ## #### */ static BaseType_t prvSizeDateFile( FTPClient_t *pxClient, char *pcFileName, BaseType_t xSendDate ) { BaseType_t xResult = pdFALSE; char *pcPtr; /* SIZE: get the size of a file (xSendDate = 0) MDTM: get data and time properties (xSendDate = 1) */ xMakeAbsolute( pxClient, pxClient->pcFileName, sizeof( pxClient->pcFileName ), pcFileName ); pcPtr = strrchr( pxClient->pcFileName, '/' ); if( ( pcPtr != NULL ) && ( pcPtr[ 1 ] != '\0' ) ) { FF_Stat_t xStatBuf; int32_t iRc = ff_stat( pxClient->pcFileName, &xStatBuf ); if (iRc < 0 ) FreeRTOS_printf( ("In %s: %s\n", pxClient->pcFileName, ( const char* )strerror( stdioGET_ERRNO() ) ) ); if( iRc == 0 ) { BaseType_t xLength; /* "YYYYMMDDhhmmss" */ if( xSendDate != pdFALSE ) { #if( ffconfigTIME_SUPPORT != 0 ) { FF_TimeStruct_t tmStruct; time_t secs = xStatBuf.st_mtime; FreeRTOS_gmtime_r( &secs, &tmStruct ); xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "213 %04u%02u%02u%02u%02u%02u\r\n", tmStruct.tm_year + 1900, tmStruct.tm_mon+1, tmStruct.tm_mday, tmStruct.tm_hour, tmStruct.tm_min, tmStruct.tm_sec ); } #else { xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "213 19700101000000\r\n", } #endif } else { xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "213 %lu\r\n", xStatBuf.st_size ); } prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); xResult = pdTRUE; } else { FreeRTOS_printf( ("ftp::sizeDateFile: No such file %s\n", pxClient->pcFileName ) ); } } else { FreeRTOS_printf( ("ftp::sizeDateFile: Invalid file name: %s ?\n", pxClient->pcFileName ) ); } if( xResult == pdFALSE ) { prvSendReply( pxClient->xSocket, REPL_450, 0 ); /* "Requested file action not taken". */ } return xResult; } /*-----------------------------------------------------------*/ /* ## ## ## ## ##### ###### ## ## ##### ### ### # # # # # # ### ### # # # ### # # # # # # # # ### # # # # # # # # # # # # # # # # # # # # #### # # ###### # # # # # # # # # # # # ## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ## ##### ### ## # # ##### */ static BaseType_t prvMakeRemoveDir( FTPClient_t *pxClient, const char *pcDirectory, BaseType_t xDoRemove ) { BaseType_t xResult; BaseType_t xLength; int32_t iRc; int iErrorNo; /* MKD: Make / create a directory (xDoRemove = 0) RMD: Remove a directory (xDoRemove = 1) */ xMakeAbsolute( pxClient, pxClient->pcFileName, sizeof( pxClient->pcFileName ), pcDirectory ); if( xDoRemove ) { iRc = ff_rmdir( pxClient->pcFileName ); } else { #if( ffconfigMKDIR_RECURSIVE != 0 ) { iRc = ff_mkdir( pxClient->pcFileName, pdFALSE ); } #else { iRc = ff_mkdir( pxClient->pcFileName ); } #endif /* ffconfigMKDIR_RECURSIVE */ } xResult = pdTRUE; if( iRc >= 0 ) { xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "257 \"%s\" directory %s\r\n", pxClient->pcFileName, xDoRemove ? "removed" : "created" ); } else { const char *errMsg = "other error"; BaseType_t xFTPCode = 521; xResult = pdFALSE; iErrorNo = stdioGET_ERRNO(); switch( iErrorNo ) { case pdFREERTOS_ERRNO_EEXIST: errMsg = "Directory already exists"; break; case pdFREERTOS_ERRNO_ENOTDIR: errMsg = "Invalid path"; break; /* -34 The path of the file was not found. *//*_RB_ As before, what do these negative numbers relate to? */ case pdFREERTOS_ERRNO_ENOTEMPTY:errMsg = "Dir not empty"; break; case pdFREERTOS_ERRNO_EROFS: errMsg = "Read-only"; break; /* -33 Tried to FF_Open() a file marked read only. */ default: errMsg = strerror( iErrorNo ); break; } if( iErrorNo == pdFREERTOS_ERRNO_ENOSPC ) { xFTPCode = 552; } xLength = snprintf( pcCOMMAND_BUFFER, sizeof( pcCOMMAND_BUFFER ), "%ld-\"%s\" %s;\r\n" "%ld taking no action\r\n", xFTPCode, pxClient->pcFileName, errMsg, xFTPCode ); FreeRTOS_printf( ( "%sdir '%s': %s\n", xDoRemove ? "rm" : "mk", pxClient->pcFileName, errMsg ) ); } prvSendReply( pxClient->xSocket, pcCOMMAND_BUFFER, xLength ); return xResult; } /*-----------------------------------------------------------*/ static portINLINE BaseType_t IsDigit( char cChar ) { BaseType_t xResult; if( cChar >= '0' && cChar <= '9' ) { xResult = pdTRUE; } else { xResult = pdFALSE; } return xResult; } static BaseType_t prvSendReply( Socket_t xSocket, const char *pcBuffer, BaseType_t xLength ) { BaseType_t xResult; if( xLength == 0 ) { xLength = strlen( pcBuffer ); } xResult = FreeRTOS_send( xSocket, ( const void * )pcBuffer, ( size_t ) xLength, 0 ); if( IsDigit( ( int ) pcBuffer[ 0 ] ) && IsDigit( ( int ) pcBuffer[ 1 ] ) && IsDigit( ( int ) pcBuffer[ 2 ] ) && IsDigit( ( int ) pcBuffer[ 3 ] ) ) { const char *last = pcBuffer + strlen( pcBuffer ); int iLength; while( ( last > pcBuffer ) && ( ( last[ -1 ] == ftpASCII_CR ) || ( last[ -1 ] == ftpASCII_LF ) ) ) { last--; } iLength = ( int )( last - pcBuffer ); FF_PRINTF( " %-*.*s", iLength, iLength, pcBuffer ); } return xResult; } /*-----------------------------------------------------------*/ #if( ipconfigFTP_HAS_RECEIVED_HOOK != 0 ) /* * The following function is called for every file received: * void vApplicationFTPReceivedHook( pcFileName, ulSize, pxFTPClient ); * This callback function may do a callback to vFTPReplyMessage() to send messages * to the FTP client like: * 200-Please wait: Received new firmware * 200-Please wait: Please wait a few seconds for reboot */ void vFTPReplyMessage( struct xFTP_CLIENT *pxFTPClient, const char *pcMessage ) { if( ( pxFTPClient != NULL ) && ( pxFTPClient->xSocket != NULL ) ) { prvSendReply( pxFTPClient->xSocket, pcMessage, 0 ); } } /*-----------------------------------------------------------*/ #endif /* ipconfigFTP_HAS_RECEIVED_HOOK != 0 */ /* * Some explanation: * The FTP client may send: "DELE readme.txt" * Here the complete path is constructed consisting of 3 parts: * * pxClient->pcRootDir + pxClient->pcCurrentDir + pcFileName * * 'pcCurrentDir' will not be applied for an absolute path like in "DELE /.htaccess" */ BaseType_t xMakeAbsolute( FTPClient_t *pxClient, char *pcBuffer, BaseType_t xBufferLength, const char *pcFileName ) { BaseType_t xLength = strlen( pxClient->pcRootDir ); if( pcFileName[ 0 ] != '/' ) { char *pcNewDirBuffer = pcNEW_DIR; BaseType_t xCurLength; xCurLength = strlen( pxClient->pcCurrentDir ); if( pcBuffer == pcNEW_DIR ) { /* In one call, the result already goes into pcNEW_DIR. Use pcFILE_BUFFER in that case */ pcNewDirBuffer = pcFILE_BUFFER; } snprintf( pcNewDirBuffer, sizeof( pcNEW_DIR ), "%s%s%s", pxClient->pcCurrentDir, pxClient->pcCurrentDir[ xCurLength - 1 ] == '/' ? "" : "/", pcFileName ); pcFileName = pcNewDirBuffer; } if( strncasecmp( pxClient->pcRootDir, pcFileName, xLength ) == 0 ) { xLength = snprintf( pcBuffer, xBufferLength, "%s", pcFileName ); } else { xLength = snprintf( pcBuffer, xBufferLength, "%s/%s", pxClient->pcRootDir, pcFileName[ 0 ] == '/' ? ( pcFileName + 1 ) : pcFileName ); } #if( ipconfigFTP_FS_USES_BACKSLAH == 1 ) for( pcPtr = pcBuffer; *pcPtr; pcPtr++ ) { if( pcPtr[ 0 ] == '/' ) { pcPtr[ 0 ] = '\\'; } } #endif return xLength; } /*-----------------------------------------------------------*/ BaseType_t xMakeRelative( FTPClient_t *pxClient, char *pcBuffer, BaseType_t xBufferLength, const char *pcFileName ) { BaseType_t xLength = strlen( pxClient->pcRootDir ); if( strncasecmp ( pxClient->pcRootDir, pcFileName, xLength ) == 0 ) { xLength = snprintf( pcBuffer, xBufferLength, "%s", pcFileName + xLength ); } else { xLength = snprintf( pcBuffer, xBufferLength, "%s", pcFileName ); } return xLength; } /*-----------------------------------------------------------*/ #endif /* ipconfigUSE_FTP */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-TCP/portable/BufferManagement/BufferAllocation_1.c
/* FreeRTOS+TCP V2.0.11 Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. http://aws.amazon.com/freertos http://www.FreeRTOS.org */ /****************************************************************************** * * See the following web page for essential buffer allocation scheme usage and * configuration details: * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Ethernet_Buffer_Management.html * ******************************************************************************/ /* Standard includes. */ #include <stdint.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_IP_Private.h" #include "NetworkInterface.h" #include "NetworkBufferManagement.h" /* For an Ethernet interrupt to be able to obtain a network buffer there must be at least this number of buffers available. */ #define baINTERRUPT_BUFFER_GET_THRESHOLD ( 3 ) /* A list of free (available) NetworkBufferDescriptor_t structures. */ static List_t xFreeBuffersList; /* Some statistics about the use of buffers. */ static UBaseType_t uxMinimumFreeNetworkBuffers = 0u; /* Declares the pool of NetworkBufferDescriptor_t structures that are available to the system. All the network buffers referenced from xFreeBuffersList exist in this array. The array is not accessed directly except during initialisation, when the xFreeBuffersList is filled (as all the buffers are free when the system is booted). */ static NetworkBufferDescriptor_t xNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ]; /* This constant is defined as true to let FreeRTOS_TCP_IP.c know that the network buffers have constant size, large enough to hold the biggest Ethernet packet. No resizing will be done. */ const BaseType_t xBufferAllocFixedSize = pdTRUE; /* The semaphore used to obtain network buffers. */ static SemaphoreHandle_t xNetworkBufferSemaphore = NULL; #if( ipconfigTCP_IP_SANITY != 0 ) static char cIsLow = pdFALSE; UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc ); #else static UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc ); #endif /* ipconfigTCP_IP_SANITY */ static void prvShowWarnings( void ); /* The user can define their own ipconfigBUFFER_ALLOC_LOCK() and ipconfigBUFFER_ALLOC_UNLOCK() macros, especially for use form an ISR. If these are not defined then default them to call the normal enter/exit critical section macros. */ #if !defined( ipconfigBUFFER_ALLOC_LOCK ) #define ipconfigBUFFER_ALLOC_INIT( ) do {} while (0) #define ipconfigBUFFER_ALLOC_LOCK_FROM_ISR() \ UBaseType_t uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ { #define ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR() \ portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ } #define ipconfigBUFFER_ALLOC_LOCK() taskENTER_CRITICAL() #define ipconfigBUFFER_ALLOC_UNLOCK() taskEXIT_CRITICAL() #endif /* ipconfigBUFFER_ALLOC_LOCK */ /*-----------------------------------------------------------*/ #if( ipconfigTCP_IP_SANITY != 0 ) /* HT: SANITY code will be removed as soon as the library is stable * and and ready to become public * Function below gives information about the use of buffers */ #define WARN_LOW ( 2 ) #define WARN_HIGH ( ( 5 * ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ) / 10 ) #endif /* ipconfigTCP_IP_SANITY */ /*-----------------------------------------------------------*/ #if( ipconfigTCP_IP_SANITY != 0 ) BaseType_t prvIsFreeBuffer( const NetworkBufferDescriptor_t *pxDescr ) { return ( bIsValidNetworkDescriptor( pxDescr ) != 0 ) && ( listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxDescr->xBufferListItem ) ) != 0 ); } /*-----------------------------------------------------------*/ static void prvShowWarnings( void ) { UBaseType_t uxCount = uxGetNumberOfFreeNetworkBuffers( ); if( ( ( cIsLow == 0 ) && ( uxCount <= WARN_LOW ) ) || ( ( cIsLow != 0 ) && ( uxCount >= WARN_HIGH ) ) ) { cIsLow = !cIsLow; FreeRTOS_debug_printf( ( "*** Warning *** %s %lu buffers left\n", cIsLow ? "only" : "now", uxCount ) ); } } /*-----------------------------------------------------------*/ UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc ) { uint32_t offset = ( uint32_t ) ( ((const char *)pxDesc) - ((const char *)xNetworkBuffers) ); if( ( offset >= sizeof( xNetworkBuffers ) ) || ( ( offset % sizeof( xNetworkBuffers[0] ) ) != 0 ) ) return pdFALSE; return (UBaseType_t) (pxDesc - xNetworkBuffers) + 1; } /*-----------------------------------------------------------*/ #else static UBaseType_t bIsValidNetworkDescriptor (const NetworkBufferDescriptor_t * pxDesc) { ( void ) pxDesc; return ( UBaseType_t ) pdTRUE; } /*-----------------------------------------------------------*/ static void prvShowWarnings( void ) { } /*-----------------------------------------------------------*/ #endif /* ipconfigTCP_IP_SANITY */ BaseType_t xNetworkBuffersInitialise( void ) { BaseType_t xReturn, x; /* Only initialise the buffers and their associated kernel objects if they have not been initialised before. */ if( xNetworkBufferSemaphore == NULL ) { /* In case alternative locking is used, the mutexes can be initialised here */ ipconfigBUFFER_ALLOC_INIT(); xNetworkBufferSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ); configASSERT( xNetworkBufferSemaphore ); if( xNetworkBufferSemaphore != NULL ) { vListInitialise( &xFreeBuffersList ); /* Initialise all the network buffers. The buffer storage comes from the network interface, and different hardware has different requirements. */ vNetworkInterfaceAllocateRAMToBuffers( xNetworkBuffers ); for( x = 0; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ ) { /* Initialise and set the owner of the buffer list items. */ vListInitialiseItem( &( xNetworkBuffers[ x ].xBufferListItem ) ); listSET_LIST_ITEM_OWNER( &( xNetworkBuffers[ x ].xBufferListItem ), &xNetworkBuffers[ x ] ); /* Currently, all buffers are available for use. */ vListInsert( &xFreeBuffersList, &( xNetworkBuffers[ x ].xBufferListItem ) ); } uxMinimumFreeNetworkBuffers = ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; } } if( xNetworkBufferSemaphore == NULL ) { xReturn = pdFAIL; } else { xReturn = pdPASS; } return xReturn; } /*-----------------------------------------------------------*/ NetworkBufferDescriptor_t *pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes, TickType_t xBlockTimeTicks ) { NetworkBufferDescriptor_t *pxReturn = NULL; BaseType_t xInvalid = pdFALSE; UBaseType_t uxCount; /* The current implementation only has a single size memory block, so the requested size parameter is not used (yet). */ ( void ) xRequestedSizeBytes; if( xNetworkBufferSemaphore != NULL ) { /* If there is a semaphore available, there is a network buffer available. */ if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS ) { /* Protect the structure as they are accessed from tasks and interrupts. */ ipconfigBUFFER_ALLOC_LOCK(); { pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList ); if( ( bIsValidNetworkDescriptor( pxReturn ) != pdFALSE_UNSIGNED ) && listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxReturn->xBufferListItem ) ) ) { uxListRemove( &( pxReturn->xBufferListItem ) ); } else { xInvalid = pdTRUE; } } ipconfigBUFFER_ALLOC_UNLOCK(); if( xInvalid == pdTRUE ) { /* _RB_ Can printf() be called from an interrupt? (comment above says this can be called from an interrupt too) */ /* _HT_ The function shall not be called from an ISR. Comment was indeed misleading. Hopefully clear now? So the printf()is OK here. */ FreeRTOS_debug_printf( ( "pxGetNetworkBufferWithDescriptor: INVALID BUFFER: %p (valid %lu)\n", pxReturn, bIsValidNetworkDescriptor( pxReturn ) ) ); pxReturn = NULL; } else { /* Reading UBaseType_t, no critical section needed. */ uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList ); /* For stats, latch the lowest number of network buffers since booting. */ if( uxMinimumFreeNetworkBuffers > uxCount ) { uxMinimumFreeNetworkBuffers = uxCount; } pxReturn->xDataLength = xRequestedSizeBytes; #if( ipconfigTCP_IP_SANITY != 0 ) { prvShowWarnings(); } #endif /* ipconfigTCP_IP_SANITY */ #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 ) { /* make sure the buffer is not linked */ pxReturn->pxNextBuffer = NULL; } #endif /* ipconfigUSE_LINKED_RX_MESSAGES */ } iptraceNETWORK_BUFFER_OBTAINED( pxReturn ); } else { iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER(); } } return pxReturn; } /*-----------------------------------------------------------*/ NetworkBufferDescriptor_t *pxNetworkBufferGetFromISR( size_t xRequestedSizeBytes ) { NetworkBufferDescriptor_t *pxReturn = NULL; /* The current implementation only has a single size memory block, so the requested size parameter is not used (yet). */ ( void ) xRequestedSizeBytes; /* If there is a semaphore available then there is a buffer available, but, as this is called from an interrupt, only take a buffer if there are at least baINTERRUPT_BUFFER_GET_THRESHOLD buffers remaining. This prevents, to a certain degree at least, a rapidly executing interrupt exhausting buffer and in so doing preventing tasks from continuing. */ if( uxQueueMessagesWaitingFromISR( ( QueueHandle_t ) xNetworkBufferSemaphore ) > ( UBaseType_t ) baINTERRUPT_BUFFER_GET_THRESHOLD ) { if( xSemaphoreTakeFromISR( xNetworkBufferSemaphore, NULL ) == pdPASS ) { /* Protect the structure as it is accessed from tasks and interrupts. */ ipconfigBUFFER_ALLOC_LOCK_FROM_ISR(); { pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList ); uxListRemove( &( pxReturn->xBufferListItem ) ); } ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR(); iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR( pxReturn ); } } if( pxReturn == NULL ) { iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR(); } return pxReturn; } /*-----------------------------------------------------------*/ BaseType_t vNetworkBufferReleaseFromISR( NetworkBufferDescriptor_t * const pxNetworkBuffer ) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; /* Ensure the buffer is returned to the list of free buffers before the counting semaphore is 'given' to say a buffer is available. */ ipconfigBUFFER_ALLOC_LOCK_FROM_ISR(); { vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) ); } ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR(); xSemaphoreGiveFromISR( xNetworkBufferSemaphore, &xHigherPriorityTaskWoken ); iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer ); return xHigherPriorityTaskWoken; } /*-----------------------------------------------------------*/ void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer ) { BaseType_t xListItemAlreadyInFreeList; if( bIsValidNetworkDescriptor( pxNetworkBuffer ) == pdFALSE_UNSIGNED ) { FreeRTOS_debug_printf( ( "vReleaseNetworkBufferAndDescriptor: Invalid buffer %p\n", pxNetworkBuffer ) ); return ; } /* Ensure the buffer is returned to the list of free buffers before the counting semaphore is 'given' to say a buffer is available. */ ipconfigBUFFER_ALLOC_LOCK(); { { xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) ); if( xListItemAlreadyInFreeList == pdFALSE ) { vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) ); } } } ipconfigBUFFER_ALLOC_UNLOCK(); if( xListItemAlreadyInFreeList ) { FreeRTOS_debug_printf( ( "vReleaseNetworkBufferAndDescriptor: %p ALREADY RELEASED (now %lu)\n", pxNetworkBuffer, uxGetNumberOfFreeNetworkBuffers( ) ) ); } if( xListItemAlreadyInFreeList == pdFALSE ) { xSemaphoreGive( xNetworkBufferSemaphore ); prvShowWarnings(); } iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer ); } /*-----------------------------------------------------------*/ UBaseType_t uxGetMinimumFreeNetworkBuffers( void ) { return uxMinimumFreeNetworkBuffers; } /*-----------------------------------------------------------*/ UBaseType_t uxGetNumberOfFreeNetworkBuffers( void ) { return listCURRENT_LIST_LENGTH( &xFreeBuffersList ); } NetworkBufferDescriptor_t *pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer, size_t xNewSizeBytes ) { /* In BufferAllocation_1.c all network buffer are allocated with a maximum size of 'ipTOTAL_ETHERNET_FRAME_SIZE'.No need to resize the network buffer. */ ( void ) xNewSizeBytes; return pxNetworkBuffer; } /*#endif */ /* ipconfigINCLUDE_TEST_CODE */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/include/ff_old_config_defines.h
<reponame>MicroEJ/FreeRTOS<gh_stars>1-10 /* * FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab! * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Authors include <NAME>, <NAME> and <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * */ /* As of 15/3/2015 all +FAT configuration items changed their prefix, e.g. FF_LITTLE_ENDIAN has become ffconfigLITTLE_ENDIAN This tempoary header file checks for the presence old configuration items and issue a compiler error if any is defined. */ #ifdef FF_LITTLE_ENDIAN #error FF_LITTLE_ENDIAN was dropped and replaced with 'ffconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN' #endif #ifdef FF_BIG_ENDIAN #error FF_BIG_ENDIAN was dropped and replaced with 'ffconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN' #endif #ifdef ffconfigLITTLE_ENDIAN #error ffconfigLITTLE_ENDIAN was dropped. #endif #ifdef ffconfigBIG_ENDIAN #error ffconfigBIG_ENDIAN was dropped. #endif #ifdef FF_HAS_CWD #error FF_HAS_CWD still defined. Please use ffconfig prefix. #endif #if !defined( pdFREERTOS_LITTLE_ENDIAN ) || !defined( pdFREERTOS_BIG_ENDIAN ) #error Missing defines from FreeRTOS #endif #ifdef FF_LFN_SUPPORT #error FF_LFN_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_INCLUDE_SHORT_NAME #error FF_INCLUDE_SHORT_NAME still defined. Please use ffconfig prefix. #endif #ifdef FF_SHORTNAME_CASE #error FF_SHORTNAME_CASE still defined. Please use ffconfig prefix. #endif #ifdef FF_UNICODE_UTF16_SUPPORT #error FF_UNICODE_UTF16_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_UNICODE_UTF8_SUPPORT #error FF_UNICODE_UTF8_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_FAT12_SUPPORT #error FF_FAT12_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_OPTIMISE_UNALIGNED_ACCESS #error FF_OPTIMISE_UNALIGNED_ACCESS still defined. Please use ffconfig prefix. #endif #ifdef FF_CACHE_WRITE_THROUGH #error FF_CACHE_WRITE_THROUGH still defined. Please use ffconfig prefix. #endif #ifdef FF_WRITE_BOTH_FATS #error FF_WRITE_BOTH_FATS still defined. Please use ffconfig prefix. #endif #ifdef FF_WRITE_FREE_COUNT #error FF_WRITE_FREE_COUNT still defined. Please use ffconfig prefix. #endif #ifdef FF_TIME_SUPPORT #error FF_TIME_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_REMOVABLE_MEDIA #error FF_REMOVABLE_MEDIA still defined. Please use ffconfig prefix. #endif #ifdef FF_MOUNT_FIND_FREE #error FF_MOUNT_FIND_FREE still defined. Please use ffconfig prefix. #endif #ifdef FF_FINDAPI_ALLOW_WILDCARDS #error FF_FINDAPI_ALLOW_WILDCARDS still defined. Please use ffconfig prefix. #endif #ifdef FF_WILDCARD_CASE_INSENSITIVE #error FF_WILDCARD_CASE_INSENSITIVE still defined. Please use ffconfig prefix. #endif #ifdef FF_PATH_CACHE #error FF_PATH_CACHE still defined. Please use ffconfig prefix. #endif #ifdef FF_PATH_CACHE_DEPTH #error FF_PATH_CACHE_DEPTH still defined. Please use ffconfig prefix. #endif #ifdef FF_HASH_CACHE #error FF_HASH_CACHE still defined. Please use ffconfig prefix. #endif #ifdef FF_HASH_FUNCTION #error FF_HASH_FUNCTION still defined. Please use ffconfig prefix. #endif #ifdef FF_HASH_TABLE_SIZE #error FF_HASH_TABLE_SIZE still defined. Please use ffconfig prefix. #endif #ifdef FF_HASH_TABLE_SIZE #error FF_HASH_TABLE_SIZE still defined. Please use ffconfig prefix. #endif #ifdef FF_MKDIR_RECURSIVE #error FF_MKDIR_RECURSIVE still defined. Please use ffconfig prefix. #endif #ifdef FF_BLKDEV_USES_SEM #error FF_BLKDEV_USES_SEM is not used any more #endif #ifdef ffconfigBLKDEV_USES_SEM #error ffconfigBLKDEV_USES_SEM is not used any more #endif #ifdef FF_MALLOC #error FF_MALLOC still defined. Please use ffconfig prefix. #endif #ifdef FF_FREE #error FF_FREE still defined. Please use ffconfig prefix. #endif #ifdef FF_64_NUM_SUPPORT #error FF_64_NUM_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_MAX_PARTITIONS #error FF_MAX_PARTITIONS still defined. Please use ffconfig prefix. #endif #ifdef FF_MAX_FILE_SYS #error FF_MAX_FILE_SYS still defined. Please use ffconfig prefix. #endif #ifdef FF_DRIVER_BUSY_SLEEP_MS #error FF_DRIVER_BUSY_SLEEP_MS still defined. Please use ffconfig prefix. #endif #ifdef FF_FPRINTF_SUPPORT #error FF_FPRINTF_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_FPRINTF_BUFFER_LENGTH #error FF_FPRINTF_BUFFER_LENGTH still defined. Please use ffconfig prefix. #endif #ifdef FF_DEBUG #error FF_DEBUG still defined. Please use ffconfig prefix. #endif #ifdef FF_HAS_FUNCTION_TAB #error FF_HAS_FUNCTION_TAB still defined. Please use ffconfig prefix. #endif #ifdef FF_FAT_CHECK #error FF_FAT_CHECK still defined. Please use ffconfig prefix. #endif #ifdef FF_MAX_FILENAME #error FF_MAX_FILENAME still defined. Please use ffconfig prefix. #endif #ifdef FF_PRINTFFF_PRINTF #error FF_PRINTFFF_PRINTF still defined. Please use ffconfig prefix. #endif #ifdef FF_FAT_USES_STAT #error FF_FAT_USES_STAT still defined. Please use ffconfig prefix. #endif #ifdef BUF_STORE_COUNT #error BUF_STORE_COUNT still defined. Please use ffconfig prefix. #endif #ifdef FF_USE_NOTIFY #error FF_USE_NOTIFY still defined. Please use ffconfig prefix. #endif #ifdef FF_DEV_SUPPORT #error FF_DEV_SUPPORT still defined. Please use ffconfig prefix. #endif #ifdef FF_FSINFO_TRUSTED #error FF_FSINFO_TRUSTED still defined. Please use ffconfig prefix. #endif #ifdef FF_LONG_ERR_MSG #error FF_LONG_ERR_MSG still defined. Please use ffconfig prefix. #endif #ifdef FF_INLINE_MEMORY_ACCESS #error FF_INLINE_MEMORY_ACCESS still defined. Please use ffconfig prefix. #endif #ifdef FF_MIRROR_FATS_UMOUNT #error FF_MIRROR_FATS_UMOUNT still defined. Please use ffconfig prefix. #endif #ifdef FF_HASH_CACHE_DEPTH #error FF_HASH_CACHE_DEPTH still defined. Please use ffconfig prefix. #endif #ifdef FF_HASH_TABLE_SUPPORT #error FF_HASH_TABLE_SUPPORT was dropped #endif #ifdef FF_INLINE_BLOCK_CALCULATIONS #error FF_INLINE_BLOCK_CALCULATIONS was dropped #endif #ifdef FF_CWD_THREAD_LOCAL_INDEX #error FF_CWD_THREAD_LOCAL_INDEX is now called ffconfigCWD_THREAD_LOCAL_INDEX #endif #ifdef FF_DEV_PATH #error FF_DEV_PATH was dropped #endif
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/jobs/src/private/aws_iot_jobs_internal.h
<filename>FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/jobs/src/private/aws_iot_jobs_internal.h<gh_stars>1-10 /* * AWS IoT Jobs V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_jobs_internal.h * @brief Internal header of Jobs library. This header should not be included in * typical application code. */ #ifndef AWS_IOT_JOBS_INTERNAL_H_ #define AWS_IOT_JOBS_INTERNAL_H_ /* The config header is always included first. */ #include "iot_config.h" /* Linear containers (lists and queues) include. */ #include "iot_linear_containers.h" /* Jobs include. */ #include "aws_iot_jobs.h" /* AWS IoT include. */ #include "aws_iot.h" /** * @def AwsIotJobs_Assert( expression ) * @brief Assertion macro for the Jobs library. * * Set @ref AWS_IOT_JOBS_ENABLE_ASSERTS to `1` to enable assertions in the Jobs * library. * * @param[in] expression Expression to be evaluated. */ #if AWS_IOT_JOBS_ENABLE_ASSERTS == 1 #ifndef AwsIotJobs_Assert #ifdef Iot_DefaultAssert #define AwsIotJobs_Assert( expression ) Iot_DefaultAssert( expression ) #else #error "Asserts are enabled for Jobs, but AwsIotJobs_Assert is not defined" #endif #endif #else #define AwsIotJobs_Assert( expression ) #endif /* Configure logs for Jobs functions. */ #ifdef AWS_IOT_LOG_LEVEL_JOBS #define LIBRARY_LOG_LEVEL AWS_IOT_LOG_LEVEL_JOBS #else #ifdef IOT_LOG_LEVEL_GLOBAL #define LIBRARY_LOG_LEVEL IOT_LOG_LEVEL_GLOBAL #else #define LIBRARY_LOG_LEVEL IOT_LOG_NONE #endif #endif #define LIBRARY_LOG_NAME ( "Jobs" ) #include "iot_logging_setup.h" /* * Provide default values for undefined memory allocation functions based on * the usage of dynamic memory allocation. */ #if IOT_STATIC_MEMORY_ONLY == 1 #include "iot_static_memory.h" /** * @brief Allocate a #_jobsOperation_t. This function should have the same * signature as [malloc] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html). */ void * AwsIotJobs_MallocOperation( size_t size ); /** * @brief Free a #_jobsOperation_t. This function should have the same * signature as [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ void AwsIotJobs_FreeOperation( void * ptr ); /** * @brief Allocate a buffer for a short string, used for topic names or client * tokens. This function should have the same signature as [malloc] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html). */ #define AwsIotJobs_MallocString Iot_MallocMessageBuffer /** * @brief Free a string. This function should have the same signature as * [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ #define AwsIotJobs_FreeString Iot_FreeMessageBuffer /** * @brief Allocate a #_jobsSubscription_t. This function should have the * same signature as [malloc] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html). */ void * AwsIotJobs_MallocSubscription( size_t size ); /** * @brief Free a #_jobsSubscription_t. This function should have the same * signature as [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ void AwsIotJobs_FreeSubscription( void * ptr ); #else /* if IOT_STATIC_MEMORY_ONLY == 1 */ #ifndef AwsIotJobs_MallocOperation #ifdef Iot_DefaultMalloc #define AwsIotJobs_MallocOperation Iot_DefaultMalloc #else #error "No malloc function defined for AwsIotJobs_MallocOperation" #endif #endif #ifndef AwsIotJobs_FreeOperation #ifdef Iot_DefaultFree #define AwsIotJobs_FreeOperation Iot_DefaultFree #else #error "No free function defined for AwsIotJobs_FreeOperation" #endif #endif #ifndef AwsIotJobs_MallocString #ifdef Iot_DefaultMalloc #define AwsIotJobs_MallocString Iot_DefaultMalloc #else #error "No malloc function defined for AwsIotJobs_MallocString" #endif #endif #ifndef AwsIotJobs_FreeString #ifdef Iot_DefaultFree #define AwsIotJobs_FreeString Iot_DefaultFree #else #error "No free function defined for AwsIotJobs_FreeString" #endif #endif #ifndef AwsIotJobs_MallocSubscription #ifdef Iot_DefaultMalloc #define AwsIotJobs_MallocSubscription Iot_DefaultMalloc #else #error "No malloc function defined for AwsIotJobs_MallocSubscription" #endif #endif #ifndef AwsIotJobs_FreeSubscription #ifdef Iot_DefaultFree #define AwsIotJobs_FreeSubscription Iot_DefaultFree #else #error "No free function defined for AwsIotJobs_FreeSubscription" #endif #endif #endif /* if IOT_STATIC_MEMORY_ONLY == 1 */ /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Provide default values for undefined configuration constants. */ #ifndef AWS_IOT_JOBS_DEFAULT_MQTT_TIMEOUT_MS #define AWS_IOT_JOBS_DEFAULT_MQTT_TIMEOUT_MS ( 5000 ) #endif #ifndef AWS_IOT_JOBS_NOTIFY_CALLBACKS #define AWS_IOT_JOBS_NOTIFY_CALLBACKS ( 1 ) #endif /** @endcond */ /** * @brief The number of currently available Jobs operations. * * The 4 Jobs operations are GET PENDING, START NEXT, DESCRIBE, and UPDATE. */ #define JOBS_OPERATION_COUNT ( 4 ) /** * @brief The number of currently available Jobs callbacks. * * The 2 Jobs callbacks are `jobs/notify` (AKA "Notify Pending") and * `/jobs/notify-next` (AKA "Notify Next"). */ #define JOBS_CALLBACK_COUNT ( 2 ) /** * @brief The string representing a Jobs GET PENDING operation in a Jobs MQTT topic. */ #define JOBS_GET_PENDING_OPERATION_STRING "/jobs/get" /** * @brief The length of #JOBS_GET_PENDING_OPERATION_STRING. */ #define JOBS_GET_PENDING_OPERATION_STRING_LENGTH ( ( uint16_t ) ( sizeof( JOBS_GET_PENDING_OPERATION_STRING ) - 1 ) ) /** * @brief The string representing a Jobs START NEXT operation in a Jobs MQTT topic. */ #define JOBS_START_NEXT_OPERATION_STRING "/jobs/start-next" /** * @brief The length of #JOBS_START_NEXT_OPERATION_STRING. */ #define JOBS_START_NEXT_OPERATION_STRING_LENGTH ( ( uint16_t ) ( sizeof( JOBS_START_NEXT_OPERATION_STRING ) - 1 ) ) /** * @brief The string representing a Jobs DESCRIBE operation in a Jobs MQTT topic. * * This string should be placed after a Job ID. */ #define JOBS_DESCRIBE_OPERATION_STRING "/get" /** * @brief The length of #JOBS_DESCRIBE_OPERATION_STRING. */ #define JOBS_DESCRIBE_OPERATION_STRING_LENGTH ( ( uint16_t ) ( sizeof( JOBS_DESCRIBE_OPERATION_STRING ) - 1 ) ) /** * @brief The string representing a Jobs UPDATE operation in a Jobs MQTT topic. * * This string should be placed after a Job ID. */ #define JOBS_UPDATE_OPERATION_STRING "/update" /** * @brief The length of #JOBS_UPDATE_OPERATION_STRING. * * This length excludes the length of the placeholder %s. */ #define JOBS_UPDATE_OPERATION_STRING_LENGTH ( ( uint16_t ) ( sizeof( JOBS_UPDATE_OPERATION_STRING ) - 1 ) ) /** * @brief The string representing the Jobs MQTT topic for receiving notifications * of pending Jobs. */ #define JOBS_NOTIFY_PENDING_CALLBACK_STRING "/jobs/notify" /** * @brief The length of #JOBS_NOTIFY_PENDING_CALLBACK_STRING. */ #define JOBS_NOTIFY_PENDING_CALLBACK_STRING_LENGTH ( ( uint16_t ) ( sizeof( JOBS_NOTIFY_PENDING_CALLBACK_STRING ) - 1 ) ) /** * @brief The string representing the Jobs MQTT topic for receiving notifications * of the next pending Job. */ #define JOBS_NOTIFY_NEXT_CALLBACK_STRING "/jobs/notify-next" /** * @brief The length of #JOBS_NOTIFY_NEXT_CALLBACK_STRING. */ #define JOBS_NOTIFY_NEXT_CALLBACK_STRING_LENGTH ( ( uint16_t ) ( sizeof( JOBS_NOTIFY_NEXT_CALLBACK_STRING ) - 1 ) ) /** * @brief The maximum length of a Job ID, per AWS IoT Service Limits. * * See https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#job-limits */ #define JOBS_MAX_ID_LENGTH ( 64 ) /** * @brief The maximum value of the Jobs step timeout, per AWS IoT Service Limits. * * See https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#job-limits */ #define JOBS_MAX_TIMEOUT ( 10080 ) /** * @brief A limit on the maximum length of a Jobs status details, per AWS IoT * Service Limits. * * See https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#job-limits * * This is actually the limit on the length of an entire Jobs document; but the * status details must also not exceed this length, */ #define JOBS_MAX_STATUS_DETAILS_LENGTH ( 32768 ) /** * @brief The length of the longest Jobs topic suffix. * * This is the length of the longest Job ID, plus the length of the "UPDATE" * operation suffix, plus the length of "/jobs/". */ #define JOBS_LONGEST_SUFFIX_LENGTH ( JOBS_MAX_ID_LENGTH + JOBS_UPDATE_OPERATION_STRING_LENGTH + 6 ) /*------------------------ Jobs internal data types -------------------------*/ /** * @brief Enumerations representing each of the Jobs library's API functions. */ typedef enum _jobsOperationType { /* Jobs operations. */ JOBS_GET_PENDING = 0, /**< @ref jobs_function_getpendingasync */ JOBS_START_NEXT = 1, /**< @ref jobs_function_startnextasync */ JOBS_DESCRIBE = 2, /**< @ref jobs_function_describeasync */ JOBS_UPDATE = 3, /**< @ref jobs_function_updateasync */ /* Jobs callbacks. */ SET_NOTIFY_PENDING_CALLBACK = 4, /**< @ref jobs_function_setnotifypendingcallback */ SET_NOTIFY_NEXT_CALLBACK = 5 /**< @ref jobs_function_setnotifynextcallback */ } _jobsOperationType_t; /** * @brief Enumerations representing each of the Jobs callback functions. */ typedef enum _jobsCallbackType { NOTIFY_PENDING_CALLBACK = 0, /**< Pending Job notification callback. */ NOTIFY_NEXT_CALLBACK = 1 /**< Next Job notification callback. */ } _jobsCallbackType_t; /** * @brief Parameter to #_AwsIotJobs_GenerateJsonRequest. */ typedef union _jsonRequestContents { const AwsIotJobsUpdateInfo_t * pUpdateInfo; /**< @brief Valid for #JOBS_START_NEXT and #JOBS_UPDATE. */ struct { int32_t executionNumber; /**< @brief Execution number. */ bool includeJobDocument; /**< @brief Whether the response should include the Job document. */ } describe; /**< @brief Valid for #JOBS_DESCRIBE. */ } _jsonRequestContents_t; /** * @brief Represents a Jobs subscriptions object. * * These structures are stored in a list. */ typedef struct _jobsSubscription { IotLink_t link; /**< @brief List link member. */ int32_t operationReferences[ JOBS_OPERATION_COUNT ]; /**< @brief Reference counters for Jobs operation topics. */ int32_t callbackReferences; /**< @brief Reference counter for Jobs callbacks. */ /** @brief Jobs callbacks for this Thing. */ AwsIotJobsCallbackInfo_t callbacks[ JOBS_CALLBACK_COUNT ][ AWS_IOT_JOBS_NOTIFY_CALLBACKS ]; /** * @brief Buffer allocated for removing Jobs topics. * * This buffer is pre-allocated to ensure that memory is available when * unsubscribing. */ char * pTopicBuffer; size_t thingNameLength; /**< @brief Length of Thing Name. */ char pThingName[]; /**< @brief Thing Name associated with this subscriptions object. */ } _jobsSubscription_t; /** * @brief Internal structure representing a single Jobs operation. * * A list of these structures keeps track of all in-progress Jobs operations. */ typedef struct _jobsOperation { IotLink_t link; /**< @brief List link member. */ /* Basic operation information. */ _jobsOperationType_t type; /**< @brief Operation type. */ uint32_t flags; /**< @brief Flags passed to operation API function. */ AwsIotJobsError_t status; /**< @brief Status of operation. */ IotMqttConnection_t mqttConnection; /**< @brief MQTT connection associated with this operation. */ _jobsSubscription_t * pSubscription; /**< @brief Jobs subscriptions object associated with this operation. */ /* Jobs request information. */ const char * pJobsRequest; /**< @brief JSON document to send to the Jobs service. */ size_t jobsRequestLength; /**< @brief Length of #_jobsOperation_t.pJobsRequest. */ const char * pClientToken; /**< @brief Client token sent with request. */ size_t clientTokenLength; /**< @brief Length of #_jobsOperation_t.pClientToken. */ /* Jobs response information. */ const char * pJobsResponse; /**< @brief Response received from the Jobs service. */ size_t jobsResponseLength; /**< @brief Length of #_jobsOperation_t.pJobsResponse. */ /** * @brief Function to allocate memory for an incoming Jobs response. * * Only used when the flag #AWS_IOT_JOBS_FLAG_WAITABLE is set. */ void * ( *mallocResponse )( size_t ); /* How to notify of an operation's completion. */ union { IotSemaphore_t waitSemaphore; /**< @brief Semaphore to be used with @ref jobs_function_wait. */ AwsIotJobsCallbackInfo_t callback; /**< @brief User-provided callback function and parameter. */ } notify; /**< @brief How to notify of an operation's completion. */ size_t jobIdLength; /**< @brief Length of #_jobsOperation_t.pJobId. */ char pJobId[]; /**< @brief Job ID, saved for DESCRIBE and UPDATE operations. */ } _jobsOperation_t; /* Declarations of names printed in logs. */ #if LIBRARY_LOG_LEVEL > IOT_LOG_NONE extern const char * const _pAwsIotJobsOperationNames[]; extern const char * const _pAwsIotJobsCallbackNames[]; #endif /* Declarations of variables for internal Jobs files. */ extern uint32_t _AwsIotJobsMqttTimeoutMs; extern IotListDouble_t _AwsIotJobsPendingOperations; extern IotListDouble_t _AwsIotJobsSubscriptions; extern IotMutex_t _AwsIotJobsPendingOperationsMutex; extern IotMutex_t _AwsIotJobsSubscriptionsMutex; /*------------------------ Jobs operation functions -------------------------*/ /** * @brief Create a record for a new in-progress Jobs operation. * * @param[in] type The type of Jobs operation for the request. * @param[in] pRequestInfo Common Jobs request parameters. * @param[in] pRequestContents Additional values to place in the JSON document, * depending on `type`. * @param[in] flags Flags variables passed to a user-facing Jobs function. * @param[in] pCallbackInfo User-provided callback function and parameter. * @param[out] pNewOperation Set to point to the new operation on success. * * @return #AWS_IOT_JOBS_SUCCESS or #AWS_IOT_JOBS_NO_MEMORY */ AwsIotJobsError_t _AwsIotJobs_CreateOperation( _jobsOperationType_t type, const AwsIotJobsRequestInfo_t * pRequestInfo, const _jsonRequestContents_t * pRequestContents, uint32_t flags, const AwsIotJobsCallbackInfo_t * pCallbackInfo, _jobsOperation_t ** pNewOperation ); /** * @brief Free resources used to record a Jobs operation. This is called when * the operation completes. * * @param[in] pData The operation which completed. This parameter is of type * `void*` to match the signature of [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ void _AwsIotJobs_DestroyOperation( void * pData ); /** * @brief Fill a buffer with a Jobs topic. * * @param[in] type One of: GET PENDING, START NEXT, DESCRIBE, or UPDATE. * @param[in] pRequestInfo Common Jobs request parameters. * @param[out] pTopicBuffer Address of the buffer for the Jobs topic. If the * pointer at this address is `NULL`, this function will allocate a new buffer; * otherwise, it will use the provided buffer. * @param[out] pOperationTopicLength Length of the Jobs operation topic (excluding * any suffix) placed in `pTopicBuffer`. * * @warning This function does not check the length of `pTopicBuffer`! Any provided * buffer must be large enough to accommodate the full Jobs topic, plus * #JOBS_LONGEST_SUFFIX_LENGTH. * * @return #AWS_IOT_JOBS_SUCCESS or #AWS_IOT_JOBS_NO_MEMORY. This function * will not return #AWS_IOT_JOBS_NO_MEMORY when a buffer is provided. */ AwsIotJobsError_t _AwsIotJobs_GenerateJobsTopic( _jobsOperationType_t type, const AwsIotJobsRequestInfo_t * pRequestInfo, char ** pTopicBuffer, uint16_t * pOperationTopicLength ); /** * @brief Process a Jobs operation by sending the necessary MQTT packets. * * @param[in] pRequestInfo Common Jobs request parameters. * @param[in] pOperation Operation data to process. * * @return #AWS_IOT_JOBS_STATUS_PENDING on success. On error, one of * #AWS_IOT_JOBS_NO_MEMORY or #AWS_IOT_JOBS_MQTT_ERROR. */ AwsIotJobsError_t _AwsIotJobs_ProcessOperation( const AwsIotJobsRequestInfo_t * pRequestInfo, _jobsOperation_t * pOperation ); /*----------------------- Jobs subscription functions -----------------------*/ /** * @brief Find a Jobs subscription object. May create a new subscription object * and adds it to the subscription list if not found. * * @param[in] pThingName Thing Name in the subscription object. * @param[in] thingNameLength Length of `pThingName`. * @param[in] createIfNotFound If `true`, attempt to create a new subscription * object if no match is found. * * @return Pointer to a Jobs subscription object, either found or newly * allocated. Returns `NULL` if no subscription object is found and a new * subscription object could not be allocated. * * @note This function should be called with the subscription list mutex locked. */ _jobsSubscription_t * _AwsIotJobs_FindSubscription( const char * pThingName, size_t thingNameLength, bool createIfNotFound ); /** * @brief Remove a Jobs subscription object from the subscription list if * unreferenced. * * @param[in] pSubscription Subscription object to check. If this object has no * active references, it is removed from the subscription list. * @param[out] pRemovedSubscription Removed subscription object, if any. Optional; * pass `NULL` to ignore. If not `NULL`, this parameter will be set to the removed * subscription and that subscription will not be destroyed. * * @note This function should be called with the subscription list mutex locked. */ void _AwsIotJobs_RemoveSubscription( _jobsSubscription_t * pSubscription, _jobsSubscription_t ** pRemovedSubscription ); /** * @brief Free resources used for a Jobs subscription object. * * @param[in] pData The subscription object to destroy. This parameter is of type * `void*` to match the signature of [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ void _AwsIotJobs_DestroySubscription( void * pData ); /** * @brief Increment the reference count of a Jobs subscriptions object. * * Also adds MQTT subscriptions if necessary. * * @param[in] pOperation The operation for which the reference count should be * incremented. * @param[in] pTopicBuffer Topic buffer containing the operation topic, used if * subscriptions need to be added. * @param[in] operationTopicLength The length of the operation topic in `pTopicBuffer`. * @param[in] callback MQTT callback function for when this operation completes. * * @warning This function does not check the length of `pTopicBuffer`! Any provided * buffer must already contain the Jobs operation topic, plus enough space for the * status suffix. * * @return #AWS_IOT_JOBS_SUCCESS on success. On error, one of * #AWS_IOT_JOBS_NO_MEMORY or #AWS_IOT_JOBS_MQTT_ERROR. * * @note This function should be called with the subscription list mutex locked. */ AwsIotJobsError_t _AwsIotJobs_IncrementReferences( _jobsOperation_t * pOperation, char * pTopicBuffer, uint16_t operationTopicLength, AwsIotMqttCallbackFunction_t callback ); /** * @brief Decrement the reference count of a Jobs subscriptions object. * * Also removed MQTT subscriptions and deletes the subscription object if necessary. * * @param[in] pOperation The operation for which the reference count should be * decremented. * @param[in] pTopicBuffer Topic buffer containing the operation topic, used if * subscriptions need to be removed. * @param[out] pRemovedSubscription Set to point to a removed subscription. * Optional; pass `NULL` to ignore. If not `NULL`, this function will not destroy * a removed subscription. * * @warning This function does not check the length of `pTopicBuffer`! Any provided * buffer must be large enough to accommodate the full Jobs topic, plus * #JOBS_LONGEST_SUFFIX_LENGTH. * * @note This function should be called with the subscription list mutex locked. */ void _AwsIotJobs_DecrementReferences( _jobsOperation_t * pOperation, char * pTopicBuffer, _jobsSubscription_t ** pRemovedSubscription ); /*------------------------ Jobs serializer functions ------------------------*/ /** * @brief Generates a Jobs JSON request document from an #AwsIotJobsRequestInfo_t * and an #AwsIotJobsUpdateInfo_t. * * @param[in] type The type of Jobs operation for the request. * @param[in] pRequestInfo Common Jobs request parameters. * @param[in] pRequestContents Additional values to place in the JSON document, * depending on `type`. * @param[in] pOperation Operation associated with the Jobs request. * * @return #AWS_IOT_JOBS_SUCCESS on success; otherwise, #AWS_IOT_JOBS_NO_MEMORY. */ AwsIotJobsError_t _AwsIotJobs_GenerateJsonRequest( _jobsOperationType_t type, const AwsIotJobsRequestInfo_t * pRequestInfo, const _jsonRequestContents_t * pRequestContents, _jobsOperation_t * pOperation ); /** * @brief Parse a response received from the Jobs service. * * @param[in] status Either ACCEPTED or REJECTED. * @param[in] pResponse The response received from the Jobs service. * @param[in] responseLength Length of `pResponse`. * @param[out] pOperation Associated Jobs operation, where parse results are * written. */ void _AwsIotJobs_ParseResponse( AwsIotStatus_t status, const char * pResponse, size_t responseLength, _jobsOperation_t * pOperation ); #endif /* ifndef AWS_IOT_JOBS_INTERNAL_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Plus/Source/FreeRTOS-Plus-TCP/FreeRTOS_TCP_WIN.c
<reponame>MicroEJ/FreeRTOS /* * FreeRTOS+TCP V2.2.0 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /* * FreeRTOS_TCP_WIN.c * Module which handles the TCP windowing schemes for FreeRTOS+TCP. Many * functions have two versions - one for FreeRTOS+TCP (full) and one for * FreeRTOS+TCP (lite). * * In this module all ports and IP addresses and sequence numbers are * being stored in host byte-order. */ /* Standard includes. */ #include <stdint.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_UDP_IP.h" #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" #include "FreeRTOS_IP_Private.h" #include "NetworkBufferManagement.h" #include "FreeRTOS_TCP_WIN.h" /* Constants used for Smoothed Round Trip Time (SRTT). */ #define winSRTT_INCREMENT_NEW 2 #define winSRTT_INCREMENT_CURRENT 6 #define winSRTT_DECREMENT_NEW 1 #define winSRTT_DECREMENT_CURRENT 7 #define winSRTT_CAP_mS 50 #if( ipconfigUSE_TCP_WIN == 1 ) #define xTCPWindowRxNew( pxWindow, ulSequenceNumber, lCount ) xTCPWindowNew( pxWindow, ulSequenceNumber, lCount, pdTRUE ) #define xTCPWindowTxNew( pxWindow, ulSequenceNumber, lCount ) xTCPWindowNew( pxWindow, ulSequenceNumber, lCount, pdFALSE ) /* The code to send a single Selective ACK (SACK): * NOP (0x01), NOP (0x01), SACK (0x05), LEN (0x0a), * followed by a lower and a higher sequence number, * where LEN is 2 + 2*4 = 10 bytes. */ #if( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN ) #define OPTION_CODE_SINGLE_SACK ( 0x0101050aUL ) #else #define OPTION_CODE_SINGLE_SACK ( 0x0a050101UL ) #endif /* Normal retransmission: * A packet will be retransmitted after a Retransmit Time-Out (RTO). * Fast retransmission: * When 3 packets with a higher sequence number have been acknowledged * by the peer, it is very unlikely a current packet will ever arrive. * It will be retransmitted far before the RTO. */ #define DUPLICATE_ACKS_BEFORE_FAST_RETRANSMIT ( 3u ) /* If there have been several retransmissions (4), decrease the * size of the transmission window to at most 2 times MSS. */ #define MAX_TRANSMIT_COUNT_USING_LARGE_WINDOW ( 4u ) #endif /* configUSE_TCP_WIN */ /*-----------------------------------------------------------*/ extern void vListInsertGeneric( List_t * const pxList, ListItem_t * const pxNewListItem, MiniListItem_t * const pxWhere ); /* * All TCP sockets share a pool of segment descriptors (TCPSegment_t) * Available descriptors are stored in the 'xSegmentList' * When a socket owns a descriptor, it will either be stored in * 'xTxSegments' or 'xRxSegments' * As soon as a package has been confirmed, the descriptor will be returned * to the segment pool */ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvCreateSectors( void ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Find a segment with a given sequence number in the list of received * segments: 'pxWindow->xRxSegments'. */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxFind( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Allocate a new segment * The socket will borrow all segments from a common pool: 'xSegmentList', * which is a list of 'TCPSegment_t' */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowNew( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, int32_t lCount, BaseType_t xIsForRx ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* When the peer has a close request (FIN flag), the driver will check if * there are missing packets in the Rx-queue * It will accept the closure of the connection if both conditions are true: * - the Rx-queue is empty * - we've ACK'd the highest Rx sequence number seen */ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowRxEmpty( TCPWindow_t *pxWindow ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Detaches and returns the head of a queue */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowGetHead( List_t *pxList ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Returns the head of a queue but it won't be detached */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowPeekHead( List_t *pxList ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Free entry pxSegment because it's not used anymore * The ownership will be passed back to the segment pool */ #if( ipconfigUSE_TCP_WIN == 1 ) static void vTCPWindowFree( TCPSegment_t *pxSegment ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * A segment has been received with sequence number 'ulSequenceNumber', where * 'ulCurrentSequenceNumber == ulSequenceNumber', which means that exactly this * segment was expected. xTCPWindowRxConfirm() will check if there is already * another segment with a sequence number between (ulSequenceNumber) and * (ulSequenceNumber+xLength). Normally none will be found, because the next Rx * segment should have a sequence number equal to '(ulSequenceNumber+xLength)'. */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxConfirm( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * FreeRTOS+TCP stores data in circular buffers. Calculate the next position to * store. */ #if( ipconfigUSE_TCP_WIN == 1 ) static int32_t lTCPIncrementTxPosition( int32_t lPosition, int32_t lMax, int32_t lCount ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * This function will look if there is new transmission data. It will return * true if there is data to be sent. */ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * An acknowledge was received. See if some outstanding data may be removed * from the transmission queue(s). */ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowTxCheckAck( TCPWindow_t *pxWindow, uint32_t ulFirst, uint32_t ulLast ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * A higher Tx block has been acknowledged. Now iterate through the xWaitQueue * to find a possible condition for a FAST retransmission. */ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowFastRetransmit( TCPWindow_t *pxWindow, uint32_t ulFirst ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /* TCP segment pool. */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPSegments = NULL; #endif /* ipconfigUSE_TCP_WIN == 1 */ /* List of free TCP segments. */ #if( ipconfigUSE_TCP_WIN == 1 ) static List_t xSegmentList; #endif /* Logging verbosity level. */ BaseType_t xTCPWindowLoggingLevel = 0; #if( ipconfigUSE_TCP_WIN == 1 ) /* Some 32-bit arithmetic: comparing sequence numbers */ static portINLINE BaseType_t xSequenceLessThanOrEqual( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceLessThanOrEqual( uint32_t a, uint32_t b ) { /* Test if a <= b Return true if the unsigned subtraction of (b-a) doesn't generate an arithmetic overflow. */ return ( ( b - a ) & 0x80000000UL ) == 0UL; } #endif /* ipconfigUSE_TCP_WIN */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static portINLINE BaseType_t xSequenceLessThan( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceLessThan( uint32_t a, uint32_t b ) { /* Test if a < b */ return ( ( b - a - 1UL ) & 0x80000000UL ) == 0UL; } #endif /* ipconfigUSE_TCP_WIN */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static portINLINE BaseType_t xSequenceGreaterThan( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceGreaterThan( uint32_t a, uint32_t b ) { /* Test if a > b */ return ( ( a - b - 1UL ) & 0x80000000UL ) == 0UL; } #endif /* ipconfigUSE_TCP_WIN */ /*-----------------------------------------------------------*/ static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a, uint32_t b ) { /* Test if a >= b */ return ( ( a - b ) & 0x80000000UL ) == 0UL; } /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static portINLINE void vListInsertFifo( List_t * const pxList, ListItem_t * const pxNewListItem ); static portINLINE void vListInsertFifo( List_t * const pxList, ListItem_t * const pxNewListItem ) { vListInsertGeneric( pxList, pxNewListItem, &pxList->xListEnd ); } #endif /*-----------------------------------------------------------*/ static portINLINE void vTCPTimerSet( TCPTimer_t *pxTimer ); static portINLINE void vTCPTimerSet( TCPTimer_t *pxTimer ) { pxTimer->ulBorn = xTaskGetTickCount ( ); } /*-----------------------------------------------------------*/ static portINLINE uint32_t ulTimerGetAge( TCPTimer_t *pxTimer ); static portINLINE uint32_t ulTimerGetAge( TCPTimer_t *pxTimer ) { return ( ( xTaskGetTickCount() - pxTimer->ulBorn ) * portTICK_PERIOD_MS ); } /*-----------------------------------------------------------*/ /* _HT_ GCC (using the settings that I'm using) checks for every public function if it is preceded by a prototype. Later this prototype will be located in list.h? */ extern void vListInsertGeneric( List_t * const pxList, ListItem_t * const pxNewListItem, MiniListItem_t * const pxWhere ); void vListInsertGeneric( List_t * const pxList, ListItem_t * const pxNewListItem, MiniListItem_t * const pxWhere ) { /* Insert a new list item into pxList, it does not sort the list, but it puts the item just before xListEnd, so it will be the last item returned by listGET_HEAD_ENTRY() */ pxNewListItem->pxNext = (struct xLIST_ITEM * configLIST_VOLATILE)pxWhere; pxNewListItem->pxPrevious = pxWhere->pxPrevious; pxWhere->pxPrevious->pxNext = pxNewListItem; pxWhere->pxPrevious = pxNewListItem; /* Remember which list the item is in. */ listLIST_ITEM_CONTAINER( pxNewListItem ) = ( void * ) pxList; ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvCreateSectors( void ) { BaseType_t xIndex, xReturn; /* Allocate space for 'xTCPSegments' and store them in 'xSegmentList'. */ vListInitialise( &xSegmentList ); xTCPSegments = ( TCPSegment_t * ) pvPortMallocLarge( ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ); if( xTCPSegments == NULL ) { FreeRTOS_debug_printf( ( "prvCreateSectors: malloc %lu failed\n", ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ) ); xReturn = pdFAIL; } else { /* Clear the allocated space. */ memset( xTCPSegments, '\0', ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ); for( xIndex = 0; xIndex < ipconfigTCP_WIN_SEG_COUNT; xIndex++ ) { /* Could call vListInitialiseItem here but all data has been nulled already. Set the owner to a segment descriptor. */ listSET_LIST_ITEM_OWNER( &( xTCPSegments[ xIndex ].xListItem ), ( void* ) &( xTCPSegments[ xIndex ] ) ); listSET_LIST_ITEM_OWNER( &( xTCPSegments[ xIndex ].xQueueItem ), ( void* ) &( xTCPSegments[ xIndex ] ) ); /* And add it to the pool of available segments */ vListInsertFifo( &xSegmentList, &( xTCPSegments[xIndex].xListItem ) ); } xReturn = pdPASS; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxFind( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ) { const ListItem_t *pxIterator; const MiniListItem_t* pxEnd; TCPSegment_t *pxSegment, *pxReturn = NULL; /* Find a segment with a given sequence number in the list of received segments. */ pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &pxWindow->xRxSegments ); for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); pxIterator != ( const ListItem_t * ) pxEnd; pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) ) { pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); if( pxSegment->ulSequenceNumber == ulSequenceNumber ) { pxReturn = pxSegment; break; } } return pxReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowNew( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, int32_t lCount, BaseType_t xIsForRx ) { TCPSegment_t *pxSegment; ListItem_t * pxItem; /* Allocate a new segment. The socket will borrow all segments from a common pool: 'xSegmentList', which is a list of 'TCPSegment_t' */ if( listLIST_IS_EMPTY( &xSegmentList ) != pdFALSE ) { /* If the TCP-stack runs out of segments, you might consider increasing 'ipconfigTCP_WIN_SEG_COUNT'. */ FreeRTOS_debug_printf( ( "xTCPWindow%cxNew: Error: all segments occupied\n", xIsForRx ? 'R' : 'T' ) ); pxSegment = NULL; } else { /* Pop the item at the head of the list. Semaphore protection is not required as only the IP task will call these functions. */ pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( &xSegmentList ); pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxItem ); configASSERT( pxItem != NULL ); configASSERT( pxSegment != NULL ); /* Remove the item from xSegmentList. */ uxListRemove( pxItem ); /* Add it to either the connections' Rx or Tx queue. */ vListInsertFifo( xIsForRx ? &pxWindow->xRxSegments : &pxWindow->xTxSegments, pxItem ); /* And set the segment's timer to zero */ vTCPTimerSet( &pxSegment->xTransmitTimer ); pxSegment->u.ulFlags = 0; pxSegment->u.bits.bIsForRx = ( xIsForRx != 0 ); pxSegment->lMaxLength = lCount; pxSegment->lDataLength = lCount; pxSegment->ulSequenceNumber = ulSequenceNumber; #if( ipconfigHAS_DEBUG_PRINTF != 0 ) { static UBaseType_t xLowestLength = ipconfigTCP_WIN_SEG_COUNT; UBaseType_t xLength = listCURRENT_LIST_LENGTH( &xSegmentList ); if( xLowestLength > xLength ) { xLowestLength = xLength; } } #endif /* ipconfigHAS_DEBUG_PRINTF */ } return pxSegment; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowRxEmpty( TCPWindow_t *pxWindow ) { BaseType_t xReturn; /* When the peer has a close request (FIN flag), the driver will check if there are missing packets in the Rx-queue. It will accept the closure of the connection if both conditions are true: - the Rx-queue is empty - the highest Rx sequence number has been ACK'ed */ if( listLIST_IS_EMPTY( ( &pxWindow->xRxSegments ) ) == pdFALSE ) { /* Rx data has been stored while earlier packets were missing. */ xReturn = pdFALSE; } else if( xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber ) != pdFALSE ) { /* No Rx packets are being stored and the highest sequence number that has been received has been ACKed. */ xReturn = pdTRUE; } else { FreeRTOS_debug_printf( ( "xTCPWindowRxEmpty: cur %lu highest %lu (empty)\n", ( pxWindow->rx.ulCurrentSequenceNumber - pxWindow->rx.ulFirstSequenceNumber ), ( pxWindow->rx.ulHighestSequenceNumber - pxWindow->rx.ulFirstSequenceNumber ) ) ); xReturn = pdFALSE; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowGetHead( List_t *pxList ) { TCPSegment_t *pxSegment; ListItem_t * pxItem; /* Detaches and returns the head of a queue. */ if( listLIST_IS_EMPTY( pxList ) != pdFALSE ) { pxSegment = NULL; } else { pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( pxList ); pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxItem ); uxListRemove( pxItem ); } return pxSegment; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowPeekHead( List_t *pxList ) { ListItem_t *pxItem; TCPSegment_t *pxReturn; /* Returns the head of a queue but it won't be detached. */ if( listLIST_IS_EMPTY( pxList ) != pdFALSE ) { pxReturn = NULL; } else { pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( pxList ); pxReturn = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxItem ); } return pxReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static void vTCPWindowFree( TCPSegment_t *pxSegment ) { /* Free entry pxSegment because it's not used any more. The ownership will be passed back to the segment pool. Unlink it from one of the queues, if any. */ if( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) != NULL ) { uxListRemove( &( pxSegment->xQueueItem ) ); } pxSegment->ulSequenceNumber = 0u; pxSegment->lDataLength = 0l; pxSegment->u.ulFlags = 0u; /* Take it out of xRxSegments/xTxSegments */ if( listLIST_ITEM_CONTAINER( &( pxSegment->xListItem ) ) != NULL ) { uxListRemove( &( pxSegment->xListItem ) ); } /* Return it to xSegmentList */ vListInsertFifo( &xSegmentList, &( pxSegment->xListItem ) ); } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) void vTCPWindowDestroy( TCPWindow_t *pxWindow ) { List_t * pxSegments; BaseType_t xRound; TCPSegment_t *pxSegment; /* Destroy a window. A TCP window doesn't serve any more. Return all owned segments to the pool. In order to save code, it will make 2 rounds, one to remove the segments from xRxSegments, and a second round to clear xTxSegments*/ for( xRound = 0; xRound < 2; xRound++ ) { if( xRound != 0 ) { pxSegments = &( pxWindow->xRxSegments ); } else { pxSegments = &( pxWindow->xTxSegments ); } if( listLIST_IS_INITIALISED( pxSegments ) != pdFALSE ) { while( listCURRENT_LIST_LENGTH( pxSegments ) > 0U ) { pxSegment = ( TCPSegment_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxSegments ); vTCPWindowFree( pxSegment ); } } } } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ void vTCPWindowCreate( TCPWindow_t *pxWindow, uint32_t ulRxWindowLength, uint32_t ulTxWindowLength, uint32_t ulAckNumber, uint32_t ulSequenceNumber, uint32_t ulMSS ) { /* Create and initialize a window. */ #if( ipconfigUSE_TCP_WIN == 1 ) { if( xTCPSegments == NULL ) { prvCreateSectors(); } vListInitialise( &pxWindow->xTxSegments ); vListInitialise( &pxWindow->xRxSegments ); vListInitialise( &pxWindow->xPriorityQueue ); /* Priority queue: segments which must be sent immediately */ vListInitialise( &pxWindow->xTxQueue ); /* Transmit queue: segments queued for transmission */ vListInitialise( &pxWindow->xWaitQueue ); /* Waiting queue: outstanding segments */ } #endif /* ipconfigUSE_TCP_WIN == 1 */ if( xTCPWindowLoggingLevel != 0 ) { FreeRTOS_debug_printf( ( "vTCPWindowCreate: for WinLen = Rx/Tx: %lu/%lu\n", ulRxWindowLength, ulTxWindowLength ) ); } pxWindow->xSize.ulRxWindowLength = ulRxWindowLength; pxWindow->xSize.ulTxWindowLength = ulTxWindowLength; vTCPWindowInit( pxWindow, ulAckNumber, ulSequenceNumber, ulMSS ); } /*-----------------------------------------------------------*/ void vTCPWindowInit( TCPWindow_t *pxWindow, uint32_t ulAckNumber, uint32_t ulSequenceNumber, uint32_t ulMSS ) { const int32_t l500ms = 500; pxWindow->u.ulFlags = 0ul; pxWindow->u.bits.bHasInit = pdTRUE_UNSIGNED; if( ulMSS != 0ul ) { if( pxWindow->usMSSInit != 0u ) { pxWindow->usMSSInit = ( uint16_t ) ulMSS; } if( ( ulMSS < ( uint32_t ) pxWindow->usMSS ) || ( pxWindow->usMSS == 0u ) ) { pxWindow->xSize.ulRxWindowLength = ( pxWindow->xSize.ulRxWindowLength / ulMSS ) * ulMSS; pxWindow->usMSS = ( uint16_t ) ulMSS; } } #if( ipconfigUSE_TCP_WIN == 0 ) { pxWindow->xTxSegment.lMaxLength = ( int32_t ) pxWindow->usMSS; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*Start with a timeout of 2 * 500 ms (1 sec). */ pxWindow->lSRTT = l500ms; /* Just for logging, to print relative sequence numbers. */ pxWindow->rx.ulFirstSequenceNumber = ulAckNumber; /* The segment asked for in the next transmission. */ pxWindow->rx.ulCurrentSequenceNumber = ulAckNumber; /* The right-hand side of the receive window. */ pxWindow->rx.ulHighestSequenceNumber = ulAckNumber; pxWindow->tx.ulFirstSequenceNumber = ulSequenceNumber; /* The segment asked for in next transmission. */ pxWindow->tx.ulCurrentSequenceNumber = ulSequenceNumber; /* The sequence number given to the next outgoing byte to be added is maintained by lTCPWindowTxAdd(). */ pxWindow->ulNextTxSequenceNumber = ulSequenceNumber; /* The right-hand side of the transmit window. */ pxWindow->tx.ulHighestSequenceNumber = ulSequenceNumber; pxWindow->ulOurSequenceNumber = ulSequenceNumber; } /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) void vTCPSegmentCleanup( void ) { /* Free and clear the TCP segments pointer. This function should only be called * once FreeRTOS+TCP will no longer be used. No thread-safety is provided for this * function. */ if( xTCPSegments != NULL ) { vPortFreeLarge( xTCPSegments ); xTCPSegments = NULL; } } #endif /* ipconfgiUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /*============================================================================= * * ###### # # * # # # # * # # # # * # # #### * ###### ## * # ## #### * # # # # * # # # # * ### ## # # * Rx functions * *=============================================================================*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxConfirm( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength ) { TCPSegment_t *pxBest = NULL; const ListItem_t *pxIterator; uint32_t ulNextSequenceNumber = ulSequenceNumber + ulLength; const MiniListItem_t* pxEnd = ( const MiniListItem_t* ) listGET_END_MARKER( &pxWindow->xRxSegments ); TCPSegment_t *pxSegment; /* A segment has been received with sequence number 'ulSequenceNumber', where 'ulCurrentSequenceNumber == ulSequenceNumber', which means that exactly this segment was expected. xTCPWindowRxConfirm() will check if there is already another segment with a sequence number between (ulSequenceNumber) and (ulSequenceNumber+ulLength). Normally none will be found, because the next RX segment should have a sequence number equal to '(ulSequenceNumber+ulLength)'. */ /* Iterate through all RX segments that are stored: */ for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); pxIterator != ( const ListItem_t * ) pxEnd; pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) ) { pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); /* And see if there is a segment for which: 'ulSequenceNumber' <= 'pxSegment->ulSequenceNumber' < 'ulNextSequenceNumber' If there are more matching segments, the one with the lowest sequence number shall be taken */ if( ( xSequenceGreaterThanOrEqual( pxSegment->ulSequenceNumber, ulSequenceNumber ) != 0 ) && ( xSequenceLessThan( pxSegment->ulSequenceNumber, ulNextSequenceNumber ) != 0 ) ) { if( ( pxBest == NULL ) || ( xSequenceLessThan( pxSegment->ulSequenceNumber, pxBest->ulSequenceNumber ) != 0 ) ) { pxBest = pxSegment; } } } if( ( pxBest != NULL ) && ( ( pxBest->ulSequenceNumber != ulSequenceNumber ) || ( pxBest->lDataLength != ( int32_t ) ulLength ) ) ) { FreeRTOS_flush_logging(); FreeRTOS_debug_printf( ( "xTCPWindowRxConfirm[%u]: search %lu (+%ld=%lu) found %lu (+%ld=%lu)\n", pxWindow->usPeerPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, ulLength, ulSequenceNumber + ulLength - pxWindow->rx.ulFirstSequenceNumber, pxBest->ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, pxBest->lDataLength, pxBest->ulSequenceNumber + ( ( uint32_t ) pxBest->lDataLength ) - pxWindow->rx.ulFirstSequenceNumber ) ); } return pxBest; } #endif /* ipconfgiUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) int32_t lTCPWindowRxCheck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength, uint32_t ulSpace ) { uint32_t ulCurrentSequenceNumber, ulLast, ulSavedSequenceNumber; int32_t lReturn, lDistance; TCPSegment_t *pxFound; /* If lTCPWindowRxCheck( ) returns == 0, the packet will be passed directly to user (segment is expected). If it returns a positive number, an earlier packet is missing, but this packet may be stored. If negative, the packet has already been stored, or it is out-of-order, or there is not enough space. As a side-effect, pxWindow->ulUserDataLength will get set to non-zero, if more Rx data may be passed to the user after this packet. */ ulCurrentSequenceNumber = pxWindow->rx.ulCurrentSequenceNumber; /* For Selective Ack (SACK), used when out-of-sequence data come in. */ pxWindow->ucOptionLength = 0u; /* Non-zero if TCP-windows contains data which must be popped. */ pxWindow->ulUserDataLength = 0ul; if( ulCurrentSequenceNumber == ulSequenceNumber ) { /* This is the packet with the lowest sequence number we're waiting for. It can be passed directly to the rx stream. */ if( ulLength > ulSpace ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck: Refuse %lu bytes, due to lack of space (%lu)\n", ulLength, ulSpace ) ); lReturn = -1; } else { ulCurrentSequenceNumber += ulLength; if( listCURRENT_LIST_LENGTH( &( pxWindow->xRxSegments ) ) != 0 ) { ulSavedSequenceNumber = ulCurrentSequenceNumber; /* Clean up all sequence received between ulSequenceNumber and ulSequenceNumber + ulLength since they are duplicated. If the server is forced to retransmit packets several time in a row it might send a batch of concatenated packet for speed. So we cannot rely on the packets between ulSequenceNumber and ulSequenceNumber + ulLength to be sequential and it is better to just clean them out. */ do { pxFound = xTCPWindowRxConfirm( pxWindow, ulSequenceNumber, ulLength ); if ( pxFound != NULL ) { /* Remove it because it will be passed to user directly. */ vTCPWindowFree( pxFound ); } } while ( pxFound ); /* Check for following segments that are already in the queue and increment ulCurrentSequenceNumber. */ while( ( pxFound = xTCPWindowRxFind( pxWindow, ulCurrentSequenceNumber ) ) != NULL ) { ulCurrentSequenceNumber += ( uint32_t ) pxFound->lDataLength; /* As all packet below this one have been passed to the user it can be discarded. */ vTCPWindowFree( pxFound ); } if( ulSavedSequenceNumber != ulCurrentSequenceNumber ) { /* After the current data-package, there is more data to be popped. */ pxWindow->ulUserDataLength = ulCurrentSequenceNumber - ulSavedSequenceNumber; if( xTCPWindowLoggingLevel >= 1 ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%d,%d]: retran %lu (Found %lu bytes at %lu cnt %ld)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, pxWindow->ulUserDataLength, ulSavedSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, listCURRENT_LIST_LENGTH( &pxWindow->xRxSegments ) ) ); } } } pxWindow->rx.ulCurrentSequenceNumber = ulCurrentSequenceNumber; /* Packet was expected, may be passed directly to the socket buffer or application. Store the packet at offset 0. */ lReturn = 0; } } else if( ulCurrentSequenceNumber == ( ulSequenceNumber + 1UL ) ) { /* Looks like a TCP keep-alive message. Do not accept/store Rx data ulUserDataLength = 0. Not packet out-of-sync. Just reply to it. */ lReturn = -1; } else { /* The packet is not the one expected. See if it falls within the Rx window so it can be stored. */ /* An "out-of-sequence" segment was received, must have missed one. Prepare a SACK (Selective ACK). */ ulLast = ulSequenceNumber + ulLength; lDistance = ( int32_t ) ( ulLast - ulCurrentSequenceNumber ); if( lDistance <= 0 ) { /* An earlier has been received, must be a retransmission of a packet that has been accepted already. No need to send out a Selective ACK (SACK). */ lReturn = -1; } else if( lDistance > ( int32_t ) ulSpace ) { /* The new segment is ahead of rx.ulCurrentSequenceNumber. The sequence number of this packet is too far ahead, ignore it. */ FreeRTOS_debug_printf( ( "lTCPWindowRxCheck: Refuse %lu+%lu bytes, due to lack of space (%lu)\n", lDistance, ulLength, ulSpace ) ); lReturn = -1; } else { /* See if there is more data in a contiguous block to make the SACK describe a longer range of data. */ /* TODO: SACK's may also be delayed for a short period * This is useful because subsequent packets will be SACK'd with * single one message */ while( ( pxFound = xTCPWindowRxFind( pxWindow, ulLast ) ) != NULL ) { ulLast += ( uint32_t ) pxFound->lDataLength; } if( xTCPWindowLoggingLevel >= 1 ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%d,%d]: seqnr %lu exp %lu (dist %ld) SACK to %lu\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, ulCurrentSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, ( BaseType_t ) ( ulSequenceNumber - ulCurrentSequenceNumber ), /* want this signed */ ulLast - pxWindow->rx.ulFirstSequenceNumber ) ); } /* Now prepare the SACK message. Code OPTION_CODE_SINGLE_SACK already in network byte order. */ pxWindow->ulOptionsData[0] = OPTION_CODE_SINGLE_SACK; /* First sequence number that we received. */ pxWindow->ulOptionsData[1] = FreeRTOS_htonl( ulSequenceNumber ); /* Last + 1 */ pxWindow->ulOptionsData[2] = FreeRTOS_htonl( ulLast ); /* Which make 12 (3*4) option bytes. */ pxWindow->ucOptionLength = 3 * sizeof( pxWindow->ulOptionsData[ 0 ] ); pxFound = xTCPWindowRxFind( pxWindow, ulSequenceNumber ); if( pxFound != NULL ) { /* This out-of-sequence packet has been received for a second time. It is already stored but do send a SACK again. */ lReturn = -1; } else { pxFound = xTCPWindowRxNew( pxWindow, ulSequenceNumber, ( int32_t ) ulLength ); if( pxFound == NULL ) { /* Can not send a SACK, because the segment cannot be stored. */ pxWindow->ucOptionLength = 0u; /* Needs to be stored but there is no segment available. */ lReturn = -1; } else { if( xTCPWindowLoggingLevel != 0 ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%u,%u]: seqnr %lu (cnt %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, listCURRENT_LIST_LENGTH( &pxWindow->xRxSegments ) ) ); FreeRTOS_flush_logging( ); } /* Return a positive value. The packet may be accepted and stored but an earlier packet is still missing. */ lReturn = ( int32_t ) ( ulSequenceNumber - ulCurrentSequenceNumber ); } } } } return lReturn; } #endif /* ipconfgiUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /*============================================================================= * * ######### # # * # # # # # * # # # * # #### * # ## * # #### * # # # * # # # * ##### # # * * Tx functions * *=============================================================================*/ #if( ipconfigUSE_TCP_WIN == 1 ) static int32_t lTCPIncrementTxPosition( int32_t lPosition, int32_t lMax, int32_t lCount ) { /* +TCP stores data in circular buffers. Calculate the next position to store. */ lPosition += lCount; if( lPosition >= lMax ) { lPosition -= lMax; } return lPosition; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) int32_t lTCPWindowTxAdd( TCPWindow_t *pxWindow, uint32_t ulLength, int32_t lPosition, int32_t lMax ) { int32_t lBytesLeft = ( int32_t ) ulLength, lToWrite; int32_t lDone = 0; TCPSegment_t *pxSegment = pxWindow->pxHeadSegment; /* Puts a message in the Tx-window (after buffer size has been verified). */ if( pxSegment != NULL ) { if( pxSegment->lDataLength < pxSegment->lMaxLength ) { if( ( pxSegment->u.bits.bOutstanding == pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength != 0 ) ) { /* Adding data to a segment that was already in the TX queue. It will be filled-up to a maximum of MSS (maximum segment size). */ lToWrite = FreeRTOS_min_int32( lBytesLeft, pxSegment->lMaxLength - pxSegment->lDataLength ); pxSegment->lDataLength += lToWrite; if( pxSegment->lDataLength >= pxSegment->lMaxLength ) { /* This segment is full, don't add more bytes. */ pxWindow->pxHeadSegment = NULL; } lBytesLeft -= lToWrite; /* ulNextTxSequenceNumber is the sequence number of the next byte to be stored for transmission. */ pxWindow->ulNextTxSequenceNumber += ( uint32_t ) lToWrite; /* Increased the return value. */ lDone += lToWrite; /* Some detailed logging, for those who're interested. */ if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != 0 ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: Add %4lu bytes for seqNr %lu len %4lu (nxt %lu) pos %lu\n", ulLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lDataLength, pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lStreamPos ) ); FreeRTOS_flush_logging( ); } /* Calculate the next position in the circular data buffer, knowing its maximum length 'lMax'. */ lPosition = lTCPIncrementTxPosition( lPosition, lMax, lToWrite ); } } } while( lBytesLeft > 0 ) { /* The current transmission segment is full, create new segments as needed. */ pxSegment = xTCPWindowTxNew( pxWindow, pxWindow->ulNextTxSequenceNumber, pxWindow->usMSS ); if( pxSegment != NULL ) { /* Store as many as needed, but no more than the maximum (MSS). */ lToWrite = FreeRTOS_min_int32( lBytesLeft, pxSegment->lMaxLength ); pxSegment->lDataLength = lToWrite; pxSegment->lStreamPos = lPosition; lBytesLeft -= lToWrite; lPosition = lTCPIncrementTxPosition( lPosition, lMax, lToWrite ); pxWindow->ulNextTxSequenceNumber += ( uint32_t ) lToWrite; lDone += lToWrite; /* Link this segment in the Tx-Queue. */ vListInsertFifo( &( pxWindow->xTxQueue ), &( pxSegment->xQueueItem ) ); /* Let 'pxHeadSegment' point to this segment if there is still space. */ if( pxSegment->lDataLength < pxSegment->lMaxLength ) { pxWindow->pxHeadSegment = pxSegment; } else { pxWindow->pxHeadSegment = NULL; } if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != 0 ) { if( ( xTCPWindowLoggingLevel >= 3 ) || ( ( xTCPWindowLoggingLevel >= 2 ) && ( pxWindow->pxHeadSegment != NULL ) ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: New %4ld bytes for seqNr %lu len %4lu (nxt %lu) pos %lu\n", ulLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lDataLength, pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lStreamPos ) ); FreeRTOS_flush_logging( ); } } } else { /* A sever situation: running out of segments for transmission. No more data can be sent at the moment. */ if( lDone != 0 ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: Sorry all buffers full (cancel %ld bytes)\n", lBytesLeft ) ); } break; } } return lDone; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowTxDone( TCPWindow_t *pxWindow ) { return listLIST_IS_EMPTY( ( &pxWindow->xTxSegments) ); } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ) { uint32_t ulTxOutstanding; BaseType_t xHasSpace; TCPSegment_t *pxSegment; /* This function will look if there is new transmission data. It will return true if there is data to be sent. */ pxSegment = xTCPWindowPeekHead( &( pxWindow->xTxQueue ) ); if( pxSegment == NULL ) { xHasSpace = pdFALSE; } else { /* How much data is outstanding, i.e. how much data has been sent but not yet acknowledged ? */ if( pxWindow->tx.ulHighestSequenceNumber >= pxWindow->tx.ulCurrentSequenceNumber ) { ulTxOutstanding = pxWindow->tx.ulHighestSequenceNumber - pxWindow->tx.ulCurrentSequenceNumber; } else { ulTxOutstanding = 0UL; } /* Subtract this from the peer's space. */ ulWindowSize -= FreeRTOS_min_uint32( ulWindowSize, ulTxOutstanding ); /* See if the next segment may be sent. */ if( ulWindowSize >= ( uint32_t ) pxSegment->lDataLength ) { xHasSpace = pdTRUE; } else { xHasSpace = pdFALSE; } /* If 'xHasSpace', it looks like the peer has at least space for 1 more new segment of size MSS. xSize.ulTxWindowLength is the self-imposed limitation of the transmission window (in case of many resends it may be decreased). */ if( ( ulTxOutstanding != 0UL ) && ( pxWindow->xSize.ulTxWindowLength < ulTxOutstanding + ( ( uint32_t ) pxSegment->lDataLength ) ) ) { xHasSpace = pdFALSE; } } return xHasSpace; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowTxHasData( TCPWindow_t *pxWindow, uint32_t ulWindowSize, TickType_t *pulDelay ) { TCPSegment_t *pxSegment; BaseType_t xReturn; TickType_t ulAge, ulMaxAge; *pulDelay = 0u; if( listLIST_IS_EMPTY( &pxWindow->xPriorityQueue ) == pdFALSE ) { /* No need to look at retransmissions or new transmission as long as there are priority segments. *pulDelay equals zero, meaning it must be sent out immediately. */ xReturn = pdTRUE; } else { pxSegment = xTCPWindowPeekHead( &( pxWindow->xWaitQueue ) ); if( pxSegment != NULL ) { /* There is an outstanding segment, see if it is time to resend it. */ ulAge = ulTimerGetAge( &pxSegment->xTransmitTimer ); /* After a packet has been sent for the first time, it will wait '1 * lSRTT' ms for an ACK. A second time it will wait '2 * lSRTT' ms, each time doubling the time-out */ ulMaxAge = ( 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulMaxAge > ulAge ) { /* A segment must be sent after this amount of msecs */ *pulDelay = ulMaxAge - ulAge; } xReturn = pdTRUE; } else { /* No priority segment, no outstanding data, see if there is new transmission data. */ pxSegment = xTCPWindowPeekHead( &pxWindow->xTxQueue ); /* See if it fits in the peer's reception window. */ if( pxSegment == NULL ) { xReturn = pdFALSE; } else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) { /* Too many outstanding messages. */ xReturn = pdFALSE; } else if( ( pxWindow->u.bits.bSendFullSize != pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength < pxSegment->lMaxLength ) ) { /* 'bSendFullSize' is a special optimisation. If true, the driver will only sent completely filled packets (of MSS bytes). */ xReturn = pdFALSE; } else { xReturn = pdTRUE; } } } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) uint32_t ulTCPWindowTxGet( TCPWindow_t *pxWindow, uint32_t ulWindowSize, int32_t *plPosition ) { TCPSegment_t *pxSegment; uint32_t ulMaxTime; uint32_t ulReturn = ~0UL; /* Fetches data to be sent-out now. Priority messages: segments with a resend need no check current sliding window size. */ pxSegment = xTCPWindowGetHead( &( pxWindow->xPriorityQueue ) ); pxWindow->ulOurSequenceNumber = pxWindow->tx.ulHighestSequenceNumber; if( pxSegment == NULL ) { /* Waiting messages: outstanding messages with a running timer neither check peer's reception window size because these packets have been sent earlier. */ pxSegment = xTCPWindowPeekHead( &( pxWindow->xWaitQueue ) ); if( pxSegment != NULL ) { /* Do check the timing. */ ulMaxTime = ( 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulTimerGetAge( &pxSegment->xTransmitTimer ) > ulMaxTime ) { /* A normal (non-fast) retransmission. Move it from the head of the waiting queue. */ pxSegment = xTCPWindowGetHead( &( pxWindow->xWaitQueue ) ); pxSegment->u.bits.ucDupAckCount = pdFALSE_UNSIGNED; /* Some detailed logging. */ if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != 0 ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: WaitQueue %ld bytes for sequence number %lu (%lX)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxSegment->lDataLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->ulSequenceNumber ) ); FreeRTOS_flush_logging( ); } } else { pxSegment = NULL; } } if( pxSegment == NULL ) { /* New messages: sent-out for the first time. Check current sliding window size of peer. */ pxSegment = xTCPWindowPeekHead( &( pxWindow->xTxQueue ) ); if( pxSegment == NULL ) { /* No segments queued. */ ulReturn = 0UL; } else if( ( pxWindow->u.bits.bSendFullSize != pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength < pxSegment->lMaxLength ) ) { /* A segment has been queued but the driver waits until it has a full size of MSS. */ ulReturn = 0; } else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) { /* Peer has no more space at this moment. */ ulReturn = 0; } else { /* Move it out of the Tx queue. */ pxSegment = xTCPWindowGetHead( &( pxWindow->xTxQueue ) ); /* Don't let pxHeadSegment point to this segment any more, so no more data will be added. */ if( pxWindow->pxHeadSegment == pxSegment ) { pxWindow->pxHeadSegment = NULL; } /* pxWindow->tx.highest registers the highest sequence number in our transmission window. */ pxWindow->tx.ulHighestSequenceNumber = pxSegment->ulSequenceNumber + ( ( uint32_t ) pxSegment->lDataLength ); /* ...and more detailed logging */ if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: XmitQueue %ld bytes for sequence number %lu (ws %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxSegment->lDataLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulWindowSize ) ); FreeRTOS_flush_logging( ); } } } } else { /* There is a priority segment. It doesn't need any checking for space or timeouts. */ if( xTCPWindowLoggingLevel != 0 ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: PrioQueue %ld bytes for sequence number %lu (ws %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxSegment->lDataLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulWindowSize ) ); FreeRTOS_flush_logging( ); } } /* See if it has already been determined to return 0. */ if( ulReturn != 0UL ) { configASSERT( listLIST_ITEM_CONTAINER( &(pxSegment->xQueueItem ) ) == NULL ); /* Now that the segment will be transmitted, add it to the tail of the waiting queue. */ vListInsertFifo( &pxWindow->xWaitQueue, &pxSegment->xQueueItem ); /* And mark it as outstanding. */ pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED; /* Administer the transmit count, needed for fast retransmissions. */ ( pxSegment->u.bits.ucTransmitCount )++; /* If there have been several retransmissions (4), decrease the size of the transmission window to at most 2 times MSS. */ if( pxSegment->u.bits.ucTransmitCount == MAX_TRANSMIT_COUNT_USING_LARGE_WINDOW ) { if( pxWindow->xSize.ulTxWindowLength > ( 2U * pxWindow->usMSS ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u - %d]: Change Tx window: %lu -> %u\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxWindow->xSize.ulTxWindowLength, 2 * pxWindow->usMSS ) ); pxWindow->xSize.ulTxWindowLength = ( 2UL * pxWindow->usMSS ); } } /* Clear the transmit timer. */ vTCPTimerSet( &( pxSegment->xTransmitTimer ) ); pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber; /* Inform the caller where to find the data within the queue. */ *plPosition = pxSegment->lStreamPos; /* And return the length of the data segment */ ulReturn = ( uint32_t ) pxSegment->lDataLength; } return ulReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowTxCheckAck( TCPWindow_t *pxWindow, uint32_t ulFirst, uint32_t ulLast ) { uint32_t ulBytesConfirmed = 0u; uint32_t ulSequenceNumber = ulFirst, ulDataLength; const ListItem_t *pxIterator; const MiniListItem_t *pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &pxWindow->xTxSegments ); BaseType_t xDoUnlink; TCPSegment_t *pxSegment; /* An acknowledgement or a selective ACK (SACK) was received. See if some outstanding data may be removed from the transmission queue(s). All TX segments for which ( ( ulSequenceNumber >= ulFirst ) && ( ulSequenceNumber < ulLast ) in a contiguous block. Note that the segments are stored in xTxSegments in a strict sequential order. */ /* SRTT[i] = (1-a) * SRTT[i-1] + a * RTT 0 < a < 1; usually a = 1/8 RTO = 2 * SRTT where: RTT is Round Trip Time SRTT is Smoothed RTT RTO is Retransmit timeout A Smoothed RTT will increase quickly, but it is conservative when becoming smaller. */ for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); ( pxIterator != ( const ListItem_t * ) pxEnd ) && ( xSequenceLessThan( ulSequenceNumber, ulLast ) != 0 ); ) { xDoUnlink = pdFALSE; pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); /* Move to the next item because the current item might get removed. */ pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ); /* Continue if this segment does not fall within the ACK'd range. */ if( xSequenceGreaterThan( ulSequenceNumber, pxSegment->ulSequenceNumber ) != pdFALSE ) { continue; } /* Is it ready? */ if( ulSequenceNumber != pxSegment->ulSequenceNumber ) { break; } ulDataLength = ( uint32_t ) pxSegment->lDataLength; if( pxSegment->u.bits.bAcked == pdFALSE_UNSIGNED ) { if( xSequenceGreaterThan( pxSegment->ulSequenceNumber + ( uint32_t )ulDataLength, ulLast ) != pdFALSE ) { /* What happens? Only part of this segment was accepted, probably due to WND limits AAAAAAA BBBBBBB << acked aaaaaaa aaaa << sent */ #if( ipconfigHAS_DEBUG_PRINTF != 0 ) { uint32_t ulFirstSeq = pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber; FreeRTOS_debug_printf( ( "prvTCPWindowTxCheckAck[%u.%u]: %lu - %lu Partial sequence number %lu - %lu\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulFirstSeq - pxWindow->tx.ulFirstSequenceNumber, ulLast - pxWindow->tx.ulFirstSequenceNumber, ulFirstSeq, ulFirstSeq + ulDataLength ) ); } #endif /* ipconfigHAS_DEBUG_PRINTF */ break; } /* This segment is fully ACK'd, set the flag. */ pxSegment->u.bits.bAcked = pdTRUE_UNSIGNED; /* Calculate the RTT only if the segment was sent-out for the first time and if this is the last ACK'd segment in a range. */ if( ( pxSegment->u.bits.ucTransmitCount == 1 ) && ( ( pxSegment->ulSequenceNumber + ulDataLength ) == ulLast ) ) { int32_t mS = ( int32_t ) ulTimerGetAge( &( pxSegment->xTransmitTimer ) ); if( pxWindow->lSRTT >= mS ) { /* RTT becomes smaller: adapt slowly. */ pxWindow->lSRTT = ( ( winSRTT_DECREMENT_NEW * mS ) + ( winSRTT_DECREMENT_CURRENT * pxWindow->lSRTT ) ) / ( winSRTT_DECREMENT_NEW + winSRTT_DECREMENT_CURRENT ); } else { /* RTT becomes larger: adapt quicker */ pxWindow->lSRTT = ( ( winSRTT_INCREMENT_NEW * mS ) + ( winSRTT_INCREMENT_CURRENT * pxWindow->lSRTT ) ) / ( winSRTT_INCREMENT_NEW + winSRTT_INCREMENT_CURRENT ); } /* Cap to the minimum of 50ms. */ if( pxWindow->lSRTT < winSRTT_CAP_mS ) { pxWindow->lSRTT = winSRTT_CAP_mS; } } /* Unlink it from the 3 queues, but do not destroy it (yet). */ xDoUnlink = pdTRUE; } /* pxSegment->u.bits.bAcked is now true. Is it located at the left side of the transmission queue? If so, it may be freed. */ if( ulSequenceNumber == pxWindow->tx.ulCurrentSequenceNumber ) { if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "prvTCPWindowTxCheckAck: %lu - %lu Ready sequence number %lu\n", ulFirst - pxWindow->tx.ulFirstSequenceNumber, ulLast - pxWindow->tx.ulFirstSequenceNumber, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ) ); } /* Increase the left-hand value of the transmission window. */ pxWindow->tx.ulCurrentSequenceNumber += ulDataLength; /* This function will return the number of bytes that the tail of txStream may be advanced. */ ulBytesConfirmed += ulDataLength; /* All segments below tx.ulCurrentSequenceNumber may be freed. */ vTCPWindowFree( pxSegment ); /* No need to unlink it any more. */ xDoUnlink = pdFALSE; } if( ( xDoUnlink != pdFALSE ) && ( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) != NULL ) ) { /* Remove item from its queues. */ uxListRemove( &pxSegment->xQueueItem ); } ulSequenceNumber += ulDataLength; } return ulBytesConfirmed; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowFastRetransmit( TCPWindow_t *pxWindow, uint32_t ulFirst ) { const ListItem_t *pxIterator; const MiniListItem_t* pxEnd; TCPSegment_t *pxSegment; uint32_t ulCount = 0UL; /* A higher Tx block has been acknowledged. Now iterate through the xWaitQueue to find a possible condition for a FAST retransmission. */ pxEnd = ( const MiniListItem_t* ) listGET_END_MARKER( &( pxWindow->xWaitQueue ) ); for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); pxIterator != ( const ListItem_t * ) pxEnd; ) { /* Get the owner, which is a TCP segment. */ pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); /* Hop to the next item before the current gets unlinked. */ pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ); /* Fast retransmission: When 3 packets with a higher sequence number have been acknowledged by the peer, it is very unlikely a current packet will ever arrive. It will be retransmitted far before the RTO. */ if( ( pxSegment->u.bits.bAcked == pdFALSE_UNSIGNED ) && ( xSequenceLessThan( pxSegment->ulSequenceNumber, ulFirst ) != pdFALSE ) && ( ++( pxSegment->u.bits.ucDupAckCount ) == DUPLICATE_ACKS_BEFORE_FAST_RETRANSMIT ) ) { pxSegment->u.bits.ucTransmitCount = pdFALSE_UNSIGNED; /* Not clearing 'ucDupAckCount' yet as more SACK's might come in which might lead to a second fast rexmit. */ if( ( xTCPWindowLoggingLevel >= 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "prvTCPWindowFastRetransmit: Requeue sequence number %lu < %lu\n", pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulFirst - pxWindow->tx.ulFirstSequenceNumber ) ); FreeRTOS_flush_logging( ); } /* Remove it from xWaitQueue. */ uxListRemove( &pxSegment->xQueueItem ); /* Add this segment to the priority queue so it gets retransmitted immediately. */ vListInsertFifo( &( pxWindow->xPriorityQueue ), &( pxSegment->xQueueItem ) ); ulCount++; } } return ulCount; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) uint32_t ulTCPWindowTxAck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ) { uint32_t ulFirstSequence, ulReturn; /* Receive a normal ACK. */ ulFirstSequence = pxWindow->tx.ulCurrentSequenceNumber; if( xSequenceLessThanOrEqual( ulSequenceNumber, ulFirstSequence ) != pdFALSE ) { ulReturn = 0UL; } else { ulReturn = prvTCPWindowTxCheckAck( pxWindow, ulFirstSequence, ulSequenceNumber ); } return ulReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) uint32_t ulTCPWindowTxSack( TCPWindow_t *pxWindow, uint32_t ulFirst, uint32_t ulLast ) { uint32_t ulAckCount = 0UL; uint32_t ulCurrentSequenceNumber = pxWindow->tx.ulCurrentSequenceNumber; /* Receive a SACK option. */ ulAckCount = prvTCPWindowTxCheckAck( pxWindow, ulFirst, ulLast ); prvTCPWindowFastRetransmit( pxWindow, ulFirst ); if( ( xTCPWindowLoggingLevel >= 1 ) && ( xSequenceGreaterThan( ulFirst, ulCurrentSequenceNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxSack[%u,%u]: from %lu to %lu (ack = %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulFirst - pxWindow->tx.ulFirstSequenceNumber, ulLast - pxWindow->tx.ulFirstSequenceNumber, pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ) ); FreeRTOS_flush_logging( ); } return ulAckCount; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /* ##### # ##### #### ###### # # # # # # # # # # # # # # # # # # ### ##### # # # # # # # # # # # # # # ##### # # # # # # #### # # # # # # # # # # # # # # # # # #### # # # # #### ##### # # # #### #### #### # ### */ #if( ipconfigUSE_TCP_WIN == 0 ) int32_t lTCPWindowRxCheck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength, uint32_t ulSpace ) { int32_t iReturn; /* Data was received at 'ulSequenceNumber'. See if it was expected and if there is enough space to store the new data. */ if( ( pxWindow->rx.ulCurrentSequenceNumber != ulSequenceNumber ) || ( ulSpace < ulLength ) ) { iReturn = -1; } else { pxWindow->rx.ulCurrentSequenceNumber += ( uint32_t ) ulLength; iReturn = 0; } return iReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) int32_t lTCPWindowTxAdd( TCPWindow_t *pxWindow, uint32_t ulLength, int32_t lPosition, int32_t lMax ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); int32_t lResult; /* Data is being scheduled for transmission. */ /* lMax would indicate the size of the txStream. */ ( void ) lMax; /* This is tiny TCP: there is only 1 segment for outgoing data. As long as 'lDataLength' is unequal to zero, the segment is still occupied. */ if( pxSegment->lDataLength > 0 ) { lResult = 0L; } else { if( ulLength > ( uint32_t ) pxSegment->lMaxLength ) { if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: can only store %ld / %ld bytes\n", ulLength, pxSegment->lMaxLength ) ); } ulLength = ( uint32_t ) pxSegment->lMaxLength; } if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: SeqNr %ld (%ld) Len %ld\n", pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulLength ) ); } /* The sequence number of the first byte in this packet. */ pxSegment->ulSequenceNumber = pxWindow->ulNextTxSequenceNumber; pxSegment->lDataLength = ( int32_t ) ulLength; pxSegment->lStreamPos = lPosition; pxSegment->u.ulFlags = 0UL; vTCPTimerSet( &( pxSegment->xTransmitTimer ) ); /* Increase the sequence number of the next data to be stored for transmission. */ pxWindow->ulNextTxSequenceNumber += ulLength; lResult = ( int32_t )ulLength; } return lResult; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) uint32_t ulTCPWindowTxGet( TCPWindow_t *pxWindow, uint32_t ulWindowSize, int32_t *plPosition ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); uint32_t ulLength = ( uint32_t ) pxSegment->lDataLength; uint32_t ulMaxTime; if( ulLength != 0UL ) { /* _HT_ Still under investigation */ ( void ) ulWindowSize; if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED ) { /* As 'ucTransmitCount' has a minimum of 1, take 2 * RTT */ ulMaxTime = ( ( uint32_t ) 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulTimerGetAge( &( pxSegment->xTransmitTimer ) ) < ulMaxTime ) { ulLength = 0ul; } } if( ulLength != 0ul ) { pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED; pxSegment->u.bits.ucTransmitCount++; vTCPTimerSet (&pxSegment->xTransmitTimer); pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber; *plPosition = pxSegment->lStreamPos; } } return ulLength; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) BaseType_t xTCPWindowTxDone( TCPWindow_t *pxWindow ) { BaseType_t xReturn; /* Has the outstanding data been sent because user wants to shutdown? */ if( pxWindow->xTxSegment.lDataLength == 0 ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ); static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ) { BaseType_t xReturn; if( ulWindowSize >= pxWindow->usMSSInit ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) BaseType_t xTCPWindowTxHasData( TCPWindow_t *pxWindow, uint32_t ulWindowSize, TickType_t *pulDelay ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); BaseType_t xReturn; TickType_t ulAge, ulMaxAge; /* Check data to be sent. */ *pulDelay = ( TickType_t ) 0; if( pxSegment->lDataLength == 0 ) { /* Got nothing to send right now. */ xReturn = pdFALSE; } else { if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED ) { ulAge = ulTimerGetAge ( &pxSegment->xTransmitTimer ); ulMaxAge = ( ( TickType_t ) 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulMaxAge > ulAge ) { *pulDelay = ulMaxAge - ulAge; } xReturn = pdTRUE; } else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) { /* Too many outstanding messages. */ xReturn = pdFALSE; } else { xReturn = pdTRUE; } } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) uint32_t ulTCPWindowTxAck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); uint32_t ulDataLength = ( uint32_t ) pxSegment->lDataLength; /* Receive a normal ACK */ if( ulDataLength != 0ul ) { if( ulSequenceNumber < ( pxWindow->tx.ulCurrentSequenceNumber + ulDataLength ) ) { if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) { FreeRTOS_debug_printf( ( "win_tx_ack: acked %ld expc %ld len %ld\n", ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulDataLength ) ); } /* Nothing to send right now. */ ulDataLength = 0ul; } else { pxWindow->tx.ulCurrentSequenceNumber += ulDataLength; if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "win_tx_ack: acked seqnr %ld len %ld\n", ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulDataLength ) ); } pxSegment->lDataLength = 0; } } return ulDataLength; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) BaseType_t xTCPWindowRxEmpty( TCPWindow_t *pxWindow ) { /* Return true if 'ulCurrentSequenceNumber >= ulHighestSequenceNumber' 'ulCurrentSequenceNumber' is the highest sequence number stored, 'ulHighestSequenceNumber' is the highest sequence number seen. */ return xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber ); } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) /* Destroy a window (always returns NULL) */ void vTCPWindowDestroy( TCPWindow_t *pxWindow ) { /* As in tiny TCP there are no shared segments descriptors, there is nothing to release. */ ( void ) pxWindow; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/include/ff_format.h
/* * FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab! * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Authors include <NAME>, <NAME> and <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * */ /** * @file ff_format.c * @ingroup FORMAT * **/ #ifndef _FF_FORMAT_H_ #define _FF_FORMAT_H_ #ifdef __cplusplus extern "C" { #endif #ifndef PLUS_FAT_H #error this header will be included from "ff_headers.h" #endif /*---------- PROTOTYPES */ /* PUBLIC (Interfaces): */ typedef enum _FF_SizeType { eSizeIsQuota, /* Assign a quotum (sum of xSizes is free, all disk space will be allocated) */ eSizeIsPercent, /* Assign a percentage of the available space (sum of xSizes must be <= 100) */ eSizeIsSectors, /* Assign fixed number of sectors (sum of xSizes must be < ulSectorCount) */ } eSizeType_t; typedef struct _FF_PartitionParameters { uint32_t ulSectorCount; /* Total number of sectors on the disk, including hidden/reserved */ /* Must be obtained from the block driver */ uint32_t ulHiddenSectors; /* Keep at least these initial sectors free */ uint32_t ulInterSpace; /* Number of sectors to keep free between partitions (when 0 -> 2048) */ BaseType_t xSizes[ ffconfigMAX_PARTITIONS ]; /* E.g. 80, 20, 0, 0 (see eSizeType) */ BaseType_t xPrimaryCount; /* The number of partitions that must be "primary" */ eSizeType_t eSizeType; } FF_PartitionParameters_t; FF_Error_t FF_Partition( FF_Disk_t *pxDisk, FF_PartitionParameters_t *pParams ); FF_Error_t FF_Format( FF_Disk_t *pxDisk, BaseType_t xPartitionNumber, BaseType_t xPreferFAT16, BaseType_t xSmallClusters ); /* Private : */ #ifdef __cplusplus } /* extern "C" */ #endif #endif
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_IoT_Libraries/shadow/shadow_device_operations/mbedtls_config.h
/* * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* This file configures mbed TLS for FreeRTOS. */ #ifndef MBEDTLS_CONFIG_H_ #define MBEDTLS_CONFIG_H_ /* FreeRTOS include. */ #include "FreeRTOS.h" /* Generate errors if deprecated functions are used. */ #define MBEDTLS_DEPRECATED_REMOVED /* Place AES tables in ROM. */ #define MBEDTLS_AES_ROM_TABLES /* Enable the following cipher modes. */ #define MBEDTLS_CIPHER_MODE_CBC #define MBEDTLS_CIPHER_MODE_CFB #define MBEDTLS_CIPHER_MODE_CTR /* Enable the following cipher padding modes. */ #define MBEDTLS_CIPHER_PADDING_PKCS7 #define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS #define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN #define MBEDTLS_CIPHER_PADDING_ZEROS /* Cipher suite configuration. */ #define MBEDTLS_REMOVE_ARC4_CIPHERSUITES #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_NIST_OPTIM #define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED #define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED /* Enable all SSL alert messages. */ #define MBEDTLS_SSL_ALL_ALERT_MESSAGES /* Enable the following SSL features. */ #define MBEDTLS_SSL_ENCRYPT_THEN_MAC #define MBEDTLS_SSL_EXTENDED_MASTER_SECRET #define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH #define MBEDTLS_SSL_PROTO_TLS1_2 #define MBEDTLS_SSL_ALPN #define MBEDTLS_SSL_SERVER_NAME_INDICATION /* Check certificate key usage. */ #define MBEDTLS_X509_CHECK_KEY_USAGE #define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE /* Disable platform entropy functions. */ #define MBEDTLS_NO_PLATFORM_ENTROPY /* Enable the following mbed TLS features. */ #define MBEDTLS_AES_C #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BASE64_C #define MBEDTLS_BIGNUM_C #define MBEDTLS_CIPHER_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_ECDH_C #define MBEDTLS_ECDSA_C #define MBEDTLS_ECP_C #define MBEDTLS_ENTROPY_C #define MBEDTLS_GCM_C #define MBEDTLS_MD_C #define MBEDTLS_OID_C #define MBEDTLS_PEM_PARSE_C #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_PKCS1_V15 #define MBEDTLS_PLATFORM_C #define MBEDTLS_RSA_C #define MBEDTLS_SHA1_C #define MBEDTLS_SHA256_C #define MBEDTLS_SSL_CLI_C #define MBEDTLS_SSL_TLS_C #define MBEDTLS_THREADING_ALT #define MBEDTLS_THREADING_C #define MBEDTLS_X509_USE_C #define MBEDTLS_X509_CRT_PARSE_C /* Set the memory allocation functions on FreeRTOS. */ void * mbedtls_platform_calloc( size_t nmemb, size_t size ); void mbedtls_platform_free( void * ptr ); #define MBEDTLS_PLATFORM_MEMORY #define MBEDTLS_PLATFORM_CALLOC_MACRO mbedtls_platform_calloc #define MBEDTLS_PLATFORM_FREE_MACRO mbedtls_platform_free /* The network send and receive functions on FreeRTOS. */ int mbedtls_platform_send( void * ctx, const unsigned char * buf, size_t len ); int mbedtls_platform_recv( void * ctx, unsigned char * buf, size_t len ); /* The entropy poll function. */ int mbedtls_platform_entropy_poll( void * data, unsigned char * output, size_t len, size_t * olen ); #include "mbedtls/check_config.h" #endif /* ifndef MBEDTLS_CONFIG_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/jobs/src/aws_iot_jobs_subscription.c
<reponame>MicroEJ/FreeRTOS /* * AWS IoT Jobs V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_jobs_subscription.c * @brief Implements functions for interacting with the Jobs library's * subscription list. */ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <string.h> /* Jobs internal include. */ #include "private/aws_iot_jobs_internal.h" /* Error handling include. */ #include "iot_error.h" /* Platform layer includes. */ #include "platform/iot_threads.h" /* MQTT include. */ #include "iot_mqtt.h" /*-----------------------------------------------------------*/ /** * @brief Match two #_jobsSubscription_t by Thing Name. * * @param[in] pSubscriptionLink Pointer to the link member of a #_jobsSubscription_t * containing the Thing Name to check. * @param[in] pMatch Pointer to a `AwsIotThingName_t`. * * @return `true` if the Thing Names match; `false` otherwise. */ static bool _jobsSubscription_match( const IotLink_t * pSubscriptionLink, void * pMatch ); /*-----------------------------------------------------------*/ /** * @brief List of active Jobs subscriptions objects. */ IotListDouble_t _AwsIotJobsSubscriptions = { 0 }; /** * @brief Protects #_AwsIotJobsSubscriptions from concurrent access. */ IotMutex_t _AwsIotJobsSubscriptionsMutex; /*-----------------------------------------------------------*/ static bool _jobsSubscription_match( const IotLink_t * pSubscriptionLink, void * pMatch ) { bool match = false; /* Because this function is called from a container function, the given link * must never be NULL. */ AwsIotJobs_Assert( pSubscriptionLink != NULL ); const _jobsSubscription_t * pSubscription = IotLink_Container( _jobsSubscription_t, pSubscriptionLink, link ); const AwsIotThingName_t * pThingName = ( AwsIotThingName_t * ) pMatch; if( pThingName->thingNameLength == pSubscription->thingNameLength ) { /* Check for matching Thing Names. */ match = ( strncmp( pThingName->pThingName, pSubscription->pThingName, pThingName->thingNameLength ) == 0 ); } return match; } /*-----------------------------------------------------------*/ _jobsSubscription_t * _AwsIotJobs_FindSubscription( const char * pThingName, size_t thingNameLength, bool createIfNotFound ) { _jobsSubscription_t * pSubscription = NULL; IotLink_t * pSubscriptionLink = NULL; AwsIotThingName_t thingName = { 0 }; thingName.pThingName = pThingName; thingName.thingNameLength = thingNameLength; /* Search the list for an existing subscription for Thing Name. */ pSubscriptionLink = IotListDouble_FindFirstMatch( &( _AwsIotJobsSubscriptions ), NULL, _jobsSubscription_match, &thingName ); /* Check if a subscription was found. */ if( pSubscriptionLink == NULL ) { if( createIfNotFound == true ) { /* No subscription found. Allocate a new subscription. */ pSubscription = AwsIotJobs_MallocSubscription( sizeof( _jobsSubscription_t ) + thingNameLength ); if( pSubscription != NULL ) { /* Clear the new subscription. */ ( void ) memset( pSubscription, 0x00, sizeof( _jobsSubscription_t ) + thingNameLength ); /* Set the Thing Name length and copy the Thing Name into the new subscription. */ pSubscription->thingNameLength = thingNameLength; ( void ) memcpy( pSubscription->pThingName, pThingName, thingNameLength ); /* Add the new subscription to the subscription list. */ IotListDouble_InsertHead( &( _AwsIotJobsSubscriptions ), &( pSubscription->link ) ); IotLogDebug( "Created new Jobs subscriptions object for %.*s.", thingNameLength, pThingName ); } else { IotLogError( "Failed to allocate memory for %.*s Jobs subscriptions.", thingNameLength, pThingName ); } } } else { IotLogDebug( "Found existing Jobs subscriptions object for %.*s.", thingNameLength, pThingName ); pSubscription = IotLink_Container( _jobsSubscription_t, pSubscriptionLink, link ); } return pSubscription; } /*-----------------------------------------------------------*/ void _AwsIotJobs_RemoveSubscription( _jobsSubscription_t * pSubscription, _jobsSubscription_t ** pRemovedSubscription ) { IOT_FUNCTION_ENTRY( bool, true ); int32_t i = 0, callbackIndex = 0; IotLogDebug( "Checking if subscription object for %.*s can be removed.", pSubscription->thingNameLength, pSubscription->pThingName ); /* Check for active operations. If any Jobs operation's subscription * reference count is not 0, then the subscription cannot be removed. */ for( i = 0; i < JOBS_OPERATION_COUNT; i++ ) { if( pSubscription->operationReferences[ i ] > 0 ) { IotLogDebug( "Reference count %ld for %.*s subscription object. " "Subscription cannot be removed yet.", ( long int ) pSubscription->operationReferences[ i ], pSubscription->thingNameLength, pSubscription->pThingName ); IOT_SET_AND_GOTO_CLEANUP( false ); } else if( pSubscription->operationReferences[ i ] == AWS_IOT_PERSISTENT_SUBSCRIPTION ) { IotLogDebug( "Subscription object for %.*s has persistent subscriptions. " "Subscription will not be removed.", pSubscription->thingNameLength, pSubscription->pThingName ); IOT_SET_AND_GOTO_CLEANUP( false ); } } /* Check for active subscriptions. If any Jobs callbacks are active, then the * subscription cannot be removed. */ if( pSubscription->callbackReferences > 0 ) { IotLogDebug( "Notify callbacks are using %.*s subscription object. " "Subscription cannot be removed yet.", pSubscription->thingNameLength, pSubscription->pThingName ); IOT_SET_AND_GOTO_CLEANUP( false ); } for( i = 0; i < JOBS_CALLBACK_COUNT; i++ ) { for( callbackIndex = 0; callbackIndex < AWS_IOT_JOBS_NOTIFY_CALLBACKS; callbackIndex++ ) { if( pSubscription->callbacks[ i ][ callbackIndex ].function != NULL ) { IotLogDebug( "Found active Jobs %s callback for %.*s subscription object. " "Subscription cannot be removed yet.", _pAwsIotJobsCallbackNames[ i ], pSubscription->thingNameLength, pSubscription->pThingName ); IOT_SET_AND_GOTO_CLEANUP( false ); } } } /* Remove the subscription if unused. */ IOT_FUNCTION_CLEANUP_BEGIN(); if( status == true ) { /* No Jobs operation subscription references or active Jobs callbacks. * Remove the subscription object. */ IotListDouble_Remove( &( pSubscription->link ) ); IotLogDebug( "Removed subscription object for %.*s.", pSubscription->thingNameLength, pSubscription->pThingName ); /* If the caller requested the removed subscription, set the output parameter. * Otherwise, free the memory used by the subscription. */ if( pRemovedSubscription != NULL ) { *pRemovedSubscription = pSubscription; } else { _AwsIotJobs_DestroySubscription( pSubscription ); } } } /*-----------------------------------------------------------*/ void _AwsIotJobs_DestroySubscription( void * pData ) { _jobsSubscription_t * pSubscription = ( _jobsSubscription_t * ) pData; /* Free the topic buffer if allocated. */ if( pSubscription->pTopicBuffer != NULL ) { AwsIotJobs_FreeString( pSubscription->pTopicBuffer ); } /* Free memory used by subscription. */ AwsIotJobs_FreeSubscription( pSubscription ); } /*-----------------------------------------------------------*/ AwsIotJobsError_t _AwsIotJobs_IncrementReferences( _jobsOperation_t * pOperation, char * pTopicBuffer, uint16_t operationTopicLength, AwsIotMqttCallbackFunction_t callback ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_SUCCESS ); const _jobsOperationType_t type = pOperation->type; _jobsSubscription_t * pSubscription = pOperation->pSubscription; IotMqttError_t subscriptionStatus = IOT_MQTT_STATUS_PENDING; AwsIotSubscriptionInfo_t subscriptionInfo = { 0 }; /* Do nothing if this operation has persistent subscriptions. */ if( pSubscription->operationReferences[ type ] == AWS_IOT_PERSISTENT_SUBSCRIPTION ) { IotLogDebug( "Jobs %s for %.*s has persistent subscriptions. Reference " "count will not be incremented.", _pAwsIotJobsOperationNames[ type ], pSubscription->thingNameLength, pSubscription->pThingName ); IOT_GOTO_CLEANUP(); } /* When persistent subscriptions are not present, the reference count must * not be negative. */ AwsIotJobs_Assert( pSubscription->operationReferences[ type ] >= 0 ); /* Check if there are any existing references for this operation. */ if( pSubscription->operationReferences[ type ] == 0 ) { /* Set the parameters needed to add subscriptions. */ subscriptionInfo.mqttConnection = pOperation->mqttConnection; subscriptionInfo.callbackFunction = callback; subscriptionInfo.timeout = _AwsIotJobsMqttTimeoutMs; subscriptionInfo.pTopicFilterBase = pTopicBuffer; subscriptionInfo.topicFilterBaseLength = operationTopicLength; subscriptionStatus = AwsIot_ModifySubscriptions( IotMqtt_SubscribeSync, &subscriptionInfo ); /* Convert MQTT return code to Jobs return code. */ switch( subscriptionStatus ) { case IOT_MQTT_SUCCESS: status = AWS_IOT_JOBS_SUCCESS; break; case IOT_MQTT_NO_MEMORY: status = AWS_IOT_JOBS_NO_MEMORY; break; default: status = AWS_IOT_JOBS_MQTT_ERROR; break; } if( status != AWS_IOT_JOBS_SUCCESS ) { IOT_GOTO_CLEANUP(); } } /* Increment the number of subscription references for this operation when * the keep subscriptions flag is not set. */ if( ( pOperation->flags & AWS_IOT_JOBS_FLAG_KEEP_SUBSCRIPTIONS ) == 0 ) { ( pSubscription->operationReferences[ type ] )++; IotLogDebug( "Jobs %s subscriptions for %.*s now has count %d.", _pAwsIotJobsOperationNames[ type ], pSubscription->thingNameLength, pSubscription->pThingName, pSubscription->operationReferences[ type ] ); } /* Otherwise, set the persistent subscriptions flag. */ else { pSubscription->operationReferences[ type ] = AWS_IOT_PERSISTENT_SUBSCRIPTION; IotLogDebug( "Set persistent subscriptions flag for Jobs %s of %.*s.", _pAwsIotJobsOperationNames[ type ], pSubscription->thingNameLength, pSubscription->pThingName ); } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ void _AwsIotJobs_DecrementReferences( _jobsOperation_t * pOperation, char * pTopicBuffer, _jobsSubscription_t ** pRemovedSubscription ) { const _jobsOperationType_t type = pOperation->type; _jobsSubscription_t * pSubscription = pOperation->pSubscription; uint16_t operationTopicLength = 0; AwsIotSubscriptionInfo_t subscriptionInfo = { 0 }; AwsIotJobsRequestInfo_t requestInfo = AWS_IOT_JOBS_REQUEST_INFO_INITIALIZER; /* Do nothing if this Jobs operation has persistent subscriptions. */ if( pSubscription->operationReferences[ type ] != AWS_IOT_PERSISTENT_SUBSCRIPTION ) { /* Decrement the number of subscription references for this operation. * Ensure that it's positive. */ ( pSubscription->operationReferences[ type ] )--; AwsIotJobs_Assert( pSubscription->operationReferences[ type ] >= 0 ); /* Check if the number of references has reached 0. */ if( pSubscription->operationReferences[ type ] == 0 ) { IotLogDebug( "Reference count for %.*s %s is 0. Unsubscribing.", pSubscription->thingNameLength, pSubscription->pThingName, _pAwsIotJobsOperationNames[ type ] ); /* Subscription must have a topic buffer. */ AwsIotJobs_Assert( pSubscription->pTopicBuffer != NULL ); /* Set the parameters needed to generate a Jobs topic. */ requestInfo.pThingName = pSubscription->pThingName; requestInfo.thingNameLength = pSubscription->thingNameLength; requestInfo.pJobId = pOperation->pJobId; requestInfo.jobIdLength = pOperation->jobIdLength; /* Generate the prefix of the Jobs topic. This function will not * fail when given a buffer. */ ( void ) _AwsIotJobs_GenerateJobsTopic( ( _jobsOperationType_t ) type, &requestInfo, &( pSubscription->pTopicBuffer ), &operationTopicLength ); /* Set the parameters needed to remove subscriptions. */ subscriptionInfo.mqttConnection = pOperation->mqttConnection; subscriptionInfo.timeout = _AwsIotJobsMqttTimeoutMs; subscriptionInfo.pTopicFilterBase = pTopicBuffer; subscriptionInfo.topicFilterBaseLength = operationTopicLength; ( void ) AwsIot_ModifySubscriptions( IotMqtt_UnsubscribeSync, &subscriptionInfo ); } /* Check if this subscription should be deleted. */ _AwsIotJobs_RemoveSubscription( pSubscription, pRemovedSubscription ); } else { IotLogDebug( "Jobs %s for %.*s has persistent subscriptions. Reference " "count will not be decremented.", _pAwsIotJobsOperationNames[ type ], pSubscription->thingNameLength, pSubscription->pThingName ); } } /*-----------------------------------------------------------*/ AwsIotJobsError_t AwsIotJobs_RemovePersistentSubscriptions( const AwsIotJobsRequestInfo_t * pRequestInfo, uint32_t flags ) { IOT_FUNCTION_ENTRY( AwsIotJobsError_t, AWS_IOT_JOBS_SUCCESS ); int32_t i = 0; uint16_t operationTopicLength = 0; IotMqttError_t unsubscribeStatus = IOT_MQTT_STATUS_PENDING; AwsIotSubscriptionInfo_t subscriptionInfo = { 0 }; _jobsSubscription_t * pSubscription = NULL; IotLink_t * pSubscriptionLink = NULL; AwsIotThingName_t thingName = { 0 }; thingName.pThingName = pRequestInfo->pThingName; thingName.thingNameLength = pRequestInfo->thingNameLength; IotLogInfo( "Removing persistent subscriptions for %.*s.", pRequestInfo->thingNameLength, pRequestInfo->pThingName ); /* Check parameters. */ if( pRequestInfo->mqttConnection == IOT_MQTT_CONNECTION_INITIALIZER ) { IotLogError( "MQTT connection is not initialized." ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( AwsIot_ValidateThingName( pRequestInfo->pThingName, pRequestInfo->thingNameLength ) == false ) { IotLogError( "Thing Name is not valid." ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( ( ( flags & AWS_IOT_JOBS_FLAG_REMOVE_DESCRIBE_SUBSCRIPTIONS ) != 0 ) || ( ( flags & AWS_IOT_JOBS_FLAG_REMOVE_UPDATE_SUBSCRIPTIONS ) != 0 ) ) { if( ( pRequestInfo->pJobId == NULL ) || ( pRequestInfo->jobIdLength == 0 ) ) { IotLogError( "Job ID must be set." ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } if( pRequestInfo->jobIdLength > JOBS_MAX_ID_LENGTH ) { IotLogError( "Job ID cannot be longer than %d.", JOBS_MAX_ID_LENGTH ); IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_JOBS_BAD_PARAMETER ); } } IotMutex_Lock( &( _AwsIotJobsSubscriptionsMutex ) ); /* Search the list for an existing subscription for Thing Name. */ pSubscriptionLink = IotListDouble_FindFirstMatch( &( _AwsIotJobsSubscriptions ), NULL, _jobsSubscription_match, &thingName ); if( pSubscriptionLink != NULL ) { IotLogDebug( "Found subscription object for %.*s. Checking for persistent " "subscriptions to remove.", pRequestInfo->thingNameLength, pRequestInfo->pThingName ); pSubscription = IotLink_Container( _jobsSubscription_t, pSubscriptionLink, link ); for( i = 0; i < JOBS_OPERATION_COUNT; i++ ) { if( ( flags & ( 0x1UL << i ) ) != 0 ) { IotLogDebug( "Removing %.*s %s persistent subscriptions.", pRequestInfo->thingNameLength, pRequestInfo->pThingName, _pAwsIotJobsOperationNames[ i ] ); /* Subscription must have a topic buffer. */ AwsIotJobs_Assert( pSubscription->pTopicBuffer != NULL ); if( pSubscription->operationReferences[ i ] == AWS_IOT_PERSISTENT_SUBSCRIPTION ) { /* Generate the prefix of the Jobs topic. This function will not * fail when given a buffer. */ ( void ) _AwsIotJobs_GenerateJobsTopic( ( _jobsOperationType_t ) i, pRequestInfo, &( pSubscription->pTopicBuffer ), &operationTopicLength ); /* Set the parameters needed to remove subscriptions. */ subscriptionInfo.mqttConnection = pRequestInfo->mqttConnection; subscriptionInfo.timeout = _AwsIotJobsMqttTimeoutMs; subscriptionInfo.pTopicFilterBase = pSubscription->pTopicBuffer; subscriptionInfo.topicFilterBaseLength = operationTopicLength; unsubscribeStatus = AwsIot_ModifySubscriptions( IotMqtt_UnsubscribeSync, &subscriptionInfo ); /* Convert MQTT return code to Shadow return code. */ switch( unsubscribeStatus ) { case IOT_MQTT_SUCCESS: status = AWS_IOT_JOBS_SUCCESS; break; case IOT_MQTT_NO_MEMORY: status = AWS_IOT_JOBS_NO_MEMORY; break; default: status = AWS_IOT_JOBS_MQTT_ERROR; break; } if( status != AWS_IOT_JOBS_SUCCESS ) { break; } /* Clear the persistent subscriptions flag and check if the * subscription can be removed. */ pSubscription->operationReferences[ i ] = 0; _AwsIotJobs_RemoveSubscription( pSubscription, NULL ); } else { IotLogDebug( "%.*s %s does not have persistent subscriptions.", pRequestInfo->thingNameLength, pRequestInfo->pThingName, _pAwsIotJobsOperationNames[ i ] ); } } } } else { IotLogWarn( "No subscription object found for %.*s", pRequestInfo->thingNameLength, pRequestInfo->pThingName ); } IotMutex_Unlock( &( _AwsIotJobsSubscriptionsMutex ) ); IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_Plus_TCP_and_FAT_Windows_Simulator/DemoTasks/UDPSelectServer.c
/* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from <NAME>, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* * A number of sockets are created and added to a set. One task then blocks on * the set while the other task sends data to a (pseudo) random member of the * set. The value sent increments from 0 to selMAX_TX_VALUE, and when all the * values have been sent a check is made that each expected value has indeed * been received before the cycle re-starts. * * See the following web page for essential demo usage and configuration * details: * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/examples_FreeRTOS_simulator.html */ /* Standard includes. */ #include <stdint.h> #include <stdio.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" /* Demo project includes. */ #include "UDPSelectServer.h" /* Exclude the whole file if select() is not being supported. */ #if( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) /* The numbers of sockets added to the set. */ #define selNUMBER_OF_SOCKETS ( 3 ) /* Each cycle of the demo sends the value 0 to selMAX_TX_VALUE to a socket in the set. */ #define selMAX_TX_VALUE ( 100 ) /*-----------------------------------------------------------*/ /* * The Tx task that sends the data to the sockets created by the Rx task and * added to the select set. */ static void prvMultipleSocketTxTask( void *pvParameters ); /* * Uses the FreeRTOS_select() API function to receive from multiple sockets. * This task expects to receive every value from 0 to selMAX_TX_VALUE during * each cycle of the demo. An array with an index for each value it expects to * receive is used to record which values were and were not received. */ static void prvMultipleSocketRxTask( void *pvParameters ); /*-----------------------------------------------------------*/ /* The sockets used in FreeRTOS_select(). */ static Socket_t xRxSockets[ selNUMBER_OF_SOCKETS ] = { 0 }; /* Used to monitor the status of the task. */ static volatile uint32_t ulTxCycles = 0, ulRxCycles = 0, ulFailedRxCycles = 0, ulErrorOccurred = pdFALSE; /* The block time used by the Tx task when sending - other delays are derived from this value. */ const TickType_t xSendBlockTime = pdMS_TO_TICKS( 400 ); const TickType_t xReceiveBlockTime = pdMS_TO_TICKS( 600 ); /* The Tx task needs to know the handle of the Rx task. */ static TaskHandle_t xRxTaskHandle; /*-----------------------------------------------------------*/ void vStartUDPSelectServerTasks( uint16_t usStackSize, uint32_t ulFirstPortNumber, UBaseType_t uxPriority ) { /* Create a task that sends to multiple sockets, and the task that uses the FreeRTOS_select() function to receive from multiple sockets. The first port number to use is passed into both tasks using the task's parameter. Other port numbers are consecutive from the first. */ xTaskCreate( prvMultipleSocketTxTask, "MultiTx", usStackSize, ( void * ) ulFirstPortNumber, uxPriority, NULL ); xTaskCreate( prvMultipleSocketRxTask, "MultiRx", usStackSize, ( void * ) ulFirstPortNumber, uxPriority, &xRxTaskHandle ); } /*-----------------------------------------------------------*/ static void prvMultipleSocketRxTask( void *pvParameters ) { SocketSet_t xFD_Set; Socket_t xSocket; struct freertos_sockaddr xAddress; uint32_t xClientLength = sizeof( struct freertos_sockaddr ), ulFirstRxPortNumber, x; uint32_t ulReceivedValue = 0, ulCount; uint8_t ucReceivedValues[ selMAX_TX_VALUE ]; /* If the array position is pdTRUE then the corresponding value has been received. */ int32_t lBytes; const TickType_t xRxBlockTime = 0; BaseType_t xResult; /* The number of the port the first Rx socket will be bound to is passed in as the task parameter. Other port numbers used are consecutive from this. */ ulFirstRxPortNumber = ( uint32_t ) pvParameters; /* Create the set for sockets that will be passed into FreeRTOS_select(). */ xFD_Set = FreeRTOS_CreateSocketSet(); /* Create the sockets and add them to the set. */ for( x = 0; x < selNUMBER_OF_SOCKETS; x++ ) { /* Create the next Rx socket. */ xRxSockets[ x ] = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP ); configASSERT( xRxSockets[ x ] != FREERTOS_INVALID_SOCKET ); /* Bind to the next port number. */ xAddress.sin_port = FreeRTOS_htons( ( uint16_t ) ( ulFirstRxPortNumber + x ) ); FreeRTOS_bind( xRxSockets[ x ], &xAddress, sizeof( struct freertos_sockaddr ) ); /* There should always be data available after FreeRTOS_select() so blocking on a read should not be necessary. */ FreeRTOS_setsockopt( xRxSockets[ x ], 0, FREERTOS_SO_RCVTIMEO, &xRxBlockTime, sizeof( xRxBlockTime ) ); /* Add the created socket to the set. */ FreeRTOS_FD_SET( xRxSockets[ x ], xFD_Set, eSELECT_ALL ); } for( ;; ) { /* No values have yet been received so set each array position to pdFALSE. Each expected Rx value has a corresponding array position. */ memset( ( void * ) ucReceivedValues, pdFALSE, sizeof( ucReceivedValues ) ); /* Wait for the other task to resume this task - indicating that it is about to start sending. */ vTaskSuspend( NULL ); /* Expect to receive selMAX_TX_VALUE values. */ ulCount = 0; while( ulCount < selMAX_TX_VALUE ) { /* Wait for a socket from the set to become available for reading. */ xResult = FreeRTOS_select( xFD_Set, xReceiveBlockTime ); if( xResult != 0 ) { /* See which sockets have data waiting to be read. */ for( x = 0; x < selNUMBER_OF_SOCKETS; x++ ) { xSocket = xRxSockets[ x ]; /* Find the expected value for this socket */ if( FreeRTOS_FD_ISSET( xSocket, xFD_Set ) != 0 ) { while( ( lBytes = FreeRTOS_recvfrom( xSocket, &( ulReceivedValue ), sizeof( uint32_t ), 0, &xAddress, &xClientLength ) ) > 0 ) { /* Received another message. */ ulCount++; /* It is always expected that the read will pass. */ configASSERT( ( size_t ) lBytes == ( sizeof( uint32_t ) ) ); /* Don't expect to receive anything greater than selMAX_TX_VALUE - 1. */ configASSERT( ulReceivedValue < selMAX_TX_VALUE ); /* Don't expect to receive any value twice. */ configASSERT( ucReceivedValues[ ulReceivedValue ] != pdTRUE ); if( ucReceivedValues[ ulReceivedValue ] != pdTRUE ) { /* Mark the value as received by setting its index in the received array to pdTRUE. */ ucReceivedValues[ ulReceivedValue ] = pdTRUE; } else { ulErrorOccurred = pdTRUE; } } } } } else { /* No value was received in time. */ break; } } /* Were all values received? */ if( ulCount == selMAX_TX_VALUE ) { /* Check all selMAX_TX_VALUE values are present and correct before starting a new cycle. It is valid for a few values at the beginning of the array to be missing as they may have been dropped for ARP messages, so start a few indexes in. */ for( ulCount = 4; ulCount < selMAX_TX_VALUE; ulCount++ ) { configASSERT( ucReceivedValues[ ulCount ] == pdTRUE ); if( ucReceivedValues[ ulCount ] != pdTRUE ) { /* The value corresponding to this array position was never received. In a real application UDP is not reliable, but in this tightly controlled test it is unusual for a packet to be dropped. */ ulErrorOccurred = pdTRUE; } } ulRxCycles++; } else { /* Just for viewing in the debugger. */ ulFailedRxCycles++; } } } /*-----------------------------------------------------------*/ static void prvMultipleSocketTxTask( void *pvParameters ) { uint32_t ulTxValue = 0; struct freertos_sockaddr xDestinationAddress; uint32_t ulIPAddress, ulFirstDestinationPortNumber, xPortNumber; Socket_t xTxSocket; uint32_t ulSendCount[ selNUMBER_OF_SOCKETS ]; memset( ulSendCount, '\0', sizeof( ulSendCount ) ); /* The first destination port number is passed in as the task parameter. Other destination port numbers used are consecutive from this. */ ulFirstDestinationPortNumber = ( uint32_t ) pvParameters; /* Create the socket used to send to the sockets created by the Rx task. Let the IP stack select a port to bind to. */ xTxSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP ); FreeRTOS_bind( xTxSocket, NULL, sizeof( struct freertos_sockaddr ) ); /* The Rx and Tx tasks execute at the same priority so it is possible that the Tx task will fill up the send queue - set a Tx block time to ensure flow control is managed if this happens. */ FreeRTOS_setsockopt( xTxSocket, 0, FREERTOS_SO_SNDTIMEO, &xSendBlockTime, sizeof( xSendBlockTime ) ); /* It is assumed that this task is not created until the network is up, so the IP address can be obtained immediately. Store the IP address being used in ulIPAddress. This is done so the socket can send to a different port on the same IP address. */ FreeRTOS_GetAddressConfiguration( &ulIPAddress, NULL, NULL, NULL ); /* This test sends to itself, so data sent from here is received by a server socket on the same IP address. Setup the freertos_sockaddr structure with this nodes IP address. */ xDestinationAddress.sin_addr = ulIPAddress; /* Block for a short time to ensure the task implemented by the prvMultipleSocketRxTask() function has finished creating the Rx sockets. */ while( eTaskGetState( xRxTaskHandle ) != eSuspended ) { vTaskDelay( xSendBlockTime ); } vTaskResume( xRxTaskHandle ); for( ;; ) { /* Pseudo randomly select the destination port number from the range of valid destination port numbers. */ xPortNumber = ipconfigRAND32() % selNUMBER_OF_SOCKETS; ulSendCount[ xPortNumber ]++; xDestinationAddress.sin_port = ( uint16_t ) ( ulFirstDestinationPortNumber + xPortNumber ); xDestinationAddress.sin_port = FreeRTOS_htons( xDestinationAddress.sin_port ); /* Send an incrementing value to the pseudo randomly selected port. */ FreeRTOS_sendto( xTxSocket, &ulTxValue, sizeof( ulTxValue ), 0, &xDestinationAddress, sizeof( xDestinationAddress ) ); ulTxValue++; if( ulTxValue >= selMAX_TX_VALUE ) { /* Start over. */ ulTxValue = 0; /* As a sanity check that this demo is valid, ensure each socket has been used at least once. */ for( xPortNumber = 0; xPortNumber < selNUMBER_OF_SOCKETS; xPortNumber++ ) { if( ulSendCount[ xPortNumber ] == 0 ) { ulErrorOccurred = pdTRUE; } ulSendCount[ xPortNumber ] = 0; } /* Allow the Rx task to check it has received all the values. */ while( eTaskGetState( xRxTaskHandle ) != eSuspended ) { vTaskDelay( xSendBlockTime ); } vTaskResume( xRxTaskHandle ); /* Increment to show this task is still executing. */ ulTxCycles++; } /* Delay here because in the Windows simulator the MAC interrupt simulator delays, so network traffic cannot be received any faster than this. */ vTaskDelay( configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY << 2 ); } } /*-----------------------------------------------------------*/ BaseType_t xAreUDPSelectTasksStillRunning( void ) { static uint32_t ulLastRxCycles = 0, ulLastTxCycles = 0; BaseType_t ulError; ulError = ulErrorOccurred; if( ulRxCycles == ulLastRxCycles ) { ulError |= pdTRUE; } if( ulTxCycles == ulLastTxCycles ) { ulError |= pdTRUE; } ulLastRxCycles = ulRxCycles; ulLastTxCycles = ulTxCycles; return !ulError; } /* The whole file is excluded if select() is not being supported. */ #endif /* ipconfigSUPPORT_SELECT_FUNCTION */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/abstractions/platform/freertos/include/platform/iot_network_freertos.h
<reponame>MicroEJ/FreeRTOS /* * Amazon FreeRTOS Platform V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /** * @file iot_network_freertos.h * @brief Declares the network stack functions specified in iot_network.h for * FreeRTOS+TCP. */ #ifndef _IOT_NETWORK_FREERTOS_H_ #define _IOT_NETWORK_FREERTOS_H_ /* Standard includes. */ #include <stdbool.h> /* Platform types include. */ #include "types/iot_platform_types.h" /* Platform network include. */ #include "platform/iot_network.h" /** * @brief Provides a default value for an #IotNetworkConnectionFreeRTOS_t. * * All instances of #IotNetworkConnectionFreeRTOS_t should be initialized with * this constant. * * @warning Failing to initialize an #IotNetworkConnectionFreeRTOS_t with this * initializer may result in undefined behavior! * @note This initializer may change at any time in future versions, but its * name will remain the same. */ #define IOT_NETWORK_CONNECTION_FREERTOS_INITIALIZER { 0 } /** * @brief Generic initializer for an #IotNetworkServerInfo_t. * * @note This initializer may change at any time in future versions, but its * name will remain the same. */ #define IOT_NETWORK_SERVER_INFO_FREERTOS_INITIALIZER { 0 } /** * @brief Generic initializer for an #IotNetworkCredentials_t. * * @note This initializer may change at any time in future versions, but its * name will remain the same. */ #define IOT_NETWORK_CREDENTIALS_FREERTOS_INITIALIZER { 0 } /** * @brief Provides a pointer to an #IotNetworkInterface_t that uses the functions * declared in this file. */ #define IOT_NETWORK_INTERFACE_FREERTOS ( &( IotNetworkFreeRTOS ) ) /** * @brief One-time initialization function for this network stack. */ IotNetworkError_t IotNetworkFreeRTOS_Init( void ); /** * @brief One-time cleanup function for this network stack. */ void IotNetworkFreeRTOS_Cleanup( void ); /** * @brief An implementation of #IotNetworkInterface_t::create for FreeRTOS+TCP * sockets. */ IotNetworkError_t IotNetworkFreeRTOS_Create( IotNetworkServerInfo_t pServerInfo, IotNetworkCredentials_t pCredentialInfo, IotNetworkConnection_t * pConnection ); /** * @brief An implementation of #IotNetworkInterface_t::setReceiveCallback for * FreeRTOS+TCP sockets. */ IotNetworkError_t IotNetworkFreeRTOS_SetReceiveCallback( IotNetworkConnection_t pConnection, IotNetworkReceiveCallback_t receiveCallback, void * pContext ); /** * @brief An implementation of #IotNetworkInterface_t::send for FreeRTOS+TCP * sockets. */ size_t IotNetworkFreeRTOS_Send( IotNetworkConnection_t pConnection, const uint8_t * pMessage, size_t messageLength ); /** * @brief An implementation of #IotNetworkInterface_t::receive for FreeRTOS+TCP * sockets. */ size_t IotNetworkFreeRTOS_Receive( IotNetworkConnection_t pConnection, uint8_t * pBuffer, size_t bytesRequested ); /** * @brief An implementation of #IotNetworkInterface::receiveUpto for FreeRTOS+TCP * sockets. */ size_t IotNetworkFreeRTOS_ReceiveUpto( IotNetworkConnection_t pConnection, uint8_t * pBuffer, size_t bufferSize ); /** * @brief An implementation of #IotNetworkInterface_t::close for FreeRTOS+TCP * sockets. */ IotNetworkError_t IotNetworkFreeRTOS_Close( IotNetworkConnection_t pConnection ); /** * @brief An implementation of #IotNetworkInterface_t::destroy for FreeRTOS+TCP * sockets. */ IotNetworkError_t IotNetworkFreeRTOS_Destroy( IotNetworkConnection_t pConnection ); /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Declaration of a network interface struct using the functions in this file. */ extern const IotNetworkInterface_t IotNetworkFreeRTOS; /** @endcond */ #endif /* ifndef _IOT_NETWORK_FREERTOS_H_ */
MicroEJ/FreeRTOS
FreeRTOS/Demo/CORTEX_LM3S811_GCC/microej/src/LLBSP.c
/* * C * * Copyright 2020 MicroEJ Corp. All rights reserved. * Use of this source code is governed by a BSD-style license that can be found with this software. */ #include "LLBSP_impl.h" extern void _etext(void); uint8_t LLBSP_IMPL_isInReadOnlyMemory(void* ptr) { return ptr < &_etext; } /** * Writes the character <code>c</code>, cast to an unsigned char, to stdout stream. * This function is used by the default implementation of the Java <code>System.out</code>. */ void LLBSP_IMPL_putchar(int32_t c) { putchar(c); }
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/common/src/aws_iot_parser.c
<filename>FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/common/src/aws_iot_parser.c /* * AWS IoT Common V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_parser.c * @brief Parses topics for Thing Name and status. */ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <string.h> /* AWS IoT include. */ #include "aws_iot.h" /* Error handling include. */ #include "iot_error.h" /* AWS Parser include. */ #include "aws_iot_doc_parser.h" /** * @brief Minimum allowed topic length for an AWS IoT status topic. * * Topics must contain at least: * - The common prefix * - The suffix "/accepted" or "/rejected" * - 1 character for the Thing Name * - 2 characters for the operation name and the enclosing slashes */ #define MINIMUM_TOPIC_NAME_LENGTH \ ( uint16_t ) ( AWS_IOT_TOPIC_PREFIX_LENGTH + \ AWS_IOT_ACCEPTED_SUFFIX_LENGTH + \ 1 + 2 ) /** * @brief The longest client token accepted by AWS IoT service, per AWS IoT * service limits. */ #define MAX_CLIENT_TOKEN_LENGTH ( 64 ) /*-----------------------------------------------------------*/ bool AwsIot_GetClientToken( const char * pJsonDocument, size_t jsonDocumentLength, const char ** pClientToken, size_t * pClientTokenLength ) { /* Extract the client token from the JSON document. */ bool status = AwsIotDocParser_FindValue( pJsonDocument, jsonDocumentLength, AWS_IOT_CLIENT_TOKEN_KEY, AWS_IOT_CLIENT_TOKEN_KEY_LENGTH, pClientToken, pClientTokenLength ); if( status == true ) { /* Check that the length of the client token is valid. */ if( ( *pClientTokenLength < 2 ) || ( *pClientTokenLength > MAX_CLIENT_TOKEN_LENGTH ) ) { status = false; } } return status; } /*-----------------------------------------------------------*/ bool AwsIot_ParseThingName( const char * pTopicName, uint16_t topicNameLength, const char ** pThingName, size_t * pThingNameLength ) { IOT_FUNCTION_ENTRY( bool, true ); const char * pThingNameStart = NULL; size_t thingNameLength = 0; /* Check that the topic name is at least as long as the minimum allowed. */ if( topicNameLength < MINIMUM_TOPIC_NAME_LENGTH ) { IOT_SET_AND_GOTO_CLEANUP( false ); } /* Check that the given topic starts with the common prefix. */ if( strncmp( AWS_IOT_TOPIC_PREFIX, pTopicName, AWS_IOT_TOPIC_PREFIX_LENGTH ) != 0 ) { IOT_SET_AND_GOTO_CLEANUP( false ); } /* The Thing Name starts immediately after the topic prefix. */ pThingNameStart = pTopicName + AWS_IOT_TOPIC_PREFIX_LENGTH; /* Calculate the length of the Thing Name, which is terminated with a '/'. */ while( ( thingNameLength + AWS_IOT_TOPIC_PREFIX_LENGTH < ( size_t ) topicNameLength ) && ( pThingNameStart[ thingNameLength ] != '/' ) ) { thingNameLength++; } /* The end of the topic name was reached without finding a '/'. The topic * name is invalid. */ if( thingNameLength + AWS_IOT_TOPIC_PREFIX_LENGTH >= ( size_t ) topicNameLength ) { IOT_SET_AND_GOTO_CLEANUP( false ); } /* Set the output parameters. */ *pThingName = pThingNameStart; *pThingNameLength = thingNameLength; IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ AwsIotStatus_t AwsIot_ParseStatus( const char * pTopicName, uint16_t topicNameLength ) { IOT_FUNCTION_ENTRY( AwsIotStatus_t, AWS_IOT_UNKNOWN ); const char * pSuffixStart = NULL; /* Both 'accepted' and 'rejected' topics are of the same length * The below is a defensive check at run time to ensure that. */ Iot_DefaultAssert( AWS_IOT_ACCEPTED_SUFFIX_LENGTH == AWS_IOT_REJECTED_SUFFIX_LENGTH ); /* Check that the status topic name is at least as long as the * "accepted" suffix. This length check will be good for rejected also * as both are of 8 characters in length. */ if( topicNameLength > AWS_IOT_ACCEPTED_SUFFIX_LENGTH ) { /* Calculate where the "accepted" suffix should start. */ pSuffixStart = pTopicName + topicNameLength - AWS_IOT_ACCEPTED_SUFFIX_LENGTH; /* Check if the end of the status topic name is "/accepted". */ if( strncmp( pSuffixStart, AWS_IOT_ACCEPTED_SUFFIX, AWS_IOT_ACCEPTED_SUFFIX_LENGTH ) == 0 ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_ACCEPTED ); } /* Check if the end of the status topic name is "/rejected". */ if( strncmp( pSuffixStart, AWS_IOT_REJECTED_SUFFIX, AWS_IOT_REJECTED_SUFFIX_LENGTH ) == 0 ) { IOT_SET_AND_GOTO_CLEANUP( AWS_IOT_REJECTED ); } } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/portable/lpc18xx/ff_sddisk.c
<filename>FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/portable/lpc18xx/ff_sddisk.c<gh_stars>1-10 /* * FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab! * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Authors include <NAME>, <NAME> and <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * */ /* Standard includes. */ #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> /* LPC18xx includes. */ #include "chip.h" #include "board.h" /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "portmacro.h" /* FreeRTOS+FAT includes. */ #include "ff_sddisk.h" #include "ff_sys.h" #include "hr_gettime.h" /* Misc definitions. */ #define sdSIGNATURE 0x41404342UL #define sdHUNDRED_64_BIT ( 100ull ) #define sdBYTES_PER_MB ( 1024ull * 1024ull ) #define sdSECTORS_PER_MB ( sdBYTES_PER_MB / 512ull ) #define sdIOMAN_MEM_SIZE 4096 #define xSDCardInfo ( sd_mmc_cards[ 0 ] ) #define sdAligned( pvAddress ) ( ( ( ( size_t ) ( pvAddress ) ) & ( sizeof( size_t ) - 1 ) ) == 0 ) /*-----------------------------------------------------------*/ /*_RB_ Functions require comment blocks. */ static void prvSDMMCSetupWakeup( void *pvInfo ); static uint32_t prvSDMMCWait( void ); static void prvSDMMCDelay_ms( uint32_t time ); static void prvInitialiseCardInfo( void ); static int32_t prvSDMMC_Init( void ); static int32_t prvFFRead( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk ); static int32_t prvFFWrite( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk ); /*-----------------------------------------------------------*/ /*_RB_ Variables require a comment block where appropriate. */ static int32_t lSDDetected = 0; static mci_card_struct xCardInfo; static volatile int32_t lSDIOWaitExit; static BaseType_t xSDCardStatus; static SemaphoreHandle_t xSDCardSemaphore; static SemaphoreHandle_t xPlusFATMutex; /*-----------------------------------------------------------*/ #warning Update to make read and write functions static and make use of the FF_Disk_t type. static int32_t prvFFRead( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk ) { int32_t iReturn; /*_RB_ Many of the comments in this file apply to other functions in the file. */ if( ( pxDisk != NULL ) && ( xSDCardStatus == pdPASS ) && ( pxDisk->ulSignature == sdSIGNATURE ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) && ( ulSectorNumber < pxDisk->ulNumberOfSectors ) && ( ( pxDisk->ulNumberOfSectors - ulSectorNumber ) >= ulSectorCount ) ) { iReturn = Chip_SDMMC_ReadBlocks( LPC_SDMMC, pucBuffer, ulSectorNumber, ulSectorCount ); /*_RB_ I'm guessing 512 is a sector size, but that needs to be clear. Is it defined in a header somewhere? If so we can do a search and replace in files on it as it seems to be used everywhere. */ if( iReturn == ( ulSectorCount * 512 ) ) /*_RB_ Signed/unsigned mismatch (twice!) */ { iReturn = FF_ERR_NONE; } else { /*_RB_ Signed number used to return bitmap (again below). */ iReturn = ( FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG ); } } else { memset( ( void * ) pucBuffer, '\0', ulSectorCount * 512 ); if( pxDisk->xStatus.bIsInitialised != 0 ) { FF_PRINTF( "prvFFRead: warning: %lu + %lu > %lu\n", ulSectorNumber, ulSectorCount, pxDisk->ulNumberOfSectors ); } iReturn = ( FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG ); } return iReturn; } /*-----------------------------------------------------------*/ static int32_t prvFFWrite( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk ) { int32_t iReturn; if( ( pxDisk != NULL ) && ( xSDCardStatus == pdPASS ) && ( pxDisk->ulSignature == sdSIGNATURE ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) && ( ulSectorNumber < pxDisk->ulNumberOfSectors ) && ( ( pxDisk->ulNumberOfSectors - ulSectorNumber ) >= ulSectorCount ) ) { iReturn = Chip_SDMMC_WriteBlocks( LPC_SDMMC, pucBuffer, ulSectorNumber, ulSectorCount ); if( iReturn == ( ulSectorCount * 512 ) ) /*_RB_ Signed/unsigned mismatch (twice!) */ { iReturn = 0; } else { iReturn = ( FF_ERR_IOMAN_OUT_OF_BOUNDS_WRITE | FF_ERRFLAG ); } } else { memset( ( void * ) pucBuffer, '\0', ulSectorCount * 512 ); if( pxDisk->xStatus.bIsInitialised ) { FF_PRINTF( "prvFFWrite: warning: %lu + %lu > %lu\n", ulSectorNumber, ulSectorCount, pxDisk->ulNumberOfSectors ); } iReturn = ( FF_ERR_IOMAN_OUT_OF_BOUNDS_WRITE | FF_ERRFLAG ); } return iReturn; } /*-----------------------------------------------------------*/ void FF_SDDiskFlush( FF_Disk_t *pxDisk ) { if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) && ( pxDisk->pxIOManager != NULL ) ) { FF_FlushCache( pxDisk->pxIOManager ); } } /*-----------------------------------------------------------*/ /* Initialise the SDIO driver and mount an SD card */ FF_Disk_t *FF_SDDiskInit( const char *pcName ) { FF_Error_t xFFError; BaseType_t xPartitionNumber = 0; FF_CreationParameters_t xParameters; FF_Disk_t * pxDisk; xSDCardStatus = prvSDMMC_Init(); if( xSDCardStatus == pdPASS ) { pxDisk = ( FF_Disk_t * ) pvPortMalloc( sizeof( *pxDisk ) ); if( pxDisk != NULL ) { /* Initialise the created disk structure. */ memset( pxDisk, '\0', sizeof( *pxDisk ) ); if( xPlusFATMutex == NULL) { xPlusFATMutex = xSemaphoreCreateRecursiveMutex(); } pxDisk->ulNumberOfSectors = xCardInfo.card_info.blocknr; pxDisk->ulSignature = sdSIGNATURE; if( xPlusFATMutex != NULL) { memset( &xParameters, '\0', sizeof( xParameters ) ); xParameters.ulMemorySize = sdIOMAN_MEM_SIZE; xParameters.ulSectorSize = 512; xParameters.fnWriteBlocks = prvFFWrite; xParameters.fnReadBlocks = prvFFRead; xParameters.pxDisk = pxDisk; /* prvFFRead()/prvFFWrite() are not re-entrant and must be protected with the use of a semaphore. */ xParameters.xBlockDeviceIsReentrant = pdFALSE; /* The semaphore will be used to protect critical sections in the +FAT driver, and also to avoid concurrent calls to prvFFRead()/prvFFWrite() from different tasks. */ xParameters.pvSemaphore = ( void * ) xPlusFATMutex; pxDisk->pxIOManager = FF_CreateIOManger( &xParameters, &xFFError ); if( pxDisk->pxIOManager == NULL ) { FF_PRINTF( "FF_SDDiskInit: FF_CreateIOManger: %s\n", ( const char * ) FF_GetErrMessage( xFFError ) ); FF_SDDiskDelete( pxDisk ); pxDisk = NULL; } else { pxDisk->xStatus.bIsInitialised = pdTRUE; pxDisk->xStatus.bPartitionNumber = xPartitionNumber; if( FF_SDDiskMount( pxDisk ) == 0 ) { FF_SDDiskDelete( pxDisk ); pxDisk = NULL; } else { if( pcName == NULL ) { pcName = "/"; } FF_FS_Add( pcName, pxDisk ); FF_PRINTF( "FF_SDDiskInit: Mounted SD-card as root \"%s\"\n", pcName ); FF_SDDiskShowPartition( pxDisk ); } } /* if( pxDisk->pxIOManager != NULL ) */ } /* if( xPlusFATMutex != NULL) */ } /* if( pxDisk != NULL ) */ else { FF_PRINTF( "FF_SDDiskInit: Malloc failed\n" ); } } /* if( xSDCardStatus == pdPASS ) */ else { FF_PRINTF( "FF_SDDiskInit: prvSDMMC_Init failed\n" ); pxDisk = NULL; } return pxDisk; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskFormat( FF_Disk_t *pxDisk, BaseType_t xPartitionNumber ) { FF_Error_t xError; BaseType_t xReturn = pdFAIL; xError = FF_Unmount( pxDisk ); if( FF_isERR( xError ) != pdFALSE ) { FF_PRINTF( "FF_SDDiskFormat: unmount fails: %08x\n", ( unsigned ) xError ); } else { /* Format the drive - try FAT32 with large clusters. */ xError = FF_Format( pxDisk, xPartitionNumber, pdFALSE, pdFALSE); if( FF_isERR( xError ) ) { FF_PRINTF( "FF_SDDiskFormat: %s\n", (const char*)FF_GetErrMessage( xError ) ); } else { FF_PRINTF( "FF_SDDiskFormat: OK, now remounting\n" ); pxDisk->xStatus.bPartitionNumber = xPartitionNumber; xError = FF_SDDiskMount( pxDisk ); FF_PRINTF( "FF_SDDiskFormat: rc %08x\n", ( unsigned )xError ); if( FF_isERR( xError ) == pdFALSE ) { xReturn = pdPASS; } } } return xReturn; } /*-----------------------------------------------------------*/ /* Get a pointer to IOMAN, which can be used for all FreeRTOS+FAT functions */ BaseType_t FF_SDDiskMount( FF_Disk_t *pxDisk ) { FF_Error_t xFFError; BaseType_t xReturn; /* Mount the partition */ xFFError = FF_Mount( pxDisk, pxDisk->xStatus.bPartitionNumber ); if( FF_isERR( xFFError ) ) { FF_PRINTF( "FF_SDDiskMount: %08lX\n", xFFError ); xReturn = pdFAIL; } else { pxDisk->xStatus.bIsMounted = pdTRUE; FF_PRINTF( "****** FreeRTOS+FAT initialized %lu sectors\n", pxDisk->pxIOManager->xPartition.ulTotalSectors ); FF_SDDiskShowPartition( pxDisk ); xReturn = pdPASS; } return xReturn; } /*-----------------------------------------------------------*/ FF_IOManager_t *sddisk_ioman( FF_Disk_t *pxDisk ) { FF_IOManager_t *pxReturn; if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) ) { pxReturn = pxDisk->pxIOManager; } else { pxReturn = NULL; } return pxReturn; } /*-----------------------------------------------------------*/ /* Release all resources */ BaseType_t FF_SDDiskDelete( FF_Disk_t *pxDisk ) { if( pxDisk != NULL ) { pxDisk->ulSignature = 0; pxDisk->xStatus.bIsInitialised = 0; if( pxDisk->pxIOManager != NULL ) { if( FF_Mounted( pxDisk->pxIOManager ) != pdFALSE ) { FF_Unmount( pxDisk ); } FF_DeleteIOManager( pxDisk->pxIOManager ); } vPortFree( pxDisk ); } return 1; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskShowPartition( FF_Disk_t *pxDisk ) { FF_Error_t xError; uint64_t ullFreeSectors; uint32_t ulTotalSizeMB, ulFreeSizeMB; int iPercentageFree; FF_IOManager_t *pxIOManager; const char *pcTypeName = "unknown type"; BaseType_t xReturn = pdPASS; if( pxDisk == NULL ) { xReturn = pdFAIL; } else { pxIOManager = pxDisk->pxIOManager; FF_PRINTF( "Reading FAT and calculating Free Space\n" ); switch( pxIOManager->xPartition.ucType ) { case FF_T_FAT12: pcTypeName = "FAT12"; break; case FF_T_FAT16: pcTypeName = "FAT16"; break; case FF_T_FAT32: pcTypeName = "FAT32"; break; default: pcTypeName = "UNKOWN"; break; } FF_GetFreeSize( pxIOManager, &xError ); ullFreeSectors = pxIOManager->xPartition.ulFreeClusterCount * pxIOManager->xPartition.ulSectorsPerCluster; iPercentageFree = ( int ) ( ( sdHUNDRED_64_BIT * ullFreeSectors + pxIOManager->xPartition.ulDataSectors / 2 ) / ( ( uint64_t )pxIOManager->xPartition.ulDataSectors ) ); ulTotalSizeMB = pxIOManager->xPartition.ulDataSectors / sdSECTORS_PER_MB; ulFreeSizeMB = ( uint32_t ) ( ullFreeSectors / sdSECTORS_PER_MB ); /* It is better not to use the 64-bit format such as %Lu because it might not be implemented. */ FF_PRINTF( "Partition Nr %8u\n", pxDisk->xStatus.bPartitionNumber ); FF_PRINTF( "Type %8u (%s)\n", pxIOManager->xPartition.ucType, pcTypeName ); FF_PRINTF( "VolLabel '%8s' \n", pxIOManager->xPartition.pcVolumeLabel ); FF_PRINTF( "TotalSectors %8lu\n", pxIOManager->xPartition.ulTotalSectors ); FF_PRINTF( "SecsPerCluster %8lu\n", pxIOManager->xPartition.ulSectorsPerCluster ); FF_PRINTF( "Size %8lu MB\n", ulTotalSizeMB ); FF_PRINTF( "FreeSize %8lu MB ( %d perc free )\n", ulFreeSizeMB, iPercentageFree ); } return xReturn; } /*-----------------------------------------------------------*/ void SDIO_IRQHandler( void ) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; /* All SD based register handling is done in the callback function. The SDIO interrupt is not enabled as part of this driver and needs to be enabled/disabled in the callbacks or application as needed. This is to allow flexibility with IRQ handling for applications and RTOSes. */ /* Set wait exit flag to tell wait function we are ready. In an RTOS, this would trigger wakeup of a thread waiting for the IRQ. */ NVIC_DisableIRQ( SDIO_IRQn ); xSemaphoreGiveFromISR( xSDCardSemaphore, &xHigherPriorityTaskWoken ); lSDIOWaitExit = 1; portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } /*-----------------------------------------------------------*/ /* Sets up the SD event driven wakeup */ static void prvSDMMCSetupWakeup( void *pvInfo ) { uint32_t *ulWaitStatus = ( uint32_t * ) pvInfo; /* Wait for IRQ - for an RTOS, you would pend on an event here with a IRQ based wakeup. */ /*_RB_ Don't understand why this is spinning on a block time of 0. Is it really meant to be != pdFALSE? */ while( xSemaphoreTake( xSDCardSemaphore, 0 ) != pdFALSE ) { } NVIC_ClearPendingIRQ( SDIO_IRQn ); lSDIOWaitExit = 0; Chip_SDIF_SetIntMask( LPC_SDMMC, *ulWaitStatus ); NVIC_EnableIRQ( SDIO_IRQn ); } /*-----------------------------------------------------------*/ static uint32_t prvSDMMCWait( void ) { uint32_t ulStatus; /*_RB_ 2000 needs to be defined and use pdMS_TO_TICKS so the delay period remains constant no matter how the end user sets configTICK_RATE_MS. */ xSemaphoreTake( xSDCardSemaphore, 2000 ); ulStatus = Chip_SDIF_GetIntStatus( LPC_SDMMC ); if( ( ( ulStatus & MCI_INT_CMD_DONE ) == 0 ) || ( lSDIOWaitExit == 0 ) ) { FF_PRINTF( "Wait SD: int32_t %ld ulStatus 0x%02lX\n", lSDIOWaitExit, ulStatus ); } return ulStatus; } /*-----------------------------------------------------------*/ static void prvSDMMCDelay_ms( uint32_t ulTime ) { /* In an RTOS, the thread would sleep allowing other threads to run. For standalone operation, just spin on a timer */ vTaskDelay( pdMS_TO_TICKS( ulTime ) ); } /*-----------------------------------------------------------*/ static int32_t prvSDMMC_Init( void ) { int32_t lSDCardStatus; if( xSDCardSemaphore == NULL ) { xSDCardSemaphore = xSemaphoreCreateBinary(); configASSERT( xSDCardSemaphore ); xSemaphoreGive( xSDCardSemaphore ); } prvInitialiseCardInfo(); NVIC_SetPriority( SDIO_IRQn, configSD_INTERRUPT_PRIORITY ); /*_RB_ Board_SDMMC_Init() is library specific code that is also specific to the target development board.The SDMMC peripheral should be initialised from the application code before this code is called. */ Board_SDMMC_Init(); Chip_SDIF_Init( LPC_SDMMC ); lSDDetected = !Chip_SDIF_CardNDetect( LPC_SDMMC ); Chip_SDIF_PowerOn( LPC_SDMMC ); lSDCardStatus = Chip_SDMMC_Acquire( LPC_SDMMC, &xCardInfo ); FF_PRINTF( "Acquire: %ld\n", lSDCardStatus ); return lSDCardStatus; } /*-----------------------------------------------------------*/ static void prvInitialiseCardInfo( void ) { memset( &xCardInfo, 0, sizeof( xCardInfo ) ); xCardInfo.card_info.evsetup_cb = prvSDMMCSetupWakeup; xCardInfo.card_info.waitfunc_cb = prvSDMMCWait; xCardInfo.card_info.msdelay_func = prvSDMMCDelay_ms; }
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/standard/mqtt/src/iot_mqtt_api.c
<reponame>MicroEJ/FreeRTOS /* * IoT MQTT V2.1.0 * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file iot_mqtt_api.c * @brief Implements most user-facing functions of the MQTT library. */ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <string.h> /* Error handling include. */ #include "iot_error.h" /* MQTT internal include. */ #include "private/iot_mqtt_internal.h" /* Platform layer includes. */ #include "platform/iot_clock.h" #include "platform/iot_threads.h" /* Atomics include. */ #include "iot_atomic.h" /* Validate MQTT configuration settings. */ #if IOT_MQTT_ENABLE_ASSERTS != 0 && IOT_MQTT_ENABLE_ASSERTS != 1 #error "IOT_MQTT_ENABLE_ASSERTS must be 0 or 1." #endif #if IOT_MQTT_ENABLE_METRICS != 0 && IOT_MQTT_ENABLE_METRICS != 1 #error "IOT_MQTT_ENABLE_METRICS must be 0 or 1." #endif #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES != 0 && IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES != 1 #error "IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES must be 0 or 1." #endif #if IOT_MQTT_RESPONSE_WAIT_MS <= 0 #error "IOT_MQTT_RESPONSE_WAIT_MS cannot be 0 or negative." #endif #if IOT_MQTT_RETRY_MS_CEILING <= 0 #error "IOT_MQTT_RETRY_MS_CEILING cannot be 0 or negative." #endif /*-----------------------------------------------------------*/ /** * @brief Uninitialized value for @ref _initCalled. */ #define MQTT_LIBRARY_UNINITIALIZED ( ( uint32_t ) 0 ) /** * @brief Initialized value for @ref _initCalled. */ #define MQTT_LIBRARY_INITIALIZED ( ( uint32_t ) 1 ) /*-----------------------------------------------------------*/ /** * @brief Check if the library is initialized. * * @return `true` if IotMqtt_Init was called; `false` otherwise. */ static bool _checkInit( void ); /** * @brief Set the unsubscribed flag of an MQTT subscription. * * @param[in] pSubscriptionLink Pointer to the link member of an #_mqttSubscription_t. * @param[in] pMatch Not used. * * @return Always returns `true`. */ static bool _mqttSubscription_setUnsubscribe( const IotLink_t * pSubscriptionLink, void * pMatch ); /** * @brief Destroy an MQTT subscription if its reference count is 0. * * @param[in] pData The subscription to destroy. This parameter is of type * `void*` for compatibility with [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ static void _mqttSubscription_tryDestroy( void * pData ); /** * @brief Decrement the reference count of an MQTT operation and attempt to * destroy it. * * @param[in] pData The operation data to destroy. This parameter is of type * `void*` for compatibility with [free] * (http://pubs.opengroup.org/onlinepubs/9699919799/functions/free.html). */ static void _mqttOperation_tryDestroy( void * pData ); /** * @brief Initialize the keep-alive operation for an MQTT connection. * * @param[in] pNetworkInfo User-provided network information for the new * connection. * @param[in] keepAliveSeconds User-provided keep-alive interval. * @param[out] pMqttConnection The MQTT connection associated with the keep-alive. * * @return `true` if the keep-alive job was successfully created; `false` otherwise. */ static bool _createKeepAliveOperation( const IotMqttNetworkInfo_t * pNetworkInfo, uint16_t keepAliveSeconds, _mqttConnection_t * pMqttConnection ); /** * @brief Initialize a network connection, creating it if necessary. * * @param[in] pNetworkInfo User-provided network information for the connection * connection. * @param[out] pNetworkConnection On success, the created and/or initialized network connection. * @param[out] pCreatedNewNetworkConnection On success, `true` if a new network connection was created; `false` if an existing one will be used. * * @return Any #IotNetworkError_t, as defined by the network stack. */ static IotNetworkError_t _createNetworkConnection( const IotMqttNetworkInfo_t * pNetworkInfo, IotNetworkConnection_t * pNetworkConnection, bool * pCreatedNewNetworkConnection ); /** * @brief Creates a new MQTT connection and initializes its members. * * @param[in] awsIotMqttMode Specifies if this connection is to an AWS IoT MQTT server. * @param[in] pNetworkInfo User-provided network information for the new * connection. * @param[in] keepAliveSeconds User-provided keep-alive interval for the new connection. * * @return Pointer to a newly-created MQTT connection; `NULL` on failure. */ static _mqttConnection_t * _createMqttConnection( bool awsIotMqttMode, const IotMqttNetworkInfo_t * pNetworkInfo, uint16_t keepAliveSeconds ); /** * @brief Destroys the members of an MQTT connection. * * @param[in] pMqttConnection Which connection to destroy. */ static void _destroyMqttConnection( _mqttConnection_t * pMqttConnection ); /** * @brief Common setup function for subscribe and unsubscribe operations. * * See @ref mqtt_function_subscribeasync or @ref mqtt_function_unsubscribeasync for a * description of the parameters and return values. */ static IotMqttError_t _subscriptionCommonSetup( IotMqttOperationType_t operation, IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, IotMqttOperation_t * const pOperationReference ); /** * @brief Utility function for creating and serializing subscription requests * * See @ref mqtt_function_subscribeasync or @ref mqtt_function_unsubscribeasync for a * description of the parameters and return values. */ static IotMqttError_t _subscriptionCreateAndSerialize( IotMqttOperationType_t operation, IotMqttConnection_t mqttConnection, IotMqttSerializeSubscribe_t serializeSubscription, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, _mqttOperation_t ** ppSubscriptionOperation ); /** * @brief The common component of both @ref mqtt_function_subscribeasync and @ref * mqtt_function_unsubscribeasync. * * See @ref mqtt_function_subscribeasync or @ref mqtt_function_unsubscribeasync for a * description of the parameters and return values. */ static IotMqttError_t _subscriptionCommon( IotMqttOperationType_t operation, IotMqttConnection_t mqttConnection, IotMqttSerializeSubscribe_t serializeSubscription, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, IotMqttOperation_t * const pOperationReference ); /** * @cond DOXYGEN_IGNORE * Doxygen should ignore this section. * * Declaration of local MQTT serializer override selectors */ #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 _SERIALIZER_OVERRIDE_SELECTOR( IotMqttSerializePingreq_t, _getMqttPingreqSerializer, _IotMqtt_SerializePingreq, serialize.pingreq ) _SERIALIZER_OVERRIDE_SELECTOR( IotMqtt_SerializePublish_t, _getMqttPublishSerializer, _IotMqtt_SerializePublish, serialize.publish ) _SERIALIZER_OVERRIDE_SELECTOR( IotMqttFreePacket_t, _getMqttFreePacketFunc, _IotMqtt_FreePacket, freePacket ) _SERIALIZER_OVERRIDE_SELECTOR( IotMqttSerializeSubscribe_t, _getMqttSubscribeSerializer, _IotMqtt_SerializeSubscribe, serialize.subscribe ) _SERIALIZER_OVERRIDE_SELECTOR( IotMqttSerializeSubscribe_t, _getMqttUnsubscribeSerializer, _IotMqtt_SerializeUnsubscribe, serialize.unsubscribe ) _SERIALIZER_OVERRIDE_SELECTOR( IotMqttSerializeConnect_t, _getMqttConnectSerializer, _IotMqtt_SerializeConnect, serialize.connect ) _SERIALIZER_OVERRIDE_SELECTOR( IotMqttSerializeDisconnect_t, _getMqttDisconnectSerializer, _IotMqtt_SerializeDisconnect, serialize.disconnect ) #else /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */ #define _getMqttPingreqSerializer( pSerializer ) _IotMqtt_SerializePingreq #define _getMqttPublishSerializer( pSerializer ) _IotMqtt_SerializePublish #define _getMqttFreePacketFunc( pSerializer ) _IotMqtt_FreePacket #define _getMqttSubscribeSerializer( pSerializer ) _IotMqtt_SerializeSubscribe #define _getMqttUnsubscribeSerializer( pSerializer ) _IotMqtt_SerializeUnsubscribe #define _getMqttConnectSerializer( pSerializer ) _IotMqtt_SerializeConnect #define _getMqttDisconnectSerializer( pSerializer ) _IotMqtt_SerializeDisconnect #endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */ /** @endcond */ /*-----------------------------------------------------------*/ /** * @brief Tracks whether @ref mqtt_function_init has been called. * * API functions will fail if @ref mqtt_function_init was not called. */ static volatile uint32_t _initCalled = MQTT_LIBRARY_UNINITIALIZED; /*-----------------------------------------------------------*/ static bool _checkInit( void ) { bool status = true; if( _initCalled == MQTT_LIBRARY_UNINITIALIZED ) { IotLogError( "IotMqtt_Init was not called." ); status = false; } else { EMPTY_ELSE_MARKER; } return status; } /*-----------------------------------------------------------*/ static bool _mqttSubscription_setUnsubscribe( const IotLink_t * pSubscriptionLink, void * pMatch ) { /* Because this function is called from a container function, the given link * must never be NULL. */ IotMqtt_Assert( pSubscriptionLink != NULL ); _mqttSubscription_t * pSubscription = IotLink_Container( _mqttSubscription_t, pSubscriptionLink, link ); /* Silence warnings about unused parameters. */ ( void ) pMatch; /* Set the unsubscribed flag. */ pSubscription->unsubscribed = true; return true; } /*-----------------------------------------------------------*/ static void _mqttSubscription_tryDestroy( void * pData ) { _mqttSubscription_t * pSubscription = ( _mqttSubscription_t * ) pData; /* Reference count must not be negative. */ IotMqtt_Assert( pSubscription->references >= 0 ); /* Unsubscribed flag should be set. */ IotMqtt_Assert( pSubscription->unsubscribed == true ); /* Free the subscription if it has no references. */ if( pSubscription->references == 0 ) { IotMqtt_FreeSubscription( pSubscription ); } else { EMPTY_ELSE_MARKER; } } /*-----------------------------------------------------------*/ static void _mqttOperation_tryDestroy( void * pData ) { _mqttOperation_t * pOperation = ( _mqttOperation_t * ) pData; IotTaskPoolError_t taskPoolStatus = IOT_TASKPOOL_SUCCESS; /* Incoming PUBLISH operations may always be freed. */ if( pOperation->incomingPublish == true ) { /* Cancel the incoming PUBLISH operation's job. */ taskPoolStatus = IotTaskPool_TryCancel( IOT_SYSTEM_TASKPOOL, pOperation->job, NULL ); /* If the operation's job was not canceled, it must be already executing. * Any other return value is invalid. */ IotMqtt_Assert( ( taskPoolStatus == IOT_TASKPOOL_SUCCESS ) || ( taskPoolStatus == IOT_TASKPOOL_CANCEL_FAILED ) ); /* Check if the incoming PUBLISH job was canceled. */ if( taskPoolStatus == IOT_TASKPOOL_SUCCESS ) { /* Job was canceled. Process incoming PUBLISH now to clean up. */ _IotMqtt_ProcessIncomingPublish( IOT_SYSTEM_TASKPOOL, pOperation->job, pOperation ); } else { /* The executing job will process the PUBLISH, so nothing is done here. */ EMPTY_ELSE_MARKER; } } else { /* Decrement reference count and destroy operation if possible. */ if( _IotMqtt_DecrementOperationReferences( pOperation, true ) == true ) { _IotMqtt_DestroyOperation( pOperation ); } else { EMPTY_ELSE_MARKER; } } } /*-----------------------------------------------------------*/ static bool _createKeepAliveOperation( const IotMqttNetworkInfo_t * pNetworkInfo, uint16_t keepAliveSeconds, _mqttConnection_t * pMqttConnection ) { bool status = true; IotMqttError_t serializeStatus = IOT_MQTT_SUCCESS; IotTaskPoolError_t jobStatus = IOT_TASKPOOL_SUCCESS; /* Network information is not used when MQTT packet serializers are disabled. */ ( void ) pNetworkInfo; /* Set PINGREQ operation members. */ pMqttConnection->pingreq.u.operation.type = IOT_MQTT_PINGREQ; /* Convert the keep-alive interval to milliseconds. */ pMqttConnection->pingreq.u.operation.periodic.ping.keepAliveMs = keepAliveSeconds * 1000; pMqttConnection->pingreq.u.operation.periodic.ping.nextPeriodMs = keepAliveSeconds * 1000; /* Generate a PINGREQ packet. */ serializeStatus = _getMqttPingreqSerializer( pMqttConnection->pSerializer )( &( pMqttConnection->pingreq.u.operation.pMqttPacket ), &( pMqttConnection->pingreq.u.operation.packetSize ) ); if( serializeStatus != IOT_MQTT_SUCCESS ) { IotLogError( "Failed to allocate PINGREQ packet for new connection." ); status = false; } else { /* Create the task pool job that processes keep-alive. */ jobStatus = IotTaskPool_CreateJob( _IotMqtt_ProcessKeepAlive, pMqttConnection, &( pMqttConnection->pingreq.jobStorage ), &( pMqttConnection->pingreq.job ) ); /* Task pool job creation for a pre-allocated job should never fail. * Abort the program if it does. */ if( jobStatus != IOT_TASKPOOL_SUCCESS ) { IotLogError( "Failed to create keep-alive job for new connection." ); IotMqtt_Assert( false ); } else { EMPTY_ELSE_MARKER; } /* Keep-alive references its MQTT connection, so increment reference. */ ( pMqttConnection->references )++; } return status; } /*-----------------------------------------------------------*/ static IotNetworkError_t _createNetworkConnection( const IotMqttNetworkInfo_t * pNetworkInfo, IotNetworkConnection_t * pNetworkConnection, bool * pCreatedNewNetworkConnection ) { IOT_FUNCTION_ENTRY( IotNetworkError_t, IOT_NETWORK_SUCCESS ); /* Network info must not be NULL. */ if( pNetworkInfo == NULL ) { IotLogError( "Network information cannot be NULL." ); IOT_SET_AND_GOTO_CLEANUP( IOT_NETWORK_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } /* Create a new network connection if requested. Otherwise, copy the existing * network connection. */ if( pNetworkInfo->createNetworkConnection == true ) { status = pNetworkInfo->pNetworkInterface->create( pNetworkInfo->u.setup.pNetworkServerInfo, pNetworkInfo->u.setup.pNetworkCredentialInfo, pNetworkConnection ); if( status == IOT_NETWORK_SUCCESS ) { /* This MQTT connection owns the network connection it created and * should destroy it on cleanup. */ *pCreatedNewNetworkConnection = true; } else { IotLogError( "Failed to create network connection: %d", status ); IOT_GOTO_CLEANUP(); } } else { /* A connection already exists; the caller should not destroy * it on cleanup. */ *pNetworkConnection = pNetworkInfo->u.pNetworkConnection; *pCreatedNewNetworkConnection = false; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ static _mqttConnection_t * _createMqttConnection( bool awsIotMqttMode, const IotMqttNetworkInfo_t * pNetworkInfo, uint16_t keepAliveSeconds ) { IOT_FUNCTION_ENTRY( bool, true ); _mqttConnection_t * pMqttConnection = NULL; bool referencesMutexCreated = false, subscriptionMutexCreated = false; /* Allocate memory for the new MQTT connection. */ pMqttConnection = IotMqtt_MallocConnection( sizeof( _mqttConnection_t ) ); if( pMqttConnection == NULL ) { IotLogError( "Failed to allocate memory for new connection." ); IOT_SET_AND_GOTO_CLEANUP( false ); } else { /* Clear the MQTT connection, then copy the MQTT server mode, network * interface, and disconnect callback. */ ( void ) memset( pMqttConnection, 0x00, sizeof( _mqttConnection_t ) ); pMqttConnection->awsIotMqttMode = awsIotMqttMode; pMqttConnection->pNetworkInterface = pNetworkInfo->pNetworkInterface; pMqttConnection->disconnectCallback = pNetworkInfo->disconnectCallback; /* Start a new MQTT connection with a reference count of 1. */ pMqttConnection->references = 1; } /* Create the references mutex for a new connection. It is a recursive mutex. */ referencesMutexCreated = IotMutex_Create( &( pMqttConnection->referencesMutex ), true ); if( referencesMutexCreated == false ) { IotLogError( "Failed to create references mutex for new connection." ); IOT_SET_AND_GOTO_CLEANUP( false ); } else { EMPTY_ELSE_MARKER; } /* Create the subscription mutex for a new connection. */ subscriptionMutexCreated = IotMutex_Create( &( pMqttConnection->subscriptionMutex ), false ); if( subscriptionMutexCreated == false ) { IotLogError( "Failed to create subscription mutex for new connection." ); IOT_SET_AND_GOTO_CLEANUP( false ); } else { EMPTY_ELSE_MARKER; } /* Create the new connection's subscription and operation lists. */ IotListDouble_Create( &( pMqttConnection->subscriptionList ) ); IotListDouble_Create( &( pMqttConnection->pendingProcessing ) ); IotListDouble_Create( &( pMqttConnection->pendingResponse ) ); /* Check if keep-alive is active for this connection. */ if( keepAliveSeconds != 0 ) { if( _createKeepAliveOperation( pNetworkInfo, keepAliveSeconds, pMqttConnection ) == false ) { IOT_SET_AND_GOTO_CLEANUP( false ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } /* Clean up mutexes and connection if this function failed. */ IOT_FUNCTION_CLEANUP_BEGIN(); if( status == false ) { if( subscriptionMutexCreated == true ) { IotMutex_Destroy( &( pMqttConnection->subscriptionMutex ) ); } else { EMPTY_ELSE_MARKER; } if( referencesMutexCreated == true ) { IotMutex_Destroy( &( pMqttConnection->referencesMutex ) ); } else { EMPTY_ELSE_MARKER; } if( pMqttConnection != NULL ) { IotMqtt_FreeConnection( pMqttConnection ); pMqttConnection = NULL; } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } return pMqttConnection; } /*-----------------------------------------------------------*/ static void _destroyMqttConnection( _mqttConnection_t * pMqttConnection ) { IotNetworkError_t networkStatus = IOT_NETWORK_SUCCESS; /* Clean up keep-alive if still allocated. */ if( pMqttConnection->pingreq.u.operation.periodic.ping.keepAliveMs != 0 ) { IotLogDebug( "(MQTT connection %p) Cleaning up keep-alive.", pMqttConnection ); _getMqttFreePacketFunc( pMqttConnection->pSerializer )( pMqttConnection->pingreq.u.operation.pMqttPacket ); /* Clear data about the keep-alive. */ pMqttConnection->pingreq.u.operation.periodic.ping.keepAliveMs = 0; pMqttConnection->pingreq.u.operation.pMqttPacket = NULL; pMqttConnection->pingreq.u.operation.packetSize = 0; /* Decrement reference count. */ pMqttConnection->references--; } else { EMPTY_ELSE_MARKER; } /* A connection to be destroyed should have no keep-alive and at most 1 * reference. */ IotMqtt_Assert( pMqttConnection->references <= 1 ); IotMqtt_Assert( pMqttConnection->pingreq.u.operation.periodic.ping.keepAliveMs == 0 ); IotMqtt_Assert( pMqttConnection->pingreq.u.operation.pMqttPacket == NULL ); IotMqtt_Assert( pMqttConnection->pingreq.u.operation.packetSize == 0 ); /* Remove all subscriptions. */ IotMutex_Lock( &( pMqttConnection->subscriptionMutex ) ); IotListDouble_RemoveAllMatches( &( pMqttConnection->subscriptionList ), _mqttSubscription_setUnsubscribe, NULL, _mqttSubscription_tryDestroy, offsetof( _mqttSubscription_t, link ) ); IotMutex_Unlock( &( pMqttConnection->subscriptionMutex ) ); /* Destroy an owned network connection. */ if( pMqttConnection->ownNetworkConnection == true ) { networkStatus = pMqttConnection->pNetworkInterface->destroy( pMqttConnection->pNetworkConnection ); if( networkStatus != IOT_NETWORK_SUCCESS ) { IotLogWarn( "(MQTT connection %p) Failed to destroy network connection.", pMqttConnection ); } else { IotLogInfo( "(MQTT connection %p) Network connection destroyed.", pMqttConnection ); } } else { EMPTY_ELSE_MARKER; } /* Destroy mutexes. */ IotMutex_Destroy( &( pMqttConnection->referencesMutex ) ); IotMutex_Destroy( &( pMqttConnection->subscriptionMutex ) ); IotLogDebug( "(MQTT connection %p) Connection destroyed.", pMqttConnection ); /* Free connection. */ IotMqtt_FreeConnection( pMqttConnection ); } /*-----------------------------------------------------------*/ static IotMqttError_t _subscriptionCommonSetup( IotMqttOperationType_t operation, IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, IotMqttOperation_t * const pOperationReference ) { IOT_FUNCTION_ENTRY( IotMqttError_t, IOT_MQTT_SUCCESS ); /* This function should only be called for subscribe or unsubscribe. */ IotMqtt_Assert( ( operation == IOT_MQTT_SUBSCRIBE ) || ( operation == IOT_MQTT_UNSUBSCRIBE ) ); /* Check that IotMqtt_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NOT_INITIALIZED ); } else { EMPTY_ELSE_MARKER; } /* Check that all elements in the subscription list are valid. */ if( _IotMqtt_ValidateSubscriptionList( operation, mqttConnection->awsIotMqttMode, pSubscriptionList, subscriptionCount ) == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } /* Check that a reference pointer is provided for a waitable operation. */ if( ( flags & IOT_MQTT_FLAG_WAITABLE ) == IOT_MQTT_FLAG_WAITABLE ) { if( pOperationReference == NULL ) { IotLogError( "Reference must be provided for a waitable %s.", IotMqtt_OperationType( operation ) ); IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ static IotMqttError_t _subscriptionCreateAndSerialize( IotMqttOperationType_t operation, IotMqttConnection_t mqttConnection, IotMqttSerializeSubscribe_t serializeSubscription, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, _mqttOperation_t ** ppSubscriptionOperation ) { IOT_FUNCTION_ENTRY( IotMqttError_t, IOT_MQTT_SUCCESS ); _mqttOperation_t * pSubscriptionOperation = NULL; /* Create a subscription operation. */ status = _IotMqtt_CreateOperation( mqttConnection, flags, pCallbackInfo, ppSubscriptionOperation ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { pSubscriptionOperation = ( *ppSubscriptionOperation ); } /* Check the subscription operation data and set the operation type. */ IotMqtt_Assert( pSubscriptionOperation->u.operation.status == IOT_MQTT_STATUS_PENDING ); IotMqtt_Assert( pSubscriptionOperation->u.operation.periodic.retry.limit == 0 ); pSubscriptionOperation->u.operation.type = operation; /* Generate a subscription packet from the subscription list. */ status = serializeSubscription( pSubscriptionList, subscriptionCount, &( pSubscriptionOperation->u.operation.pMqttPacket ), &( pSubscriptionOperation->u.operation.packetSize ), &( pSubscriptionOperation->u.operation.packetIdentifier ) ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Check the serialized MQTT packet. */ IotMqtt_Assert( pSubscriptionOperation->u.operation.pMqttPacket != NULL ); IotMqtt_Assert( pSubscriptionOperation->u.operation.packetSize > 0 ); IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ static IotMqttError_t _subscriptionCommon( IotMqttOperationType_t operation, IotMqttConnection_t mqttConnection, IotMqttSerializeSubscribe_t serializeSubscription, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, IotMqttOperation_t * const pOperationReference ) { IOT_FUNCTION_ENTRY( IotMqttError_t, IOT_MQTT_SUCCESS ); _mqttOperation_t * pSubscriptionOperation = NULL; /* Create and serialize the subscription operation. */ status = _subscriptionCreateAndSerialize( operation, mqttConnection, serializeSubscription, pSubscriptionList, subscriptionCount, flags, pCallbackInfo, &pSubscriptionOperation ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Add the subscription list for a SUBSCRIBE. */ if( operation == IOT_MQTT_SUBSCRIBE ) { status = _IotMqtt_AddSubscriptions( mqttConnection, pSubscriptionOperation->u.operation.packetIdentifier, pSubscriptionList, subscriptionCount ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } } /* Set the reference, if provided. */ if( pOperationReference != NULL ) { *pOperationReference = pSubscriptionOperation; } else { EMPTY_ELSE_MARKER; } /* Send the SUBSCRIBE packet. */ if( ( flags & MQTT_INTERNAL_FLAG_BLOCK_ON_SEND ) == MQTT_INTERNAL_FLAG_BLOCK_ON_SEND ) { _IotMqtt_ProcessSend( IOT_SYSTEM_TASKPOOL, pSubscriptionOperation->job, pSubscriptionOperation ); } else { status = _IotMqtt_ScheduleOperation( pSubscriptionOperation, _IotMqtt_ProcessSend, 0 ); if( status != IOT_MQTT_SUCCESS ) { IotLogError( "(MQTT connection %p) Failed to schedule %s for sending.", mqttConnection, IotMqtt_OperationType( operation ) ); if( operation == IOT_MQTT_SUBSCRIBE ) { _IotMqtt_RemoveSubscriptionByPacket( mqttConnection, pSubscriptionOperation->u.operation.packetIdentifier, MQTT_REMOVE_ALL_SUBSCRIPTIONS ); } else { EMPTY_ELSE_MARKER; } /* Clear the previously set (and now invalid) reference. */ if( pOperationReference != NULL ) { *pOperationReference = IOT_MQTT_OPERATION_INITIALIZER; } else { EMPTY_ELSE_MARKER; } IOT_GOTO_CLEANUP(); } } /* Clean up if this function failed. */ IOT_FUNCTION_CLEANUP_BEGIN(); if( status != IOT_MQTT_SUCCESS ) { if( pSubscriptionOperation != NULL ) { _IotMqtt_DestroyOperation( pSubscriptionOperation ); } else { EMPTY_ELSE_MARKER; } } else { status = IOT_MQTT_STATUS_PENDING; IotLogInfo( "(MQTT connection %p) %s operation scheduled.", mqttConnection, IotMqtt_OperationType( operation ) ); } IOT_FUNCTION_CLEANUP_END(); } /*-----------------------------------------------------------*/ bool _IotMqtt_IncrementConnectionReferences( _mqttConnection_t * pMqttConnection ) { bool disconnected = false; /* Lock the mutex protecting the reference count. */ IotMutex_Lock( &( pMqttConnection->referencesMutex ) ); /* Reference count must not be negative. */ IotMqtt_Assert( pMqttConnection->references >= 0 ); /* Read connection status. */ disconnected = pMqttConnection->disconnected; /* Increment the connection's reference count if it is not disconnected. */ if( disconnected == false ) { ( pMqttConnection->references )++; IotLogDebug( "(MQTT connection %p) Reference count changed from %ld to %ld.", pMqttConnection, ( long int ) pMqttConnection->references - 1, ( long int ) pMqttConnection->references ); } else { IotLogWarn( "(MQTT connection %p) Attempt to use closed connection.", pMqttConnection ); } IotMutex_Unlock( &( pMqttConnection->referencesMutex ) ); return( disconnected == false ); } /*-----------------------------------------------------------*/ void _IotMqtt_DecrementConnectionReferences( _mqttConnection_t * pMqttConnection ) { bool destroyConnection = false; /* Lock the mutex protecting the reference count. */ IotMutex_Lock( &( pMqttConnection->referencesMutex ) ); /* Decrement reference count. It must not be negative. */ ( pMqttConnection->references )--; IotMqtt_Assert( pMqttConnection->references >= 0 ); IotLogDebug( "(MQTT connection %p) Reference count changed from %ld to %ld.", pMqttConnection, ( long int ) pMqttConnection->references + 1, ( long int ) pMqttConnection->references ); /* Check if this connection may be destroyed. */ if( pMqttConnection->references == 0 ) { destroyConnection = true; } else { EMPTY_ELSE_MARKER; } IotMutex_Unlock( &( pMqttConnection->referencesMutex ) ); /* Destroy an unreferenced MQTT connection. */ if( destroyConnection == true ) { IotLogDebug( "(MQTT connection %p) Connection will be destroyed now.", pMqttConnection ); _destroyMqttConnection( pMqttConnection ); } else { EMPTY_ELSE_MARKER; } } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_Init( void ) { IotMqttError_t status = IOT_MQTT_SUCCESS; uint32_t allowInitialization = Atomic_CompareAndSwap_u32( &_initCalled, MQTT_LIBRARY_INITIALIZED, MQTT_LIBRARY_UNINITIALIZED ); if( allowInitialization == 1 ) { /* Call any additional serializer initialization function if serializer * overrides are enabled. */ #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 #ifdef _IotMqtt_InitSerializeAdditional if( _IotMqtt_InitSerializeAdditional() == false ) { /* Log initialization status. */ IotLogError( "Failed to initialize MQTT library serializer. " ); status = IOT_MQTT_INIT_FAILED; } else { EMPTY_ELSE_MARKER; } #endif /* ifdef _IotMqtt_InitSerializeAdditional */ #endif /* if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 */ if( status == IOT_MQTT_SUCCESS ) { IotLogInfo( "MQTT library successfully initialized." ); } else { EMPTY_ELSE_MARKER; } } else { IotLogWarn( "IotMqtt_Init called with library already initialized." ); } return status; } /*-----------------------------------------------------------*/ void IotMqtt_Cleanup( void ) { uint32_t allowCleanup = Atomic_CompareAndSwap_u32( &_initCalled, MQTT_LIBRARY_UNINITIALIZED, MQTT_LIBRARY_INITIALIZED ); if( allowCleanup == 1 ) { /* Call any additional serializer cleanup initialization function if serializer * overrides are enabled. */ #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 #ifdef _IotMqtt_CleanupSerializeAdditional _IotMqtt_CleanupSerializeAdditional(); #endif #endif IotLogInfo( "MQTT library cleanup done." ); } else { IotLogWarn( "IotMqtt_Init was not called before IotMqtt_Cleanup." ); } } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_Connect( const IotMqttNetworkInfo_t * pNetworkInfo, const IotMqttConnectInfo_t * pConnectInfo, uint32_t timeoutMs, IotMqttConnection_t * const pMqttConnection ) { IOT_FUNCTION_ENTRY( IotMqttError_t, IOT_MQTT_SUCCESS ); bool ownNetworkConnection = false; IotNetworkError_t networkStatus = IOT_NETWORK_SUCCESS; IotTaskPoolError_t taskPoolStatus = IOT_TASKPOOL_SUCCESS; IotNetworkConnection_t pNetworkConnection = { 0 }; _mqttOperation_t * pOperation = NULL; _mqttConnection_t * pNewMqttConnection = NULL; /* Check that IotMqtt_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NOT_INITIALIZED ); } else { EMPTY_ELSE_MARKER; } /* Validate network interface and connect info. */ if( _IotMqtt_ValidateConnect( pConnectInfo ) == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } networkStatus = _createNetworkConnection( pNetworkInfo, &pNetworkConnection, &ownNetworkConnection ); if( networkStatus != IOT_NETWORK_SUCCESS ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NETWORK_ERROR ); } else { EMPTY_ELSE_MARKER; } IotLogInfo( "Establishing new MQTT connection." ); /* Initialize a new MQTT connection object. */ pNewMqttConnection = _createMqttConnection( pConnectInfo->awsIotMqttMode, pNetworkInfo, pConnectInfo->keepAliveSeconds ); if( pNewMqttConnection == NULL ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NO_MEMORY ); } else { /* Set the network connection associated with the MQTT connection. */ pNewMqttConnection->pNetworkConnection = pNetworkConnection; pNewMqttConnection->ownNetworkConnection = ownNetworkConnection; /* Set the MQTT packet serializer overrides. */ #if IOT_MQTT_ENABLE_SERIALIZER_OVERRIDES == 1 pNewMqttConnection->pSerializer = pNetworkInfo->pMqttSerializer; #else pNewMqttConnection->pSerializer = NULL; #endif } /* Set the MQTT receive callback. */ networkStatus = pNewMqttConnection->pNetworkInterface->setReceiveCallback( pNetworkConnection, IotMqtt_ReceiveCallback, pNewMqttConnection ); if( networkStatus != IOT_NETWORK_SUCCESS ) { IotLogError( "Failed to set MQTT network receive callback." ); IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NETWORK_ERROR ); } else { EMPTY_ELSE_MARKER; } /* Create a CONNECT operation. */ status = _IotMqtt_CreateOperation( pNewMqttConnection, IOT_MQTT_FLAG_WAITABLE, NULL, &pOperation ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Ensure the members set by operation creation and serialization * are appropriate for a blocking CONNECT. */ IotMqtt_Assert( pOperation->u.operation.status == IOT_MQTT_STATUS_PENDING ); IotMqtt_Assert( ( pOperation->u.operation.flags & IOT_MQTT_FLAG_WAITABLE ) == IOT_MQTT_FLAG_WAITABLE ); IotMqtt_Assert( pOperation->u.operation.periodic.retry.limit == 0 ); /* Set the operation type. */ pOperation->u.operation.type = IOT_MQTT_CONNECT; /* Add previous session subscriptions. */ if( pConnectInfo->pPreviousSubscriptions != NULL ) { /* Previous subscription count should have been validated as nonzero. */ IotMqtt_Assert( pConnectInfo->previousSubscriptionCount > 0 ); status = _IotMqtt_AddSubscriptions( pNewMqttConnection, 2, pConnectInfo->pPreviousSubscriptions, pConnectInfo->previousSubscriptionCount ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } /* Convert the connect info and will info objects to an MQTT CONNECT packet. */ status = _getMqttConnectSerializer( pNetworkInfo->pMqttSerializer )( pConnectInfo, &( pOperation->u.operation.pMqttPacket ), &( pOperation->u.operation.packetSize ) ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Check the serialized MQTT packet. */ IotMqtt_Assert( pOperation->u.operation.pMqttPacket != NULL ); IotMqtt_Assert( pOperation->u.operation.packetSize > 0 ); /* Send the CONNECT packet. */ _IotMqtt_ProcessSend( IOT_SYSTEM_TASKPOOL, pOperation->job, pOperation ); /* Wait for the CONNECT operation to complete, i.e. wait for CONNACK. */ status = IotMqtt_Wait( pOperation, timeoutMs ); /* The call to wait cleans up the CONNECT operation, so set the pointer * to NULL. */ pOperation = NULL; /* When a connection is successfully established, schedule keep-alive job. */ if( status == IOT_MQTT_SUCCESS ) { /* Check if a keep-alive job should be scheduled. */ if( pNewMqttConnection->pingreq.u.operation.periodic.ping.keepAliveMs != 0 ) { IotLogDebug( "Scheduling first MQTT keep-alive job." ); taskPoolStatus = IotTaskPool_ScheduleDeferred( IOT_SYSTEM_TASKPOOL, pNewMqttConnection->pingreq.job, pNewMqttConnection->pingreq.u.operation.periodic.ping.nextPeriodMs ); if( taskPoolStatus != IOT_TASKPOOL_SUCCESS ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_SCHEDULING_ERROR ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } IOT_FUNCTION_CLEANUP_BEGIN(); if( status != IOT_MQTT_SUCCESS ) { IotLogError( "Failed to establish new MQTT connection, error %s.", IotMqtt_strerror( status ) ); /* The network connection must be closed if it was created. */ if( ownNetworkConnection == true ) { networkStatus = pNetworkInfo->pNetworkInterface->close( pNetworkConnection ); if( networkStatus != IOT_NETWORK_SUCCESS ) { IotLogWarn( "Failed to close network connection." ); } else { IotLogInfo( "Network connection closed on error." ); } } else { EMPTY_ELSE_MARKER; } if( pOperation != NULL ) { _IotMqtt_DestroyOperation( pOperation ); } else { EMPTY_ELSE_MARKER; } if( pNewMqttConnection != NULL ) { _destroyMqttConnection( pNewMqttConnection ); } else { EMPTY_ELSE_MARKER; } } else { IotLogInfo( "New MQTT connection %p established.", pMqttConnection ); /* Set the output parameter. */ *pMqttConnection = pNewMqttConnection; } IOT_FUNCTION_CLEANUP_END(); } /*-----------------------------------------------------------*/ void IotMqtt_Disconnect( IotMqttConnection_t mqttConnection, uint32_t flags ) { bool disconnected = false, initCalled = false; IotMqttError_t status = IOT_MQTT_STATUS_PENDING; _mqttOperation_t * pOperation = NULL; /* Check that IotMqtt_Init was called. */ initCalled = _checkInit(); if( initCalled == false ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Only send a DISCONNECT packet if the connection is active and the "cleanup only" * flag is not set. */ if( ( flags & IOT_MQTT_FLAG_CLEANUP_ONLY ) == IOT_MQTT_FLAG_CLEANUP_ONLY ) { IOT_GOTO_CLEANUP(); } /* Read the connection status. */ IotMutex_Lock( &( mqttConnection->referencesMutex ) ); disconnected = mqttConnection->disconnected; IotMutex_Unlock( &( mqttConnection->referencesMutex ) ); if( disconnected == true ) { IOT_GOTO_CLEANUP(); } IotLogInfo( "(MQTT connection %p) Disconnecting connection.", mqttConnection ); /* Create a DISCONNECT operation. This function blocks until the DISCONNECT * packet is sent, so it sets IOT_MQTT_FLAG_WAITABLE. */ status = _IotMqtt_CreateOperation( mqttConnection, IOT_MQTT_FLAG_WAITABLE, NULL, &pOperation ); if( status == IOT_MQTT_SUCCESS ) { /* Ensure that the members set by operation creation and serialization * are appropriate for a blocking DISCONNECT. */ IotMqtt_Assert( pOperation->u.operation.status == IOT_MQTT_STATUS_PENDING ); IotMqtt_Assert( ( pOperation->u.operation.flags & IOT_MQTT_FLAG_WAITABLE ) == IOT_MQTT_FLAG_WAITABLE ); IotMqtt_Assert( pOperation->u.operation.periodic.retry.limit == 0 ); /* Set the operation type. */ pOperation->u.operation.type = IOT_MQTT_DISCONNECT; /* Generate a DISCONNECT packet. */ status = _getMqttDisconnectSerializer( mqttConnection->pSerializer )( &( pOperation->u.operation.pMqttPacket ), &( pOperation->u.operation.packetSize ) ); } else { EMPTY_ELSE_MARKER; } if( status == IOT_MQTT_SUCCESS ) { /* Check the serialized MQTT packet. */ IotMqtt_Assert( pOperation->u.operation.pMqttPacket != NULL ); IotMqtt_Assert( pOperation->u.operation.packetSize > 0 ); /* Send the DISCONNECT packet. */ _IotMqtt_ProcessSend( IOT_SYSTEM_TASKPOOL, pOperation->job, pOperation ); /* Wait a short time for the DISCONNECT packet to be transmitted. */ status = IotMqtt_Wait( pOperation, IOT_MQTT_RESPONSE_WAIT_MS ); /* A wait on DISCONNECT should only ever return SUCCESS, TIMEOUT, * or NETWORK ERROR. */ if( status == IOT_MQTT_SUCCESS ) { IotLogInfo( "(MQTT connection %p) Connection disconnected.", mqttConnection ); } else { IotMqtt_Assert( ( status == IOT_MQTT_TIMEOUT ) || ( status == IOT_MQTT_NETWORK_ERROR ) ); IotLogWarn( "(MQTT connection %p) DISCONNECT not sent, error %s.", mqttConnection, IotMqtt_strerror( status ) ); } } else { EMPTY_ELSE_MARKER; } /* This function has no return value and no cleanup, but uses the cleanup * label to exit on error. */ IOT_FUNCTION_CLEANUP_BEGIN(); if( initCalled == true ) { /* Close the underlying network connection. This also cleans up keep-alive. */ _IotMqtt_CloseNetworkConnection( IOT_MQTT_DISCONNECT_CALLED, mqttConnection ); /* Check if the connection may be destroyed. */ IotMutex_Lock( &( mqttConnection->referencesMutex ) ); /* At this point, the connection should be marked disconnected. */ IotMqtt_Assert( mqttConnection->disconnected == true ); /* Attempt cancel and destroy each operation in the connection's lists. */ IotListDouble_RemoveAll( &( mqttConnection->pendingProcessing ), _mqttOperation_tryDestroy, offsetof( _mqttOperation_t, link ) ); IotListDouble_RemoveAll( &( mqttConnection->pendingResponse ), _mqttOperation_tryDestroy, offsetof( _mqttOperation_t, link ) ); IotMutex_Unlock( &( mqttConnection->referencesMutex ) ); /* Decrement the connection reference count and destroy it if possible. */ _IotMqtt_DecrementConnectionReferences( mqttConnection ); } } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_SubscribeAsync( IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, IotMqttOperation_t * const pSubscribeOperation ) { IotMqttError_t status = _subscriptionCommonSetup( IOT_MQTT_SUBSCRIBE, mqttConnection, pSubscriptionList, subscriptionCount, flags, pSubscribeOperation ); if( IOT_MQTT_SUCCESS == status ) { status = _subscriptionCommon( IOT_MQTT_SUBSCRIBE, mqttConnection, _getMqttSubscribeSerializer( mqttConnection->pSerializer ), pSubscriptionList, subscriptionCount, flags, pCallbackInfo, pSubscribeOperation ); } else { EMPTY_ELSE_MARKER; } return status; } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_SubscribeSync( IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, uint32_t timeoutMs ) { IotMqttError_t status = IOT_MQTT_STATUS_PENDING; IotMqttOperation_t subscribeOperation = IOT_MQTT_OPERATION_INITIALIZER; /* Flags are not used, but the parameter is present for future compatibility. */ ( void ) flags; /* Call the asynchronous SUBSCRIBE function. */ status = IotMqtt_SubscribeAsync( mqttConnection, pSubscriptionList, subscriptionCount, IOT_MQTT_FLAG_WAITABLE | MQTT_INTERNAL_FLAG_BLOCK_ON_SEND, NULL, &subscribeOperation ); /* Wait for the SUBSCRIBE operation to complete. */ if( status == IOT_MQTT_STATUS_PENDING ) { status = IotMqtt_Wait( subscribeOperation, timeoutMs ); } else { EMPTY_ELSE_MARKER; } /* Ensure that a status was set. */ IotMqtt_Assert( status != IOT_MQTT_STATUS_PENDING ); return status; } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_UnsubscribeAsync( IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, IotMqttOperation_t * const pUnsubscribeOperation ) { IotMqttError_t status = _subscriptionCommonSetup( IOT_MQTT_UNSUBSCRIBE, mqttConnection, pSubscriptionList, subscriptionCount, flags, pUnsubscribeOperation ); if( IOT_MQTT_SUCCESS == status ) { /* Remove the MQTT subscription list for an UNSUBSCRIBE. */ _IotMqtt_RemoveSubscriptionByTopicFilter( mqttConnection, pSubscriptionList, subscriptionCount ); status = _subscriptionCommon( IOT_MQTT_UNSUBSCRIBE, mqttConnection, _getMqttUnsubscribeSerializer( mqttConnection->pSerializer ), pSubscriptionList, subscriptionCount, flags, pCallbackInfo, pUnsubscribeOperation ); } else { EMPTY_ELSE_MARKER; } return status; } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_UnsubscribeSync( IotMqttConnection_t mqttConnection, const IotMqttSubscription_t * pSubscriptionList, size_t subscriptionCount, uint32_t flags, uint32_t timeoutMs ) { IotMqttError_t status = IOT_MQTT_STATUS_PENDING; IotMqttOperation_t unsubscribeOperation = IOT_MQTT_OPERATION_INITIALIZER; /* Flags are not used, but the parameter is present for future compatibility. */ ( void ) flags; /* Call the asynchronous UNSUBSCRIBE function. */ status = IotMqtt_UnsubscribeAsync( mqttConnection, pSubscriptionList, subscriptionCount, IOT_MQTT_FLAG_WAITABLE | MQTT_INTERNAL_FLAG_BLOCK_ON_SEND, NULL, &unsubscribeOperation ); /* Wait for the UNSUBSCRIBE operation to complete. */ if( status == IOT_MQTT_STATUS_PENDING ) { status = IotMqtt_Wait( unsubscribeOperation, timeoutMs ); } else { EMPTY_ELSE_MARKER; } /* Ensure that a status was set. */ IotMqtt_Assert( status != IOT_MQTT_STATUS_PENDING ); return status; } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_PublishAsync( IotMqttConnection_t mqttConnection, const IotMqttPublishInfo_t * pPublishInfo, uint32_t flags, const IotMqttCallbackInfo_t * pCallbackInfo, IotMqttOperation_t * const pPublishOperation ) { IOT_FUNCTION_ENTRY( IotMqttError_t, IOT_MQTT_SUCCESS ); _mqttOperation_t * pOperation = NULL; uint8_t ** pPacketIdentifierHigh = NULL; /* Check that IotMqtt_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NOT_INITIALIZED ); } else { EMPTY_ELSE_MARKER; } /* Check that the PUBLISH information is valid. */ if( _IotMqtt_ValidatePublish( mqttConnection->awsIotMqttMode, pPublishInfo ) == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } /* Check that no notification is requested for a QoS 0 publish. */ if( pPublishInfo->qos == IOT_MQTT_QOS_0 ) { if( pCallbackInfo != NULL ) { IotLogError( "QoS 0 PUBLISH should not have notification parameters set." ); IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else if( ( flags & IOT_MQTT_FLAG_WAITABLE ) != 0 ) { IotLogError( "QoS 0 PUBLISH should not have notification parameters set." ); IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } if( pPublishOperation != NULL ) { IotLogWarn( "Ignoring reference parameter for QoS 0 publish." ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } /* Check that a reference pointer is provided for a waitable operation. */ if( ( flags & IOT_MQTT_FLAG_WAITABLE ) == IOT_MQTT_FLAG_WAITABLE ) { if( pPublishOperation == NULL ) { IotLogError( "Reference must be provided for a waitable PUBLISH." ); IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_BAD_PARAMETER ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } /* Create a PUBLISH operation. */ status = _IotMqtt_CreateOperation( mqttConnection, flags, pCallbackInfo, &pOperation ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Check the PUBLISH operation data and set the operation type. */ IotMqtt_Assert( pOperation->u.operation.status == IOT_MQTT_STATUS_PENDING ); pOperation->u.operation.type = IOT_MQTT_PUBLISH_TO_SERVER; /* In AWS IoT MQTT mode, a pointer to the packet identifier must be saved. */ if( mqttConnection->awsIotMqttMode == true ) { pPacketIdentifierHigh = &( pOperation->u.operation.pPacketIdentifierHigh ); } else { EMPTY_ELSE_MARKER; } /* Generate a PUBLISH packet from pPublishInfo. */ status = _getMqttPublishSerializer( mqttConnection->pSerializer )( pPublishInfo, &( pOperation->u.operation.pMqttPacket ), &( pOperation->u.operation.packetSize ), &( pOperation->u.operation.packetIdentifier ), pPacketIdentifierHigh ); if( status != IOT_MQTT_SUCCESS ) { IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } /* Check the serialized MQTT packet. */ IotMqtt_Assert( pOperation->u.operation.pMqttPacket != NULL ); IotMqtt_Assert( pOperation->u.operation.packetSize > 0 ); /* Initialize PUBLISH retry if retryLimit is set. */ if( pPublishInfo->retryLimit > 0 ) { /* A QoS 0 PUBLISH may not be retried. */ if( pPublishInfo->qos != IOT_MQTT_QOS_0 ) { pOperation->u.operation.periodic.retry.limit = pPublishInfo->retryLimit; pOperation->u.operation.periodic.retry.nextPeriodMs = pPublishInfo->retryMs; } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } /* Set the reference, if provided. */ if( pPublishInfo->qos != IOT_MQTT_QOS_0 ) { if( pPublishOperation != NULL ) { *pPublishOperation = pOperation; } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } /* Send the PUBLISH packet. */ if( ( flags & MQTT_INTERNAL_FLAG_BLOCK_ON_SEND ) == MQTT_INTERNAL_FLAG_BLOCK_ON_SEND ) { _IotMqtt_ProcessSend( IOT_SYSTEM_TASKPOOL, pOperation->job, pOperation ); } else { status = _IotMqtt_ScheduleOperation( pOperation, _IotMqtt_ProcessSend, 0 ); if( status != IOT_MQTT_SUCCESS ) { IotLogError( "(MQTT connection %p) Failed to enqueue PUBLISH for sending.", mqttConnection ); /* Clear the previously set (and now invalid) reference. */ if( pPublishInfo->qos != IOT_MQTT_QOS_0 ) { if( pPublishOperation != NULL ) { *pPublishOperation = IOT_MQTT_OPERATION_INITIALIZER; } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } IOT_GOTO_CLEANUP(); } else { EMPTY_ELSE_MARKER; } } /* Clean up the PUBLISH operation if this function fails. Otherwise, set the * appropriate return code based on QoS. */ IOT_FUNCTION_CLEANUP_BEGIN(); if( status != IOT_MQTT_SUCCESS ) { if( pOperation != NULL ) { _IotMqtt_DestroyOperation( pOperation ); } else { EMPTY_ELSE_MARKER; } } else { if( pPublishInfo->qos > IOT_MQTT_QOS_0 ) { status = IOT_MQTT_STATUS_PENDING; } else { EMPTY_ELSE_MARKER; } IotLogInfo( "(MQTT connection %p) MQTT PUBLISH operation queued.", mqttConnection ); } IOT_FUNCTION_CLEANUP_END(); } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_PublishSync( IotMqttConnection_t mqttConnection, const IotMqttPublishInfo_t * pPublishInfo, uint32_t flags, uint32_t timeoutMs ) { IotMqttError_t status = IOT_MQTT_STATUS_PENDING; IotMqttOperation_t publishOperation = IOT_MQTT_OPERATION_INITIALIZER, * pPublishOperation = NULL; /* Clear the flags, setting only the "serial" flag. */ flags = MQTT_INTERNAL_FLAG_BLOCK_ON_SEND; /* Set the waitable flag and reference for QoS 1 PUBLISH. */ if( pPublishInfo->qos == IOT_MQTT_QOS_1 ) { flags |= IOT_MQTT_FLAG_WAITABLE; pPublishOperation = &publishOperation; } else { EMPTY_ELSE_MARKER; } /* Call the asynchronous PUBLISH function. */ status = IotMqtt_PublishAsync( mqttConnection, pPublishInfo, flags, NULL, pPublishOperation ); /* Wait for a queued QoS 1 PUBLISH to complete. */ if( pPublishInfo->qos == IOT_MQTT_QOS_1 ) { if( status == IOT_MQTT_STATUS_PENDING ) { status = IotMqtt_Wait( publishOperation, timeoutMs ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } return status; } /*-----------------------------------------------------------*/ IotMqttError_t IotMqtt_Wait( IotMqttOperation_t operation, uint32_t timeoutMs ) { IotMqttError_t status = IOT_MQTT_SUCCESS; _mqttConnection_t * pMqttConnection = NULL; /* Check that IotMqtt_Init was called. */ if( _checkInit() == false ) { IOT_SET_AND_GOTO_CLEANUP( IOT_MQTT_NOT_INITIALIZED ); } else { EMPTY_ELSE_MARKER; } /* Validate the given operation reference. */ if( _IotMqtt_ValidateOperation( operation ) == false ) { status = IOT_MQTT_BAD_PARAMETER; } else { EMPTY_ELSE_MARKER; } /* Check the MQTT connection status. */ pMqttConnection = operation->pMqttConnection; if( status == IOT_MQTT_SUCCESS ) { IotMutex_Lock( &( pMqttConnection->referencesMutex ) ); if( pMqttConnection->disconnected == true ) { IotLogError( "(MQTT connection %p, %s operation %p) MQTT connection is closed. " "Operation cannot be waited on.", pMqttConnection, IotMqtt_OperationType( operation->u.operation.type ), operation ); status = IOT_MQTT_NETWORK_ERROR; } else { IotLogInfo( "(MQTT connection %p, %s operation %p) Waiting for operation completion.", pMqttConnection, IotMqtt_OperationType( operation->u.operation.type ), operation ); } IotMutex_Unlock( &( pMqttConnection->referencesMutex ) ); /* Only wait on an operation if the MQTT connection is active. */ if( status == IOT_MQTT_SUCCESS ) { if( IotSemaphore_TimedWait( &( operation->u.operation.notify.waitSemaphore ), timeoutMs ) == false ) { status = IOT_MQTT_TIMEOUT; /* Attempt to cancel the job of the timed out operation. */ ( void ) _IotMqtt_DecrementOperationReferences( operation, true ); /* Clean up lingering subscriptions from a timed-out SUBSCRIBE. */ if( operation->u.operation.type == IOT_MQTT_SUBSCRIBE ) { IotLogDebug( "(MQTT connection %p, SUBSCRIBE operation %p) Cleaning up" " subscriptions of timed-out SUBSCRIBE.", pMqttConnection, operation ); _IotMqtt_RemoveSubscriptionByPacket( pMqttConnection, operation->u.operation.packetIdentifier, MQTT_REMOVE_ALL_SUBSCRIPTIONS ); } else { EMPTY_ELSE_MARKER; } } else { /* Retrieve the status of the completed operation. */ status = operation->u.operation.status; } IotLogInfo( "(MQTT connection %p, %s operation %p) Wait complete with result %s.", pMqttConnection, IotMqtt_OperationType( operation->u.operation.type ), operation, IotMqtt_strerror( status ) ); } else { EMPTY_ELSE_MARKER; } /* Wait is finished; decrement operation reference count. */ if( _IotMqtt_DecrementOperationReferences( operation, false ) == true ) { _IotMqtt_DestroyOperation( operation ); } else { EMPTY_ELSE_MARKER; } } else { EMPTY_ELSE_MARKER; } IOT_FUNCTION_EXIT_NO_CLEANUP(); } /*-----------------------------------------------------------*/ const char * IotMqtt_strerror( IotMqttError_t status ) { const char * pMessage = NULL; switch( status ) { case IOT_MQTT_SUCCESS: pMessage = "SUCCESS"; break; case IOT_MQTT_STATUS_PENDING: pMessage = "PENDING"; break; case IOT_MQTT_INIT_FAILED: pMessage = "INITIALIZATION FAILED"; break; case IOT_MQTT_BAD_PARAMETER: pMessage = "BAD PARAMETER"; break; case IOT_MQTT_NO_MEMORY: pMessage = "NO MEMORY"; break; case IOT_MQTT_NETWORK_ERROR: pMessage = "NETWORK ERROR"; break; case IOT_MQTT_SCHEDULING_ERROR: pMessage = "SCHEDULING ERROR"; break; case IOT_MQTT_BAD_RESPONSE: pMessage = "BAD RESPONSE RECEIVED"; break; case IOT_MQTT_TIMEOUT: pMessage = "TIMEOUT"; break; case IOT_MQTT_SERVER_REFUSED: pMessage = "SERVER REFUSED"; break; case IOT_MQTT_RETRY_NO_RESPONSE: pMessage = "NO RESPONSE"; break; case IOT_MQTT_NOT_INITIALIZED: pMessage = "NOT INITIALIZED"; break; default: pMessage = "INVALID STATUS"; break; } return pMessage; } /*-----------------------------------------------------------*/ const char * IotMqtt_OperationType( IotMqttOperationType_t operation ) { const char * pMessage = NULL; switch( operation ) { case IOT_MQTT_CONNECT: pMessage = "CONNECT"; break; case IOT_MQTT_PUBLISH_TO_SERVER: pMessage = "PUBLISH"; break; case IOT_MQTT_PUBACK: pMessage = "PUBACK"; break; case IOT_MQTT_SUBSCRIBE: pMessage = "SUBSCRIBE"; break; case IOT_MQTT_UNSUBSCRIBE: pMessage = "UNSUBSCRIBE"; break; case IOT_MQTT_PINGREQ: pMessage = "PINGREQ"; break; case IOT_MQTT_DISCONNECT: pMessage = "DISCONNECT"; break; default: pMessage = "INVALID OPERATION"; break; } return pMessage; } /*-----------------------------------------------------------*/ /* Provide access to internal functions and variables if testing. */ #if IOT_BUILD_TESTS == 1 #include "iot_test_access_mqtt_api.c" #endif
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/c_sdk/aws/jobs/include/types/aws_iot_jobs_types.h
/* * AWS IoT Jobs V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file aws_iot_jobs_types.h * @brief Types of the Jobs library. */ #ifndef AWS_IOT_JOBS_TYPES_H_ #define AWS_IOT_JOBS_TYPES_H_ /* The config header is always included first. */ #include "iot_config.h" /* MQTT types include. */ #include "types/iot_mqtt_types.h" /*---------------------------- Jobs handle types ----------------------------*/ /** * @handles{jobs,Jobs library} */ /** * @ingroup jobs_datatypes_handles * @brief Opaque handle that references an in-progress Jobs operation. * * Set as an output parameter of @ref jobs_function_getpendingasync, @ref jobs_function_startnextasync, * @ref jobs_function_describeasync, and @ref jobs_function_updateasync. These functions send a * message to the Jobs service requesting a Jobs operation; the result of this operation * is unknown until the Jobs service sends a response. Therefore, this handle serves as a * reference to Jobs operations awaiting a response from the Jobs service. * * This reference will be valid from the successful return of @ref jobs_function_getpendingasync, * @ref jobs_function_startnextasync, @ref jobs_function_describeasync, and @ref jobs_function_updateasync. * The reference becomes invalid once the [completion callback](@ref AwsIotJobsCallbackInfo_t) * is invoked, or @ref jobs_function_wait returns. * * @initializer{AwsIotJobsOperation_t,AWS_IOT_JOBS_OPERATION_INITIALIZER} * * @see @ref jobs_function_wait and #AWS_IOT_JOBS_FLAG_WAITABLE for waiting on * a reference; or #AwsIotJobsCallbackInfo_t and #AwsIotJobsCallbackParam_t for an * asynchronous notification of completion. */ typedef struct _jobsOperation * AwsIotJobsOperation_t; /*-------------------------- Jobs enumerated types --------------------------*/ /** * @enums{jobs,Jobs library} */ /** * @ingroup jobs_datatypes_enums * @brief Return codes of [Jobs functions](@ref jobs_functions). * * The function @ref jobs_function_strerror can be used to get a return code's * description. * * The values between #AWS_IOT_JOBS_INVALID_TOPIC and #AWS_IOT_JOBS_TERMINAL_STATE * may be returned by the Jobs service upon failure of a Jobs operation. See [this page] * (https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#jobs-mqtt-error-response) * for more information. */ typedef enum AwsIotJobsError { /** * @brief Jobs operation completed successfully. * * Functions that may return this value: * - @ref jobs_function_init * - @ref jobs_function_wait * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_setnotifypendingcallback * - @ref jobs_function_setnotifynextcallback * - @ref jobs_function_removepersistentsubscriptions * * Will also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result) * when successful. */ AWS_IOT_JOBS_SUCCESS = 0, /** * @brief Jobs operation queued, awaiting result. * * Functions that may return this value: * - @ref jobs_function_getpendingasync * - @ref jobs_function_startnextasync * - @ref jobs_function_describeasync * - @ref jobs_function_updateasync */ AWS_IOT_JOBS_STATUS_PENDING = 1, /** * @brief Initialization failed. * * Functions that may return this value: * - @ref jobs_function_init */ AWS_IOT_JOBS_INIT_FAILED = 2, /** * @brief At least one parameter is invalid. * * Functions that may return this value: * - @ref jobs_function_getpendingasync and @ref jobs_function_getpendingsync * - @ref jobs_function_startnextasync and @ref jobs_function_startnextsync * - @ref jobs_function_describeasync and @ref jobs_function_describesync * - @ref jobs_function_updateasync and @ref jobs_function_updatesync * - @ref jobs_function_wait * - @ref jobs_function_setnotifypendingcallback * - @ref jobs_function_setnotifynextcallback * - @ref jobs_function_removepersistentsubscriptions */ AWS_IOT_JOBS_BAD_PARAMETER = 3, /** * @brief Jobs operation failed because of memory allocation failure. * * Functions that may return this value: * - @ref jobs_function_getpendingasync and @ref jobs_function_getpendingsync * - @ref jobs_function_startnextasync and @ref jobs_function_startnextsync * - @ref jobs_function_describeasync and @ref jobs_function_describesync * - @ref jobs_function_updateasync and @ref jobs_function_updatesync * - @ref jobs_function_setnotifypendingcallback * - @ref jobs_function_setnotifynextcallback */ AWS_IOT_JOBS_NO_MEMORY = 4, /** * @brief Jobs operation failed because of failure in MQTT library. * * Functions that may return this value: * - @ref jobs_function_getpendingasync and @ref jobs_function_getpendingsync * - @ref jobs_function_startnextasync and @ref jobs_function_startnextsync * - @ref jobs_function_describeasync and @ref jobs_function_describesync * - @ref jobs_function_updateasync and @ref jobs_function_updatesync * - @ref jobs_function_setnotifypendingcallback * - @ref jobs_function_setnotifynextcallback * - @ref jobs_function_removepersistentsubscriptions */ AWS_IOT_JOBS_MQTT_ERROR = 5, /** * @brief Response received from Jobs service not understood. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result). */ AWS_IOT_JOBS_BAD_RESPONSE = 7, /** * @brief A blocking Jobs operation timed out. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * - @ref jobs_function_setnotifypendingcallback * - @ref jobs_function_setnotifynextcallback */ AWS_IOT_JOBS_TIMEOUT = 8, /** * @brief An API function was called before @ref jobs_function_init. * * Functions that may return this value: * - @ref jobs_function_getpendingasync and @ref jobs_function_getpendingsync * - @ref jobs_function_startnextasync and @ref jobs_function_startnextsync * - @ref jobs_function_describeasync and @ref jobs_function_describesync * - @ref jobs_function_updateasync and @ref jobs_function_updatesync * - @ref jobs_function_wait * - @ref jobs_function_setnotifypendingcallback * - @ref jobs_function_setnotifynextcallback */ AWS_IOT_JOBS_NOT_INITIALIZED = 11, /** * @brief Jobs operation failed: A request was sent to an unknown topic. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result). */ AWS_IOT_JOBS_INVALID_TOPIC = 12, /** * @brief Jobs operation failed: The contents of the request were not understood. * * Jobs requests must be UTF-8 encoded JSON documents. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result). */ AWS_IOT_JOBS_INVALID_JSON = 13, /** * @brief Jobs operation failed: The contents of the request were invalid. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result). */ AWS_IOT_JOBS_INVALID_REQUEST = 14, /** * @brief Jobs operation failed: An update attempted to change the job execution * to an invalid state. * * Functions that may return this value: * - @ref jobs_function_startnextsync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result) * following a call to @ref jobs_function_startnextasync or @ref jobs_function_updateasync. */ AWS_IOT_JOBS_INVALID_STATE = 15, /** * @brief Jobs operation failed: The specified job execution does not exist. * * * Functions that may return this value: * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result) * following a call to @ref jobs_function_describeasync or @ref jobs_function_updateasync. */ AWS_IOT_JOBS_NOT_FOUND = 16, /** * @brief Jobs operation failed: The Jobs service expected a version that did * not match what was in the request. * * * Functions that may return this value: * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result) * following a call to @ref jobs_function_updateasync. */ AWS_IOT_JOBS_VERSION_MISMATCH = 17, /** * @brief Jobs operation failed: The Jobs service encountered an internal error. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result). */ AWS_IOT_JOBS_INTERNAL_ERROR = 18, /** * @brief Jobs operation failed: The request was throttled. * * Functions that may return this value: * - @ref jobs_function_getpendingsync * - @ref jobs_function_startnextsync * - @ref jobs_function_describesync * - @ref jobs_function_updatesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result). */ AWS_IOT_JOBS_THROTTLED = 19, /** * @brief Jobs operation failed: Attempt to describe a Job in a terminal state. * * Functions that may return this value: * - @ref jobs_function_describesync * - @ref jobs_function_wait * * May also be the value of a Jobs operation completion callback's<br> * [AwsIotJobsCallbackParam_t.operation.result](@ref AwsIotJobsCallbackParam_t.result) * following a call to @ref jobs_function_describeasync. */ AWS_IOT_JOBS_TERMINAL_STATE = 20 } AwsIotJobsError_t; /** * @ingroup jobs_datatypes_enums * @brief Possible states of jobs. * * The function @ref jobs_function_statename can be used to get a state's * description. * * See [this page] * (https://docs.aws.amazon.com/iot/latest/apireference/API_iot-jobs-data_JobExecutionState.html) * for more information on Job states. */ typedef enum AwsIotJobState { /** * @brief A Job is queued and awaiting execution. */ AWS_IOT_JOB_STATE_QUEUED, /** * @brief A Job is currently executing. */ AWS_IOT_JOB_STATE_IN_PROGRESS, /** * @brief A Job has failed. This is a terminal state. */ AWS_IOT_JOB_STATE_FAILED, /** * @brief A Job has succeeded. This is a terminal state. */ AWS_IOT_JOB_STATE_SUCCEEDED, /** * @brief A Job was canceled. This is a terminal state. */ AWS_IOT_JOB_STATE_CANCELED, /** * @brief A Job's timer has expired. This is a terminal state. * * Jobs are considered timed out if they remain [IN_PROGRESS] * (@ref AWS_IOT_JOB_STATE_IN_PROGRESS) for more than their * `inProgressTimeoutInMinutes` property or a [Job update](@ref jobs_function_updateasync) * was not sent within [stepTimeoutInMinutes](@ref AwsIotJobsUpdateInfo_t.stepTimeoutInMinutes). */ AWS_IOT_JOB_STATE_TIMED_OUT, /** * @brief A Job was rejected by the device. This is a terminal state. */ AWS_IOT_JOB_STATE_REJECTED, /** * @brief A Job was removed. This is a terminal state. */ AWS_IOT_JOB_STATE_REMOVED } AwsIotJobState_t; /** * @ingroup jobs_datatypes_enums * @brief Types of Jobs library callbacks. * * One of these values will be placed in #AwsIotJobsCallbackParam_t.callbackType * to identify the reason for invoking a callback function. */ typedef enum AwsIotJobsCallbackType { AWS_IOT_JOBS_GET_PENDING_COMPLETE = 0, /**< Callback invoked because a [Jobs get pending](@ref jobs_function_getpendingasync) completed. */ AWS_IOT_JOBS_START_NEXT_COMPLETE = 1, /**< Callback invoked because a [Jobs start next](@ref jobs_function_startnextasync) completed. */ AWS_IOT_JOBS_DESCRIBE_COMPLETE = 2, /**< Callback invoked because a [Jobs describe](@ref jobs_function_describeasync) completed. */ AWS_IOT_JOBS_UPDATE_COMPLETE = 3, /**< Callback invoked because a [Jobs update](@ref jobs_function_updateasync) completed. */ AWS_IOT_JOBS_NOTIFY_PENDING_CALLBACK = 4, /**< Callback invoked for an incoming message on a [Jobs notify-pending](@ref jobs_function_setnotifypendingcallback) topic. */ AWS_IOT_JOBS_NOTIFY_NEXT_CALLBACK = 5 /**< Callback invoked for an incoming message on a [Jobs notify-next](@ref jobs_function_setnotifynextcallback) topic. */ } AwsIotJobsCallbackType_t; /*-------------------------- Jobs parameter structs -------------------------*/ /** * @paramstructs{jobs,Jobs library} */ /** * @ingroup jobs_datatypes_paramstructs * @brief Parameter to a Jobs callback function. * * @paramfor Jobs callback functions * * The Jobs library passes this struct to a callback function whenever a * Jobs operation completes or a message is received on a Jobs notify-pending * or notify-next topic. * * The valid members of this struct are different based on * #AwsIotJobsCallbackParam_t.callbackType. If the callback type is * #AWS_IOT_JOBS_GET_PENDING_COMPLETE, #AWS_IOT_JOBS_START_NEXT_COMPLETE, * #AWS_IOT_JOBS_DESCRIBE_COMPLETE, or #AWS_IOT_JOBS_UPDATE_COMPLETE, then * #AwsIotJobsCallbackParam_t.operation is valid. Otherwise, if the callback type * is #AWS_IOT_JOBS_NOTIFY_PENDING_CALLBACK or #AWS_IOT_JOBS_NOTIFY_NEXT_CALLBACK, * then #AwsIotJobsCallbackParam_t.callback is valid. * * @attention Any pointers in this callback parameter may be freed as soon as the * [callback function](@ref AwsIotJobsCallbackInfo_t.function) returns. Therefore, * data must be copied if it is needed after the callback function returns. * @attention The Jobs library may set strings that are not NULL-terminated. * * @see #AwsIotJobsCallbackInfo_t for the signature of a callback function. */ typedef struct AwsIotJobsCallbackParam { AwsIotJobsCallbackType_t callbackType; /**< @brief Reason for invoking the Jobs callback function to provide context. */ const char * pThingName; /**< @brief The Thing Name associated with this Jobs callback. */ size_t thingNameLength; /**< @brief Length of #AwsIotJobsCallbackParam_t.pThingName. */ IotMqttConnection_t mqttConnection; /**< @brief The MQTT connection associated with the Jobs callback. */ union { /* Valid for completed Jobs operations. */ struct { AwsIotJobsError_t result; /**< @brief Result of Jobs operation, e.g. succeeded or failed. */ AwsIotJobsOperation_t reference; /**< @brief Reference to the Jobs operation that completed. */ const char * pResponse; /**< @brief Response retrieved from the Jobs service. */ size_t responseLength; /**< @brief Length of retrieved response. */ } operation; /**< @brief Information on a completed Jobs operation. */ /* Valid for a message on a Jobs notify-pending or notify-next topic. */ struct { const char * pDocument; /**< @brief Job execution document received on callback. */ size_t documentLength; /**< @brief Length of job execution document. */ } callback; /**< @brief Jobs document from an incoming delta or updated topic. */ } u; /**< @brief Valid member depends on callback type. */ } AwsIotJobsCallbackParam_t; /** * @ingroup jobs_datatypes_paramstructs * @brief Information on a user-provided Jobs callback function. * * @paramfor @ref jobs_function_getpendingasync, @ref jobs_function_startnextasync, * @ref jobs_function_describeasync, @ref jobs_function_updateasync, * @ref jobs_function_setnotifypendingcallback, @ref jobs_function_setnotifynextcallback * * Provides a function to be invoked when a Jobs operation completes or when a * Jobs document is received on a callback topic (notify-pending or notify-next). * * @initializer{AwsIotJobsCallbackInfo_t,AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER} */ typedef struct AwsIotJobsCallbackInfo { void * pCallbackContext; /**< @brief The first parameter to pass to the callback function. */ /** * @brief User-provided callback function signature. * * @param[in] void* #AwsIotJobsCallbackInfo_t.pCallbackContext * @param[in] AwsIotJobsCallbackParam_t* Details on the outcome of the Jobs * operation or an incoming Job document. * * @see #AwsIotJobsCallbackParam_t for more information on the second parameter. */ void ( * function )( void *, AwsIotJobsCallbackParam_t * ); /** * @brief Callback function to replace when passed to @ref jobs_function_setnotifynextcallback * or @ref jobs_function_setnotifypendingcallback. * * This member is ignored by Jobs operation functions. * * The number of callbacks of each type that may be registered for each Thing * is limited by @ref AWS_IOT_JOBS_NOTIFY_CALLBACKS. If @ref AWS_IOT_JOBS_NOTIFY_CALLBACKS * is `2`, that means that a maximum of `2` NOTIFY PENDING and `2` NOTIFY NEXT callbacks * (`4` total callbacks) may be set. This member is used to replace an existing callback * with a new one. * * To add a new callback: * @code{c} * AwsIotJobsCallbackInfo_t callbackInfo = AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER; * * callbackInfo.function = _newCallback; * callbackInfo.oldFunction = NULL; * @endcode * * For example, if the function `_oldCallback()` is currently registered: * - To replace `_oldCallback()` with a new callback function `_newCallback()`: * @code{c} * AwsIotJobsCallbackInfo_t callbackInfo = AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER; * * callbackInfo.function = _newCallback; * callbackInfo.oldFunction = _oldCallback; * @endcode * - To remove `_oldCallback()`: * @code{c} * AwsIotJobsCallbackInfo_t callbackInfo = AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER; * * callbackInfo.function = NULL; * callbackInfo.oldFunction = _oldCallback; * @endcode */ void ( * oldFunction )( void *, AwsIotJobsCallbackParam_t * ); } AwsIotJobsCallbackInfo_t; /** * @ingroup jobs_datatypes_paramstructs * @brief Common information provided to Jobs requests. * * @paramfor @ref jobs_function_getpendingasync, @ref jobs_function_getpendingsync, * @ref jobs_function_startnextasync, @ref jobs_function_startnextsync * @ref jobs_function_describeasync, @ref jobs_function_describesync, * @ref jobs_function_updateasync, @ref jobs_function_updatesync * * @initializer{AwsIotJobsRequestInfo_t,AWS_IOT_JOBS_REQUEST_INFO_INITIALIZER} */ typedef struct AwsIotJobsRequestInfo { /** * @brief The MQTT connection to use for the Jobs request. */ IotMqttConnection_t mqttConnection; /* These members allow Jobs commands to be retried. Be careful that duplicate * commands do no cause unexpected application behavior. Use of QoS 0 is recommended. */ IotMqttQos_t qos; /**< @brief QoS when sending the Jobs command. See #IotMqttPublishInfo_t.qos. */ uint32_t retryLimit; /**< @brief Maximum number of retries for the Jobs command. See #IotMqttPublishInfo_t.retryLimit. */ uint32_t retryMs; /**< @brief First retry time for the Jobs command. See IotMqttPublishInfo_t.retryMs. */ /** * @brief Function to allocate memory for an incoming response. * * This only needs to be set if #AWS_IOT_JOBS_FLAG_WAITABLE is passed. */ void * ( *mallocResponse )( size_t ); /** * @brief The Thing Name associated with the Job. */ const char * pThingName; /** * @brief Length of #AwsIotJobsRequestInfo_t.pThingName. */ size_t thingNameLength; /** * @brief The Job ID to update. * * This may be set to #AWS_IOT_JOBS_NEXT_JOB to update the next pending Job. * When using #AWS_IOT_JOBS_NEXT_JOB, #AwsIotJobsRequestInfo_t.jobIdLength * should be set to #AWS_IOT_JOBS_NEXT_JOB_LENGTH. * * This parameter is ignored for calls to @ref jobs_function_getpendingasync, * @ref jobs_function_getpendingsync, @ref jobs_function_startnextasync, * and @ref jobs_function_startnextsync. */ const char * pJobId; /** * @brief Length of #AwsIotJobsRequestInfo_t.pJobId. * * This parameter is ignored for calls to @ref jobs_function_getpendingasync, * @ref jobs_function_getpendingsync, @ref jobs_function_startnextasync, * and @ref jobs_function_startnextsync. */ size_t jobIdLength; /** * @brief An arbitrary string that identifies this Job update to the Jobs * service. * * The recommended value is #AWS_IOT_JOBS_CLIENT_TOKEN_AUTOGENERATE. */ const char * pClientToken; /** * @brief Length of #AwsIotJobsRequestInfo_t.pClientToken. */ size_t clientTokenLength; } AwsIotJobsRequestInfo_t; /** * @ingroup jobs_datatypes_paramstructs * @brief Output parameter of blocking Jobs API functions. * * @paramfor @ref jobs_function_getpendingsync, @ref jobs_function_startnextsync, * @ref jobs_function_describesync, @ref jobs_function_updatesync, * @ref jobs_function_wait * * Provides the response received from the Jobs service. The buffer for the * response is allocated with #AwsIotJobsRequestInfo_t.mallocResponse. * * @initializer{AwsIotJobsResponse_t,AWS_IOT_JOBS_RESPONSE_INITIALIZER} */ typedef struct AwsIotJobsResponse { const char * pJobsResponse; /**< @brief JSON response received from the Jobs service. */ size_t jobsResponseLength; /**< @brief Length of #AwsIotJobsResponse_t.pJobsResponse. */ } AwsIotJobsResponse_t; /** * @ingroup jobs_datatypes_paramstructs * @brief Information on a Job update for @ref jobs_function_startnextasync and * @ref jobs_function_updateasync. These functions modify a Job's state. * * @paramfor @ref jobs_function_startnextasync, @ref jobs_function_startnextsync, * @ref jobs_function_updateasync, and @ref jobs_function_updatesync. * * @initializer{AwsIotJobsUpdateInfo_t,AWS_IOT_JOBS_UPDATE_INFO_INITIALIZER} */ typedef struct AwsIotJobsUpdateInfo { /** * @brief The new status to report as a Job execution update. * * Valid values are: * - #AWS_IOT_JOB_STATE_IN_PROGRESS * - #AWS_IOT_JOB_STATE_FAILED * - #AWS_IOT_JOB_STATE_SUCCEEDED * - #AWS_IOT_JOB_STATE_REJECTED * * This parameter is ignored for calls to @ref jobs_function_startnextasync and * @ref jobs_function_startnextsync. These functions always set the state * to #AWS_IOT_JOB_STATE_IN_PROGRESS. */ AwsIotJobState_t newStatus; /** * @brief The expected current version of job execution. * * Each time a Job update is sent (for the same `JobId`), the version stored * on the AWS IoT Jobs service is updated. If this value does not match the * value stored by the Jobs service, the Job update is rejected with the code * #AWS_IOT_JOBS_VERSION_MISMATCH. * * This value is useful for ensuring the order of Job updates, i.e. that the * Jobs service does not overwrite a later update with a previous one. If not * needed, it can be set to #AWS_IOT_JOBS_NO_VERSION. * * This parameter is ignored for calls to @ref jobs_function_startnextasync and * @ref jobs_function_startnextsync. */ uint32_t expectedVersion; /** * @brief An application-defined value that identifies a Job execution on a * specific device. * * The Jobs service provides commands for tracking the status of Job execution * on a specific target. Therefore, this value is used to provide a unique * identifier of a specific Job execution on a specific target. * * This value is optional. It may be set to #AWS_IOT_JOBS_NO_EXECUTION_NUMBER * if not needed. * * This parameter is ignored for calls to @ref jobs_function_startnextasync and * @ref jobs_function_startnextsync. */ int32_t executionNumber; /** * @brief The amount of time (in minutes) before a new Job update must be reported. * * If this timeout expires without a new Job update being reported (for the same * `jobId`), the Job's status is set to #AWS_IOT_JOB_STATE_TIMED_OUT. Sending a * new Job update will reset this step timeout; a value of #AWS_IOT_JOBS_NO_TIMEOUT * will clear any previous step timeout. * * Valid values are between 1 and 10,080 (7 days). This value is optional. It may * be set to #AWS_IOT_JOBS_NO_TIMEOUT if not needed. */ int32_t stepTimeoutInMinutes; /** * @brief Whether the Job response document should contain the `JobExecutionState`. * * The default value is `false`. * * This parameter is ignored for calls to @ref jobs_function_startnextasync and * @ref jobs_function_startnextsync. */ bool includeJobExecutionState; /** * @brief Whether the Job response document should contain the `JobDocument`. * * The default value is `false`. * * This parameter is ignored for calls to @ref jobs_function_startnextasync and * @ref jobs_function_startnextsync. */ bool includeJobDocument; /** * @brief An application-defined set of JSON name-value pairs that describe * the status of Job execution. * * This value is optional. It may be set to #AWS_IOT_JOBS_NO_STATUS_DETAILS * if not needed. */ const char * pStatusDetails; /** * @brief Length of #AwsIotJobsUpdateInfo_t.pStatusDetails. */ size_t statusDetailsLength; } AwsIotJobsUpdateInfo_t; /*------------------------- Jobs defined constants --------------------------*/ /** * @brief Set #AwsIotJobsRequestInfo_t.pJobId to this value to use the next pending * Job as the Job ID. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_NEXT_JOB ( "$next" ) /** * @brief Length of #AWS_IOT_JOBS_NEXT_JOB. * * Set #AwsIotJobsRequestInfo_t.jobIdLength to this value when using * #AWS_IOT_JOBS_NEXT_JOB. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_NEXT_JOB_LENGTH ( sizeof( AWS_IOT_JOBS_NEXT_JOB ) - 1 ) /** * @brief Set #AwsIotJobsRequestInfo_t.pClientToken to this value to automatically * generate a client token for the Jobs request. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_CLIENT_TOKEN_AUTOGENERATE ( NULL ) /** * @brief Set #AwsIotJobsUpdateInfo_t.expectedVersion to this value to omit the * version in the Jobs request. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_NO_VERSION ( 0 ) /** * @brief Set #AwsIotJobsUpdateInfo_t.executionNumber to this value or pass it to * @ref jobs_function_describeasync to omit the execution number in the Jobs request. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_NO_EXECUTION_NUMBER ( -1 ) /** * @brief Set #AwsIotJobsUpdateInfo_t.stepTimeoutInMinutes to this value to omit the * step timeout in the Jobs request. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_NO_TIMEOUT ( 0 ) /** * @brief Set #AwsIotJobsUpdateInfo_t.stepTimeoutInMinutes to this value to cancel * any previously set step timeout. * * The Jobs service will return an (InvalidRequest)[@ref AWS_IOT_JOBS_INVALID_REQUEST] * error if this value is used without an existing step timeout. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_CANCEL_TIMEOUT ( -1 ) /** * @brief Set #AwsIotJobsUpdateInfo_t.pStatusDetails to this value to omit the * status details in the Jobs request. * * @note The value of this constant may change at any time in future versions, but * its name will remain the same. */ #define AWS_IOT_JOBS_NO_STATUS_DETAILS ( NULL ) /** * @constantspage{jobs,Jobs library} * * @section jobs_constants_initializers Jobs Initializers * @brief Provides default values for the data types of the Jobs library. * * @snippet this define_jobs_initializers * * All user-facing data types of the Jobs library should be initialized * using one of the following. * * @warning Failing to initialize a Jobs data type with the appropriate * initializer may result in undefined behavior! * @note The initializers may change at any time in future versions, but their * names will remain the same. * * <b>Example</b> * @code{c} * AwsIotJobsCallbackInfo_t callbackInfo = AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER; * AwsIotJobsRequestInfo_t requestInfo = AWS_IOT_JOBS_REQUEST_INFO_INITIALIZER; * AwsIotJobsUpdateInfo_t updateInfo = AWS_IOT_JOBS_UPDATE_INFO_INITIALIZER; * AwsIotJobsOperation_t operation = AWS_IOT_JOBS_OPERATION_INITIALIZER; * AwsIotJobsResponse_t response = AWS_IOT_JOBS_RESPONSE_INITIALIZER; * @endcode * * @section jobs_constants_flags Jobs Function Flags * @brief Flags that modify the behavior of Jobs library functions. * * Flags should be bitwise-ORed with each other to change the behavior of * Jobs library functions. * * The following flags are valid for the Jobs operation functions: * @ref jobs_function_getpendingasync, @ref jobs_function_startnextasync, * @ref jobs_function_describeasync, @ref jobs_function_updateasync, * and their blocking versions. * - #AWS_IOT_JOBS_FLAG_WAITABLE <br> * @copybrief AWS_IOT_JOBS_FLAG_WAITABLE * - #AWS_IOT_JOBS_FLAG_KEEP_SUBSCRIPTIONS <br> * @copybrief AWS_IOT_JOBS_FLAG_KEEP_SUBSCRIPTIONS * * The following flags are valid for @ref jobs_function_removepersistentsubscriptions. * These flags are not valid for the Jobs operation functions. * - #AWS_IOT_JOBS_FLAG_REMOVE_GET_PENDING_SUBSCRIPTIONS <br> * @copybrief AWS_IOT_JOBS_FLAG_REMOVE_GET_PENDING_SUBSCRIPTIONS * - #AWS_IOT_JOBS_FLAG_REMOVE_START_NEXT_SUBSCRIPTIONS <br> * @copybrief AWS_IOT_JOBS_FLAG_REMOVE_START_NEXT_SUBSCRIPTIONS * - #AWS_IOT_JOBS_FLAG_REMOVE_DESCRIBE_SUBSCRIPTIONS <br> * @copybrief AWS_IOT_JOBS_FLAG_REMOVE_DESCRIBE_SUBSCRIPTIONS * - #AWS_IOT_JOBS_FLAG_REMOVE_UPDATE_SUBSCRIPTIONS <br> * @copybrief AWS_IOT_JOBS_FLAG_REMOVE_UPDATE_SUBSCRIPTIONS * * @note The values of the flags may change at any time in future versions, but * their names will remain the same. Additionally, flags which may be used at * the same time will be bitwise-exclusive of each other. */ /* @[define_jobs_initializers] */ #define AWS_IOT_JOBS_CALLBACK_INFO_INITIALIZER { 0 } /**< @brief Initializer for #AwsIotJobsCallbackInfo_t. */ /** @brief Initializer for #AwsIotJobsRequestInfo_t. */ #define AWS_IOT_JOBS_REQUEST_INFO_INITIALIZER \ { .pClientToken = AWS_IOT_JOBS_CLIENT_TOKEN_AUTOGENERATE } /** @brief Initializer for #AwsIotJobsUpdateInfo_t. */ #define AWS_IOT_JOBS_UPDATE_INFO_INITIALIZER \ { .newStatus = AWS_IOT_JOB_STATE_IN_PROGRESS, \ .expectedVersion = AWS_IOT_JOBS_NO_VERSION, \ .executionNumber = AWS_IOT_JOBS_NO_EXECUTION_NUMBER, \ .stepTimeoutInMinutes = AWS_IOT_JOBS_NO_TIMEOUT, \ .includeJobExecutionState = false, \ .includeJobDocument = false, \ .pStatusDetails = AWS_IOT_JOBS_NO_STATUS_DETAILS } #define AWS_IOT_JOBS_OPERATION_INITIALIZER NULL /**< @brief Initializer for #AwsIotJobsOperation_t. */ #define AWS_IOT_JOBS_RESPONSE_INITIALIZER { 0 } /**< @brief Initializer for #AwsIotJobsResponse_t. */ /* @[define_jobs_initializers] */ /** * @brief Allows the use of @ref jobs_function_wait for blocking until completion. * * This flag is only valid if passed to the functions @ref jobs_function_getpendingasync, * @ref jobs_function_startnextasync, @ref jobs_function_describeasync, or @ref jobs_function_updateasync. * * An #AwsIotJobsOperation_t <b>MUST</b> be provided if this flag is set. * Additionally, an #AwsIotJobsCallbackInfo_t <b>MUST NOT</b> be provided. * * When this flag is set, #AwsIotJobsRequestInfo_t.mallocResponse must be set * to a function that can be used to allocate memory to hold an incoming response. * * @note If this flag is set, @ref jobs_function_wait <b>MUST</b> be called to * clean up resources. */ #define AWS_IOT_JOBS_FLAG_WAITABLE ( 0x00000001 ) /** * @brief Maintain the subscriptions for the Jobs operation topics, even after * this function returns. * * This flag is only valid if passed to the functions @ref jobs_function_getpendingasync, * @ref jobs_function_startnextasync, @ref jobs_function_describeasync, or @ref jobs_function_updateasync, * and their blocking versions. * * The Jobs service reports results of Jobs operations by publishing * messages to MQTT topics. By default, the Job operation functions subscribe to the * necessary topics, wait for the Jobs service to publish the result of the * Jobs operation, then unsubscribe from those topics. This workflow is suitable * for infrequent Jobs operations, but is inefficient for frequent, periodic * Jobs operations (where subscriptions for the Jobs operation topics would be * constantly added and removed). * * This flag causes the Jobs operation functions to maintain Jobs operation * topic subscriptions, even after the function returns. These subscriptions * may then be used by a future call to the same function. * * This flags only needs to be set once, after which subscriptions are maintained * and reused for a specific Thing Name and Jobs function. The function @ref * jobs_function_removepersistentsubscriptions may be used to remove * subscriptions maintained by this flag. */ #define AWS_IOT_JOBS_FLAG_KEEP_SUBSCRIPTIONS ( 0x00000002 ) /** * @brief Remove the persistent subscriptions from a Jobs get pending operation. * * This flag is only valid if passed to the function @ref * jobs_function_removepersistentsubscriptions. * * This flag may be passed to @ref jobs_function_removepersistentsubscriptions * to remove any subscriptions for a specific Thing Name maintained by a previous * call to @ref jobs_function_getpendingasync or @ref jobs_function_getpendingsync. * * @warning Do not call @ref jobs_function_removepersistentsubscriptions with * this flag for Thing Names with any in-progress Jobs get pending operations. */ #define AWS_IOT_JOBS_FLAG_REMOVE_GET_PENDING_SUBSCRIPTIONS ( 0x00000001 ) /** * @brief Remove the persistent subscriptions from a Jobs start next operation. * * This flag is only valid if passed to the function @ref * jobs_function_removepersistentsubscriptions. * * This flag may be passed to @ref jobs_function_removepersistentsubscriptions * to remove any subscriptions for a specific Thing Name maintained by a previous * call to @ref jobs_function_startnextasync or @ref jobs_function_startnextsync. * * @warning Do not call @ref jobs_function_removepersistentsubscriptions with * this flag for Thing Names with any in-progress Jobs start next operations. */ #define AWS_IOT_JOBS_FLAG_REMOVE_START_NEXT_SUBSCRIPTIONS ( 0x00000002 ) /** * @brief Remove the persistent subscriptions from a Jobs describe operation. * * This flag is only valid if passed to the function @ref * jobs_function_removepersistentsubscriptions. * * This flag may be passed to @ref jobs_function_removepersistentsubscriptions * to remove any subscriptions for a specific Thing Name maintained by a previous * call to @ref jobs_function_describeasync or @ref jobs_function_describesync. * * @warning Do not call @ref jobs_function_removepersistentsubscriptions with * this flag for Thing Names with any in-progress Jobs describe operations. */ #define AWS_IOT_JOBS_FLAG_REMOVE_DESCRIBE_SUBSCRIPTIONS ( 0x00000004 ) /** * @brief Remove the persistent subscriptions from a Jobs update operation. * * This flag is only valid if passed to the function @ref * jobs_function_removepersistentsubscriptions. * * This flag may be passed to @ref jobs_function_removepersistentsubscriptions * to remove any subscriptions for a specific Thing Name maintained by a previous * call to @ref jobs_function_updateasync or @ref jobs_function_updatesync. * * @warning Do not call @ref jobs_function_removepersistentsubscriptions with * this flag for Thing Names with any in-progress Jobs update operations. */ #define AWS_IOT_JOBS_FLAG_REMOVE_UPDATE_SUBSCRIPTIONS ( 0x00000008 ) #endif /* ifndef AWS_IOT_JOBS_TYPES_H_ */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-IoT-Libraries/abstractions/platform/freertos/include/iot_taskpool_freertos.h
/* * IoT Common V1.0.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file iot_taskpool.h * @brief User-facing functions of the task pool library. */ #ifndef IOT_TASKPOOL_H_ #define IOT_TASKPOOL_H_ /* The config header is always included first. */ #include "iot_config.h" /* Standard includes. */ #include <stdbool.h> #include <stdint.h> #include <stddef.h> /* Task pool types. */ #include "types/iot_taskpool_types_freertos.h" /*------------------------- Task Pool library functions --------------------------*/ /** * @functionspage{taskpool,task pool library} * - @functionname{taskpool_function_createsystemtaskpool} * - @functionname{taskpool_function_createjob} * - @functionname{taskpool_function_schedule} * - @functionname{taskpool_function_scheduledeferred} * - @functionname{taskpool_function_getstatus} * - @functionname{taskpool_function_trycancel} * - @functionname{taskpool_function_getjobstoragefromhandle} * - @functionname{taskpool_function_strerror} */ /** * @functionpage{IotTaskPool_CreateSystemTaskPool,taskpool,createsystemtaskpool} * @functionpage{IotTaskPool_CreateJob,taskpool,createjob} * @functionpage{IotTaskPool_Schedule,taskpool,schedule} * @functionpage{IotTaskPool_ScheduleDeferred,taskpool,scheduledeferred} * @functionpage{IotTaskPool_GetStatus,taskpool,getstatus} * @functionpage{IotTaskPool_TryCancel,taskpool,trycancel} * @functionpage{IotTaskPool_GetJobStorageFromHandle,taskpool,getjobstoragefromhandle} * @functionpage{IotTaskPool_strerror,taskpool,strerror} */ /** * @brief Creates the one single instance of the system task pool. * * This function should be called once by the application to initialize the one single instance of the system task pool. * An application should initialize the system task pool early in the boot sequence, before initializing any other library * (e.g. MQTT) that uses the system task pool. An application should also initialize the system * task pool before posting any jobs. Early initialization is typically easy to accomplish by creating the system task pool * before the scheduler is started. * * The shortcut @ref IOT_SYSTEM_TASKPOOL contains the system task pool handle. * * @param[in] pInfo A pointer to the task pool initialization data. * * @return One of the following: * - #IOT_TASKPOOL_SUCCESS * - #IOT_TASKPOOL_BAD_PARAMETER * - #IOT_TASKPOOL_NO_MEMORY * * @warning This function should be called only once. Calling this function more that once will result in * undefined behavior. * */ /* @[declare_taskpool_createsystemtaskpool] */ IotTaskPoolError_t IotTaskPool_CreateSystemTaskPool( const IotTaskPoolInfo_t * const pInfo ); /* @[declare_taskpool_createsystemtaskpool] */ /** * @brief Creates a job for the task pool around a user-provided storage. * * @param[in] userCallback A user-specified callback for the job. * @param[in] pUserContext A user-specified context for the callback. * @param[in,out] pJobStorage The storage for the job data structure. * @param[out] pJob A pointer to an instance of @ref IotTaskPoolJob_t that will be initialized when this * function returns successfully. This handle can be used to inspect the job status with * @ref IotTaskPool_GetStatus or cancel the job with @ref IotTaskPool_TryCancel, etc.... * * @return One of the following: * - #IOT_TASKPOOL_SUCCESS * - #IOT_TASKPOOL_BAD_PARAMETER * * */ /* @[declare_taskpool_createjob] */ IotTaskPoolError_t IotTaskPool_CreateJob( IotTaskPoolRoutine_t userCallback, void * pUserContext, IotTaskPoolJobStorage_t * const pJobStorage, IotTaskPoolJob_t * const pJob ); /* @[declare_taskpool_createjob] */ /** * @brief This function schedules a job created with @ref IotTaskPool_CreateJob against the task pool pointed to by `taskPool`. * * @param[in] taskPool A handle to an initialized taskpool. * @param[in] job A job to schedule for execution. This must be first initialized with a call to @ref IotTaskPool_CreateJob. * @param[in] flags Flags to be passed by the user, e.g. to identify the job as high priority by specifying #IOT_TASKPOOL_JOB_HIGH_PRIORITY. * * @return One of the following: * - #IOT_TASKPOOL_SUCCESS * - #IOT_TASKPOOL_BAD_PARAMETER * - #IOT_TASKPOOL_ILLEGAL_OPERATION * - #IOT_TASKPOOL_NO_MEMORY * - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS * * @note This function will not allocate memory, so it is guaranteed to succeed if the parameters are correct and the task pool * was correctly initialized, and not yet destroyed. * * <b>Example</b> * @code{c} * // An example of a user context to pass to a callback through a task pool thread. * typedef struct JobUserContext * { * uint32_t counter; * } JobUserContext_t; * * // An example of a user callback to invoke through a task pool thread. * static void ExecutionCb( IotTaskPool_t taskPool, IotTaskPoolJob_t job, void * context ) * { * ( void )taskPool; * ( void )job; * * JobUserContext_t * pUserContext = ( JobUserContext_t * )context; * * pUserContext->counter++; * } * * void TaskPoolExample( ) * { * JobUserContext_t userContext = { 0 }; * IotTaskPoolJob_t job; * IotTaskPool_t taskPool; * * // Configure the task pool to hold one thread. * // Provide proper stack size and priority per the application needs. * * const IotTaskPoolInfo_t tpInfo = { .minThreads = 1, .maxThreads = 1, .stackSize = 512, .priority = 0 }; * * // Create a task pool. * IotTaskPool_Create( &tpInfo, &taskPool ); * * // Statically allocate one job, schedule it. * IotTaskPool_CreateJob( &ExecutionCb, &userContext, &job ); * * IotTaskPoolError_t errorSchedule = IotTaskPool_Schedule( taskPool, &job, 0 ); * * switch ( errorSchedule ) * { * case IOT_TASKPOOL_SUCCESS: * break; * case IOT_TASKPOOL_BAD_PARAMETER: // Invalid parameters, such as a NULL handle, can trigger this error. * case IOT_TASKPOOL_ILLEGAL_OPERATION: // Scheduling a job that was previously scheduled or destroyed could trigger this error. * case IOT_TASKPOOL_NO_MEMORY: // Scheduling a with flag #IOT_TASKPOOL_JOB_HIGH_PRIORITY could trigger this error. * case IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS: // Scheduling a job after trying to destroy the task pool could trigger this error. * // ASSERT * break; * default: * // ASSERT * } * * // * // ... Perform other operations ... * // * * IotTaskPool_Destroy( taskPool ); * } * @endcode */ /* @[declare_taskpool_schedule] */ IotTaskPoolError_t IotTaskPool_Schedule( IotTaskPool_t taskPool, IotTaskPoolJob_t job, uint32_t flags ); /* @[declare_taskpool_schedule] */ /** * @brief This function schedules a job created with @ref IotTaskPool_CreateJob to be executed after a user-defined time interval. * * @param[in] taskPool A handle to an initialized taskpool. * @param[in] job A job to schedule for execution. This must be first initialized with a call to @ref IotTaskPool_CreateJob. * @param[in] timeMs The time in milliseconds to wait before scheduling the job. * * @return One of the following: * - #IOT_TASKPOOL_SUCCESS * - #IOT_TASKPOOL_BAD_PARAMETER * - #IOT_TASKPOOL_ILLEGAL_OPERATION * - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS * * * @note This function will not allocate memory. * * @warning The `taskPool` used in this function should be the same * used to create the job pointed to by `job`, or the results will be undefined. * */ /* @[declare_taskpool_scheduledeferred] */ IotTaskPoolError_t IotTaskPool_ScheduleDeferred( IotTaskPool_t taskPool, IotTaskPoolJob_t job, uint32_t timeMs ); /* @[declare_taskpool_scheduledeferred] */ /** * @brief This function retrieves the current status of a job. * * @param[in] taskPool A handle to an initialized taskpool. * @param[in] job The job to cancel. * @param[out] pStatus The status of the job at the time of cancellation. * * @return One of the following: * - #IOT_TASKPOOL_SUCCESS * - #IOT_TASKPOOL_BAD_PARAMETER * - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS * * @warning This function is not thread safe and the job status returned in `pStatus` may be invalid by the time * the calling thread has a chance to inspect it. */ /* @[declare_taskpool_getstatus] */ IotTaskPoolError_t IotTaskPool_GetStatus( IotTaskPool_t taskPool, IotTaskPoolJob_t job, IotTaskPoolJobStatus_t * const pStatus ); /* @[declare_taskpool_getstatus] */ /** * @brief This function tries to cancel a job that was previously scheduled with @ref IotTaskPool_Schedule. * * A job can be canceled only if it is not yet executing, i.e. if its status is * @ref IOT_TASKPOOL_STATUS_READY or @ref IOT_TASKPOOL_STATUS_SCHEDULED. Calling * @ref IotTaskPool_TryCancel on a job whose status is @ref IOT_TASKPOOL_STATUS_COMPLETED, * or #IOT_TASKPOOL_STATUS_CANCELED will yield a #IOT_TASKPOOL_CANCEL_FAILED return result. * * @param[in] taskPool A handle to an initialized taskpool. * @param[in] job The job to cancel. * @param[out] pStatus The status of the job at the time of cancellation. * * @return One of the following: * - #IOT_TASKPOOL_SUCCESS * - #IOT_TASKPOOL_BAD_PARAMETER * - #IOT_TASKPOOL_SHUTDOWN_IN_PROGRESS * - #IOT_TASKPOOL_CANCEL_FAILED * * @warning The `taskPool` used in this function should be the same * used to create the job pointed to by `job`, or the results will be undefined. * */ /* @[declare_taskpool_trycancel] */ IotTaskPoolError_t IotTaskPool_TryCancel( IotTaskPool_t taskPool, IotTaskPoolJob_t job, IotTaskPoolJobStatus_t * const pStatus ); /* @[declare_taskpool_trycancel] */ /** * @brief Returns a pointer to the job storage from an instance of a job handle * of type @ref IotTaskPoolJob_t. This function is guaranteed to succeed for a * valid job handle. * * @param[in] job The job handle. * * @return A pointer to the storage associated with the job handle `job`. * * @warning If the `job` handle used is invalid, the results will be undefined. */ /* @[declare_taskpool_getjobstoragefromhandle] */ IotTaskPoolJobStorage_t * IotTaskPool_GetJobStorageFromHandle( IotTaskPoolJob_t job ); /* @[declare_taskpool_getjobstoragefromhandle] */ /** * @brief Returns a string that describes an @ref IotTaskPoolError_t. * * Like the POSIX's `strerror`, this function returns a string describing a * return code. In this case, the return code is a task pool library error code, * `status`. * * The string returned by this function <b>MUST</b> be treated as read-only: any * attempt to modify its contents may result in a crash. Therefore, this function * is limited to usage in logging. * * @param[in] status The status to describe. * * @return A read-only string that describes `status`. * * @warning The string returned by this function must never be modified. */ /* @[declare_taskpool_strerror] */ const char * IotTaskPool_strerror( IotTaskPoolError_t status ); /* @[declare_taskpool_strerror] */ #endif /* ifndef IOT_TASKPOOL_H_ */