9 #include<jsoncpp/json/json.h>
25 #include<openssl/sha.h>
29 #include<sys/socket.h>
31 #include<openssl/bio.h>
32 #include<openssl/evp.h>
33 #include<openssl/buffer.h>
38 #include<condition_variable>
40 #include<unordered_map>
41 #include <openssl/ssl.h>
42 #include <openssl/err.h>
43 #include<openssl/crypto.h>
52 #include <sys/eventfd.h>
53 #include <sys/timerfd.h>
83 static bool createDir(
const std::string & ddir,
const mode_t &mode=0775);
92 static bool copy(
const std::string &sourceFile,
const std::string &objectFile);
101 static bool createFile(
const std::string &filePath,
const mode_t &mode=0666);
146 static std::mutex
l1;
147 static std::unordered_map<std::string,FileThreadLock>
fl2;
156 std::vector<std::string> data;
157 std::vector<std::string> backUp;
158 char *data_binary=
nullptr;
159 char *backUp_binary=
nullptr;
163 size_t multiple_backup=0;
168 std::string fileName;
170 std::string fileNameTemp;
175 uint64_t totalLines=0;
220 bool openFile(
const std::string &fileName,
const bool &create=
true,
const int &multiple=0,
const size_t &size=0,
const mode_t &mode=0666);
303 int findC(
const std::string &targetString,
const int linePos=1);
313 bool appendLineC(
const std::string &data,
const int &linePos=0);
339 bool chgLineC(
const std::string &data,
const int &linePos=0);
349 bool readLineC(std::string &data,
const int linePos);
359 std::string&
readC(std::string &data,
const int &linePos,
const int &num);
366 std::string&
readAllC(std::string &data);
382 bool readC(
char *data,
const size_t &pos,
const size_t &size);
393 bool writeC(
const char *data,
const size_t &pos,
const size_t &size);
414 int find(
const std::string &targetString,
const int linePos=1);
424 bool appendLine(
const std::string &data,
const int &linePos=0);
450 bool chgLine(
const std::string &data,
const int &linePos=0);
460 bool readLine(std::string &data,
const int linePos);
470 std::string&
read(std::string &data,
const int &linePos,
const int &num);
477 std::string&
readAll(std::string &data);
493 bool read(
char *data,
const size_t &pos,
const size_t &size);
504 bool write(
const char *data,
const size_t &pos,
const size_t &size);
561 total =
day * 24 * 60 * 60 * 1000 +
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
563 totalB = b.
day * 24 * 60 * 60 * 1000 + b.
hour * 60 * 60 * 1000 + b.
min * 60 * 1000 + b.
sec * 1000 + b.
msec;
577 total =
day * 24 * 60 * 60 * 1000 +
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
579 totalB = b.
day * 24 * 60 * 60 * 1000 + b.
hour * 60 * 60 * 1000 + b.
min * 60 * 1000 + b.
sec * 1000 + b.
msec;
593 total =
day * 24 * 60 * 60 * 1000 +
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
595 totalB = b.
day * 24 * 60 * 60 * 1000 + b.
hour * 60 * 60 * 1000 + b.
min * 60 * 1000 + b.
sec * 1000 + b.
msec;
609 total =
day * 24 * 60 * 60 * 1000 +
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
611 totalB = b.
day * 24 * 60 * 60 * 1000 + b.
hour * 60 * 60 * 1000 + b.
min * 60 * 1000 + b.
sec * 1000 + b.
msec;
625 total =
day * 24 * 60 * 60 * 1000 +
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
627 totalB = b.
day * 24 * 60 * 60 * 1000 + b.
hour * 60 * 60 * 1000 + b.
min * 60 * 1000 + b.
sec * 1000 + b.
msec;
640 long long dayy =
day;
652 if (msecc / 1000 != 0)
654 secc += msecc / 1000;
655 msecc = msecc % 1000;
684 long long dayy =
day;
690 msecc = dayy * 24 * 60 * 60 * 1000 + hourr * 60 * 60 * 1000 + minn * 60 * 1000 + secc * 1000 + msecc - b.
day * 24 * 60 * 60 * 1000 - b.
hour * 60 * 60 * 1000 - b.
min * 60 * 1000 - b.
sec * 1000 - b.
msec;
696 if (msecc / 1000 != 0)
698 secc += msecc / 1000;
699 msecc = msecc % 1000;
728 total =
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
729 double k =
day + total / 86400000.0000;
739 double k =
day * 24 +
hour + total / 36000000.0000;
749 double k =
day * 24 * 60 +
hour * 60 +
min + total / 60000.0000;
759 double k =
day * 24 * 60 * 60 +
hour * 60 * 60 +
min * 60 +
sec + total / 1000.0000;
768 total =
day * 24 * 60 * 60 * 1000 +
hour * 60 * 60 * 1000 +
min * 60 * 1000 +
sec * 1000 +
msec;
784 if (
msec / 1000 != 0)
823 std::ostream&
operator<<(std::ostream &os,
const Duration &a);
826 using Seconds = std::chrono::duration<uint64_t>;
830 #define ISO8086A "yyyy-mm-ddThh:mi:ss"
834 #define ISO8086B "yyyy-mm-ddThh:mi:ss.sss"
848 static std::string &toPGtimeFormat();
849 static std::chrono::system_clock::time_point strToTimePoint(
const std::string &timeStr,
const std::string &format =
ISO8086A);
850 static std::string& timePointToStr(
const std::chrono::system_clock::time_point &tp, std::string &timeStr,
const std::string &format =
ISO8086A);
859 static std::string&
getTime(std::string &timeStr,
const std::string &format =
ISO8086A);
868 static bool convertFormat(std::string &timeStr,
const std::string &oldFormat,
const std::string &newFormat =
ISO8086A);
889 static std::string&
calculateTime(
const std::string &time1,
const Duration &time2, std::string &result,
const std::string &am,
const std::string &format1 =
ISO8086A,
const std::string &format2 =
ISO8086A);
899 static bool compareTime(
const std::string &time1,
const std::string &time2,
const std::string &format1 =
ISO8086A,
const std::string &format2 =
ISO8086A);
903 std::chrono::steady_clock::time_point start;
904 std::chrono::steady_clock::time_point end;
944 std::string timeFormat;
945 std::string contentFormat;
946 std::atomic<bool> consumerGuard{
true};
947 std::mutex queueMutex;
948 std::condition_variable queueCV;
949 std::queue<std::string> logQueue;
950 std::thread consumerThread;
965 bool openFile(
const std::string &fileName,
const std::string &timeFormat =
ISO8086A,
const std::string &contentFormat =
" ");
986 void writeLog(
const std::string &data);
999 bool deleteLogByTime(
const std::string &date1 =
"1",
const std::string &date2 =
"2");
1029 static bool encryptSymmetric(
const unsigned char *before,
const size_t &length,
const unsigned char *passwd,
const unsigned char *iv,
unsigned char *after);
1040 static bool decryptSymmetric(
const unsigned char *before,
const size_t &length,
const unsigned char *passwd,
const unsigned char *iv,
unsigned char *after);
1053 static std::string&
sha1(
const std::string &ori_str, std::string &result);
1066 static std::string&
sha11(
const std::string &ori_str, std::string &result);
1081 static std::string&
bitOutput(
char input, std::string &result);
1089 static std::string&
bitOutput(
const std::string &input, std::string &result);
1098 static char&
bitOutput_bit(
char input,
const int pos,
char &result);
1106 static unsigned long&
bitStrToNumber(
const std::string &input,
unsigned long &result);
1116 static unsigned long&
bitToNumber(
const std::string &input,
unsigned long &result);
1124 static char&
toBit(
const std::string &input,
char &result);
1132 static std::string&
toBit(
const std::string &input, std::string &result);
1205 static std::string&
getPreciesFloat(
const float &number,
const int &bit, std::string &str);
1222 static std::string&
getPreciesDouble(
const double &number,
const int &bit, std::string &str);
1267 static size_t get_split_str(
const std::string_view& ori_str, std::string_view &str,
const std::string_view &a,
const std::string_view &b,
const size_t &pos = 0);
1278 static std::string_view&
get_value_str(
const std::string_view& ori_str, std::string_view &str,
const std::string& name);
1287 static std::string_view&
get_value_header(
const std::string_view& ori_str, std::string_view &str,
const std::string& name);
1297 static std::string_view&
get_location_str(
const std::string_view& ori_str, std::string_view &str);
1307 static std::string_view&
getLocPara(
const std::string_view &url, std::string_view &locPara);
1316 static std::string_view&
getPara(
const std::string_view &url, std::string_view ¶);
1336 static size_t get_split_str(
const std::string_view& ori_str, std::string &str,
const std::string_view &a,
const std::string_view &b,
const size_t &pos = 0);
1347 static std::string&
get_value_str(
const std::string& ori_str, std::string &str,
const std::string& name);
1356 static std::string&
get_value_header(
const std::string& ori_str, std::string &str,
const std::string& name);
1366 static std::string&
get_location_str(
const std::string& ori_str, std::string &str);
1376 static std::string&
getLocPara(
const std::string &url, std::string &locPara);
1385 static std::string&
getPara(
const std::string &url, std::string ¶);
1396 static std::string&
getIP(
const std::string &url, std::string &IP);
1407 static int&
getPort(
const std::string &url,
int &port);
1417 static std::string
createHeader(
const std::string& first,
const std::string& second);
1438 template<
class... Args>
1439 static std::string
createHeader(
const std::string& first,
const std::string& second, Args... args)
1441 std::string cf = first +
": " + second +
"\r\n" +
createHeader(args...);
1478 static int&
toInt(
const std::string_view&ori_str,
int &result,
const int &i = -1);
1485 static int&
str16toInt(
const std::string_view&ori_str,
int &result,
const int &i=-1);
1494 static long&
toLong(
const std::string_view&ori_str,
long &result,
const long &i = -1);
1503 static float&
toFloat(
const std::string&ori_str,
float &result,
const float &i = -1);
1512 static double&
toDouble(
const std::string&ori_str,
double &result,
const double &i = -1);
1520 static bool&
toBool(
const std::string_view&ori_str,
bool &result);
1531 static std::string&
strto16(
const std::string &ori_str, std::string &result);
1593 static std::string&
maskCalculate(std::string &data,
const std::string &mask);
1613 static int getValue(
const std::string &oriStr,std::string& result,
const std::string &type=
"value",
const std::string &name=
"a",
const int &num=0);
1620 static std::string
toString(
const Json::Value &val);
1626 static Json::Value
toJsonArray(
const std::string & str);
1636 template<
class T1,
class T2>
1641 if constexpr (std::is_integral_v<T2>) {
1642 root[first] = Json::Value(static_cast<Json::Int64>(second));
1644 root[first] = second;
1646 Json::StreamWriterBuilder builder;
1647 std::string jsonString = Json::writeString(builder, root);
1661 template<
class T1,
class T2,
class... Args>
1666 if constexpr (std::is_integral_v<T2>) {
1667 root[first] = Json::Value(static_cast<Json::Int64>(second));
1669 root[first] = second;
1672 Json::StreamWriterBuilder builder;
1673 std::string jsonString = Json::writeString(builder, root);
1674 jsonString = jsonString.erase(jsonString.length() - 2);
1676 return jsonString +
"," + kk;
1689 Json::Value root(Json::arrayValue);
1691 Json::StreamWriterBuilder builder;
1692 std::string jsonString = Json::writeString(builder, root);
1704 template<
class T,
class... Args>
1707 Json::Value root(Json::arrayValue);
1710 Json::StreamWriterBuilder builder;
1711 std::string jsonString = Json::writeString(builder, root);
1712 jsonString = jsonString.erase(jsonString.length() - 2);
1714 return jsonString +
"," + kk;
1723 static std::string
jsonAdd(
const std::string &a,
const std::string &b);
1730 static std::string&
jsonFormatify(
const std::string &a, std::string &b);
1737 static std::string&
jsonToUTF8(
const std::string &input, std::string &output);
1844 std::deque<std::chrono::steady_clock::time_point>
history;
1903 std::unordered_map<int, ConnectionState>
conns;
2024 : maxConnections(maxConn), connectionTimeout(idleTimeout) {}
2068 void setPathLimit(
const std::string &path,
const int ×,
const int &secs);
2089 const int ×,
const int &secs);
2106 const std::string_view &path,
2107 const int ×,
const int &secs);
2121 void clearIP(
const std::string &ip,
const int &fd);
2141 const int ×,
const int &secs,
2142 const std::chrono::steady_clock::time_point &now);
2146 int connectionTimeout;
2152 std::unordered_map<std::string, IPInformation> table;
2153 std::unordered_map<std::string, std::pair<int,int>> pathConfig;
2156 std::unordered_map<std::string, std::chrono::steady_clock::time_point> blacklist;
2158 inline void logSecurity(
const std::string &msgCN,
const std::string &msgEN);
2212 void close(
const bool &cle =
true);
2254 int sendData(
const std::string &data,
const bool &block =
true);
2278 int sendData(
const char *data,
const uint64_t &length,
const bool &block =
true);
2323 int recvData(std::string &data,
const uint64_t &length);
2336 int recvData(
char *data,
const uint64_t &length);
2346 std::string serverIP =
"";
2347 int serverPort = -1;
2350 SSL_CTX *ctx =
nullptr;
2357 void closeAndUnCreate();
2358 bool initCTX(
const char *ca,
const char *cert =
"",
const char *key =
"",
const char *passwd =
"");
2372 TcpClient(
const bool &TLS =
false,
const char *ca =
"",
const char *cert =
"",
const char *key =
"",
const char *passwd =
"");
2379 bool connect(
const std::string &ip,
const int &port);
2393 void resetCTX(
const bool &TLS =
false,
const char *ca =
"",
const char *cert =
"",
const char *key =
"",
const char *passwd =
"");
2445 HttpClient(
const bool &TLS =
false,
const char *ca =
"",
const char *cert =
"",
const char *key =
"",
const char *passwd =
"") :
TcpClient(TLS, ca, cert, key, passwd) {}
2464 bool getRequest(
const std::string &url,
const std::string &
header =
"",
const std::string &header1 =
"Connection: keep-alive",
const int &
sec=-1);
2483 bool postRequest(
const std::string &url,
const std::string &
body =
"",
const std::string &
header =
"",
const std::string &header1 =
"Connection: keep-alive",
const int &
sec=-1);
2503 bool getRequestFromFD(
const int &
fd, SSL *
ssl,
const std::string &url,
const std::string &
header =
"",
const std::string &header1 =
"Connection: keep-alive",
const int &
sec=2);
2524 bool postRequestFromFD(
const int &
fd, SSL *
ssl,
const std::string &url,
const std::string &
body =
"",
const std::string &
header =
"",
const std::string &header1 =
"Connection: keep-alive",
const int &
sec=2);
2549 std::function<bool(const int &fd)> fc = [](
const int &fd)->
bool
2551 std::function<void(const int &fd)> fcEnd = [](
const int &fd)->
void
2553 std::function<bool(const int &fd)> fcTimeOut = [](
const int &fd)->
bool
2585 void setFunction(std::function<
bool(
const int &fd)> fc) { this->fc = fc; }
2593 void setEndFunction(std::function<
void(
const int &fd)> fcEnd) { this->fcEnd = fcEnd; };
2637 std::function<bool(const std::string &message, WebSocketClient &k)> fc = [](
const std::string &message,
WebSocketClient &k)->
bool
2638 {std::cout<<
"Received: "<<message<<std::endl;
return true;};
2657 WebSocketClient(
const bool &TLS =
false,
const char *ca =
"",
const char *cert =
"",
const char *key =
"",
const char *passwd =
"") :
TcpClient(TLS, ca, cert, key, passwd) {}
2677 bool connect(
const std::string &url,
const int &min = 20);
2700 bool sendMessage(
const std::string &message,
const std::string &type =
"0001");
2710 void close(
const std::string &closeCodeAndMessage,
const bool &wait =
true);
2729 void close(
const short &code = 1000,
const std::string &message =
"bye",
const bool &wait =
true);
2797 std::unordered_map<std::string,std::any>
ctx;
2842 bool sendBack(
const std::string &data,
const std::string &header =
"",
const std::string &code =
"200 OK",
const std::string &header1 =
"");
2856 bool sendBack(
const char *data,
const size_t &length,
const char *header=
"\0",
const char *code=
"200 OK\0",
const char *header1=
"\0",
const size_t &header_length=50);
2915 std::unordered_map<std::string,std::any>
ctx;
2941 std::unordered_map<std::string,std::any>
ctx;
3048 std::function<void(const int &fd)> closeFun=[](
const int &fd)->
void
3054 std::function<bool(TcpFDHandler &k,TcpInformation &inf)> globalSolveFun=[](TcpFDHandler &k,TcpInformation &inf)->
bool
3056 std::unordered_map<std::string,std::vector<std::function<int(TcpFDHandler &k,TcpInformation &inf)>>> solveFun;
3057 std::function<int(TcpFDHandler &k,TcpInformation &inf)> parseKey=[](TcpFDHandler &k,TcpInformation &inf)->
int
3058 {inf.ctx[
"key"]=inf.data;
return 1;};
3064 void epolll(
const int &evsNum);
3066 virtual void handler_netevent(
const int &fd);
3067 virtual void handler_workerevent(
const int &fd,
const int &ret);
3068 virtual void handleHeartbeat()=0;
3081 void putTask(
const std::function<
int(TcpFDHandler &k,TcpInformation &inf)> &fun,TcpFDHandler &k,TcpInformation &inf);
3140 const unsigned long long &
maxFD = 1000000,
3143 const int &connectionNumLimit = 20,
3149 const int &connectionTimeout = 60
3170 bool startListen(
const int &port,
const int &threads = 8);
3198 bool setTLS(
const char *cert,
const char *key,
const char *passwd,
const char *ca);
3238 this->securitySendBackFun = fc;
3276 const std::string &key,
3279 auto [it, inserted] = solveFun.try_emplace(key);
3280 it->second.push_back(std::move(fc));
3306 this->parseKey = parseKeyFun;
3326 virtual bool close(
const int &fd);
3330 void setCloseFun(std::function<
void(
const int &fd)> closeFun){this->closeFun=closeFun;}
3341 SSL*
getSSL(
const int &fd);
3360 std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>> globalSolveFun;
3364 std::vector<std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)>>
3367 std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKey =
3369 inf.
ctx[
"key"] = inf.loc;
3374 void handler_netevent(
const int &fd);
3375 void handler_workerevent(
const int &fd,
const int &ret);
3376 void handleHeartbeat(){}
3464 const unsigned long long &
maxFD = 1000000,
3467 const int &connectionNumLimit = 10,
3473 const int &connectionTimeout = 30
3524 this->securitySendBackFun = fc;
3591 const std::string &key,
3595 auto [it, inserted] = solveFun.try_emplace(key);
3596 it->second.push_back(std::move(fc));
3632 this->parseKey = parseKeyFun;
3705 bool sendMessage(
const std::string &msg,
const std::string &type =
"0001");
3715 std::unordered_map<int, WebSocketFDInformation> wbclientfd;
3719 std::function<bool(WebSocketFDInformation &k)> fcc =
3724 std::function<bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fccc =
3728 std::function<bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> globalSolveFun =
3735 std::vector<std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)>>>
3738 std::function<int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> parseKey =
3740 inf.
ctx[
"key"] = inf.message;
3750 void handler_netevent(
const int &fd);
3751 void handler_workerevent(
const int &fd,
const int &ret);
3753 void closeAck(
const int &fd,
const std::string &closeCodeAndMessage);
3754 void closeAck(
const int &fd,
const short &code = 1000,
const std::string &message =
"bye");
3758 void handleHeartbeat();
3760 bool closeWithoutLock(
const int &fd,
const std::string &closeCodeAndMessage);
3761 bool closeWithoutLock(
const int &fd,
const short &code = 1000,
const std::string &message =
"bye");
3844 const unsigned long long &
maxFD = 1000000,
3847 const int &connectionNumLimit = 5,
3853 const int &connectionTimeout = 120
3904 this->securitySendBackFun = fc;
3922 this->globalSolveFun = fc;
3967 const std::string &key,
3970 auto [it, inserted] = solveFun.try_emplace(key);
3971 it->second.push_back(std::move(fc));
3982 this->parseKey = parseKeyFun;
3991 this->seca = seca * 60;
4011 bool closeFD(
const int &fd,
const std::string &closeCodeAndMessage);
4020 bool closeFD(
const int &fd,
const short &code = 1000,
const std::string &message =
"bye");
4031 const std::string &msg,
4032 const std::string &type =
"0001")
4048 bool close(
const int &fd);
4065 void sendMessage(
const std::string &msg,
const std::string &type =
"0001");
4098 void setFD(
const int &fd,
const bool &
flag1 =
false,
const int &
sec = -1,
const bool &
flag2 =
false);
4121 void close(
const bool &cle =
true);
4142 int sendData(
const std::string &data,
const std::string &ip,
const int &port,
const bool &block =
true);
4163 int sendData(
const char *data,
const uint64_t &length,
const std::string &ip,
const int &port,
const bool &block =
true);
4178 int recvData(std::string &data,
const uint64_t &length, std::string &ip,
int &port);
4193 int recvData(
char *data,
const uint64_t &length, std::string &ip,
int &port);
4239 bool createFD(
const int &port,
const bool &
flag1 =
false,
const int &
sec = -1,
const bool &
flag2 =
true);
4324 struct semid_ds *buf;
4325 unsigned short *arry;
4350 bool init(key_t key,
unsigned short value = 1,
short sem_flg = SEM_UNDO);
4360 bool wait(
short value = -1);
4370 bool post(
short value = 1);
4397 #define MAX_PROCESS_NAME 100
4401 #define MAX_PROCESS_INF 1000
4405 #define SHARED_MEMORY_KEY 0x5095
4409 #define SHARED_MEMORY_LOCK_KEY 0x5095
4465 bool join(
const char *name,
const char *argv0 =
"",
const char *argv1 =
"",
const char *argv2 =
"");
4481 static bool HBCheck(
const int &sec);
4522 template<
class... Args>
4523 static bool startProcess(
const std::string &name,
const int &sec = -1, Args ...args)
4525 std::vector<const char *> paramList={args...,
nullptr};
4535 execv(name.c_str(),
const_cast<char* const*
>(paramList.data()));
4539 for(
int ii=1;ii<=64;ii++)
4550 signal(SIGCHLD,SIG_DFL);
4557 execv(name.c_str(),
const_cast<char* const*
>(paramList.data()));
4592 template<
class Fn,
class... Args>
4593 static typename std::enable_if<!std::is_convertible<Fn, std::string>::value,
bool>::type
4605 auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4610 for(
int ii=1;ii<=64;ii++)
4621 signal(SIGCHLD,SIG_DFL);
4628 auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4645 using Task = std::function<void()>;
4683 for (
size_t i = 0; i < n; ++i) {
4684 threads_.emplace_back([
this] {
4709 std::lock_guard<std::mutex> lk(mtx_);
4710 tasks_.push(std::move(task));
4727 std::lock_guard<std::mutex> lk(mtx_);
4731 for (
auto &t : threads_)
4733 if (t.joinable()) t.join();
4754 std::unique_lock<std::mutex> lk(mtx_);
4755 cv_.wait(lk, [
this] {
4756 return stop_ || !tasks_.empty();
4758 if (stop_ && tasks_.empty())
4762 task = std::move(tasks_.front());
4770 std::vector<std::thread> threads_;
4771 std::queue<Task> tasks_;
4773 std::condition_variable cv_;
void setSecuritySendBackFun(std::function< void(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
Set the callback invoked when an information security policy is violated.
Definition: sttnet_English.h:3519
static std::string & transfer_websocket_key(std::string &str)
Generate the Sec-WebSocket-Accept field value in the WebSocket handshake response.
Unified connection & request security gate (IP-level + fd-level, multi-strategy limiting + blacklist)...
Definition: sttnet_English.h:2014
int sendData(const std::string &data, const std::string &ip, const int &port, const bool &block=true)
Send string data to the target.
std::chrono::duration< uint64_t > Seconds
Definition: sttnet_English.h:826
bool close()
Close all connections and stop listening.
bool operator>(const Duration &b)
Determine if the current time interval is greater than another time interval.
Definition: sttnet_English.h:558
int getServerPort()
Return the port of the connected client.
Definition: sttnet_English.h:2413
int fd
Low-level sockets.
Definition: sttnet_English.h:3003
SSL * getSSL()
Get the encrypted SSL handle of this object.
Definition: sttnet_English.h:2207
int solveRequest(TcpFDInf &TcpInf, HttpRequestInformation &HttpInf, const unsigned long &buffer_size, const int ×=1)
Parse Http/Https request.
Definition: sttnet_English.h:1929
int checkFrequency
Definition: sttnet_English.h:3046
bool isStart()
Return the timing status of the object.
Definition: sttnet_English.h:932
int fd
Definition: sttnet_English.h:2176
bool startTiming()
Start timing.
bool connect(const std::string &ip, const int &port)
Initiate a TCP connection to the server.
TcpFDInf * clientfd
Definition: sttnet_English.h:3024
~WebSocketClient()
Destructor of WebSocketClient class, gracefully disconnects when destroying the object.
std::string getServerIp()
Return the server ip if connected to the server.
Definition: sttnet_English.h:2745
bool unblock
Definition: sttnet_English.h:3032
int ret
Return value -2: Failure and connection closed required; -1: Failure but connection closed not requir...
Definition: sttnet_English.h:3007
void setFD(const int &fd, SSL *ssl=nullptr, const bool &flag1=false, const bool &flag2=true)
Initialize the object, pass in socket and other parameters.
Definition: sttnet_English.h:2816
TCP socket operation class.
Definition: sttnet_English.h:2173
bool readLine(std::string &data, const int linePos)
Read a single line.
static std::string createJson(T1 first, T2 second, Args...args)
Create a JSON string composed of multiple key-value pairs (recursive variadic template).
Definition: sttnet_English.h:1662
std::string & readAll(std::string &data)
Read all lines.
double tokens
Definition: sttnet_English.h:1847
A structure representing a time interval, supporting granularity in days, hours, minutes, seconds, and milliseconds.
Definition: sttnet_English.h:526
std::string & readAllC(std::string &data)
Read all lines.
void setGlobalSolveFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
Sets a global backup function.
Definition: sttnet_English.h:3542
WebSocket protocol operation class Only pass in the socket, then use this class for WebSocket operati...
Definition: sttnet_English.h:3657
static void setLogFile(file::LogFile *logfile=nullptr, const std::string &language="")
Set the log file object for the logging system If the passed log file object is uninitialized (empty)...
static void init(file::LogFile *logfile=nullptr, const std::string &language="")
Execute the setExceptionHandling and setfile::LogFile functions to complete the initialization of sig...
DefenseDecision allowRequest(const std::string &ip, const int &fd, const std::string_view &path, const int ×, const int &secs)
Security decision for a single request on an existing connection.
bool isConnect()
Determine if the object has a socket bound.
Definition: sttnet_English.h:2230
void setPathLimit(const std::string &path, const int ×, const int &secs)
Configure extra rate limits for a specific path (path-level rule).
Class for time operations, calculations, and timing.
Definition: sttnet_English.h:843
bool createFD(const int &port, const bool &flag1=false, const int &sec=-1, const bool &flag2=true)
Destroy the original socket and recreate a server.
int getFD()
Get the socket of this object.
Definition: sttnet_English.h:2202
static long getRandomNumber(const long &a, const long &b)
Generate a random integer.
static int & str16toInt(const std::string_view &ori_str, int &result, const int &i=-1)
Convert a hexadecimal number's string representation to a decimal int type number.
void putTask(const std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> &fun, WebSocketServerFDHandler &k, WebSocketFDInformation &inf)
Submit a task to the worker thread pool.
bool deleteLine(const int &linePos=0)
Delete a line.
void waitAndQuit(const time::Duration &t=time::Duration{0, 0, 0, 10, 10})
Start the epoll exit countdown until new messages arrive on the socket If no new messages arrive by t...
Definition: sttnet_English.h:2620
bool connect(const std::string &url, const int &min=20)
Connect to a websocket server.
bool operator<=(const Duration &b)
Determine if the current time interval is less than or equal to another time interval.
Definition: sttnet_English.h:622
static std::string & sha11(const std::string &ori_str, std::string &result)
Calculate the SHA-1 hash value of the input string and return it as a hexadecimal string...
Http/HttpServer server operation class.
Definition: sttnet_English.h:3355
int recvData(std::string &data, const uint64_t &length, std::string &ip, int &port)
Receive data once into a string container.
int sendData(const std::string &data, const bool &block=true)
Send string data to the connected socket.
bool sendMessage(const int &fd, const std::string &msg, const std::string &type="0001")
Send a WebSocket message to a specific client.
Definition: sttnet_English.h:4029
void setCloseFun(std::function< void(const int &fd)> closeFun)
set function after tcp connection close
Definition: sttnet_English.h:3330
Data structure for pushing tasks into a completion queue after they are completed at the work site...
Definition: sttnet_English.h:2998
pid_t pid
Process ID.
Definition: sttnet_English.h:4419
WebSocketClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
Constructor of WebSocketClient class.
Definition: sttnet_English.h:2657
Duration(long long a, int b, int c, int d, int e)
Constructor, taking days, hours, minutes, seconds, milliseconds.
Definition: sttnet_English.h:551
int violations
Definition: sttnet_English.h:1840
bool post(short value=1)
V operation (release), attempts to add value to the semaphore.
int getFD()
Return fd.
Definition: sttnet_English.h:4116
static unsigned long & htonl_ntohl_64(unsigned long &data)
Reverse the endianness of a 64-bit unsigned integer (big endian <-> little endian).
bool stopListen()
Stop listening.
Duration endTiming()
Stop timing.
char argv1[20]
Second parameter of the process.
Definition: sttnet_English.h:4435
bool writeC(const char *data, const size_t &pos, const size_t &size)
Write a data block.
bool postRequestFromFD(const int &fd, SSL *ssl, const std::string &url, const std::string &body="", const std::string &header="", const std::string &header1="Connection: keep-alive", const int &sec=2)
Send a POST request to the server.
std::string loc
The file path.
Definition: sttnet_English.h:120
unsigned long p_buffer_now
Receives a spatial position pointer.
Definition: sttnet_English.h:2984
bool isConnect()
Return the connection status of the object.
Definition: sttnet_English.h:2418
std::ostream & operator<<(std::ostream &os, const Duration &a)
Output the Duration object to a stream in a readable format.
int sec
Seconds.
Definition: sttnet_English.h:543
~TcpServer()
Destructor of TcpServer class.
Definition: sttnet_English.h:3346
double convertToMin()
Convert the current time interval to a floating-point representation in minutes.
Definition: sttnet_English.h:745
void putTask(const std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> &fun, HttpServerFDHandler &k, HttpRequestInformation &inf)
Submit a task to the worker thread pool.
int recvDataByLength(std::string &data, const uint64_t &length, const int &sec=2)
Blocking receive of specified length of data from a connected socket into a string.
static bool decryptSymmetric(const unsigned char *before, const size_t &length, const unsigned char *passwd, const unsigned char *iv, unsigned char *after)
Symmetric decryption function in AES-256-CBC mode.
static std::string & generateMask_4(std::string &mask)
Generate a 32-bit (4-byte) random mask.
void clearIP(const std::string &ip, const int &fd)
Reclaim state for an fd when the connection is closed.
static long & toLong(const std::string_view &ori_str, long &result, const long &i=-1)
Convert string to long type.
static std::string & getRandomStr_base64(std::string &str, const int &length)
Generate a pseudo-random string of specified length within the Base64 character set, and append '=' at the end to complete the Base64 string format.
static float & toFloat(const std::string &ori_str, float &result, const float &i=-1)
Convert string to float type.
unsigned long buffer_size
Definition: sttnet_English.h:3019
std::string getServerPort()
Return the server port if connected to the server.
Definition: sttnet_English.h:2750
int counter
Definition: sttnet_English.h:1839
unsigned long long maxFD
Definition: sttnet_English.h:3020
bool closeFile(const bool &del=false)
Close the log file opened by the object.
TcpClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
Constructor of TcpClient class.
std::chrono::steady_clock::time_point lastActivity
Definition: sttnet_English.h:1872
int serverType
Definition: sttnet_English.h:3041
#define ISO8086A
Define the macro ISO8086A as "yyyy-mm-ddThh:mi:ss".
Definition: sttnet_English.h:830
void setTimeOutFunction(std::function< bool(const int &fd)> fcTimeOut)
Set the callback function triggered after epoll timeout Register a callback function.
Definition: sttnet_English.h:2603
bool flag2
Definition: sttnet_English.h:2178
Duration recoverForm(const long long &t)
Recover the standard days-hours-minutes-seconds-milliseconds format from given milliseconds.
Definition: sttnet_English.h:776
static std::string createArray(T first)
Create a JSON array string containing only one element.
Definition: sttnet_English.h:1687
void close(const bool &cle=true)
Empty the object and close the socket.
UdpClient(const bool &flag1=false, const int &sec=-1)
Constructor.
void putTask(const std::function< int(TcpFDHandler &k, TcpInformation &inf)> &fun, TcpFDHandler &k, TcpInformation &inf)
Add a task to a worker thread pool and have it completed by worker threads.
std::queue< std::any > pendindQueue
Queue waiting to be processed.
Definition: sttnet_English.h:2992
Responsible for conversion between strings and numbers.
Definition: sttnet_English.h:1467
~EpollSingle()
Destructor of EpollSingle Calls eldListen to block and exit epoll.
Definition: sttnet_English.h:2625
int threads
Records how many threads are currently using the file.
Definition: sttnet_English.h:124
static double & toDouble(const std::string &ori_str, double &result, const double &i=-1)
Convert string to double type.
static std::string language
Language selection for the system's logging system, default is English.
Definition: sttnet_English.h:4271
static std::string & getPreciesFloat(const float &number, const int &bit, std::string &str)
Format a floating-point number into a string representation with a specified number of decimal places...
Class responsible for process heartbeat monitoring and scheduling Used to monitor service processes a...
Definition: sttnet_English.h:4449
bool flag1
Definition: sttnet_English.h:2177
std::deque< std::chrono::steady_clock::time_point > history
Definition: sttnet_English.h:1844
void startListen(const int &fd, const bool &flag=true, const time::Duration &dt=time::Duration{0, 0, 20, 0, 0})
Start listening.
Duration checkTime()
Check time during timing.
void format()
Format the data.
size_t getFileSize()
Get the size of the file opened in binary mode.
Definition: sttnet_English.h:264
bool deleteAllC()
Delete all lines.
Definition: sttnet_English.h:1931
Tcp server class.
Definition: sttnet_English.h:3014
stt::system::WorkerPool * workpool
Definition: sttnet_English.h:3018
static std::string createArray(T first, Args...args)
Create a JSON array string composed of multiple elements (recursive variadic template).
Definition: sttnet_English.h:1705
static std::mutex l1
Definition: sttnet_English.h:146
bool startListen(const int &port, const int &threads=8)
Start the TCP server listening program.
std::string port
Client port.
Definition: sttnet_English.h:2960
void setFunction(const std::string &key, std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
Register a message handler callback for a specific key.
Definition: sttnet_English.h:3966
UDP operation class Pass in the socket for UDP protocol operations.
Definition: sttnet_English.h:4083
void blockSet(const int &sec=-1)
Set the socket in the object to blocking mode.
int requestTimes
Definition: sttnet_English.h:3045
int recvData(std::string &data, const uint64_t &length)
Receive data once from a connected socket into a string container.
bool flag1
Definition: sttnet_English.h:4087
size_t getSize1()
Get the size of the file opened in binary mode in memory.
Definition: sttnet_English.h:273
static std::enable_if<!std::is_convertible< Fn, std::string >::value, bool >::type startProcess(Fn &&fn, const int &sec=-1, Args &&...args)
Create a child process through a function (with the option to restart periodically) ...
Definition: sttnet_English.h:4594
~File()
Destructor.
Definition: sttnet_English.h:231
static std::string_view & get_location_str(const std::string_view &ori_str, std::string_view &str)
Extract the path and query part from the URL.
HttpClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
Constructor of HttpClient class.
Definition: sttnet_English.h:2445
static std::string_view & getLocPara(const std::string_view &url, std::string_view &locPara)
Extract the path part of the URL (excluding the query).
WebSocketServer server operation class.
Definition: sttnet_English.h:3712
Operation class for parsing and responding to Http/https requests Only pass in the socket...
Definition: sttnet_English.h:2806
void setGlobalSolveFunction(std::function< bool(TcpFDHandler &k, TcpInformation &inf)> fc)
Set global fallback function.
Definition: sttnet_English.h:3251
bool closeFD(const int &fd, const std::string &closeCodeAndMessage)
Close a WebSocket connection using an encoded close payload.
bool chgLineC(const std::string &data, const int &linePos=0)
Modify a line.
bool operator<(const Duration &b)
Determine if the current time interval is less than another time interval.
Definition: sttnet_English.h:574
bool isConnect()
Return the connection status.
Definition: sttnet_English.h:2735
static bool HBCheck(const int &sec)
Check the heartbeat monitoring system If the time difference between the last heartbeat update and th...
Responsible for encryption, decryption, and hashing.
Definition: sttnet_English.h:1016
Responsible for floating-point precision processing.
Definition: sttnet_English.h:1193
static std::string & sha1(const std::string &ori_str, std::string &result)
Calculate the SHA-1 hash value (raw binary form) of the input string.
void stop()
Stop the thread pool and wait for all threads to exit.
Definition: sttnet_English.h:4724
SSL_CTX * ctx
Definition: sttnet_English.h:3033
bool deleteLogByTime(const std::string &date1="1", const std::string &date2="2")
Delete logs within a specified time interval.
std::string & read(std::string &data, const int &linePos, const int &num)
Read multiple lines.
static void list()
Output information of all processes in the heartbeat monitoring system.
static std::string & jsonToUTF8(const std::string &input, std::string &output)
Convert in a JSON string to UTF-8 characters.
Responsible for conversion between binary data and strings.
Definition: sttnet_English.h:1071
static unsigned long & bitToNumber(const std::string &input, unsigned long &result)
Convert a string to binary and then to the corresponding numeric value.
class of solving json data
Definition: sttnet_English.h:1598
static std::string & generateMask_4(std::string &mask)
Generate a 32-bit (4-byte) random mask.
static Duration & calculateTime(const std::string &time1, const std::string &time2, Duration &result, const std::string &format1=ISO8086A, const std::string &format2=ISO8086A)
Calculate the difference between two time strings.
static Json::Value toJsonArray(const std::string &str)
Parse a JSON string into Json::Value.
LogFile()
Constructor, initializes the consumer thread.
bool renew()
Update the heartbeat of the current process.
~HttpServer()
Destructor.
Definition: sttnet_English.h:3650
std::chrono::steady_clock::time_point lastTime
Definition: sttnet_English.h:1841
int connectionTimes
Definition: sttnet_English.h:3043
~csemp()
Destructor, does not automatically destroy the semaphore.
std::unordered_map< std::string, RateState > pathRate
Definition: sttnet_English.h:1871
Structure for process information.
Definition: sttnet_English.h:4414
std::string & readC(std::string &data, const int &linePos, const int &num)
Read multiple lines.
static std::unordered_map< std::string, FileThreadLock > fl2
Definition: sttnet_English.h:147
void resetCTX(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
Reset TLS encryption parameters for the first time or reconfigure.
bool getRequest(const std::string &url, const std::string &header="", const std::string &header1="Connection: keep-alive", const int &sec=-1)
Send a GET request to the server.
static std::string base64_encode(const std::string &input)
Base64 encode a string.
bool deleteLineC(const int &linePos=0)
Delete a line.
bool multiUseSet()
Set SO_REUSEADDR mode.
static std::string createHeader(const std::string &first, const std::string &second)
Create an HTTP request header field string.
int getvalue()
Get the current value of the semaphore.
TCP client operation class.
Definition: sttnet_English.h:2343
Responsible for HTTP string and URL parsing Including functions to extract parameters, IP, port, request header fields, etc., from URLs or request messages.
Definition: sttnet_English.h:1248
double convertToHour()
Convert the current time interval to a floating-point representation in hours.
Definition: sttnet_English.h:735
void setGetKeyFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKeyFun)
Set the callback function used to parse the key.
Definition: sttnet_English.h:3628
csemp()
Constructor, initializes internal state.
Definition: sttnet_English.h:4338
time_t lastTime
Last heartbeat time of the process, as a timestamp.
Definition: sttnet_English.h:4423
long long day
Days.
Definition: sttnet_English.h:531
static int & getPort(const std::string &url, int &port)
Extract the port number from the URL.
int sec
Definition: sttnet_English.h:4089
static void setExceptionHandling()
Set system signals.
bool chgLine(const std::string &data, const int &linePos=0)
Modify a line.
void setGetKeyFunction(std::function< int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
Set the callback function used to parse the key.
Definition: sttnet_English.h:3303
static std::string & strto16(const std::string &ori_str, std::string &result)
Convert a normal string to its corresponding hexadecimal representation string (hex string)...
void redrawTLS()
Revoke TLS encryption, CA certificate, etc.
void setGlobalSolveFunction(std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
Set the global fallback handler.
Definition: sttnet_English.h:3919
bool close()
If the object has a socket connection, close and release the connection and socket, and create a new socket.
void setSecuritySendBackFun(std::function< void(TcpFDHandler &k, TcpInformation &inf)> fc)
Set the callback invoked when an information security policy is violated.
Definition: sttnet_English.h:3233
void setFunction(const std::string &key, std::function< int(TcpFDHandler &k, TcpInformation &inf)> fc)
Register a callback function for a specific key.
Definition: sttnet_English.h:3275
std::mutex lock
The lock for this file.
Definition: sttnet_English.h:128
int min
Minutes.
Definition: sttnet_English.h:539
void endListenWithSignal()
Send a signal to end epoll.
Definition: sttnet_English.h:2614
static float & getValidFloat(float &number, const int &bit)
Dynamically adjust the decimal precision based on the value, retaining a specified number of signific...
bool unlockMemory(const bool &rec=false)
Write data from memory to disk.
WorkerPool(size_t n)
Constructor, creates a specified number of worker threads.
Definition: sttnet_English.h:4681
SSL * ssl
Definition: sttnet_English.h:2179
bool readLineC(std::string &data, const int linePos)
Read a single line.
static bool & toBool(const std::string_view &ori_str, bool &result)
Convert string to bool type.
static char & toBit(const std::string &input, char &result)
Compress a "01" string of up to 8 bits into 1 byte (char).
void setConnectStrategy(const RateLimitType &type)
Set the strategy used for connection-rate limiting.
bool createFD(const bool &flag1=false, const int &sec=-1)
Destroy the original socket and recreate a client.
char argv2[20]
Third parameter of the process.
Definition: sttnet_English.h:4439
void setStartFunction(std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fccc)
Set the callback invoked immediately after a WebSocket connection is established. ...
Definition: sttnet_English.h:3932
UdpServer(const int &port, const bool &flag1=false, const int &sec=-1, const bool &flag2=true)
Constructor.
static std::string toString(const Json::Value &val)
Convert Json::Value to a string.
bool write(const char *data, const size_t &pos, const size_t &size)
Write a data block.
bool TLS
Definition: sttnet_English.h:3034
HttpServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=10, const int &connectionSecs=1, const int &connectionTimes=3, const int &requestSecs=1, const int &requestTimes=20, const int &checkFrequency=30, const int &connectionTimeout=30)
Constructor.
Definition: sttnet_English.h:3463
double convertToSec()
Convert the current time interval to a floating-point representation in seconds.
Definition: sttnet_English.h:755
static std::string base64_decode(const std::string &input)
Decode a Base64 encoded string.
std::chrono::duration< uint64_t, std::milli > Milliseconds
Definition: sttnet_English.h:825
std::string getUrl()
Return the url if connected to the server.
Definition: sttnet_English.h:2740
static file::LogFile * logfile
Pointer to the log file object for reading and writing logs in the system.
Definition: sttnet_English.h:4267
TLSState
Definition: sttnet_English.h:2918
bool connectionDetect(const std::string &ip, const int &fd)
Detect and cleanup an idle/zombie connection.
static std::string createHeader(const std::string &first, const std::string &second, Args...args)
Recursively construct multiple HTTP request header fields.
Definition: sttnet_English.h:1439
time::Duration operator+(const time::Duration &b)
Add two time intervals.
Definition: sttnet_English.h:638
Listen to a single handle with epoll.
Definition: sttnet_English.h:2544
TcpServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=20, const int &connectionSecs=1, const int &connectionTimes=6, const int &requestSecs=1, const int &requestTimes=40, const int &checkFrequency=60, const int &connectionTimeout=60)
Constructor.
Definition: sttnet_English.h:3139
static std::string & transfer_websocket_key(std::string &str)
Generate the Sec-WebSocket-Accept field value in the WebSocket handshake response.
int workerEventFD
Definition: sttnet_English.h:3040
int FDStatus
Record which step the current state machine is at.
Definition: sttnet_English.h:2988
bool getRequestFromFD(const int &fd, SSL *ssl, const std::string &url, const std::string &header="", const std::string &header1="Connection: keep-alive", const int &sec=2)
Send a GET request to the server from a tcp socket.
void setPathStrategy(const RateLimitType &type)
Set the strategy used for path-level extra limiting.
bool sendMessage(const std::string &message, const std::string &type="0001")
Send a WebSocket message.
~WorkerPool()
destructor
Definition: sttnet_English.h:4695
bool flag3
if the connection lost while using sendData function with block=true,this flag will be set to true ...
Definition: sttnet_English.h:2185
void setSecuritySendBackFun(std::function< void(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
Set the callback invoked when an information security policy is violated.
Definition: sttnet_English.h:3899
WebSocketServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=5, const int &connectionSecs=10, const int &connectionTimes=3, const int &requestSecs=1, const int &requestTimes=10, const int &checkFrequency=60, const int &connectionTimeout=120)
Constructor.
Definition: sttnet_English.h:3843
bool lockMemory()
Read data from disk into memory.
bool sendMessage(const std::string &msg, const std::string &type="0001")
Send a websocket message.
static std::string & bitOutput(char input, std::string &result)
Convert a single character to its corresponding 8-bit binary string.
void setFD(const int &fd, SSL *ssl=nullptr, const bool &flag1=false, const bool &flag2=true)
Initialize the object, pass in socket and other parameters.
Definition: sttnet_English.h:3667
int connectionSecs
Definition: sttnet_English.h:3042
FileThreadLock(const std::string &loc, const int &threads)
The constructor of this structure.
Definition: sttnet_English.h:134
bool operator>=(const Duration &b)
Determine if the current time interval is greater than or equal to another time interval.
Definition: sttnet_English.h:606
bool wait(short value=-1)
P operation (wait), attempts to subtract value from the semaphore.
bool destroy()
Destroy the current semaphore.
int fd
Definition: sttnet_English.h:4086
std::string getFileName()
Get the name of the opened file.
Definition: sttnet_English.h:246
~TcpClient()
Destructor of TcpClient, closes and releases the socket and its connection.
Definition: sttnet_English.h:2402
static std::string_view & getPara(const std::string_view &url, std::string_view ¶)
Get the query parameter string in the URL (including ?).
void setGetKeyFunction(std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> parseKeyFun)
Set the key parsing callback.
Definition: sttnet_English.h:3979
void setEndFunction(std::function< void(const int &fd)> fcEnd)
Set the callback function before epoll exits Register a callback function.
Definition: sttnet_English.h:2593
std::string body
Server response body.
Definition: sttnet_English.h:2538
static std::string & getIP(const std::string &url, std::string &IP)
Extract the host IP or domain name from the URL.
~HBSystem()
Destructor of HBSystem.
Responsible for string operations related to the WebSocket protocol.
Definition: sttnet_English.h:1448
Duration getDt()
Get the last timing duration.
Definition: sttnet_English.h:927
Data encoding/decoding, mask processing, etc.
Definition: sttnet_English.h:1536
int findC(const std::string &targetString, const int linePos=1)
Find a line.
std::function< void()> Task
Definition: sttnet_English.h:4645
~UdpServer()
Destructor, closes the socket when the object's life ends.
Definition: sttnet_English.h:4243
bool startListen(const int &port, const int &threads=8)
Start the HTTP server listening loop.
Definition: sttnet_English.h:3642
bool operator==(const Duration &b)
Determine if the current time interval is equal to another time interval.
Definition: sttnet_English.h:590
bool appendLineC(const std::string &data, const int &linePos=0)
Insert a line.
Runtime state for one limiter key (reused by multiple strategies).
Definition: sttnet_English.h:1836
bool deleteFromHBS()
Remove the current process from the heartbeat system.
bool join(const char *name, const char *argv0="", const char *argv1="", const char *argv2="")
Add a process to the heartbeat system.
void close(const bool &cle=true)
Close the object.
char * buffer
Receives the space pointer.
Definition: sttnet_English.h:2980
static unsigned long & bitStrToNumber(const std::string &input, unsigned long &result)
Convert a "01" string (binary string) to an unsigned integer.
A structure that records the relationship between files and threads.
Definition: sttnet_English.h:115
static size_t get_split_str(const std::string_view &ori_str, std::string_view &str, const std::string_view &a, const std::string_view &b, const size_t &pos=0)
Extract a substring between two markers from the original string.
int status
The current fd status, used to save the processor logic.
Definition: sttnet_English.h:2964
void writeLog(const std::string &data)
Write a line of log.
bool init(key_t key, unsigned short value=1, short sem_flg=SEM_UNDO)
Initialize the semaphore.
int sec
Definition: sttnet_English.h:2180
void setJudgeFunction(std::function< bool(WebSocketFDInformation &)> fcc)
Set the handshake validation callback.
Definition: sttnet_English.h:3948
#define MAX_PROCESS_NAME
Define the macro MAX_PROCESS_NAME as 100, meaning the process name in process information does not ex...
Definition: sttnet_English.h:4397
static bool convertFormat(std::string &timeStr, const std::string &oldFormat, const std::string &newFormat=ISO8086A)
Convert the format of a time string.
Class for initializing the service system.
Definition: sttnet_English.h:4261
~UdpClient()
Destructor, closes the socket when the object's life ends.
Definition: sttnet_English.h:4217
bool close()
Close listening and all connected sockets.
bool deleteAll()
Delete all lines.
uint64_t getFileLine()
Get the number of lines in the opened file.
Definition: sttnet_English.h:255
void setFD(const int &fd, const bool &flag1=false, const int &sec=-1, const bool &flag2=false)
Set fd.
~LogFile()
The destructor writes the log and then closes the consumer thread.
bool isOpen()
Check if the object has opened a file.
Definition: sttnet_English.h:236
DefenseDecision allowConnect(const std::string &ip, const int &fd, const int ×, const int &secs)
Security decision for a newly accepted connection (IP-level gate).
int flag1
Definition: sttnet_English.h:3025
bool isReturn()
Get the server response status.
Definition: sttnet_English.h:2530
int requestSecs
Definition: sttnet_English.h:3044
std::string_view data
Save the data received from the client.
Definition: sttnet_English.h:2968
int getMessage(TcpFDInf &Tcpinf, WebSocketFDInformation &Websocketinf, const unsigned long &buffer_size, const int &ii=1)
Get a websocket message.
bool flag2
Definition: sttnet_English.h:4088
Security and limiter state for a single connection (fd).
Definition: sttnet_English.h:1867
int fd
Definition: sttnet_English.h:1869
RateState requestRate
Definition: sttnet_English.h:1870
static std::string & jsonFormatify(const std::string &a, std::string &b)
Remove indentation, spaces, etc., from a formatted JSON string to make it compact.
std::string header
Server response header.
Definition: sttnet_English.h:2534
bool openFile(const std::string &fileName, const bool &create=true, const int &multiple=0, const size_t &size=0, const mode_t &mode=0666)
Open a file.
static std::string & maskCalculate(std::string &data, const std::string &mask)
Perform XOR operation (XOR Masking) on a string using a given 4-byte mask.
TLSState tls_state
tls state
Definition: sttnet_English.h:2976
Websocket client operation class.
Definition: sttnet_English.h:2633
bool isBinary()
Check if the object has opened the file in binary mode.
Definition: sttnet_English.h:241
void blockSet(const int &sec=-1)
Set to blocking mode.
void setFD(const int &fd, SSL *ssl, const bool &flag1=false, const bool &flag2=false, const int &sec=-1)
Initialize the object with a socket.
std::string getServerIP()
Return the IP of the connected server.
Definition: sttnet_English.h:2408
static std::string & getPreciesDouble(const double &number, const int &bit, std::string &str)
Format a double-precision floating-point number into a string representation with a specified number ...
void submit(Task task)
Submit a task to the thread pool.
Definition: sttnet_English.h:4706
Synchronization tool class encapsulating System V semaphores.
Definition: sttnet_English.h:4313
bool openFile(const std::string &fileName, const std::string &timeFormat=ISO8086A, const std::string &contentFormat=" ")
Open a log file.
RateLimitType
Rate limiting algorithm / strategy type.
Definition: sttnet_English.h:1807
bool clearLog()
Clear all logs.
Responsible for endianness conversion.
Definition: sttnet_English.h:1173
time::Duration operator-(const time::Duration &b)
Calculate the difference between two time intervals (current object minus parameter b)...
Definition: sttnet_English.h:682
static bool encryptSymmetric(const unsigned char *before, const size_t &length, const unsigned char *passwd, const unsigned char *iv, unsigned char *after)
Symmetric encryption function in AES-256-CBC mode.
~WebSocketServer()
Destructor.
Definition: sttnet_English.h:4072
void setRequestStrategy(const RateLimitType &type)
Set the strategy used for fd-level request limiting.
std::mutex che
Definition: sttnet_English.h:149
bool startListen(const int &port, const int &threads=8)
Start the WebSocket server.
Definition: sttnet_English.h:4054
std::string getFileName()
Get the file name opened by the object.
Definition: sttnet_English.h:975
Udp server operation class.
Definition: sttnet_English.h:4222
double convertToDay()
Convert the current time interval to a floating-point representation in days.
Definition: sttnet_English.h:725
bool isListen()
Return epoll listening status.
Definition: sttnet_English.h:2575
Http/Https client operation class.
Definition: sttnet_English.h:2428
char argv0[20]
First parameter of the process.
Definition: sttnet_English.h:4431
int fd
Socket file descriptor.
Definition: sttnet_English.h:2952
bool postRequest(const std::string &url, const std::string &body="", const std::string &header="", const std::string &header1="Connection: keep-alive", const int &sec=-1)
Send a POST request to the server.
bool security_open
Definition: sttnet_English.h:3037
bool setTLS(const char *cert, const char *key, const char *passwd, const char *ca)
Enable TLS encryption and configure server-side certificate and key.
void formatC()
Format the data.
Static utility class for process management.
Definition: sttnet_English.h:4497
static std::string_view & get_value_str(const std::string_view &ori_str, std::string_view &str, const std::string &name)
Extract the value of a specified key from the URL query parameters.
bool sendBack(const std::string &data, const std::string &header="", const std::string &code="200 OK", const std::string &header1="")
Send Http/Https response.
static std::string_view & get_value_header(const std::string_view &ori_str, std::string_view &str, const std::string &name)
Extract the value of a specified field from the HTTP request header.
static int getValue(const std::string &oriStr, std::string &result, const std::string &type="value", const std::string &name="a", const int &num=0)
Extract the value or nested structure of a specified field in a JSON string.
int hour
Hours.
Definition: sttnet_English.h:535
long long convertToMsec()
Convert the current time interval to total milliseconds.
Definition: sttnet_English.h:765
void setFunction(std::function< bool(const int &fd)> fc)
Set the processing function after epoll triggering Register a callback function.
Definition: sttnet_English.h:2585
Udp client operation class.
Definition: sttnet_English.h:4199
static int & toInt(const std::string_view &ori_str, int &result, const int &i=-1)
Convert string to int type.
static std::string createJson(T1 first, T2 second)
Create a JSON string containing only one key-value pair.
Definition: sttnet_English.h:1637
Structure to save TCP client information.
Definition: sttnet_English.h:2947
static std::string jsonAdd(const std::string &a, const std::string &b)
Concatenate two JSON strings into a valid JSON (suitable for object or array concatenation).
static bool compareTime(const std::string &time1, const std::string &time2, const std::string &format1=ISO8086A, const std::string &format2=ISO8086A)
Compare the magnitudes of two time strings.
void setFunction(const std::string &key, std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
Register a callback function for a specific key.
Definition: sttnet_English.h:3590
security::ConnectionLimiter connectionLimiter
Definition: sttnet_English.h:3021
bool closeFile(const bool &del=false)
Close the opened file.
bool appendLine(const std::string &data, const int &linePos=0)
Insert a line.
std::string ip
Client IP.
Definition: sttnet_English.h:2956
bool isOpen()
Get the status of whether the log file is open.
Definition: sttnet_English.h:970
DefenseDecision
Security decision returned by ConnectionLimiter.
Definition: sttnet_English.h:1927
void setHBTimeOutTime(const int &secb)
Set heartbeat response timeout.
Definition: sttnet_English.h:3999
ConnectionLimiter(const int &maxConn=20, const int &idleTimeout=60)
Constructor.
Definition: sttnet_English.h:2023
Log file operation class.
Definition: sttnet_English.h:941
A class for reading and writing disk files.
Definition: sttnet_English.h:143
int msec
Milliseconds.
Definition: sttnet_English.h:547
std::queue< WorkerMessage > finishQueue
Definition: sttnet_English.h:3017
Related to random number and string generation.
Definition: sttnet_English.h:1137
int find(const std::string &targetString, const int linePos=1)
Find a line.
static char & bitOutput_bit(char input, const int pos, char &result)
Get the pos-th bit (from left to right) of the character input (binary) and return '1' or '0'...
bool endListen()
End epoll listening Will block until epoll exits completely.
void unblockSet()
Set the socket in the object to non-blocking mode.
SSL * ssl
If encrypted, store the encryption handle.
Definition: sttnet_English.h:2972
bool isListen()
Return the listening status of the object.
Definition: sttnet_English.h:3336
bool multiUseSet()
Set the socket in the object to SO_REUSEADDR mode.
char name[MAX_PROCESS_NAME]
Process name.
Definition: sttnet_English.h:4427
Definition: sttnet_English.h:1930
static bool startProcess(const std::string &name, const int &sec=-1, Args...args)
Start a new process (with the option to restart periodically)
Definition: sttnet_English.h:4523
SSL * getSSL(const int &fd)
Query the connection with the server, pass in the socket, and return the encrypted SSL handle...
void unblockSet()
Set to non-blocking mode.
static std::string & getTime(std::string &timeStr, const std::string &format=ISO8086A)
Get the current time.
void setTimeOutTime(const int &seca)
Set heartbeat interval.
Definition: sttnet_English.h:3989
void setFunction(std::function< bool(const std::string &message, WebSocketClient &k)> fc)
Set the callback function after receiving a message from the server Register a callback function...
Definition: sttnet_English.h:2668
std::chrono::steady_clock::time_point lastRefill
Definition: sttnet_English.h:1848
Fixed-size worker thread pool.
Definition: sttnet_English.h:4671