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>
54 #include <cstddef>
55 #include <cstdint>
56 #include <new>
57 #include <vector>
61 namespace stt
62 {
63  namespace system
64  {
65  class WorkerPool;
93 template <typename T>
94 class MPSCQueue {
95 public:
96  explicit MPSCQueue(std::size_t capacity_pow2)
97  : capacity_(capacity_pow2),
98  mask_(capacity_pow2 - 1),
99  buffer_(capacity_pow2),
100  head_(0),
101  tail_(0)
102  {
103  // capacity must be power of two
104  if (capacity_ < 2 || (capacity_ & mask_) != 0) {
105  // You can replace with your own assert/log
106  throw std::invalid_argument("MPSCQueue capacity must be power of two and >= 2");
107  }
108 
109  // Initialize per-slot sequence
110  for (std::size_t i = 0; i < capacity_; ++i) {
111  buffer_[i].seq.store(i, std::memory_order_relaxed);
112  }
113  }
114 
115  MPSCQueue(const MPSCQueue&) = delete;
116  MPSCQueue& operator=(const MPSCQueue&) = delete;
117 
119  // Drain remaining items to call destructors if needed
120  T tmp;
121  while (pop(tmp)) {}
122  }
123 
128  bool push(T&& v) noexcept(std::is_nothrow_move_constructible_v<T>) {
129  return emplace_impl(std::move(v));
130  }
131 
132  bool push(const T& v) noexcept(std::is_nothrow_copy_constructible_v<T>) {
133  return emplace_impl(v);
134  }
135 
140  bool pop(T& out) noexcept(std::is_nothrow_move_assignable_v<T> &&
141  std::is_nothrow_move_constructible_v<T>)
142  {
143  Slot& slot = buffer_[head_ & mask_];
144  const std::size_t seq = slot.seq.load(std::memory_order_acquire);
145  const std::intptr_t dif = static_cast<std::intptr_t>(seq) - static_cast<std::intptr_t>(head_ + 1);
146 
147  if (dif != 0) {
148  // seq != head+1 => empty
149  return false;
150  }
151 
152  // Move out
153  out = std::move(*slot.ptr());
154 
155  // Destroy in-place
156  slot.destroy();
157 
158  // Mark slot as free for producers:
159  // seq = head + capacity
160  slot.seq.store(head_ + capacity_, std::memory_order_release);
161 
162  ++head_;
163  return true;
164  }
165 
170  std::size_t approx_size() const noexcept {
171  const std::size_t t = tail_.load(std::memory_order_relaxed);
172  const std::size_t h = head_; // consumer-only
173  return (t >= h) ? (t - h) : 0;
174  }
175 
176 private:
177  struct Slot {
178  std::atomic<std::size_t> seq;
179  typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
180  bool has_value = false;
181 
182  T* ptr() noexcept { return reinterpret_cast<T*>(&storage); }
183  const T* ptr() const noexcept { return reinterpret_cast<const T*>(&storage); }
184 
185  template <class U>
186  void construct(U&& v) noexcept(std::is_nothrow_constructible_v<T, U&&>) {
187  ::new (static_cast<void*>(&storage)) T(std::forward<U>(v));
188  has_value = true;
189  }
190 
191  void destroy() noexcept {
192  if (has_value) {
193  ptr()->~T();
194  has_value = false;
195  }
196  }
197  };
198 
199  template <class U>
200  bool emplace_impl(U&& v) noexcept(std::is_nothrow_constructible_v<T, U&&>) {
201  std::size_t pos = tail_.load(std::memory_order_relaxed);
202 
203  for (;;) {
204  Slot& slot = buffer_[pos & mask_];
205  const std::size_t seq = slot.seq.load(std::memory_order_acquire);
206  const std::intptr_t dif = static_cast<std::intptr_t>(seq) - static_cast<std::intptr_t>(pos);
207 
208  if (dif == 0) {
209  // slot is free for this pos
210  if (tail_.compare_exchange_weak(
211  pos, pos + 1,
212  std::memory_order_relaxed,
213  std::memory_order_relaxed))
214  {
215  // We own this slot now
216  slot.construct(std::forward<U>(v));
217  // Publish to consumer: seq = pos+1 means "ready"
218  slot.seq.store(pos + 1, std::memory_order_release);
219  return true;
220  }
221  // CAS failed: pos updated with current tail; retry
222  } else if (dif < 0) {
223  // slot seq < pos => queue is full (producer wrapped)
224  return false;
225  } else {
226  // Another producer is ahead; move pos forward
227  pos = tail_.load(std::memory_order_relaxed);
228  }
229  }
230  }
231 
232 private:
233  const std::size_t capacity_;
234  const std::size_t mask_;
235  std::vector<Slot> buffer_;
236 
237  // Single consumer only
238  std::size_t head_;
239 
240  // Multi-producer
241  std::atomic<std::size_t> tail_;
242 };
243 
244  }
250  namespace file
251  {
255  class FileTool
256  {
257  public:
265  static bool createDir(const std::string & ddir,const mode_t &mode=0775);
274  static bool copy(const std::string &sourceFile,const std::string &objectFile);
283  static bool createFile(const std::string &filePath,const mode_t &mode=0666);
290  static size_t get_file_size(const std::string &fileName);
291  };
292 
298  {
302  std::string loc;
306  int threads;
310  std::mutex lock;
316  FileThreadLock(const std::string &loc,const int &threads):loc(loc),threads(threads){};
317  };
318 
325  class File:private FileTool
326  {
327  protected:
328  static std::mutex l1;
329  static std::unordered_map<std::string,FileThreadLock> fl2;
330  protected:
331  std::mutex che;
332 
333  private:
334  void lockfl2();
335  void unlockfl2();
336  private:
337  std::ifstream fin;
338  std::vector<std::string> data;
339  std::vector<std::string> backUp;
340  char *data_binary=nullptr;
341  char *backUp_binary=nullptr;
342  size_t size1=0;
343  size_t size2=0;
344  int multiple=0;
345  size_t multiple_backup=0;
346  size_t malloced=0;
347  std::mutex fl1;
348 
349  std::ofstream fout;
350  std::string fileName;
351 
352  std::string fileNameTemp;
353  bool flag=false;
354  bool binary;
355  mode_t mode;
356  size_t size=0;
357  uint64_t totalLines=0;
358  private:
359  void toMemory();
360  bool toDisk();
361  public:
402  bool openFile(const std::string &fileName,const bool &create=true,const int &multiple=0,const size_t &size=0,const mode_t &mode=0666);
408  bool closeFile(const bool &del=false);
413  ~File(){closeFile(false);}
418  bool isOpen(){return flag;}
423  bool isBinary(){return binary;}
428  std::string getFileName(){return fileName;}
437  uint64_t getFileLine(){return totalLines;}
446  size_t getFileSize(){return size;}
455  size_t getSize1(){return size1;}
456  public:
462  bool lockMemory();
470  bool unlockMemory(const bool &rec=false);
471  public:
485  int findC(const std::string &targetString,const int linePos=1);
495  bool appendLineC(const std::string &data,const int &linePos=0);
504  bool deleteLineC(const int &linePos=0);
511  bool deleteAllC();
521  bool chgLineC(const std::string &data,const int &linePos=0);
531  bool readLineC(std::string &data,const int linePos);
541  std::string& readC(std::string &data,const int &linePos,const int &num);
548  std::string& readAllC(std::string &data);
564  bool readC(char *data,const size_t &pos,const size_t &size);
575  bool writeC(const char *data,const size_t &pos,const size_t &size);
580  bool formatC();
582  public:
596  int find(const std::string &targetString,const int linePos=1);
606  bool appendLine(const std::string &data,const int &linePos=0);
615  bool deleteLine(const int &linePos=0);
622  bool deleteAll();
632  bool chgLine(const std::string &data,const int &linePos=0);
642  bool readLine(std::string &data,const int linePos);
652  std::string& read(std::string &data,const int &linePos,const int &num);
659  std::string& readAll(std::string &data);
675  bool read(char *data,const size_t &pos,const size_t &size);
686  bool write(const char *data,const size_t &pos,const size_t &size);
691  void format();
693  };
694  }
700  namespace time
701  {
708  struct Duration
709 {
713  long long day;
717  int hour;
721  int min;
725  int sec;
729  int msec;
733  Duration(long long a, int b, int c, int d, int e) : day(a), hour(b), min(c), sec(d), msec(e) {}
734  Duration() = default;
740  bool operator>(const Duration &b)
741  {
742  long long total;
743  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
744  long long totalB;
745  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
746  if (total > totalB)
747  return true;
748  else
749  return false;
750  }
756  bool operator<(const Duration &b)
757  {
758  long long total;
759  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
760  long long totalB;
761  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
762  if (total < totalB)
763  return true;
764  else
765  return false;
766  }
772  bool operator==(const Duration &b)
773  {
774  long long total;
775  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
776  long long totalB;
777  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
778  if (total == totalB)
779  return true;
780  else
781  return false;
782  }
788  bool operator>=(const Duration &b)
789  {
790  long long total;
791  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
792  long long totalB;
793  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
794  if (total >= totalB)
795  return true;
796  else
797  return false;
798  }
804  bool operator<=(const Duration &b)
805  {
806  long long total;
807  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
808  long long totalB;
809  totalB = b.day * 24 * 60 * 60 * 1000 + b.hour * 60 * 60 * 1000 + b.min * 60 * 1000 + b.sec * 1000 + b.msec;
810  if (total <= totalB)
811  return true;
812  else
813  return false;
814  }
821  {
822  long long dayy = day;
823  int hourr = hour;
824  int minn = min;
825  int secc = sec;
826  int msecc = msec;
827 
828  msecc += b.msec;
829  secc += b.sec;
830  minn += b.min;
831  hourr += b.hour;
832  dayy += b.day;
833 
834  if (msecc / 1000 != 0)
835  {
836  secc += msecc / 1000;
837  msecc = msecc % 1000;
838  }
839 
840  if (secc / 60 != 0)
841  {
842  minn += secc / 60;
843  secc = secc % 60;
844  }
845 
846  if (minn / 60 != 0)
847  {
848  hourr += minn / 60;
849  minn = minn % 60;
850  }
851 
852  if (hourr / 24 != 0)
853  {
854  dayy += hourr / 24;
855  hourr = hourr % 24;
856  }
857  return time::Duration(dayy, hourr, minn, secc, msecc);
858  }
865  {
866  long long dayy = day;
867  int hourr = hour;
868  int minn = min;
869  int secc = sec;
870  int msecc = msec;
871 
872  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;
873  secc = 0;
874  minn = 0;
875  hourr = 0;
876  dayy = 0;
877 
878  if (msecc / 1000 != 0)
879  {
880  secc += msecc / 1000;
881  msecc = msecc % 1000;
882  }
883 
884  if (secc / 60 != 0)
885  {
886  minn += secc / 60;
887  secc = secc % 60;
888  }
889 
890  if (minn / 60 != 0)
891  {
892  hourr += minn / 60;
893  minn = minn % 60;
894  }
895 
896  if (hourr / 24 != 0)
897  {
898  dayy += hourr / 24;
899  hourr = hourr % 24;
900  }
901  return time::Duration(dayy, hourr, minn, secc, msecc);
902  }
903 
907  double convertToDay()
908  {
909  long long total;
910  total = hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
911  double k = day + total / 86400000.0000;
912  return k;
913  }
917  double convertToHour()
918  {
919  long long total;
920  total = min * 60 * 1000 + sec * 1000 + msec;
921  double k = day * 24 + hour + total / 36000000.0000;
922  return k;
923  }
927  double convertToMin()
928  {
929  long long total;
930  total = sec * 1000 + msec;
931  double k = day * 24 * 60 + hour * 60 + min + total / 60000.0000;
932  return k;
933  }
937  double convertToSec()
938  {
939  long long total;
940  total = msec;
941  double k = day * 24 * 60 * 60 + hour * 60 * 60 + min * 60 + sec + total / 1000.0000;
942  return k;
943  }
947  long long convertToMsec()
948  {
949  long long total;
950  total = day * 24 * 60 * 60 * 1000 + hour * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000 + msec;
951  return total;
952  }
958  Duration recoverForm(const long long &t)
959  {
960  msec = t;
961  sec = 0;
962  min = 0;
963  hour = 0;
964  day = 0;
965 
966  if (msec / 1000 != 0)
967  {
968  sec += msec / 1000;
969  msec = msec % 1000;
970  }
971 
972  if (sec / 60 != 0)
973  {
974  min += sec / 60;
975  sec = sec % 60;
976  }
977 
978  if (min / 60 != 0)
979  {
980  hour += min / 60;
981  min = min % 60;
982  }
983 
984  if (hour / 24 != 0)
985  {
986  day += hour / 24;
987  hour = hour % 24;
988  }
989  return Duration(day, hour, min, sec, msec);
990  }
991 };
1005 std::ostream& operator<<(std::ostream &os, const Duration &a);
1006 
1007 using Milliseconds = std::chrono::duration<uint64_t, std::milli>;
1008 using Seconds = std::chrono::duration<uint64_t>;
1012 #define ISO8086A "yyyy-mm-ddThh:mi:ss"
1013 
1016 #define ISO8086B "yyyy-mm-ddThh:mi:ss.sss"
1017 
1018 
1026 {
1027 private:
1028  static Duration& dTOD(const Milliseconds& d1, Duration &D1);
1029  static Milliseconds& DTOd(const Duration &D1, Milliseconds& d1);
1030  static std::string &toPGtimeFormat();
1031  static std::chrono::system_clock::time_point strToTimePoint(const std::string &timeStr, const std::string &format = ISO8086A);
1032  static std::string& timePointToStr(const std::chrono::system_clock::time_point &tp, std::string &timeStr, const std::string &format = ISO8086A);
1033 public:
1041  static std::string& getTime(std::string &timeStr, const std::string &format = ISO8086A);
1050  static bool convertFormat(std::string &timeStr, const std::string &oldFormat, const std::string &newFormat = ISO8086A);
1060  static Duration& calculateTime(const std::string &time1, const std::string &time2, Duration &result, const std::string &format1 = ISO8086A, const std::string &format2 = ISO8086A);
1071  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);
1081  static bool compareTime(const std::string &time1, const std::string &time2, const std::string &format1 = ISO8086A, const std::string &format2 = ISO8086A);
1082 private:
1083  Duration dt{-1, -1, -1, -1, -1};
1084  bool flag = false;
1085  std::chrono::steady_clock::time_point start;
1086  std::chrono::steady_clock::time_point end;
1087 public:
1092  bool startTiming();
1097  Duration checkTime();
1103  Duration endTiming();
1104 public:
1109  Duration getDt() { return dt; }
1114  bool isStart() { return flag; }
1115 };
1116 }
1117 namespace file
1118 {
1124 class LogFile : private time::DateTime, protected file::File
1125 {
1126 private:
1127  std::string timeFormat;
1128  std::string contentFormat;
1129  std::atomic<bool> consumerGuard{true};
1130  //std::mutex queueMutex;
1131  //std::condition_variable queueCV;
1133  std::thread consumerThread;
1134 public:
1161  LogFile(const size_t &logQueue_cap=8192):logQueue(logQueue_cap)
1162  {
1163  consumerGuard=true;
1164  consumerThread = std::thread([this]()->void
1165  {
1166  std::string content;
1167  content.reserve(1024);
1168  std::string time;
1169  content.reserve(1074);
1170  while(this->consumerGuard)
1171  {
1172  while(this->logQueue.pop(content))//非空则执行
1173  {
1174  getTime(time,timeFormat);
1175  time+=contentFormat;
1176  time+=content;
1177  this->appendLine(time);
1178  }
1179  std::this_thread::sleep_for(std::chrono::microseconds(500));
1180 
1181  }
1182  });
1183  }
1193  bool openFile(const std::string &fileName, const std::string &timeFormat = ISO8086A, const std::string &contentFormat = " ");
1198  bool isOpen() { return File::isOpen(); }
1203  std::string getFileName() { return File::getFileName(); }
1209  bool closeFile(const bool &del = false);
1214  void writeLog(const std::string &data);
1219  bool clearLog();
1227  bool deleteLogByTime(const std::string &date1 = "1", const std::string &date2 = "2");
1231  ~LogFile();
1232 };
1233 }
1239  namespace data
1240  {
1245  {
1246  public:
1257  static bool encryptSymmetric(const unsigned char *before, const size_t &length, const unsigned char *passwd, const unsigned char *iv, unsigned char *after);
1268  static bool decryptSymmetric(const unsigned char *before, const size_t &length, const unsigned char *passwd, const unsigned char *iv, unsigned char *after);
1281  static std::string& sha1(const std::string &ori_str, std::string &result);
1294  static std::string& sha11(const std::string &ori_str, std::string &result);
1295  };
1299  class BitUtil
1300  {
1301  public:
1309  static std::string& bitOutput(char input, std::string &result);
1317  static std::string& bitOutput(const std::string &input, std::string &result);
1326  static char& bitOutput_bit(char input, const int pos, char &result);
1334  static unsigned long& bitStrToNumber(const std::string &input, unsigned long &result);
1344  static unsigned long& bitToNumber(const std::string &input, unsigned long &result);
1352  static char& toBit(const std::string &input, char &result);
1360  static std::string& toBit(const std::string &input, std::string &result);
1361  };
1366  {
1367  public:
1375  static long getRandomNumber(const long &a, const long &b);
1382  static std::string& getRandomStr_base64(std::string &str, const int &length);
1396  static std::string& generateMask_4(std::string &mask);
1397  };
1402  {
1403  public:
1415  static unsigned long& htonl_ntohl_64(unsigned long &data); // 64-bit unsigned number conversion to big/little endian (network byte order)
1416  };
1417 
1422  {
1423  public:
1424 
1433  static std::string& getPreciesFloat(const float &number, const int &bit, std::string &str);
1441  static float& getPreciesFloat(float &number, const int &bit);
1450  static std::string& getPreciesDouble(const double &number, const int &bit, std::string &str);
1458  static double& getPreciesDouble(double &number, const int &bit);
1470  static float& getValidFloat(float &number, const int &bit);
1471  };
1477  {
1478  public:
1495  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);
1506  static std::string_view& get_value_str(const std::string_view& ori_str, std::string_view &str, const std::string& name);
1515  static std::string_view& get_value_header(const std::string_view& ori_str, std::string_view &str, const std::string& name);
1525  static std::string_view& get_location_str(const std::string_view& ori_str, std::string_view &str);
1535  static std::string_view& getLocPara(const std::string_view &url, std::string_view &locPara);
1544  static std::string_view& getPara(const std::string_view &url, std::string_view &para);
1545 
1546 
1547 
1564  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);
1575  static std::string& get_value_str(const std::string& ori_str, std::string &str, const std::string& name);
1584  static std::string& get_value_header(const std::string& ori_str, std::string &str, const std::string& name);
1594  static std::string& get_location_str(const std::string& ori_str, std::string &str);
1604  static std::string& getLocPara(const std::string &url, std::string &locPara);
1613  static std::string& getPara(const std::string &url, std::string &para);
1624  static std::string& getIP(const std::string &url, std::string &IP);
1635  static int& getPort(const std::string &url, int &port);
1645  static std::string createHeader(const std::string& first, const std::string& second);
1666  template<class... Args>
1667  static std::string createHeader(const std::string& first, const std::string& second, Args... args)
1668  {
1669  std::string cf = first + ": " + second + "\r\n" + createHeader(args...);
1670  return cf;
1671  }
1672  };
1677  {
1678  public:
1690  static std::string& transfer_websocket_key(std::string &str);
1691  };
1696  {
1697  public:
1706  static int& toInt(const std::string_view&ori_str, int &result, const int &i = -1);
1713  static int& str16toInt(const std::string_view&ori_str, int &result,const int &i=-1);
1722  static long& toLong(const std::string_view&ori_str, long &result, const long &i = -1);
1731  static float& toFloat(const std::string&ori_str, float &result, const float &i = -1);
1740  static double& toDouble(const std::string&ori_str, double &result, const double &i = -1);
1748  static bool& toBool(const std::string_view&ori_str, bool &result);
1759  static std::string& strto16(const std::string &ori_str, std::string &result); // String to hexadecimal string (Not needed for now) (To be fixed)
1760  };
1765  {
1766  public:
1775  static std::string base64_encode(const std::string &input);
1784  static std::string base64_decode(const std::string &input);
1796  static std::string& transfer_websocket_key(std::string &str);
1810  static std::string& generateMask_4(std::string &mask);
1821  static std::string& maskCalculate(std::string &data, const std::string &mask);
1822  };
1827  {
1828  public:
1841  static int getValue(const std::string &oriStr,std::string& result,const std::string &type="value",const std::string &name="a",const int &num=0);
1842 
1848  static std::string toString(const Json::Value &val);
1854  static Json::Value toJsonArray(const std::string & str);
1864  template<class T1, class T2>
1865  static std::string createJson(T1 first, T2 second)
1866  {
1867  Json::Value root;
1868  //root[first] = second;
1869  if constexpr (std::is_integral_v<T2>) {
1870  root[first] = Json::Value(static_cast<Json::Int64>(second));
1871  } else {
1872  root[first] = second;
1873  }
1874  Json::StreamWriterBuilder builder;
1875  std::string jsonString = Json::writeString(builder, root);
1876  return jsonString;
1877  }
1889  template<class T1, class T2, class... Args>
1890  static std::string createJson(T1 first, T2 second, Args... args)
1891  {
1892  Json::Value root;
1893  //root[first] = second;
1894  if constexpr (std::is_integral_v<T2>) {
1895  root[first] = Json::Value(static_cast<Json::Int64>(second));
1896  } else {
1897  root[first] = second;
1898  }
1899  std::string kk = createJson(args...);
1900  Json::StreamWriterBuilder builder;
1901  std::string jsonString = Json::writeString(builder, root);
1902  jsonString = jsonString.erase(jsonString.length() - 2);
1903  kk = kk.substr(1);
1904  return jsonString + "," + kk;
1905 
1906  }
1914  template<class T>
1915  static std::string createArray(T first)
1916  {
1917  Json::Value root(Json::arrayValue);
1918  root.append(first);
1919  Json::StreamWriterBuilder builder;
1920  std::string jsonString = Json::writeString(builder, root);
1921  return jsonString;
1922  }
1932  template<class T, class... Args>
1933  static std::string createArray(T first, Args... args)
1934  {
1935  Json::Value root(Json::arrayValue);
1936  root.append(first);
1937  std::string kk = createArray(args...);
1938  Json::StreamWriterBuilder builder;
1939  std::string jsonString = Json::writeString(builder, root);
1940  jsonString = jsonString.erase(jsonString.length() - 2);
1941  kk = kk.substr(1);
1942  return jsonString + "," + kk;
1943 
1944  }
1951  static std::string jsonAdd(const std::string &a, const std::string &b);
1958  static std::string& jsonFormatify(const std::string &a, std::string &b);
1965  static std::string& jsonToUTF8(const std::string &input, std::string &output);
1966  };
1967  }
1968 
1972  namespace security
1973  {
2035 enum class RateLimitType
2036 {
2037  Cooldown, // Punishment-based: hit limit => cooldown, require quiet secs to recover
2038  FixedWindow, // Fixed window counter: each secs is a window, allow up to times
2039  SlidingWindow, // Sliding window: count events within the last secs (timestamp deque)
2040  TokenBucket // Token bucket: allow bursts + control long-term average rate
2041 };
2042 
2043 
2065 {
2066  // Common
2067  int counter = 0;
2068  int violations = 0;
2069  std::chrono::steady_clock::time_point lastTime{};
2070 
2071  // SlidingWindow
2072  std::deque<std::chrono::steady_clock::time_point> history;
2073 
2074  // TokenBucket
2075  double tokens = 0.0;
2076  std::chrono::steady_clock::time_point lastRefill{};
2077 };
2078 
2079 
2096 {
2097  int fd = -1;
2099  std::unordered_map<std::string, RateState> pathRate;
2100  std::chrono::steady_clock::time_point lastActivity{};
2101 };
2102 
2103 
2127 {
2128  int activeConnections = 0;
2130  int badScore = 0; // IP risk score used for escalation
2131  std::unordered_map<int, ConnectionState> conns; // fd -> state
2132 };
2133 
2134 
2156 {
2157  ALLOW = 0,
2158  DROP = 1,
2159  CLOSE = 2
2160 };
2161 
2162 
2243 {
2244 public:
2251  ConnectionLimiter(const int& maxConn = 20, const int& idleTimeout = 60)
2252  : maxConnections(maxConn), connectionTimeout(idleTimeout) {}
2253 
2254  // ========== Strategy configuration ==========
2255 
2262  void setConnectStrategy(const RateLimitType &type);
2263 
2270  void setRequestStrategy(const RateLimitType &type);
2271 
2278  void setPathStrategy(const RateLimitType &type);
2279 
2280  // ========== Path configuration ==========
2281 
2296  void setPathLimit(const std::string &path, const int &times, const int &secs);
2297 
2298  // ========== Core decisions ==========
2299 
2316  DefenseDecision allowConnect(const std::string &ip, const int &fd,
2317  const int &times, const int &secs);
2318 
2333  DefenseDecision allowRequest(const std::string &ip, const int &fd,
2334  const std::string_view &path,
2335  const int &times, const int &secs);
2336 
2337  // ========== Lifecycle ==========
2338 
2349  void clearIP(const std::string &ip, const int &fd);
2350 
2364  bool connectionDetect(const std::string &ip, const int &fd);
2400 void banIP(const std::string &ip,
2401  int banSeconds,
2402  const std::string &reasonCN,
2403  const std::string &reasonEN);
2409 void unbanIP(const std::string &ip);
2417 bool isBanned(const std::string &ip) const;
2418 
2419 
2420 private:
2421  // Core limiter primitive
2422  bool allow(RateState &st, const RateLimitType &type,
2423  const int &times, const int &secs,
2424  const std::chrono::steady_clock::time_point &now);
2425 
2426 private:
2427  int maxConnections;
2428  int connectionTimeout;
2429 
2430  RateLimitType connectStrategy = RateLimitType::Cooldown;
2431  RateLimitType requestStrategy = RateLimitType::SlidingWindow;
2432  RateLimitType pathStrategy = RateLimitType::SlidingWindow;
2433 
2434  std::unordered_map<std::string, IPInformation> table;
2435  std::unordered_map<std::string, std::pair<int,int>> pathConfig;
2436 
2437  // IP -> unban time
2438  std::unordered_map<std::string, std::chrono::steady_clock::time_point> blacklist;
2439 
2440  inline void logSecurity(const std::string &msgCN, const std::string &msgEN);
2441 };
2442 
2443  }
2444 
2450  namespace network
2451  {
2456  {
2457  protected:
2458  int fd = -1;
2459  bool flag1 = false;
2460  bool flag2 = false;
2461  SSL *ssl = nullptr;
2462  int sec=-1;
2463  public:
2467  bool flag3 = false;
2468  public:
2479  void setFD(const int &fd, SSL *ssl, const bool &flag1 = false, const bool &flag2 = false,const int &sec=-1);
2484  int getFD() { return fd; }
2489  SSL *getSSL() { return ssl; }
2494  void close(const bool &cle = true);
2499  void blockSet(const int &sec = -1);
2503  void unblockSet();
2507  bool multiUseSet();
2512  bool isConnect() { if (fd == -1) return false; else return true; }
2513  public:
2536  int sendData(const std::string &data, const bool &block = true);
2560  int sendData(const char *data, const uint64_t &length, const bool &block = true);
2576  int recvDataByLength(std::string &data, const uint64_t &length, const int &sec = 2);
2592  int recvDataByLength(char *data, const uint64_t &length, const int &sec = 2);
2605  int recvData(std::string &data, const uint64_t &length);
2618  int recvData(char *data, const uint64_t &length);
2619  };
2620 
2625  class TcpClient : public TcpFDHandler
2626  {
2627  private:
2628  std::string serverIP = "";
2629  int serverPort = -1;
2630  bool flag = false;
2631  bool TLS;
2632  SSL_CTX *ctx = nullptr;
2633  const char *ca;
2634  const char *cert;
2635  const char *key;
2636  const char *passwd;
2637  private:
2638  bool createFD();
2639  void closeAndUnCreate();
2640  bool initCTX(const char *ca, const char *cert = "", const char *key = "", const char *passwd = "");
2641  public:
2654  TcpClient(const bool &TLS = false, const char *ca = "", const char *cert = "", const char *key = "", const char *passwd = "");
2661  bool connect(const std::string &ip, const int &port);
2675  void resetCTX(const bool &TLS = false, const char *ca = "", const char *cert = "", const char *key = "", const char *passwd = "");
2680  bool close();
2684  ~TcpClient() { closeAndUnCreate(); }
2685  public:
2690  std::string getServerIP() { return serverIP; }
2695  int getServerPort() { return serverPort; }
2700  bool isConnect() { return flag; }
2701  };
2702 
2710  class HttpClient : private TcpClient
2711  {
2712  private:
2713  bool flag = false;
2714  public:
2727  HttpClient(const bool &TLS = false, const char *ca = "", const char *cert = "", const char *key = "", const char *passwd = "") : TcpClient(TLS, ca, cert, key, passwd) {}
2728  public:
2746  bool getRequest(const std::string &url, const std::string &header = "", const std::string &header1 = "Connection: keep-alive",const int &sec=-1);
2765  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);
2785  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);
2806  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);
2807  public:
2812  bool isReturn() { return flag; }
2816  std::string header = "";
2820  std::string body = "";
2821  };
2822 
2827  {
2828  private:
2829  int fd;
2830  bool flag = true;
2831  std::function<bool(const int &fd)> fc = [](const int &fd)->bool
2832  {return true;};
2833  std::function<void(const int &fd)> fcEnd = [](const int &fd)->void
2834  {};
2835  std::function<bool(const int &fd)> fcTimeOut = [](const int &fd)->bool
2836  {return true;};
2837  bool flag1 = true;
2838  bool flag2 = false;
2839  time::Duration dt{0,20,0,0,0};
2840  bool flag3 = false;
2841  time::Duration t;
2842  private:
2843  void epolll();
2844  public:
2851  void startListen(const int &fd, const bool &flag = true, const time::Duration &dt = time::Duration{0,0,20,0,0});
2852  public:
2857  bool isListen() { return flag2; }
2867  void setFunction(std::function<bool(const int &fd)> fc) { this->fc = fc; }
2875  void setEndFunction(std::function<void(const int &fd)> fcEnd) { this->fcEnd = fcEnd; };
2885  void setTimeOutFunction(std::function<bool(const int &fd)> fcTimeOut) { this->fcTimeOut = fcTimeOut; };
2891  bool endListen();
2896  void endListenWithSignal() { flag1 = false; }
2902  void waitAndQuit(const time::Duration &t = time::Duration{0,0,0,10,10}) { flag3 = true; this->t = t; }
2907  ~EpollSingle() { endListen(); }
2908  };
2909 
2915  class WebSocketClient : private TcpClient
2916  {
2917  private:
2918  bool flag4 = false;
2919  std::function<bool(const std::string &message, WebSocketClient &k)> fc = [](const std::string &message, WebSocketClient &k)->bool
2920  {std::cout<<"Received: "<<message<<std::endl;return true;};
2921  std::string url;
2922  EpollSingle k;
2923  bool flag5 = false;
2924  private:
2925  bool close1();
2926  public:
2939  WebSocketClient(const bool &TLS = false, const char *ca = "", const char *cert = "", const char *key = "", const char *passwd = "") : TcpClient(TLS, ca, cert, key, passwd) {}
2950  void setFunction(std::function<bool(const std::string &message, WebSocketClient &k)> fc) { this->fc = fc; }
2959  bool connect(const std::string &url, const int &min = 20);
2982  bool sendMessage(const std::string &message, const std::string &type = "0001");
2992  void close(const std::string &closeCodeAndMessage, const bool &wait = true);
3011  void close(const short &code = 1000, const std::string &message = "bye", const bool &wait = true);
3012  public:
3017  bool isConnect() { return flag4; }
3022  std::string getUrl() { return url; }
3027  std::string getServerIp() { return TcpClient::getServerIP(); }
3032  std::string getServerPort() { return TcpClient::getServerIP(); }
3036  ~WebSocketClient();
3037  };
3038 
3043  {
3047  int fd;
3055  std::string type;
3059  std::string locPara;
3063  std::string loc;
3067  std::string para;
3071  std::string header;
3075  std::string body;
3079  std::string body_chunked;
3083  std::unordered_map<std::string,std::any> ctx;
3084 
3085  };
3086 
3087  struct TcpFDInf;
3093  {
3094  public:
3102  void setFD(const int &fd, SSL *ssl = nullptr, const bool &flag1 = false, const bool &flag2 = true) { TcpFDHandler::setFD(fd, ssl, flag1, flag2); }
3118  int solveRequest(TcpFDInf &TcpInf,HttpRequestInformation &HttpInf,const unsigned long &buffer_size,const int &times=1);
3128  bool sendBack(const std::string &data, const std::string &header = "", const std::string &code = "200 OK", const std::string &header1 = "");
3142  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);
3143  };
3144 
3149  {
3153  int fd;
3165  std::string locPara;
3169  std::string header;
3173  time_t HBTime = 0;
3177  time_t response;
3181  size_t recv_length;
3193  std::string message="";
3197  bool fin;
3201  std::string mask;
3205  std::unordered_map<std::string,std::any> ctx;
3210  };
3211 
3212  enum class TLSState : uint8_t {
3213  NONE = 0, // 非 TLS 连接(普通 TCP)
3214  HANDSHAKING, // TLS 握手中(SSL_accept 还没完成)
3215  ESTABLISHED, // TLS 已建立,可以 SSL_read / SSL_write
3216  ERROR // TLS 出错(可选)
3217  };
3218 
3223  {
3227  int fd;
3235  std::string data;
3239  std::unordered_map<std::string,std::any> ctx;
3240  };
3241 
3245  struct TcpFDInf
3246  {
3250  int fd;
3258  std::string ip;
3262  std::string port;
3266  int status;
3270  std::string_view data;
3274  SSL* ssl;
3282  char *buffer;
3286  unsigned long p_buffer_now;
3294  std::queue<std::any> pendindQueue;
3295  };
3296 
3301  {
3305  int fd;
3309  int ret;
3310  };
3311 
3316  class TcpServer
3317  {
3318  protected:
3321  unsigned long buffer_size;
3322  unsigned long long maxFD;
3324  //std::unordered_map<int,TcpFDInf> clientfd;
3325  //std::mutex lc1;
3327  int flag1=true;
3328  //std::queue<QueueFD> *fdQueue;
3329  //std::mutex *lq1;
3330  //std::condition_variable cv1;
3331  //std::condition_variable *cv;
3332  //int consumerNum;
3333  //std::mutex lco1;
3334  bool unblock;
3335  SSL_CTX *ctx=nullptr;
3336  bool TLS=false;
3337  //std::unordered_map<int,SSL*> tlsfd;
3338  //std::mutex ltl1;
3340  //bool flag_detect;
3341  //bool flag_detect_status;
3343  int serverType; // 1 tcp 2 http 3 websocket
3350  private:
3351  std::function<void(const int &fd)> closeFun=[](const int &fd)->void
3352  {
3353 
3354  };
3355  std::function<void(TcpFDHandler &k,TcpInformation &inf)> securitySendBackFun=[](TcpFDHandler &k,TcpInformation &inf)->void
3356  {};
3357  std::function<bool(TcpFDHandler &k,TcpInformation &inf)> globalSolveFun=[](TcpFDHandler &k,TcpInformation &inf)->bool
3358  {return true;};
3359  std::unordered_map<std::string,std::vector<std::function<int(TcpFDHandler &k,TcpInformation &inf)>>> solveFun;
3360  std::function<int(TcpFDHandler &k,TcpInformation &inf)> parseKey=[](TcpFDHandler &k,TcpInformation &inf)->int
3361  {inf.ctx["key"]=inf.data;return 1;};
3362  int fd=-1;
3363  int port=-1;
3364  int flag=false;
3365  bool flag2=false;
3366  private:
3367  void epolll(const int &evsNum);
3368  //virtual void consumer(const int &threadID);
3369  virtual void handler_netevent(const int &fd);
3370  virtual void handler_workerevent(const int &fd,const int &ret);
3371  virtual void handleHeartbeat()=0;
3372  public:
3384  void putTask(const std::function<int(TcpFDHandler &k,TcpInformation &inf)> &fun,TcpFDHandler &k,TcpInformation &inf);
3466  const unsigned long long &maxFD = 1000000,
3467  const int &buffer_size = 256,
3468  const size_t &finishQueue_cap=65536,
3469  const bool &security_open = true,
3470  const int &connectionNumLimit = 20,
3471  const int &connectionSecs = 1,
3472  const int &connectionTimes = 6,
3473  const int &requestSecs = 1,
3474  const int &requestTimes = 40,
3475  const int &checkFrequency = 60,
3476  const int &connectionTimeout = 60
3477 )
3478 : maxFD(maxFD),
3479  buffer_size(buffer_size * 1024),
3480  finishQueue(finishQueue_cap),
3481  security_open(security_open),
3482  connectionSecs(connectionSecs),
3483  connectionTimes(connectionTimes),
3484  requestSecs(requestSecs),
3485  requestTimes(requestTimes),
3486  connectionLimiter(connectionNumLimit, connectionTimeout),
3487  checkFrequency(checkFrequency)
3488 {
3489  serverType = 1;
3490 }
3491 
3498  bool startListen(const int &port, const int &threads = 8);
3526  bool setTLS(const char *cert, const char *key, const char *passwd, const char *ca);
3530  void redrawTLS();
3562  std::function<void(TcpFDHandler &k,
3563  TcpInformation &inf)> fc
3564 )
3565 {
3566  this->securitySendBackFun = fc;
3567 }
3568 
3569 
3579  void setGlobalSolveFunction(std::function<bool(TcpFDHandler &k,TcpInformation &inf)> fc){this->globalSolveFun=fc;}
3604  const std::string &key,
3605  std::function<int(TcpFDHandler &k, TcpInformation &inf)> fc)
3606 {
3607  auto [it, inserted] = solveFun.try_emplace(key);
3608  it->second.push_back(std::move(fc));
3609 }
3610 
3632  std::function<int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
3633 {
3634  this->parseKey = parseKeyFun;
3635 }
3641  bool stopListen();
3648  bool close();
3654  virtual bool close(const int &fd);
3658  void setCloseFun(std::function<void(const int &fd)> closeFun){this->closeFun=closeFun;}
3659  public:
3664  bool isListen() { return flag; }
3669  SSL* getSSL(const int &fd);
3674  ~TcpServer() { close(); }
3675  };
3676 
3677 
3678 
3683  class HttpServer : public TcpServer
3684 {
3685 private:
3686  std::function<void(HttpServerFDHandler &k,HttpRequestInformation &inf)> securitySendBackFun=[](HttpServerFDHandler &k,HttpRequestInformation &inf)->void
3687  {};
3688  std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>> globalSolveFun;
3689  // std::function<bool(HttpServerFDHandler &k, HttpRequestInformation &inf)> globalSolveFun = {};
3690  std::unordered_map<
3691  std::string,
3692  std::vector<std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)>>
3693  > solveFun;
3694 
3695  std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKey =
3696  [](HttpServerFDHandler &k, HttpRequestInformation &inf) -> int {
3697  inf.ctx["key"] = inf.loc;
3698  return 1;
3699  };
3700  HttpRequestInformation *httpinf;
3701 
3702 private:
3703  void handler_netevent(const int &fd);
3704  void handler_workerevent(const int &fd, const int &ret);
3705  void handleHeartbeat(){}
3706 
3707 public:
3729  void putTask(
3730  const std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> &fun,
3733  );
3734 
3816  const unsigned long long &maxFD = 1000000,
3817  const int &buffer_size = 256,
3818  const size_t &finishQueue_cap=65536,
3819  const bool &security_open = true,
3820  const int &connectionNumLimit = 10,
3821  const int &connectionSecs = 1,
3822  const int &connectionTimes = 3,
3823  const int &requestSecs = 1,
3824  const int &requestTimes = 20,
3825  const int &checkFrequency = 30,
3826  const int &connectionTimeout = 30
3827 )
3828 : TcpServer(
3829  maxFD,
3830  buffer_size,
3831  finishQueue_cap,
3832  security_open,
3833  connectionNumLimit,
3834  connectionSecs,
3835  connectionTimes,
3836  requestSecs,
3837  requestTimes,
3838  checkFrequency,
3839  connectionTimeout
3840  )
3841 {
3842  serverType = 2;
3843 }
3874  std::function<void(HttpServerFDHandler &k,
3875  HttpRequestInformation &inf)> fc
3876 )
3877 {
3878  this->securitySendBackFun = fc;
3879 }
3880 
3896  void setGlobalSolveFunction(std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc){globalSolveFun.push_back(std::move(fc));}
3945  const std::string &key,
3946  std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc
3947  )
3948  {
3949  auto [it, inserted] = solveFun.try_emplace(key);
3950  it->second.push_back(std::move(fc));
3951  }
3952 
3983  std::function<int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKeyFun
3984  )
3985  {
3986  this->parseKey = parseKeyFun;
3987  }
3988 
3996  bool startListen(const int &port, const int &threads = 8)
3997  {
3998  httpinf = new HttpRequestInformation[maxFD];
3999  return TcpServer::startListen(port, threads);
4000  }
4001 
4005  ~HttpServer() {delete[] httpinf;}
4006 };
4007 
4013  {
4014  public:
4022  void setFD(const int &fd, SSL *ssl = nullptr, const bool &flag1 = false, const bool &flag2 = true) { TcpFDHandler::setFD(fd, ssl, flag1, flag2); }
4045  int getMessage(TcpFDInf &Tcpinf,WebSocketFDInformation &Websocketinf,const unsigned long &buffer_size,const int &ii=1);
4060  bool sendMessage(const std::string &msg, const std::string &type = "0001");
4061 
4062  };
4063 
4068 {
4069 private:
4070  std::unordered_map<int, WebSocketFDInformation> wbclientfd;
4071  std::function<void(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> securitySendBackFun=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->void
4072  {};
4073 
4074  std::function<bool(WebSocketFDInformation &k)> fcc =
4075  [](WebSocketFDInformation &k) {
4076  return true;
4077  };
4078 
4079  std::function<bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fccc =
4081  {return true;};
4082 
4083  std::function<bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> globalSolveFun =
4084  [](WebSocketServerFDHandler &k, WebSocketFDInformation &inf) -> bool {
4085  return true;
4086  };
4087 
4088  std::unordered_map<
4089  std::string,
4090  std::vector<std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)>>>
4091  solveFun;
4092 
4093  std::function<int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> parseKey =
4094  [](WebSocketServerFDHandler &k, WebSocketFDInformation &inf) -> int {
4095  inf.ctx["key"] = inf.message;
4096  return 1;
4097  };
4098 
4099  int seca = 20 * 60; // heartbeat interval (seconds)
4100  int secb = 30; // heartbeat response timeout (seconds)
4101 
4102 
4103 
4104 private:
4105  void handler_netevent(const int &fd);
4106  void handler_workerevent(const int &fd, const int &ret);
4107 
4108  void closeAck(const int &fd, const std::string &closeCodeAndMessage);
4109  void closeAck(const int &fd, const short &code = 1000, const std::string &message = "bye");
4110 
4111 
4112 
4113  void handleHeartbeat();
4114 
4115  bool closeWithoutLock(const int &fd, const std::string &closeCodeAndMessage);
4116  bool closeWithoutLock(const int &fd, const short &code = 1000, const std::string &message = "bye");
4117 
4118 public:
4135  void putTask(
4136  const std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)> &fun,
4138  WebSocketFDInformation &inf);
4139 
4222  const unsigned long long &maxFD = 1000000,
4223  const int &buffer_size = 256,
4224  const size_t &finishQueue_cap=65536,
4225  const bool &security_open = true,
4226  const int &connectionNumLimit = 5,
4227  const int &connectionSecs = 10,
4228  const int &connectionTimes = 3,
4229  const int &requestSecs = 1,
4230  const int &requestTimes = 10,
4231  const int &checkFrequency = 60,
4232  const int &connectionTimeout = 120
4233 )
4234 : TcpServer(
4235  maxFD,
4236  buffer_size,
4237  finishQueue_cap,
4238  security_open,
4239  connectionNumLimit,
4240  connectionSecs,
4241  connectionTimes,
4242  requestSecs,
4243  requestTimes,
4244  checkFrequency,
4245  connectionTimeout
4246  )
4247 {
4248  serverType = 3;
4249 }
4280  std::function<void(WebSocketServerFDHandler &k,
4281  WebSocketFDInformation &inf)> fc
4282 )
4283 {
4284  this->securitySendBackFun = fc;
4285 }
4286 
4287 
4300  std::function<bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
4301  {
4302  this->globalSolveFun = fc;
4303  }
4304 
4313  std::function<bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fccc)
4314  {
4315  this->fccc = fccc;
4316  }
4317 
4328  void setJudgeFunction(std::function<bool(WebSocketFDInformation &)> fcc)
4329  {
4330  this->fcc = fcc;
4331  }
4332 
4347  const std::string &key,
4348  std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
4349  {
4350  auto [it, inserted] = solveFun.try_emplace(key);
4351  it->second.push_back(std::move(fc));
4352  }
4353 
4360  std::function<int(WebSocketServerFDHandler &, WebSocketFDInformation &)> parseKeyFun)
4361  {
4362  this->parseKey = parseKeyFun;
4363  }
4364 
4369  void setTimeOutTime(const int &seca)
4370  {
4371  this->seca = seca * 60;
4372  }
4373 
4379  void setHBTimeOutTime(const int &secb)
4380  {
4381  this->secb = secb;
4382  }
4383 
4391  bool closeFD(const int &fd, const std::string &closeCodeAndMessage);
4392 
4400  bool closeFD(const int &fd, const short &code = 1000, const std::string &message = "bye");
4401 
4410  const int &fd,
4411  const std::string &msg,
4412  const std::string &type = "0001")
4413  {
4415  k.setFD(fd, getSSL(fd), unblock);
4416  return k.sendMessage(msg, type);
4417  }
4418 
4423  bool close();
4428  bool close(const int &fd);
4434  bool startListen(const int &port, const int &threads = 8)
4435  {
4436  //std::thread(&WebSocketServer::HB, this).detach();
4437  return TcpServer::startListen(port, threads);
4438  }
4439 
4445  void sendMessage(const std::string &msg, const std::string &type = "0001");
4446 
4453  {
4454 
4455  }
4456 };
4457 
4458 
4464  {
4465  protected:
4466  int fd = -1;
4467  bool flag1 = false;
4468  bool flag2 = false;
4469  int sec = -1;
4470  public:
4478  void setFD(const int &fd, const bool &flag1 = false, const int &sec = -1, const bool &flag2 = false);
4483  void blockSet(const int &sec = -1);
4487  void unblockSet();
4492  bool multiUseSet();
4496  int getFD() { return fd; }
4501  void close(const bool &cle = true);
4522  int sendData(const std::string &data, const std::string &ip, const int &port, const bool &block = true);
4543  int sendData(const char *data, const uint64_t &length, const std::string &ip, const int &port, const bool &block = true);
4558  int recvData(std::string &data, const uint64_t &length, std::string &ip, int &port);
4573  int recvData(char *data, const uint64_t &length, std::string &ip, int &port);
4574 
4575  };
4579  class UdpClient : public UdpFDHandler
4580  {
4581  public:
4587  UdpClient(const bool &flag1 = false, const int &sec = -1);
4593  bool createFD(const bool &flag1 = false, const int &sec = -1);
4597  ~UdpClient() { close(); }
4598  };
4602  class UdpServer : public UdpFDHandler
4603  {
4604  public:
4612  UdpServer(const int &port, const bool &flag1 = false, const int &sec = -1, const bool &flag2 = true);
4619  bool createFD(const int &port, const bool &flag1 = false, const int &sec = -1, const bool &flag2 = true);
4623  ~UdpServer() { close(); }
4624  };
4625  }
4631  namespace system
4632  {
4642  {
4643  public:
4651  static std::string language;
4652  private:
4653  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);}
4654  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);}
4655  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);}
4656  public:
4665  static void setExceptionHandling();
4675  static void setLogFile(file::LogFile *logfile = nullptr, const std::string &language = "");
4682  static void init(file::LogFile *logfile = nullptr, const std::string &language = "");
4683  };
4684 
4693  class csemp
4694  {
4695  private:
4701  union semun
4702  {
4703  int val;
4704  struct semid_ds *buf;
4705  unsigned short *arry;
4706  };
4707 
4708  int m_semid;
4709  short m_sem_flg;
4710 
4711  csemp(const csemp &) = delete;
4712  csemp &operator=(const csemp &) = delete;
4713 
4714  public:
4718  csemp():m_semid(-1){}
4719 
4730  bool init(key_t key, unsigned short value = 1, short sem_flg = SEM_UNDO);
4731 
4740  bool wait(short value = -1);
4741 
4750  bool post(short value = 1);
4751 
4757  int getvalue();
4758 
4766  bool destroy();
4767 
4771  ~csemp();
4772  };
4773 
4777  #define MAX_PROCESS_NAME 100
4778 
4781  #define MAX_PROCESS_INF 1000
4782 
4785  #define SHARED_MEMORY_KEY 0x5095
4786 
4789  #define SHARED_MEMORY_LOCK_KEY 0x5095
4790 
4794  struct ProcessInf
4795  {
4799  pid_t pid;
4803  time_t lastTime;
4807  char name[MAX_PROCESS_NAME];
4811  char argv0[20];
4815  char argv1[20];
4819  char argv2[20];
4820  };
4821 
4829  class HBSystem
4830  {
4831  private:
4832 
4833  static ProcessInf *p;
4834  static csemp plock;
4835  static bool isJoin;
4836  public:
4845  bool join(const char *name, const char *argv0 = "", const char *argv1 = "", const char *argv2 = "");
4850  bool renew();
4854  static void list();
4861  static bool HBCheck(const int &sec);
4866  bool deleteFromHBS();
4871  ~HBSystem();
4872  };
4873 
4877  class Process
4878  {
4879  public:
4880 
4881 
4902  template<class... Args>
4903  static bool startProcess(const std::string &name, const int &sec = -1, Args ...args)
4904  {
4905  std::vector<const char *> paramList={args...,nullptr};
4906  if(sec==-1)
4907  {
4908  pid_t pid=fork();
4909  if(pid==-1)
4910  return false;
4911  if(pid>0)
4912  return true;
4913  else
4914  {
4915  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4916  return false;
4917  }
4918  }
4919  for(int ii=1;ii<=64;ii++)
4920  signal(ii,SIG_IGN);
4921  pid_t pid=fork();
4922  if(pid==-1)
4923  return false;
4924  if(pid>0)
4925  {
4926  return true;
4927  }
4928  else
4929  {
4930  signal(SIGCHLD,SIG_DFL);
4931  signal(15,SIG_DFL);
4932  while(1)
4933  {
4934  pid=fork();
4935  if(fork()==0)
4936  {
4937  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4938  exit(0);
4939  }
4940  else if(pid>0)
4941  {
4942  int sts;
4943  wait(&sts);
4944  sleep(sec);
4945  }
4946  else
4947  continue;
4948  }
4949  }
4950  }
4972  template<class Fn, class... Args>
4973  static typename std::enable_if<!std::is_convertible<Fn, std::string>::value, bool>::type
4974  startProcess(Fn&& fn, const int &sec = -1, Args &&...args)
4975  {
4976  if(sec==-1)
4977  {
4978  pid_t pid=fork();
4979  if(pid==-1)
4980  return false;
4981  if(pid>0)
4982  return true;
4983  else
4984  {
4985  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4986  f();
4987  return true;
4988  }
4989  }
4990  for(int ii=1;ii<=64;ii++)
4991  signal(ii,SIG_IGN);
4992  pid_t pid=fork();
4993  if(pid==-1)
4994  return false;
4995  if(pid>0)
4996  {
4997  return true;
4998  }
4999  else
5000  {
5001  signal(SIGCHLD,SIG_DFL);
5002  signal(15,SIG_DFL);
5003  while(1)
5004  {
5005  pid=fork();
5006  if(pid==0)
5007  {
5008  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
5009  f();
5010  return true;
5011  }
5012  else if(pid>0)
5013  {
5014  int sts;
5015  wait(&sts);
5016  sleep(sec);
5017  }
5018  else
5019  continue;
5020  }
5021  }
5022  }
5023  };
5024 
5025  using Task = std::function<void()>;
5051  class WorkerPool
5052  {
5053  public:
5061  explicit WorkerPool(size_t n):stop_(false)
5062  {
5063  for (size_t i = 0; i < n; ++i) {
5064  threads_.emplace_back([this] {
5065  this->workerLoop();
5066  });
5067  }
5068  }
5076  {
5077  stop();
5078  }
5086  void submit(Task task)
5087  {
5088  {
5089  std::lock_guard<std::mutex> lk(mtx_);
5090  tasks_.push(std::move(task));
5091  }
5092  cv_.notify_one();
5093  }
5104  void stop()
5105  {
5106  {
5107  std::lock_guard<std::mutex> lk(mtx_);
5108  stop_ = true;
5109  }
5110  cv_.notify_all();
5111  for (auto &t : threads_)
5112  {
5113  if (t.joinable()) t.join();
5114  }
5115  }
5116 
5117  private:
5128  void workerLoop()
5129  {
5130  while (true)
5131  {
5132  Task task;
5133  {
5134  std::unique_lock<std::mutex> lk(mtx_);
5135  cv_.wait(lk, [this] {
5136  return stop_ || !tasks_.empty();
5137  });
5138  if (stop_ && tasks_.empty())
5139  {
5140  return;
5141  }
5142  task = std::move(tasks_.front());
5143  tasks_.pop();
5144  }
5145  task(); // perform tasks
5146  }
5147  }
5148 
5149  private:
5150  std::vector<std::thread> threads_;
5151  std::queue<Task> tasks_;
5152  std::mutex mtx_;
5153  std::condition_variable cv_;
5154  bool stop_;
5155  };
5156  }
5157 
5158 
5159 }
5160 
5161 
5162 #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:3873
time_t response
Time of last received message.
Definition: sttnet_English.h:3177
Unified connection &amp; request security gate (IP-level + fd-level, multi-strategy limiting + blacklist)...
Definition: sttnet_English.h:2242
std::chrono::duration< uint64_t > Seconds
Definition: sttnet_English.h:1008
bool operator>(const Duration &b)
Determine if the current time interval is greater than another time interval.
Definition: sttnet_English.h:740
int getServerPort()
Return the port of the connected client.
Definition: sttnet_English.h:2695
int fd
Low-level sockets.
Definition: sttnet_English.h:3305
SSL * getSSL()
Get the encrypted SSL handle of this object.
Definition: sttnet_English.h:2489
Definition: sttnet_English.h:2157
int checkFrequency
Definition: sttnet_English.h:3348
bool isStart()
Return the timing status of the object.
Definition: sttnet_English.h:1114
bool fin
state of fin
Definition: sttnet_English.h:3197
std::string header
Http/Https request header during the handshake phase.
Definition: sttnet_English.h:3169
TcpFDInf * clientfd
Definition: sttnet_English.h:3326
std::string getServerIp()
Return the server ip if connected to the server.
Definition: sttnet_English.h:3027
bool unblock
Definition: sttnet_English.h:3334
int ret
Return value -2: Failure and connection closed required; -1: Failure but connection closed not requir...
Definition: sttnet_English.h:3309
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:3102
TCP socket operation class.
Definition: sttnet_English.h:2455
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:1890
A structure representing a time interval, supporting granularity in days, hours, minutes, seconds, and milliseconds.
Definition: sttnet_English.h:708
void setGlobalSolveFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
Sets a global backup function.
Definition: sttnet_English.h:3896
WebSocket protocol operation class Only pass in the socket, then use this class for WebSocket operati...
Definition: sttnet_English.h:4012
bool isConnect()
Determine if the object has a socket bound.
Definition: sttnet_English.h:2512
Class for time operations, calculations, and timing.
Definition: sttnet_English.h:1025
int getFD()
Get the socket of this object.
Definition: sttnet_English.h:2484
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:2902
bool operator<=(const Duration &b)
Determine if the current time interval is less than or equal to another time interval.
Definition: sttnet_English.h:804
Http/HttpServer server operation class.
Definition: sttnet_English.h:3683
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:4409
void setCloseFun(std::function< void(const int &fd)> closeFun)
set function after tcp connection close
Definition: sttnet_English.h:3658
std::string body_chunked
Request body (chunked)
Definition: sttnet_English.h:3079
Data structure for pushing tasks into a completion queue after they are completed at the work site...
Definition: sttnet_English.h:3300
pid_t pid
Process ID.
Definition: sttnet_English.h:4799
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:2939
Duration(long long a, int b, int c, int d, int e)
Constructor, taking days, hours, minutes, seconds, milliseconds.
Definition: sttnet_English.h:733
int getFD()
Return fd.
Definition: sttnet_English.h:4496
Security state and connection set for a single IP.
Definition: sttnet_English.h:2126
std::string body
Request body.
Definition: sttnet_English.h:3075
std::string loc
The file path.
Definition: sttnet_English.h:302
unsigned long p_buffer_now
Receives a spatial position pointer.
Definition: sttnet_English.h:3286
bool isConnect()
Return the connection status of the object.
Definition: sttnet_English.h:2700
MPSCQueue & operator=(const MPSCQueue &)=delete
std::ostream & operator<<(std::ostream &os, const Duration &a)
Output the Duration object to a stream in a readable format.
LogFile(const size_t &logQueue_cap=8192)
Constructor, initializes the consumer thread.
Definition: sttnet_English.h:1161
int sec
Seconds.
Definition: sttnet_English.h:725
~TcpServer()
Destructor of TcpServer class.
Definition: sttnet_English.h:3674
double convertToMin()
Convert the current time interval to a floating-point representation in minutes.
Definition: sttnet_English.h:927
int fd
Low-level socket.
Definition: sttnet_English.h:3047
unsigned long buffer_size
Definition: sttnet_English.h:3321
std::string getServerPort()
Return the server port if connected to the server.
Definition: sttnet_English.h:3032
unsigned long long maxFD
Definition: sttnet_English.h:3322
int serverType
Definition: sttnet_English.h:3343
#define ISO8086A
Define the macro ISO8086A as &quot;yyyy-mm-ddThh:mi:ss&quot;.
Definition: sttnet_English.h:1012
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:2885
Duration recoverForm(const long long &t)
Recover the standard days-hours-minutes-seconds-milliseconds format from given milliseconds.
Definition: sttnet_English.h:958
static std::string createArray(T first)
Create a JSON array string containing only one element.
Definition: sttnet_English.h:1915
std::queue< std::any > pendindQueue
Queue waiting to be processed.
Definition: sttnet_English.h:3294
Responsible for conversion between strings and numbers.
Definition: sttnet_English.h:1695
~EpollSingle()
Destructor of EpollSingle Calls eldListen to block and exit epoll.
Definition: sttnet_English.h:2907
int threads
Records how many threads are currently using the file.
Definition: sttnet_English.h:306
std::string para
parameters in url
Definition: sttnet_English.h:3067
static std::string language
Language selection for the system&#39;s logging system, default is English.
Definition: sttnet_English.h:4651
Class responsible for process heartbeat monitoring and scheduling Used to monitor service processes a...
Definition: sttnet_English.h:4829
std::deque< std::chrono::steady_clock::time_point > history
Definition: sttnet_English.h:2072
size_t getFileSize()
Get the size of the file opened in binary mode.
Definition: sttnet_English.h:446
Definition: sttnet_English.h:2159
Tcp server class.
Definition: sttnet_English.h:3316
uint64_t connection_obj_fd
connection objection fd
Definition: sttnet_English.h:3254
stt::system::WorkerPool * workpool
Definition: sttnet_English.h:3320
static std::string createArray(T first, Args...args)
Create a JSON array string composed of multiple elements (recursive variadic template).
Definition: sttnet_English.h:1933
static std::mutex l1
Definition: sttnet_English.h:328
std::string port
Client port.
Definition: sttnet_English.h:3262
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:4346
UDP operation class Pass in the socket for UDP protocol operations.
Definition: sttnet_English.h:4463
int requestTimes
Definition: sttnet_English.h:3347
size_t getSize1()
Get the size of the file opened in binary mode in memory.
Definition: sttnet_English.h:455
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:4974
uint64_t connection_obj_fd
Definition: sttnet_English.h:3349
~File()
Destructor.
Definition: sttnet_English.h:413
std::string loc
path in url
Definition: sttnet_English.h:3063
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:2727
bool push(const T &v) noexcept(std::is_nothrow_copy_constructible_v< T >)
Definition: sttnet_English.h:132
WebSocketServer server operation class.
Definition: sttnet_English.h:4067
std::string locPara
Http/Https path and parameters during the handshake phase.
Definition: sttnet_English.h:3165
Operation class for parsing and responding to Http/https requests Only pass in the socket...
Definition: sttnet_English.h:3092
void setGlobalSolveFunction(std::function< bool(TcpFDHandler &k, TcpInformation &inf)> fc)
Set global fallback function.
Definition: sttnet_English.h:3579
bool operator<(const Duration &b)
Determine if the current time interval is less than another time interval.
Definition: sttnet_English.h:756
bool isConnect()
Return the connection status.
Definition: sttnet_English.h:3017
Responsible for encryption, decryption, and hashing.
Definition: sttnet_English.h:1244
Responsible for floating-point precision processing.
Definition: sttnet_English.h:1421
void stop()
Stop the thread pool and wait for all threads to exit.
Definition: sttnet_English.h:5104
SSL_CTX * ctx
Definition: sttnet_English.h:3335
Responsible for conversion between binary data and strings.
Definition: sttnet_English.h:1299
class of solving json data
Definition: sttnet_English.h:1826
bool push(T &&v) noexcept(std::is_nothrow_move_constructible_v< T >)
Try push (non-blocking). Returns false if queue is full. 尝试入队(非阻塞),队列满则返回 false.
Definition: sttnet_English.h:128
std::unordered_map< std::string, std::any > ctx
required data warehouse
Definition: sttnet_English.h:3239
~HttpServer()
Destructor.
Definition: sttnet_English.h:4005
uint64_t connection_obj_fd
connection objection fd
Definition: sttnet_English.h:3051
int connectionTimes
Definition: sttnet_English.h:3345
MPSCQueue(std::size_t capacity_pow2)
Definition: sttnet_English.h:96
std::unordered_map< std::string, RateState > pathRate
Definition: sttnet_English.h:2099
Structure for process information.
Definition: sttnet_English.h:4794
static std::unordered_map< std::string, FileThreadLock > fl2
Definition: sttnet_English.h:329
std::size_t approx_size() const noexcept
Approximate size (may be inaccurate under concurrency) 近似长度(并发下可能不精确)
Definition: sttnet_English.h:170
TCP client operation class.
Definition: sttnet_English.h:2625
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:1476
double convertToHour()
Convert the current time interval to a floating-point representation in hours.
Definition: sttnet_English.h:917
void setGetKeyFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKeyFun)
Set the callback function used to parse the key.
Definition: sttnet_English.h:3982
csemp()
Constructor, initializes internal state.
Definition: sttnet_English.h:4718
time_t lastTime
Last heartbeat time of the process, as a timestamp.
Definition: sttnet_English.h:4803
long long day
Days.
Definition: sttnet_English.h:713
void setGetKeyFunction(std::function< int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
Set the callback function used to parse the key.
Definition: sttnet_English.h:3631
void setGlobalSolveFunction(std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fc)
Set the global fallback handler.
Definition: sttnet_English.h:4299
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:3561
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:3603
std::mutex lock
The lock for this file.
Definition: sttnet_English.h:310
int min
Minutes.
Definition: sttnet_English.h:721
void endListenWithSignal()
Send a signal to end epoll.
Definition: sttnet_English.h:2896
Structure to save HTTP/HTTPS request information.
Definition: sttnet_English.h:3042
std::unordered_map< std::string, std::any > ctx
required data warehouse
Definition: sttnet_English.h:3205
WorkerPool(size_t n)
Constructor, creates a specified number of worker threads.
Definition: sttnet_English.h:5061
void setStartFunction(std::function< bool(WebSocketServerFDHandler &, WebSocketFDInformation &)> fccc)
Set the callback invoked immediately after a WebSocket connection is established. ...
Definition: sttnet_English.h:4312
Lock-free bounded MPSC queue (Multi-Producer Single-Consumer) 无锁有界多生产者单消费者队列(环形缓冲) ...
Definition: sttnet_English.h:94
WebSocketServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const size_t &finishQueue_cap=65536, 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:4221
RateState connectRate
Definition: sttnet_English.h:2129
double convertToSec()
Convert the current time interval to a floating-point representation in seconds.
Definition: sttnet_English.h:937
std::chrono::duration< uint64_t, std::milli > Milliseconds
Definition: sttnet_English.h:1007
std::string getUrl()
Return the url if connected to the server.
Definition: sttnet_English.h:3022
static file::LogFile * logfile
Pointer to the log file object for reading and writing logs in the system.
Definition: sttnet_English.h:4647
TLSState
Definition: sttnet_English.h:3212
size_t recv_length
Length to be received.
Definition: sttnet_English.h:3181
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:1667
time::Duration operator+(const time::Duration &b)
Add two time intervals.
Definition: sttnet_English.h:820
Listen to a single handle with epoll.
Definition: sttnet_English.h:2826
int workerEventFD
Definition: sttnet_English.h:3342
int FDStatus
Record which step the current state machine is at.
Definition: sttnet_English.h:3290
std::string header
Request header.
Definition: sttnet_English.h:3071
~WorkerPool()
destructor
Definition: sttnet_English.h:5075
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:4279
bool sendMessage(const std::string &msg, const std::string &type="0001")
Send a websocket message.
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:4022
int connectionSecs
Definition: sttnet_English.h:3344
FileThreadLock(const std::string &loc, const int &threads)
The constructor of this structure.
Definition: sttnet_English.h:316
bool operator>=(const Duration &b)
Determine if the current time interval is greater than or equal to another time interval.
Definition: sttnet_English.h:788
Structure to save client WS/WSS request information.
Definition: sttnet_English.h:3148
std::string getFileName()
Get the name of the opened file.
Definition: sttnet_English.h:428
~TcpClient()
Destructor of TcpClient, closes and releases the socket and its connection.
Definition: sttnet_English.h:2684
void setGetKeyFunction(std::function< int(WebSocketServerFDHandler &, WebSocketFDInformation &)> parseKeyFun)
Set the key parsing callback.
Definition: sttnet_English.h:4359
void setEndFunction(std::function< void(const int &fd)> fcEnd)
Set the callback function before epoll exits Register a callback function.
Definition: sttnet_English.h:2875
bool pop(T &out) noexcept(std::is_nothrow_move_assignable_v< T > &&std::is_nothrow_move_constructible_v< T >)
Try pop (single consumer). Returns false if empty. 尝试出队(单消费者),空则返回 false.
Definition: sttnet_English.h:140
Responsible for string operations related to the WebSocket protocol.
Definition: sttnet_English.h:1676
Duration getDt()
Get the last timing duration.
Definition: sttnet_English.h:1109
Data encoding/decoding, mask processing, etc.
Definition: sttnet_English.h:1764
std::function< void()> Task
Definition: sttnet_English.h:5025
~UdpServer()
Destructor, closes the socket when the object&#39;s life ends.
Definition: sttnet_English.h:4623
bool startListen(const int &port, const int &threads=8)
Start the HTTP server listening loop.
Definition: sttnet_English.h:3996
Save TCP client information.
Definition: sttnet_English.h:3222
bool operator==(const Duration &b)
Determine if the current time interval is equal to another time interval.
Definition: sttnet_English.h:772
Runtime state for one limiter key (reused by multiple strategies).
Definition: sttnet_English.h:2064
int message_type
Message type.
Definition: sttnet_English.h:3189
std::unordered_map< std::string, std::any > ctx
required data warehouse
Definition: sttnet_English.h:3083
char * buffer
Receives the space pointer.
Definition: sttnet_English.h:3282
A structure that records the relationship between files and threads.
Definition: sttnet_English.h:297
int fd
socket fd
Definition: sttnet_English.h:3227
int status
The current fd status, used to save the processor logic.
Definition: sttnet_English.h:3266
void writeLog(const std::string &data)
Write a line of log.
std::string locPara
Path and parameters in URL.
Definition: sttnet_English.h:3059
void setJudgeFunction(std::function< bool(WebSocketFDInformation &)> fcc)
Set the handshake validation callback.
Definition: sttnet_English.h:4328
#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:4777
Class for initializing the service system.
Definition: sttnet_English.h:4641
~UdpClient()
Destructor, closes the socket when the object&#39;s life ends.
Definition: sttnet_English.h:4597
std::string data
Naked data.
Definition: sttnet_English.h:3235
uint64_t getFileLine()
Get the number of lines in the opened file.
Definition: sttnet_English.h:437
bool isOpen()
Check if the object has opened a file.
Definition: sttnet_English.h:418
bool isReturn()
Get the server response status.
Definition: sttnet_English.h:2812
int requestSecs
Definition: sttnet_English.h:3346
std::string_view data
Save the data received from the client.
Definition: sttnet_English.h:3270
Security and limiter state for a single connection (fd).
Definition: sttnet_English.h:2095
RateState requestRate
Definition: sttnet_English.h:2098
std::string type
Request type.
Definition: sttnet_English.h:3055
TLSState tls_state
tls state
Definition: sttnet_English.h:3278
uint64_t connection_obj_fd
connection objection fd
Definition: sttnet_English.h:3231
Websocket client operation class.
Definition: sttnet_English.h:2915
bool isBinary()
Check if the object has opened the file in binary mode.
Definition: sttnet_English.h:423
std::string getServerIP()
Return the IP of the connected server.
Definition: sttnet_English.h:2690
uint64_t connection_obj_fd
connection objection fd
Definition: sttnet_English.h:3157
void submit(Task task)
Submit a task to the thread pool.
Definition: sttnet_English.h:5086
Synchronization tool class encapsulating System V semaphores.
Definition: sttnet_English.h:4693
std::string mask
mask
Definition: sttnet_English.h:3201
~MPSCQueue()
Definition: sttnet_English.h:118
RateLimitType
Rate limiting algorithm / strategy type.
Definition: sttnet_English.h:2035
Responsible for endianness conversion.
Definition: sttnet_English.h:1401
time::Duration operator-(const time::Duration &b)
Calculate the difference between two time intervals (current object minus parameter b)...
Definition: sttnet_English.h:864
~WebSocketServer()
Destructor.
Definition: sttnet_English.h:4452
TcpServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const size_t &finishQueue_cap=65536, 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:3465
std::mutex che
Definition: sttnet_English.h:331
bool startListen(const int &port, const int &threads=8)
Start the WebSocket server.
Definition: sttnet_English.h:4434
std::string getFileName()
Get the file name opened by the object.
Definition: sttnet_English.h:1203
Udp server operation class.
Definition: sttnet_English.h:4602
double convertToDay()
Convert the current time interval to a floating-point representation in days.
Definition: sttnet_English.h:907
bool isListen()
Return epoll listening status.
Definition: sttnet_English.h:2857
Http/Https client operation class.
Definition: sttnet_English.h:2710
bool closeflag
true: Close frame sent, false: Close frame not sent
Definition: sttnet_English.h:3161
int fd
Socket file descriptor.
Definition: sttnet_English.h:3250
size_t have_recv_length
Length have received.
Definition: sttnet_English.h:3185
bool security_open
Definition: sttnet_English.h:3339
HttpRequestInformation httpinf
http information in handshake stage
Definition: sttnet_English.h:3209
Static utility class for process management.
Definition: sttnet_English.h:4877
int hour
Hours.
Definition: sttnet_English.h:717
long long convertToMsec()
Convert the current time interval to total milliseconds.
Definition: sttnet_English.h:947
void setFunction(std::function< bool(const int &fd)> fc)
Set the processing function after epoll triggering Register a callback function.
Definition: sttnet_English.h:2867
Udp client operation class.
Definition: sttnet_English.h:4579
static std::string createJson(T1 first, T2 second)
Create a JSON string containing only one key-value pair.
Definition: sttnet_English.h:1865
Structure to save TCP client information.
Definition: sttnet_English.h:3245
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:3944
security::ConnectionLimiter connectionLimiter
Definition: sttnet_English.h:3323
std::string ip
Client IP.
Definition: sttnet_English.h:3258
bool isOpen()
Get the status of whether the log file is open.
Definition: sttnet_English.h:1198
DefenseDecision
Security decision returned by ConnectionLimiter.
Definition: sttnet_English.h:2155
int fd
Underlying socket descriptor.
Definition: sttnet_English.h:3153
void setHBTimeOutTime(const int &secb)
Set heartbeat response timeout.
Definition: sttnet_English.h:4379
A utility class that provides static functions for file operations.
Definition: sttnet_English.h:255
ConnectionLimiter(const int &maxConn=20, const int &idleTimeout=60)
Constructor.
Definition: sttnet_English.h:2251
Log file operation class.
Definition: sttnet_English.h:1124
A class for reading and writing disk files.
Definition: sttnet_English.h:325
int msec
Milliseconds.
Definition: sttnet_English.h:729
Related to random number and string generation.
Definition: sttnet_English.h:1365
SSL * ssl
If encrypted, store the encryption handle.
Definition: sttnet_English.h:3274
bool isListen()
Return the listening status of the object.
Definition: sttnet_English.h:3664
Definition: sttnet_English.h:2158
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:4903
void setTimeOutTime(const int &seca)
Set heartbeat interval.
Definition: sttnet_English.h:4369
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:2950
HttpServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const size_t &finishQueue_cap=65536, 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:3815
system::MPSCQueue< WorkerMessage > finishQueue
Definition: sttnet_English.h:3319
Fixed-size worker thread pool.
Definition: sttnet_English.h:5051
std::unordered_map< int, ConnectionState > conns
Definition: sttnet_English.h:2131