STTNet
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
sttnet_English.h
Go to the documentation of this file.
1 
7 #ifndef PUBLIC_H
8 #define PUBLIC_H 1
9 #include<jsoncpp/json/json.h>
10 #include<string_view>
11 #include<string>
12 #include<atomic>
13 #include<iostream>
14 #include<unistd.h>
15 #include<sys/stat.h>
16 #include<fstream>
17 #include<fcntl.h>
18 #include<sstream>
19 #include<mutex>
20 #include<chrono>
21 #include<iomanip>
22 #include<random>
23 #include<cmath>
24 #include<thread>
25 #include<openssl/sha.h>
26 #include<netdb.h>
27 #include<arpa/inet.h>
28 #include<sys/types.h>
29 #include<sys/socket.h>
30 #include<cstring>
31 #include<openssl/bio.h>
32 #include<openssl/evp.h>
33 #include<openssl/buffer.h>
34 #include<functional>
35 #include<list>
36 #include<queue>
37 #include<sys/epoll.h>
38 #include<condition_variable>
39 #include <regex>
40 #include<unordered_map>
41 #include <openssl/ssl.h>
42 #include <openssl/err.h>
43 #include<openssl/crypto.h>
44 #include<signal.h>
45 #include<sys/ipc.h>
46 #include<sys/sem.h>
47 #include<sys/wait.h>
48 #include<sys/shm.h>
49 #include<type_traits>
50 #include<charconv>
51 #include<any>
52 #include <sys/eventfd.h>
53 #include <sys/timerfd.h>
57 namespace stt
58 {
59  namespace system
60  {
61  class WorkerPool;
62  }
68  namespace file
69  {
73  class FileTool
74  {
75  public:
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);
108  static size_t get_file_size(const std::string &fileName);
109  };
110 
116  {
120  std::string loc;
124  int threads;
128  std::mutex lock;
134  FileThreadLock(const std::string &loc,const int &threads):loc(loc),threads(threads){};
135  };
136 
143  class File:private FileTool
144  {
145  protected:
146  static std::mutex l1;
147  static std::unordered_map<std::string,FileThreadLock> fl2;
148  protected:
149  std::mutex che;
150 
151  private:
152  void lockfl2();
153  void unlockfl2();
154  private:
155  std::ifstream fin;
156  std::vector<std::string> data;
157  std::vector<std::string> backUp;
158  char *data_binary=nullptr;
159  char *backUp_binary=nullptr;
160  size_t size1=0;
161  size_t size2=0;
162  int multiple=0;
163  size_t multiple_backup=0;
164  size_t malloced=0;
165  std::mutex fl1;
166 
167  std::ofstream fout;
168  std::string fileName;
169 
170  std::string fileNameTemp;
171  bool flag=false;
172  bool binary;
173  mode_t mode;
174  size_t size=0;
175  uint64_t totalLines=0;
176  private:
177  void toMemory();
178  bool toDisk();
179  public:
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);
226  bool closeFile(const bool &del=false);
231  ~File(){closeFile(false);}
236  bool isOpen(){return flag;}
241  bool isBinary(){return binary;}
246  std::string getFileName(){return fileName;}
255  uint64_t getFileLine(){return totalLines;}
264  size_t getFileSize(){return size;}
273  size_t getSize1(){return size1;}
274  public:
280  bool lockMemory();
288  bool unlockMemory(const bool &rec=false);
289  public:
303  int findC(const std::string &targetString,const int linePos=1);
313  bool appendLineC(const std::string &data,const int &linePos=0);
322  bool deleteLineC(const int &linePos=0);
329  bool deleteAllC();
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);
398  void formatC();
400  public:
414  int find(const std::string &targetString,const int linePos=1);
424  bool appendLine(const std::string &data,const int &linePos=0);
433  bool deleteLine(const int &linePos=0);
440  bool deleteAll();
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);
509  void format();
511  };
512  }
518  namespace time
519  {
526  struct Duration
527 {
531  long long day;
535  int hour;
539  int min;
543  int sec;
547  int msec;
551  Duration(long long a, int b, int c, int d, int e) : day(a), hour(b), min(c), sec(d), msec(e) {}
552  Duration() = default;
558  bool operator>(const Duration &b)
559  {
560  long long total;
561  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
562  long long totalB;
563  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
564  if (total > totalB)
565  return true;
566  else
567  return false;
568  }
574  bool operator<(const Duration &b)
575  {
576  long long total;
577  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
578  long long totalB;
579  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
580  if (total < totalB)
581  return true;
582  else
583  return false;
584  }
590  bool operator==(const Duration &b)
591  {
592  long long total;
593  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
594  long long totalB;
595  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
596  if (total == totalB)
597  return true;
598  else
599  return false;
600  }
606  bool operator>=(const Duration &b)
607  {
608  long long total;
609  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
610  long long totalB;
611  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
612  if (total >= totalB)
613  return true;
614  else
615  return false;
616  }
622  bool operator<=(const Duration &b)
623  {
624  long long total;
625  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
626  long long totalB;
627  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
628  if (total <= totalB)
629  return true;
630  else
631  return false;
632  }
639  {
640  long long dayy = day;
641  int hourr = hour;
642  int minn = min;
643  int secc = sec;
644  int msecc = msec;
645 
646  msecc += b.msec;
647  secc += b.sec;
648  minn += b.min;
649  hourr += b.hour;
650  dayy += b.day;
651 
652  if (msecc / 1000 != 0)
653  {
654  secc += msecc / 1000;
655  msecc = msecc % 1000;
656  }
657 
658  if (secc / 60 != 0)
659  {
660  minn += secc / 60;
661  secc = secc % 60;
662  }
663 
664  if (minn / 60 != 0)
665  {
666  hourr += minn / 60;
667  minn = minn % 60;
668  }
669 
670  if (hourr / 24 != 0)
671  {
672  dayy += hourr / 24;
673  hourr = hourr % 24;
674  }
675  return time::Duration(dayy, hourr, minn, secc, msecc);
676  }
683  {
684  long long dayy = day;
685  int hourr = hour;
686  int minn = min;
687  int secc = sec;
688  int msecc = msec;
689 
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;
691  secc = 0;
692  minn = 0;
693  hourr = 0;
694  dayy = 0;
695 
696  if (msecc / 1000 != 0)
697  {
698  secc += msecc / 1000;
699  msecc = msecc % 1000;
700  }
701 
702  if (secc / 60 != 0)
703  {
704  minn += secc / 60;
705  secc = secc % 60;
706  }
707 
708  if (minn / 60 != 0)
709  {
710  hourr += minn / 60;
711  minn = minn % 60;
712  }
713 
714  if (hourr / 24 != 0)
715  {
716  dayy += hourr / 24;
717  hourr = hourr % 24;
718  }
719  return time::Duration(dayy, hourr, minn, secc, msecc);
720  }
721 
725  double convertToDay()
726  {
727  long long total;
728  total = hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
729  double k = day + total / 86400000.0000;
730  return k;
731  }
735  double convertToHour()
736  {
737  long long total;
738  total = min * 60 * 1000 + sec * 1000 + msec;
739  double k = day * 24 + hour + total / 36000000.0000;
740  return k;
741  }
745  double convertToMin()
746  {
747  long long total;
748  total = sec * 1000 + msec;
749  double k = day * 24 * 60 + hour * 60 + min + total / 60000.0000;
750  return k;
751  }
755  double convertToSec()
756  {
757  long long total;
758  total = msec;
759  double k = day * 24 * 60 * 60 + hour * 60 * 60 + min * 60 + sec + total / 1000.0000;
760  return k;
761  }
765  long long convertToMsec()
766  {
767  long long total;
768  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
769  return total;
770  }
776  Duration recoverForm(const long long &t)
777  {
778  msec = t;
779  sec = 0;
780  min = 0;
781  hour = 0;
782  day = 0;
783 
784  if (msec / 1000 != 0)
785  {
786  sec += msec / 1000;
787  msec = msec % 1000;
788  }
789 
790  if (sec / 60 != 0)
791  {
792  min += sec / 60;
793  sec = sec % 60;
794  }
795 
796  if (min / 60 != 0)
797  {
798  hour += min / 60;
799  min = min % 60;
800  }
801 
802  if (hour / 24 != 0)
803  {
804  day += hour / 24;
805  hour = hour % 24;
806  }
807  return Duration(day, hour, min, sec, msec);
808  }
809 };
823 std::ostream& operator<<(std::ostream &os, const Duration &a);
824 
825 using Milliseconds = std::chrono::duration<uint64_t, std::milli>;
826 using Seconds = std::chrono::duration<uint64_t>;
830 #define ISO8086A "yyyy-mm-ddThh:mi:ss"
831 
834 #define ISO8086B "yyyy-mm-ddThh:mi:ss.sss"
835 
836 
843 class DateTime
844 {
845 private:
846  static Duration& dTOD(const Milliseconds& d1, Duration &D1);
847  static Milliseconds& DTOd(const Duration &D1, Milliseconds& d1);
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);
851 public:
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);
878  static Duration& calculateTime(const std::string &time1, const std::string &time2, Duration &result, const std::string &format1 = ISO8086A, const std::string &format2 = 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);
900 private:
901  Duration dt{-1, -1, -1, -1, -1};
902  bool flag = false;
903  std::chrono::steady_clock::time_point start;
904  std::chrono::steady_clock::time_point end;
905 public:
910  bool startTiming();
922 public:
927  Duration getDt() { return dt; }
932  bool isStart() { return flag; }
933 };
934 }
935 namespace file
936 {
941 class LogFile : private time::DateTime, protected file::File
942 {
943 private:
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;
951 public:
955  LogFile();
965  bool openFile(const std::string &fileName, const std::string &timeFormat = ISO8086A, const std::string &contentFormat = " ");
970  bool isOpen() { return File::isOpen(); }
975  std::string getFileName() { return File::getFileName(); }
981  bool closeFile(const bool &del = false);
986  void writeLog(const std::string &data);
991  bool clearLog();
999  bool deleteLogByTime(const std::string &date1 = "1", const std::string &date2 = "2");
1003  ~LogFile();
1004 };
1005 }
1011  namespace data
1012  {
1017  {
1018  public:
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);
1067  };
1071  class BitUtil
1072  {
1073  public:
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);
1133  };
1138  {
1139  public:
1147  static long getRandomNumber(const long &a, const long &b);
1154  static std::string& getRandomStr_base64(std::string &str, const int &length);
1168  static std::string& generateMask_4(std::string &mask);
1169  };
1174  {
1175  public:
1187  static unsigned long& htonl_ntohl_64(unsigned long &data); // 64-bit unsigned number conversion to big/little endian (network byte order)
1188  };
1189 
1194  {
1195  public:
1196 
1205  static std::string& getPreciesFloat(const float &number, const int &bit, std::string &str);
1213  static float& getPreciesFloat(float &number, const int &bit);
1222  static std::string& getPreciesDouble(const double &number, const int &bit, std::string &str);
1230  static double& getPreciesDouble(double &number, const int &bit);
1242  static float& getValidFloat(float &number, const int &bit);
1243  };
1249  {
1250  public:
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 &para);
1317 
1318 
1319 
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 &para);
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)
1440  {
1441  std::string cf = first + ": " + second + "\r\n" + createHeader(args...);
1442  return cf;
1443  }
1444  };
1449  {
1450  public:
1462  static std::string& transfer_websocket_key(std::string &str);
1463  };
1468  {
1469  public:
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); // String to hexadecimal string (Not needed for now) (To be fixed)
1532  };
1537  {
1538  public:
1547  static std::string base64_encode(const std::string &input);
1556  static std::string base64_decode(const std::string &input);
1568  static std::string& transfer_websocket_key(std::string &str);
1582  static std::string& generateMask_4(std::string &mask);
1593  static std::string& maskCalculate(std::string &data, const std::string &mask);
1594  };
1599  {
1600  public:
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);
1614 
1620  static std::string toString(const Json::Value &val);
1626  static Json::Value toJsonArray(const std::string & str);
1636  template<class T1, class T2>
1637  static std::string createJson(T1 first, T2 second)
1638  {
1639  Json::Value root;
1640  //root[first] = second;
1641  if constexpr (std::is_integral_v<T2>) {
1642  root[first] = Json::Value(static_cast<Json::Int64>(second));
1643  } else {
1644  root[first] = second;
1645  }
1646  Json::StreamWriterBuilder builder;
1647  std::string jsonString = Json::writeString(builder, root);
1648  return jsonString;
1649  }
1661  template<class T1, class T2, class... Args>
1662  static std::string createJson(T1 first, T2 second, Args... args)
1663  {
1664  Json::Value root;
1665  //root[first] = second;
1666  if constexpr (std::is_integral_v<T2>) {
1667  root[first] = Json::Value(static_cast<Json::Int64>(second));
1668  } else {
1669  root[first] = second;
1670  }
1671  std::string kk = createJson(args...);
1672  Json::StreamWriterBuilder builder;
1673  std::string jsonString = Json::writeString(builder, root);
1674  jsonString = jsonString.erase(jsonString.length() - 2);
1675  kk = kk.substr(1);
1676  return jsonString + "," + kk;
1677 
1678  }
1686  template<class T>
1687  static std::string createArray(T first)
1688  {
1689  Json::Value root(Json::arrayValue);
1690  root.append(first);
1691  Json::StreamWriterBuilder builder;
1692  std::string jsonString = Json::writeString(builder, root);
1693  return jsonString;
1694  }
1704  template<class T, class... Args>
1705  static std::string createArray(T first, Args... args)
1706  {
1707  Json::Value root(Json::arrayValue);
1708  root.append(first);
1709  std::string kk = createArray(args...);
1710  Json::StreamWriterBuilder builder;
1711  std::string jsonString = Json::writeString(builder, root);
1712  jsonString = jsonString.erase(jsonString.length() - 2);
1713  kk = kk.substr(1);
1714  return jsonString + "," + kk;
1715 
1716  }
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);
1738  };
1739  }
1740 
1744  namespace security
1745  {
1807 enum class RateLimitType
1808 {
1809  Cooldown, // Punishment-based: hit limit => cooldown, require quiet secs to recover
1810  FixedWindow, // Fixed window counter: each secs is a window, allow up to times
1811  SlidingWindow, // Sliding window: count events within the last secs (timestamp deque)
1812  TokenBucket // Token bucket: allow bursts + control long-term average rate
1813 };
1814 
1815 
1837 {
1838  // Common
1839  int counter = 0;
1840  int violations = 0;
1841  std::chrono::steady_clock::time_point lastTime{};
1842 
1843  // SlidingWindow
1844  std::deque<std::chrono::steady_clock::time_point> history;
1845 
1846  // TokenBucket
1847  double tokens = 0.0;
1848  std::chrono::steady_clock::time_point lastRefill{};
1849 };
1850 
1851 
1868 {
1869  int fd = -1;
1871  std::unordered_map<std::string, RateState> pathRate;
1872  std::chrono::steady_clock::time_point lastActivity{};
1873 };
1874 
1875 
1899 {
1902  int badScore = 0; // IP risk score used for escalation
1903  std::unordered_map<int, ConnectionState> conns; // fd -> state
1904 };
1905 
1906 
1928 {
1929  ALLOW = 0,
1930  DROP = 1,
1931  CLOSE = 2
1932 };
1933 
1934 
2015 {
2016 public:
2023  ConnectionLimiter(const int& maxConn = 20, const int& idleTimeout = 60)
2024  : maxConnections(maxConn), connectionTimeout(idleTimeout) {}
2025 
2026  // ========== Strategy configuration ==========
2027 
2034  void setConnectStrategy(const RateLimitType &type);
2035 
2042  void setRequestStrategy(const RateLimitType &type);
2043 
2050  void setPathStrategy(const RateLimitType &type);
2051 
2052  // ========== Path configuration ==========
2053 
2068  void setPathLimit(const std::string &path, const int &times, const int &secs);
2069 
2070  // ========== Core decisions ==========
2071 
2088  DefenseDecision allowConnect(const std::string &ip, const int &fd,
2089  const int &times, const int &secs);
2090 
2105  DefenseDecision allowRequest(const std::string &ip, const int &fd,
2106  const std::string_view &path,
2107  const int &times, const int &secs);
2108 
2109  // ========== Lifecycle ==========
2110 
2121  void clearIP(const std::string &ip, const int &fd);
2122 
2136  bool connectionDetect(const std::string &ip, const int &fd);
2137 
2138 private:
2139  // Core limiter primitive
2140  bool allow(RateState &st, const RateLimitType &type,
2141  const int &times, const int &secs,
2142  const std::chrono::steady_clock::time_point &now);
2143 
2144 private:
2145  int maxConnections;
2146  int connectionTimeout;
2147 
2148  RateLimitType connectStrategy = RateLimitType::Cooldown;
2149  RateLimitType requestStrategy = RateLimitType::SlidingWindow;
2151 
2152  std::unordered_map<std::string, IPInformation> table;
2153  std::unordered_map<std::string, std::pair<int,int>> pathConfig;
2154 
2155  // IP -> unban time
2156  std::unordered_map<std::string, std::chrono::steady_clock::time_point> blacklist;
2157 
2158  inline void logSecurity(const std::string &msgCN, const std::string &msgEN);
2159 };
2160 
2161  }
2162 
2168  namespace network
2169  {
2174  {
2175  protected:
2176  int fd = -1;
2177  bool flag1 = false;
2178  bool flag2 = false;
2179  SSL *ssl = nullptr;
2180  int sec=-1;
2181  public:
2185  bool flag3 = false;
2186  public:
2197  void setFD(const int &fd, SSL *ssl, const bool &flag1 = false, const bool &flag2 = false,const int &sec=-1);
2202  int getFD() { return fd; }
2207  SSL *getSSL() { return ssl; }
2212  void close(const bool &cle = true);
2217  void blockSet(const int &sec = -1);
2221  void unblockSet();
2225  bool multiUseSet();
2230  bool isConnect() { if (fd == -1) return false; else return true; }
2231  public:
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);
2294  int recvDataByLength(std::string &data, const uint64_t &length, const int &sec = 2);
2310  int recvDataByLength(char *data, const uint64_t &length, const int &sec = 2);
2323  int recvData(std::string &data, const uint64_t &length);
2336  int recvData(char *data, const uint64_t &length);
2337  };
2338 
2343  class TcpClient : public TcpFDHandler
2344  {
2345  private:
2346  std::string serverIP = "";
2347  int serverPort = -1;
2348  bool flag = false;
2349  bool TLS;
2350  SSL_CTX *ctx = nullptr;
2351  const char *ca;
2352  const char *cert;
2353  const char *key;
2354  const char *passwd;
2355  private:
2356  bool createFD();
2357  void closeAndUnCreate();
2358  bool initCTX(const char *ca, const char *cert = "", const char *key = "", const char *passwd = "");
2359  public:
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 = "");
2398  bool close();
2402  ~TcpClient() { closeAndUnCreate(); }
2403  public:
2408  std::string getServerIP() { return serverIP; }
2413  int getServerPort() { return serverPort; }
2418  bool isConnect() { return flag; }
2419  };
2420 
2428  class HttpClient : private TcpClient
2429  {
2430  private:
2431  bool flag = false;
2432  public:
2445  HttpClient(const bool &TLS = false, const char *ca = "", const char *cert = "", const char *key = "", const char *passwd = "") : TcpClient(TLS, ca, cert, key, passwd) {}
2446  public:
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);
2525  public:
2530  bool isReturn() { return flag; }
2534  std::string header = "";
2538  std::string body = "";
2539  };
2540 
2545  {
2546  private:
2547  int fd;
2548  bool flag = true;
2549  std::function<bool(const int &fd)> fc = [](const int &fd)->bool
2550  {return true;};
2551  std::function<void(const int &fd)> fcEnd = [](const int &fd)->void
2552  {};
2553  std::function<bool(const int &fd)> fcTimeOut = [](const int &fd)->bool
2554  {return true;};
2555  bool flag1 = true;
2556  bool flag2 = false;
2557  time::Duration dt{0,20,0,0,0};
2558  bool flag3 = false;
2559  time::Duration t;
2560  private:
2561  void epolll();
2562  public:
2569  void startListen(const int &fd, const bool &flag = true, const time::Duration &dt = time::Duration{0,0,20,0,0});
2570  public:
2575  bool isListen() { return flag2; }
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; };
2603  void setTimeOutFunction(std::function<bool(const int &fd)> fcTimeOut) { this->fcTimeOut = fcTimeOut; };
2609  bool endListen();
2614  void endListenWithSignal() { flag1 = false; }
2620  void waitAndQuit(const time::Duration &t = time::Duration{0,0,0,10,10}) { flag3 = true; this->t = t; }
2626  };
2627 
2633  class WebSocketClient : private TcpClient
2634  {
2635  private:
2636  bool flag4 = false;
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;};
2639  std::string url;
2640  EpollSingle k;
2641  bool flag5 = false;
2642  private:
2643  bool close1();
2644  public:
2657  WebSocketClient(const bool &TLS = false, const char *ca = "", const char *cert = "", const char *key = "", const char *passwd = "") : TcpClient(TLS, ca, cert, key, passwd) {}
2668  void setFunction(std::function<bool(const std::string &message, WebSocketClient &k)> fc) { this->fc = fc; }
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);
2730  public:
2735  bool isConnect() { return flag4; }
2740  std::string getUrl() { return url; }
2745  std::string getServerIp() { return TcpClient::getServerIP(); }
2750  std::string getServerPort() { return TcpClient::getServerIP(); }
2754  ~WebSocketClient();
2755  };
2756 
2761  {
2765  int fd;
2769  std::string type;
2773  std::string locPara;
2777  std::string loc;
2781  std::string para;
2785  std::string header;
2789  std::string body;
2793  std::string body_chunked;
2797  std::unordered_map<std::string,std::any> ctx;
2798 
2799  };
2800 
2801  struct TcpFDInf;
2807  {
2808  public:
2816  void setFD(const int &fd, SSL *ssl = nullptr, const bool &flag1 = false, const bool &flag2 = true) { TcpFDHandler::setFD(fd, ssl, flag1, flag2); }
2832  int solveRequest(TcpFDInf &TcpInf,HttpRequestInformation &HttpInf,const unsigned long &buffer_size,const int &times=1);
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);
2857  };
2858 
2863  {
2867  int fd;
2875  std::string locPara;
2879  std::string header;
2883  time_t HBTime = 0;
2887  time_t response;
2891  size_t recv_length;
2903  std::string message="";
2907  bool fin;
2911  std::string mask;
2915  std::unordered_map<std::string,std::any> ctx;
2916  };
2917 
2918  enum class TLSState : uint8_t {
2919  NONE = 0, // 非 TLS 连接(普通 TCP)
2920  HANDSHAKING, // TLS 握手中(SSL_accept 还没完成)
2921  ESTABLISHED, // TLS 已建立,可以 SSL_read / SSL_write
2922  ERROR // TLS 出错(可选)
2923  };
2924 
2929  {
2933  int fd;
2937  std::string data;
2941  std::unordered_map<std::string,std::any> ctx;
2942  };
2943 
2947  struct TcpFDInf
2948  {
2952  int fd;
2956  std::string ip;
2960  std::string port;
2964  int status;
2968  std::string_view data;
2972  SSL* ssl;
2980  char *buffer;
2984  unsigned long p_buffer_now;
2992  std::queue<std::any> pendindQueue;
2993  };
2994 
2999  {
3003  int fd;
3007  int ret;
3008  };
3009 
3014  class TcpServer
3015  {
3016  protected:
3017  std::queue<WorkerMessage> finishQueue;
3019  unsigned long buffer_size;
3020  unsigned long long maxFD;
3022  //std::unordered_map<int,TcpFDInf> clientfd;
3023  //std::mutex lc1;
3025  int flag1=true;
3026  //std::queue<QueueFD> *fdQueue;
3027  //std::mutex *lq1;
3028  //std::condition_variable cv1;
3029  //std::condition_variable *cv;
3030  //int consumerNum;
3031  //std::mutex lco1;
3032  bool unblock;
3033  SSL_CTX *ctx=nullptr;
3034  bool TLS=false;
3035  //std::unordered_map<int,SSL*> tlsfd;
3036  //std::mutex ltl1;
3038  //bool flag_detect;
3039  //bool flag_detect_status;
3041  int serverType; // 1 tcp 2 http 3 websocket
3047  private:
3048  std::function<void(const int &fd)> closeFun=[](const int &fd)->void
3049  {
3050 
3051  };
3052  std::function<void(TcpFDHandler &k,TcpInformation &inf)> securitySendBackFun=[](TcpFDHandler &k,TcpInformation &inf)->void
3053  {};
3054  std::function<bool(TcpFDHandler &k,TcpInformation &inf)> globalSolveFun=[](TcpFDHandler &k,TcpInformation &inf)->bool
3055  {return true;};
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;};
3059  int fd=-1;
3060  int port=-1;
3061  int flag=false;
3062  bool flag2=false;
3063  private:
3064  void epolll(const int &evsNum);
3065  //virtual void consumer(const int &threadID);
3066  virtual void handler_netevent(const int &fd);
3067  virtual void handler_workerevent(const int &fd,const int &ret);
3068  virtual void handleHeartbeat()=0;
3069  public:
3081  void putTask(const std::function<int(TcpFDHandler &k,TcpInformation &inf)> &fun,TcpFDHandler &k,TcpInformation &inf);
3140  const unsigned long long &maxFD = 1000000,
3141  const int &buffer_size = 256,
3142  const bool &security_open = true,
3143  const int &connectionNumLimit = 20,
3144  const int &connectionSecs = 1,
3145  const int &connectionTimes = 6,
3146  const int &requestSecs = 1,
3147  const int &requestTimes = 40,
3148  const int &checkFrequency = 60,
3149  const int &connectionTimeout = 60
3150 )
3151 : maxFD(maxFD),
3152  buffer_size(buffer_size * 1024),
3158  connectionLimiter(connectionNumLimit, connectionTimeout),
3160 {
3161  serverType = 1;
3162 }
3163 
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);
3202  void redrawTLS();
3234  std::function<void(TcpFDHandler &k,
3235  TcpInformation &inf)> fc
3236 )
3237 {
3238  this->securitySendBackFun = fc;
3239 }
3240 
3241 
3251  void setGlobalSolveFunction(std::function<bool(TcpFDHandler &k,TcpInformation &inf)> fc){this->globalSolveFun=fc;}
3276  const std::string &key,
3277  std::function<int(TcpFDHandler &k, TcpInformation &inf)> fc)
3278 {
3279  auto [it, inserted] = solveFun.try_emplace(key);
3280  it->second.push_back(std::move(fc));
3281 }
3282 
3304  std::function<int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
3305 {
3306  this->parseKey = parseKeyFun;
3307 }
3313  bool stopListen();
3320  bool close();
3326  virtual bool close(const int &fd);
3330  void setCloseFun(std::function<void(const int &fd)> closeFun){this->closeFun=closeFun;}
3331  public:
3336  bool isListen() { return flag; }
3341  SSL* getSSL(const int &fd);
3347  };
3348 
3349 
3350 
3355  class HttpServer : public TcpServer
3356 {
3357 private:
3358  std::function<void(HttpServerFDHandler &k,HttpRequestInformation &inf)> securitySendBackFun=[](HttpServerFDHandler &k,HttpRequestInformation &inf)->void
3359  {};
3360  std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>> globalSolveFun;
3361  // std::function<bool(HttpServerFDHandler &k, HttpRequestInformation &inf)> globalSolveFun = {};
3362  std::unordered_map<
3363  std::string,
3364  std::vector<std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)>>
3365  > solveFun;
3366 
3367  std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKey =
3368  [](HttpServerFDHandler &k, HttpRequestInformation &inf) -> int {
3369  inf.ctx["key"] = inf.loc;
3370  return 1;
3371  };
3372 
3373 private:
3374  void handler_netevent(const int &fd);
3375  void handler_workerevent(const int &fd, const int &ret);
3376  void handleHeartbeat(){}
3377 
3378 public:
3400  void putTask(
3401  const std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> &fun,
3404  );
3405 
3464  const unsigned long long &maxFD = 1000000,
3465  const int &buffer_size = 256,
3466  const bool &security_open = true,
3467  const int &connectionNumLimit = 10,
3468  const int &connectionSecs = 1,
3469  const int &connectionTimes = 3,
3470  const int &requestSecs = 1,
3471  const int &requestTimes = 20,
3472  const int &checkFrequency = 30,
3473  const int &connectionTimeout = 30
3474 )
3475 : TcpServer(
3476  maxFD,
3477  buffer_size,
3478  security_open,
3479  connectionNumLimit,
3482  requestSecs,
3483  requestTimes,
3485  connectionTimeout
3486  )
3487 {
3488  serverType = 2;
3489 }
3520  std::function<void(HttpServerFDHandler &k,
3521  HttpRequestInformation &inf)> fc
3522 )
3523 {
3524  this->securitySendBackFun = fc;
3525 }
3526 
3542  void setGlobalSolveFunction(std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc){globalSolveFun.push_back(std::move(fc));}
3591  const std::string &key,
3592  std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc
3593  )
3594  {
3595  auto [it, inserted] = solveFun.try_emplace(key);
3596  it->second.push_back(std::move(fc));
3597  }
3598 
3629  std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKeyFun
3630  )
3631  {
3632  this->parseKey = parseKeyFun;
3633  }
3634 
3642  bool startListen(const int &port, const int &threads = 8)
3643  {
3644  return TcpServer::startListen(port, threads);
3645  }
3646 
3651 };
3652 
3658  {
3659  public:
3667  void setFD(const int &fd, SSL *ssl = nullptr, const bool &flag1 = false, const bool &flag2 = true) { TcpFDHandler::setFD(fd, ssl, flag1, flag2); }
3690  int getMessage(TcpFDInf &Tcpinf,WebSocketFDInformation &Websocketinf,const unsigned long &buffer_size,const int &ii=1);
3705  bool sendMessage(const std::string &msg, const std::string &type = "0001");
3706 
3707  };
3708 
3713 {
3714 private:
3715  std::unordered_map<int, WebSocketFDInformation> wbclientfd;
3716  std::function<void(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> securitySendBackFun=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->void
3717  {};
3718 
3719  std::function<bool(WebSocketFDInformation &k)> fcc =
3720  [](WebSocketFDInformation &k) {
3721  return true;
3722  };
3723 
3724  std::function<bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fccc =
3726  {return true};
3727 
3728  std::function<bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> globalSolveFun =
3729  [](WebSocketServerFDHandler &k, WebSocketFDInformation &inf) -> bool {
3730  return true;
3731  };
3732 
3733  std::unordered_map<
3734  std::string,
3735  std::vector<std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)>>>
3736  solveFun;
3737 
3738  std::function<int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> parseKey =
3739  [](WebSocketServerFDHandler &k, WebSocketFDInformation &inf) -> int {
3740  inf.ctx["key"] = inf.message;
3741  return 1;
3742  };
3743 
3744  int seca = 20 * 60; // heartbeat interval (seconds)
3745  int secb = 30; // heartbeat response timeout (seconds)
3746 
3747 
3748 
3749 private:
3750  void handler_netevent(const int &fd);
3751  void handler_workerevent(const int &fd, const int &ret);
3752 
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");
3755 
3756 
3757 
3758  void handleHeartbeat();
3759 
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");
3762 
3763 public:
3780  void putTask(
3781  const std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)> &fun,
3783  WebSocketFDInformation &inf);
3784 
3844  const unsigned long long &maxFD = 1000000,
3845  const int &buffer_size = 256,
3846  const bool &security_open = true,
3847  const int &connectionNumLimit = 5,
3848  const int &connectionSecs = 10,
3849  const int &connectionTimes = 3,
3850  const int &requestSecs = 1,
3851  const int &requestTimes = 10,
3852  const int &checkFrequency = 60,
3853  const int &connectionTimeout = 120
3854 )
3855 : TcpServer(
3856  maxFD,
3857  buffer_size,
3858  security_open,
3859  connectionNumLimit,
3862  requestSecs,
3863  requestTimes,
3865  connectionTimeout
3866  )
3867 {
3868  serverType = 3;
3869 }
3900  std::function<void(WebSocketServerFDHandler &k,
3901  WebSocketFDInformation &inf)> fc
3902 )
3903 {
3904  this->securitySendBackFun = fc;
3905 }
3906 
3907 
3920  std::function<bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
3921  {
3922  this->globalSolveFun = fc;
3923  }
3924 
3933  std::function<bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fccc)
3934  {
3935  this->fccc = fccc;
3936  }
3937 
3948  void setJudgeFunction(std::function<bool(WebSocketFDInformation &)> fcc)
3949  {
3950  this->fcc = fcc;
3951  }
3952 
3967  const std::string &key,
3968  std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
3969  {
3970  auto [it, inserted] = solveFun.try_emplace(key);
3971  it->second.push_back(std::move(fc));
3972  }
3973 
3980  std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)> parseKeyFun)
3981  {
3982  this->parseKey = parseKeyFun;
3983  }
3984 
3989  void setTimeOutTime(const int &seca)
3990  {
3991  this->seca = seca * 60;
3992  }
3993 
3999  void setHBTimeOutTime(const int &secb)
4000  {
4001  this->secb = secb;
4002  }
4003 
4011  bool closeFD(const int &fd, const std::string &closeCodeAndMessage);
4012 
4020  bool closeFD(const int &fd, const short &code = 1000, const std::string &message = "bye");
4021 
4030  const int &fd,
4031  const std::string &msg,
4032  const std::string &type = "0001")
4033  {
4035  k.setFD(fd, getSSL(fd), unblock);
4036  return k.sendMessage(msg, type);
4037  }
4038 
4043  bool close();
4048  bool close(const int &fd);
4054  bool startListen(const int &port, const int &threads = 8)
4055  {
4056  //std::thread(&WebSocketServer::HB, this).detach();
4057  return TcpServer::startListen(port, threads);
4058  }
4059 
4065  void sendMessage(const std::string &msg, const std::string &type = "0001");
4066 
4073  {
4074 
4075  }
4076 };
4077 
4078 
4084  {
4085  protected:
4086  int fd = -1;
4087  bool flag1 = false;
4088  bool flag2 = false;
4089  int sec = -1;
4090  public:
4098  void setFD(const int &fd, const bool &flag1 = false, const int &sec = -1, const bool &flag2 = false);
4103  void blockSet(const int &sec = -1);
4107  void unblockSet();
4112  bool multiUseSet();
4116  int getFD() { return fd; }
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);
4194 
4195  };
4199  class UdpClient : public UdpFDHandler
4200  {
4201  public:
4207  UdpClient(const bool &flag1 = false, const int &sec = -1);
4213  bool createFD(const bool &flag1 = false, const int &sec = -1);
4218  };
4222  class UdpServer : public UdpFDHandler
4223  {
4224  public:
4232  UdpServer(const int &port, const bool &flag1 = false, const int &sec = -1, const bool &flag2 = true);
4239  bool createFD(const int &port, const bool &flag1 = false, const int &sec = -1, const bool &flag2 = true);
4244  };
4245  }
4251  namespace system
4252  {
4262  {
4263  public:
4271  static std::string language;
4272  private:
4273  static void signalterminated(){std::cout<<"Terminated by uncaught exception"<<std::endl;if(ServerSetting::logfile!=nullptr){if(ServerSetting::language=="Chinese")ServerSetting::logfile->writeLog("未捕获的异常终止");else ServerSetting::logfile->writeLog("end for uncaught exception");}kill(getpid(),15);}
4274  static void signalSIGSEGV(int signal){std::cout<<"SIGSEGV"<<std::endl;if(ServerSetting::logfile!=nullptr){if(ServerSetting::language=="Chinese")ServerSetting::logfile->writeLog("信号SIGSEGV");else ServerSetting::logfile->writeLog("signal SIGSEGV");}kill(getpid(),15);}
4275  static void signalSIGABRT(int signal){std::cout<<"SIGABRT"<<std::endl;if(ServerSetting::logfile!=nullptr){if(ServerSetting::language=="Chinese")ServerSetting::logfile->writeLog("信号SIGABRT");else ServerSetting::logfile->writeLog("signal SIGABRT");}kill(getpid(),15);}
4276  public:
4285  static void setExceptionHandling();
4295  static void setLogFile(file::LogFile *logfile = nullptr, const std::string &language = "");
4302  static void init(file::LogFile *logfile = nullptr, const std::string &language = "");
4303  };
4304 
4313  class csemp
4314  {
4315  private:
4321  union semun
4322  {
4323  int val;
4324  struct semid_ds *buf;
4325  unsigned short *arry;
4326  };
4327 
4328  int m_semid;
4329  short m_sem_flg;
4330 
4331  csemp(const csemp &) = delete;
4332  csemp &operator=(const csemp &) = delete;
4333 
4334  public:
4338  csemp():m_semid(-1){}
4339 
4350  bool init(key_t key, unsigned short value = 1, short sem_flg = SEM_UNDO);
4351 
4360  bool wait(short value = -1);
4361 
4370  bool post(short value = 1);
4371 
4377  int getvalue();
4378 
4386  bool destroy();
4387 
4391  ~csemp();
4392  };
4393 
4397  #define MAX_PROCESS_NAME 100
4398 
4401  #define MAX_PROCESS_INF 1000
4402 
4405  #define SHARED_MEMORY_KEY 0x5095
4406 
4409  #define SHARED_MEMORY_LOCK_KEY 0x5095
4410 
4414  struct ProcessInf
4415  {
4419  pid_t pid;
4423  time_t lastTime;
4431  char argv0[20];
4435  char argv1[20];
4439  char argv2[20];
4440  };
4441 
4449  class HBSystem
4450  {
4451  private:
4452 
4453  static ProcessInf *p;
4454  static csemp plock;
4455  static bool isJoin;
4456  public:
4465  bool join(const char *name, const char *argv0 = "", const char *argv1 = "", const char *argv2 = "");
4470  bool renew();
4474  static void list();
4481  static bool HBCheck(const int &sec);
4486  bool deleteFromHBS();
4491  ~HBSystem();
4492  };
4493 
4497  class Process
4498  {
4499  public:
4500 
4501 
4522  template<class... Args>
4523  static bool startProcess(const std::string &name, const int &sec = -1, Args ...args)
4524  {
4525  std::vector<const char *> paramList={args...,nullptr};
4526  if(sec==-1)
4527  {
4528  pid_t pid=fork();
4529  if(pid==-1)
4530  return false;
4531  if(pid>0)
4532  return true;
4533  else
4534  {
4535  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4536  return false;
4537  }
4538  }
4539  for(int ii=1;ii<=64;ii++)
4540  signal(ii,SIG_IGN);
4541  pid_t pid=fork();
4542  if(pid==-1)
4543  return false;
4544  if(pid>0)
4545  {
4546  return true;
4547  }
4548  else
4549  {
4550  signal(SIGCHLD,SIG_DFL);
4551  signal(15,SIG_DFL);
4552  while(1)
4553  {
4554  pid=fork();
4555  if(fork()==0)
4556  {
4557  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4558  exit(0);
4559  }
4560  else if(pid>0)
4561  {
4562  int sts;
4563  wait(&sts);
4564  sleep(sec);
4565  }
4566  else
4567  continue;
4568  }
4569  }
4570  }
4592  template<class Fn, class... Args>
4593  static typename std::enable_if<!std::is_convertible<Fn, std::string>::value, bool>::type
4594  startProcess(Fn&& fn, const int &sec = -1, Args &&...args)
4595  {
4596  if(sec==-1)
4597  {
4598  pid_t pid=fork();
4599  if(pid==-1)
4600  return false;
4601  if(pid>0)
4602  return true;
4603  else
4604  {
4605  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4606  f();
4607  return true;
4608  }
4609  }
4610  for(int ii=1;ii<=64;ii++)
4611  signal(ii,SIG_IGN);
4612  pid_t pid=fork();
4613  if(pid==-1)
4614  return false;
4615  if(pid>0)
4616  {
4617  return true;
4618  }
4619  else
4620  {
4621  signal(SIGCHLD,SIG_DFL);
4622  signal(15,SIG_DFL);
4623  while(1)
4624  {
4625  pid=fork();
4626  if(pid==0)
4627  {
4628  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4629  f();
4630  return true;
4631  }
4632  else if(pid>0)
4633  {
4634  int sts;
4635  wait(&sts);
4636  sleep(sec);
4637  }
4638  else
4639  continue;
4640  }
4641  }
4642  }
4643  };
4644 
4645  using Task = std::function<void()>;
4671  class WorkerPool
4672  {
4673  public:
4681  explicit WorkerPool(size_t n):stop_(false)
4682  {
4683  for (size_t i = 0; i < n; ++i) {
4684  threads_.emplace_back([this] {
4685  this->workerLoop();
4686  });
4687  }
4688  }
4696  {
4697  stop();
4698  }
4706  void submit(Task task)
4707  {
4708  {
4709  std::lock_guard<std::mutex> lk(mtx_);
4710  tasks_.push(std::move(task));
4711  }
4712  cv_.notify_one();
4713  }
4724  void stop()
4725  {
4726  {
4727  std::lock_guard<std::mutex> lk(mtx_);
4728  stop_ = true;
4729  }
4730  cv_.notify_all();
4731  for (auto &t : threads_)
4732  {
4733  if (t.joinable()) t.join();
4734  }
4735  }
4736 
4737  private:
4748  void workerLoop()
4749  {
4750  while (true)
4751  {
4752  Task task;
4753  {
4754  std::unique_lock<std::mutex> lk(mtx_);
4755  cv_.wait(lk, [this] {
4756  return stop_ || !tasks_.empty();
4757  });
4758  if (stop_ && tasks_.empty())
4759  {
4760  return;
4761  }
4762  task = std::move(tasks_.front());
4763  tasks_.pop();
4764  }
4765  task(); // perform tasks
4766  }
4767  }
4768 
4769  private:
4770  std::vector<std::thread> threads_;
4771  std::queue<Task> tasks_;
4772  std::mutex mtx_;
4773  std::condition_variable cv_;
4774  bool stop_;
4775  };
4776  }
4777 
4778 
4779 }
4780 
4781 
4782 #endif
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.
time_t response
Time of last received message.
Definition: sttnet_English.h:2887
Unified connection &amp; 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 &times=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
bool fin
state of fin
Definition: sttnet_English.h:2907
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.
std::string header
Http/Https request header during the handshake phase.
Definition: sttnet_English.h:2879
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 size_t get_file_size(const std::string &fileName)
Get the size of a file.
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...
int badScore
Definition: sttnet_English.h:1902
DefenseDecision allowRequest(const std::string &ip, const int &fd, const std::string_view &path, const int &times, 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 &times, 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&#39;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
std::string body_chunked
Request body (chunked)
Definition: sttnet_English.h:2793
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 &lt;-&gt; 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.
Security state and connection set for a single IP.
Definition: sttnet_English.h:1898
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 body
Request body.
Definition: sttnet_English.h:2789
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 &#39;=&#39; at the end to complete the Base64 string format.
int fd
Low-level socket.
Definition: sttnet_English.h:2765
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 &quot;yyyy-mm-ddThh:mi:ss&quot;.
Definition: sttnet_English.h:830
std::string message
Message.
Definition: sttnet_English.h:2903
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
std::string para
parameters in url
Definition: sttnet_English.h:2781
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&#39;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.
static bool createFile(const std::string &filePath, const mode_t &mode=0666)
Create a new file.
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.
std::string loc
path in url
Definition: sttnet_English.h:2777
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
std::string locPara
Http/Https path and parameters during the handshake phase.
Definition: sttnet_English.h:2875
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.
std::unordered_map< std::string, std::any > ctx
required data warehouse
Definition: sttnet_English.h:2941
~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...
Structure to save HTTP/HTTPS request information.
Definition: sttnet_English.h:2760
bool unlockMemory(const bool &rec=false)
Write data from memory to disk.
std::unordered_map< std::string, std::any > ctx
required data warehouse
Definition: sttnet_English.h:2915
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 &quot;01&quot; 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
RateState connectRate
Definition: sttnet_English.h:1901
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.
size_t recv_length
Length to be received.
Definition: sttnet_English.h:2891
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.
std::string header
Request header.
Definition: sttnet_English.h:2785
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
Structure to save client WS/WSS request information.
Definition: sttnet_English.h:2862
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
static bool copy(const std::string &sourceFile, const std::string &objectFile)
Copy a file.
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 &para)
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 activeConnections
Definition: sttnet_English.h:1900
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&#39;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
Save TCP client information.
Definition: sttnet_English.h:2928
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.
static bool createDir(const std::string &ddir, const mode_t &mode=0775)
Create a new directory.
Runtime state for one limiter key (reused by multiple strategies).
Definition: sttnet_English.h:1836
int message_type
Message type.
Definition: sttnet_English.h:2899
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.
std::unordered_map< std::string, std::any > ctx
required data warehouse
Definition: sttnet_English.h:2797
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 &quot;01&quot; 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 fd
socket fd
Definition: sttnet_English.h:2933
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.
std::string locPara
Path and parameters in URL.
Definition: sttnet_English.h:2773
bool init(key_t key, unsigned short value=1, short sem_flg=SEM_UNDO)
Initialize the semaphore.
int sec
Definition: sttnet_English.h:2180
time_t HBTime
Time of sending heartbeat (fill in 0 if not sent) (should be cleared to 0 after checking) ...
Definition: sttnet_English.h:2883
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&#39;s life ends.
Definition: sttnet_English.h:4217
std::string data
Naked data.
Definition: sttnet_English.h:2937
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 &times, 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.
std::string type
Request type.
Definition: sttnet_English.h:2769
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
std::string mask
mask
Definition: sttnet_English.h:2911
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
bool closeflag
true: Close frame sent, false: Close frame not sent
Definition: sttnet_English.h:2871
char argv0[20]
First parameter of the process.
Definition: sttnet_English.h:4431
int fd
Socket file descriptor.
Definition: sttnet_English.h:2952
size_t have_recv_length
Length have received.
Definition: sttnet_English.h:2895
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
int fd
Underlying socket descriptor.
Definition: sttnet_English.h:2867
void setHBTimeOutTime(const int &secb)
Set heartbeat response timeout.
Definition: sttnet_English.h:3999
A utility class that provides static functions for file operations.
Definition: sttnet_English.h:73
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 &#39;1&#39; or &#39;0&#39;...
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
std::unordered_map< int, ConnectionState > conns
Definition: sttnet_English.h:1903