STTNet
 全部  命名空间 文件 函数 变量 类型定义 枚举 枚举值 宏定义 
sttnet.h
浏览该文件的文档.
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>
62 namespace stt
63 {
64 
65  namespace system
66  {
67  class WorkerPool;
68 
96 template <typename T>
97 class MPSCQueue {
98 public:
99  explicit MPSCQueue(std::size_t capacity_pow2)
100  : capacity_(capacity_pow2),
101  mask_(capacity_pow2 - 1),
102  buffer_(capacity_pow2),
103  head_(0),
104  tail_(0)
105  {
106  // capacity must be power of two
107  if (capacity_ < 2 || (capacity_ & mask_) != 0) {
108  // You can replace with your own assert/log
109  throw std::invalid_argument("MPSCQueue capacity must be power of two and >= 2");
110  }
111 
112  // Initialize per-slot sequence
113  for (std::size_t i = 0; i < capacity_; ++i) {
114  buffer_[i].seq.store(i, std::memory_order_relaxed);
115  }
116  }
117 
118  MPSCQueue(const MPSCQueue&) = delete;
119  MPSCQueue& operator=(const MPSCQueue&) = delete;
120 
122  // Drain remaining items to call destructors if needed
123  T tmp;
124  while (pop(tmp)) {}
125  }
126 
131  bool push(T&& v) noexcept(std::is_nothrow_move_constructible_v<T>) {
132  return emplace_impl(std::move(v));
133  }
134 
135  bool push(const T& v) noexcept(std::is_nothrow_copy_constructible_v<T>) {
136  return emplace_impl(v);
137  }
138 
143  bool pop(T& out) noexcept(std::is_nothrow_move_assignable_v<T> &&
144  std::is_nothrow_move_constructible_v<T>)
145  {
146  Slot& slot = buffer_[head_ & mask_];
147  const std::size_t seq = slot.seq.load(std::memory_order_acquire);
148  const std::intptr_t dif = static_cast<std::intptr_t>(seq) - static_cast<std::intptr_t>(head_ + 1);
149 
150  if (dif != 0) {
151  // seq != head+1 => empty
152  return false;
153  }
154 
155  // Move out
156  out = std::move(*slot.ptr());
157 
158  // Destroy in-place
159  slot.destroy();
160 
161  // Mark slot as free for producers:
162  // seq = head + capacity
163  slot.seq.store(head_ + capacity_, std::memory_order_release);
164 
165  ++head_;
166  return true;
167  }
168 
173  std::size_t approx_size() const noexcept {
174  const std::size_t t = tail_.load(std::memory_order_relaxed);
175  const std::size_t h = head_; // consumer-only
176  return (t >= h) ? (t - h) : 0;
177  }
178 
179 private:
180  struct Slot {
181  std::atomic<std::size_t> seq;
182  typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
183  bool has_value = false;
184 
185  T* ptr() noexcept { return reinterpret_cast<T*>(&storage); }
186  const T* ptr() const noexcept { return reinterpret_cast<const T*>(&storage); }
187 
188  template <class U>
189  void construct(U&& v) noexcept(std::is_nothrow_constructible_v<T, U&&>) {
190  ::new (static_cast<void*>(&storage)) T(std::forward<U>(v));
191  has_value = true;
192  }
193 
194  void destroy() noexcept {
195  if (has_value) {
196  ptr()->~T();
197  has_value = false;
198  }
199  }
200  };
201 
202  template <class U>
203  bool emplace_impl(U&& v) noexcept(std::is_nothrow_constructible_v<T, U&&>) {
204  std::size_t pos = tail_.load(std::memory_order_relaxed);
205 
206  for (;;) {
207  Slot& slot = buffer_[pos & mask_];
208  const std::size_t seq = slot.seq.load(std::memory_order_acquire);
209  const std::intptr_t dif = static_cast<std::intptr_t>(seq) - static_cast<std::intptr_t>(pos);
210 
211  if (dif == 0) {
212  // slot is free for this pos
213  if (tail_.compare_exchange_weak(
214  pos, pos + 1,
215  std::memory_order_relaxed,
216  std::memory_order_relaxed))
217  {
218  // We own this slot now
219  slot.construct(std::forward<U>(v));
220  // Publish to consumer: seq = pos+1 means "ready"
221  slot.seq.store(pos + 1, std::memory_order_release);
222  return true;
223  }
224  // CAS failed: pos updated with current tail; retry
225  } else if (dif < 0) {
226  // slot seq < pos => queue is full (producer wrapped)
227  return false;
228  } else {
229  // Another producer is ahead; move pos forward
230  pos = tail_.load(std::memory_order_relaxed);
231  }
232  }
233  }
234 
235 private:
236  const std::size_t capacity_;
237  const std::size_t mask_;
238  std::vector<Slot> buffer_;
239 
240  // Single consumer only
241  std::size_t head_;
242 
243  // Multi-producer
244  std::atomic<std::size_t> tail_;
245 };
246 
247 
248  }
254  namespace file
255  {
259  class FileTool
260  {
261  public:
269  static bool createDir(const std::string & ddir,const mode_t &mode=0775);
278  static bool copy(const std::string &sourceFile,const std::string &objectFile);
287  static bool createFile(const std::string &filePath,const mode_t &mode=0666);
294  static size_t get_file_size(const std::string &fileName);
295  };
296 
302  {
306  std::string loc;
310  int threads;
314  std::mutex lock;
320  FileThreadLock(const std::string &loc,const int &threads):loc(loc),threads(threads){};
321  };
322 
329  class File:private FileTool
330  {
331  protected:
332  static std::mutex l1;
333  static std::unordered_map<std::string,FileThreadLock> fl2;
334  protected:
335  std::mutex che;
336 
337  private:
338  void lockfl2();
339  void unlockfl2();
340  private:
341  std::ifstream fin;
342  std::vector<std::string> data;
343  std::vector<std::string> backUp;
344  char *data_binary=nullptr;
345  char *backUp_binary=nullptr;
346  size_t size1=0;
347  size_t size2=0;
348  int multiple=0;
349  size_t multiple_backup=0;
350  size_t malloced=0;
351  std::mutex fl1;
352 
353  std::ofstream fout;
354  std::string fileName;
355 
356  std::string fileNameTemp;
357  bool flag=false;
358  bool binary;
359  mode_t mode;
360  size_t size=0;
361  uint64_t totalLines=0;
362  private:
363  void toMemory();
364  bool toDisk();
365  public:
406  bool openFile(const std::string &fileName,const bool &create=true,const int &multiple=0,const size_t &size=0,const mode_t &mode=0666);
412  bool closeFile(const bool &del=false);
417  ~File(){closeFile(false);}
422  bool isOpen(){return flag;}
427  bool isBinary(){return binary;}
432  std::string getFileName(){return fileName;}
441  uint64_t getFileLine(){return totalLines;}
450  size_t getFileSize(){return size;}
459  size_t getSize1(){return size1;}
460  public:
466  bool lockMemory();
474  bool unlockMemory(const bool &rec=false);
475  public:
489  int findC(const std::string &targetString,const int linePos=1);
499  bool appendLineC(const std::string &data,const int &linePos=0);
508  bool deleteLineC(const int &linePos=0);
515  bool deleteAllC();
525  bool chgLineC(const std::string &data,const int &linePos=0);
535  bool readLineC(std::string &data,const int linePos);
545  std::string& readC(std::string &data,const int &linePos,const int &num);
552  std::string& readAllC(std::string &data);
568  bool readC(char *data,const size_t &pos,const size_t &size);
579  bool writeC(const char *data,const size_t &pos,const size_t &size);
584  bool formatC();
586  public:
600  int find(const std::string &targetString,const int linePos=1);
610  bool appendLine(const std::string &data,const int &linePos=0);
619  bool deleteLine(const int &linePos=0);
626  bool deleteAll();
636  bool chgLine(const std::string &data,const int &linePos=0);
646  bool readLine(std::string &data,const int linePos);
656  std::string& read(std::string &data,const int &linePos,const int &num);
663  std::string& readAll(std::string &data);
679  bool read(char *data,const size_t &pos,const size_t &size);
690  bool write(const char *data,const size_t &pos,const size_t &size);
695  void format();
697  };
698  }
704  namespace time
705  {
712  struct Duration
713  {
717  long long day;
721  int hour;
725  int min;
729  int sec;
733  int msec;
737  Duration(long long a,int b,int c,int d,int e):day(a),hour(b),min(c),sec(d),msec(e){}
738  Duration()=default;
744  bool operator>(const Duration &b)
745  {
746  long long total;
747  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
748  long long totalB;
749  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
750  if(total>totalB)
751  return true;
752  else
753  return false;
754  }
760  bool operator<(const Duration &b)
761  {
762  long long total;
763  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
764  long long totalB;
765  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
766  if(total<totalB)
767  return true;
768  else
769  return false;
770  }
776  bool operator==(const Duration &b)
777  {
778  long long total;
779  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
780  long long totalB;
781  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
782  if(total==totalB)
783  return true;
784  else
785  return false;
786  }
792  bool operator>=(const Duration &b)
793  {
794  long long total;
795  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
796  long long totalB;
797  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
798  if(total>=totalB)
799  return true;
800  else
801  return false;
802  }
808  bool operator<=(const Duration &b)
809  {
810  long long total;
811  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
812  long long totalB;
813  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
814  if(total<=totalB)
815  return true;
816  else
817  return false;
818  }
825  {
826  long long dayy=day;
827  int hourr=hour;
828  int minn=min;
829  int secc=sec;
830  int msecc=msec;
831 
832  msecc+=b.msec;
833  secc+=b.sec;
834  minn+=b.min;
835  hourr+=b.hour;
836  dayy+=b.day;
837 
838  if(msecc/1000!=0)
839  {
840  secc+=msecc/1000;
841  msecc=msecc%1000;
842  }
843 
844  if(secc/60!=0)
845  {
846  minn+=secc/60;
847  secc=secc%60;
848  }
849 
850  if(minn/60!=0)
851  {
852  hourr+=minn/60;
853  minn=minn%60;
854  }
855 
856  if(hourr/24!=0)
857  {
858  dayy+=hourr/24;
859  hourr=hourr%24;
860  }
861  return Duration(dayy,hourr,minn,secc,msecc);
862  }
869  {
870  long long dayy=day;
871  int hourr=hour;
872  int minn=min;
873  int secc=sec;
874  int msecc=msec;
875 
876  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;
877  secc=0;
878  minn=0;
879  hourr=0;
880  dayy=0;
881 
882  if(msecc/1000!=0)
883  {
884  secc+=msecc/1000;
885  msecc=msecc%1000;
886  }
887 
888  if(secc/60!=0)
889  {
890  minn+=secc/60;
891  secc=secc%60;
892  }
893 
894  if(minn/60!=0)
895  {
896  hourr+=minn/60;
897  minn=minn%60;
898  }
899 
900  if(hourr/24!=0)
901  {
902  dayy+=hourr/24;
903  hourr=hourr%24;
904  }
905  return Duration(dayy,hourr,minn,secc,msecc);
906  }
907 
911  double convertToDay()
912  {
913  long long total;
914  total=hour*60*60*1000+min*60*1000+sec*1000+msec;
915  double k=day+total/86400000.0000;
916  return k;
917  }
921  double convertToHour()
922  {
923  long long total;
924  total=min*60*1000+sec*1000+msec;
925  double k=day*24+hour+total/36000000.0000;
926  return k;
927  }
931  double convertToMin()
932  {
933  long long total;
934  total=sec*1000+msec;
935  double k=day*24*60+hour*60+min+total/60000.0000;
936  return k;
937  }
941  double convertToSec()
942  {
943  long long total;
944  total=msec;
945  double k=day*24*60*60+hour*60*60+min*60+sec+total/1000.0000;
946  return k;
947  }
951  long long convertToMsec()
952  {
953  long long total;
954  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
955  return total;
956  }
962  Duration recoverForm(const long long &t)
963  {
964  msec=t;
965  sec=0;
966  min=0;
967  hour=0;
968  day=0;
969 
970  if(msec/1000!=0)
971  {
972  sec+=msec/1000;
973  msec=msec%1000;
974  }
975 
976  if(sec/60!=0)
977  {
978  min+=sec/60;
979  sec=sec%60;
980  }
981 
982  if(min/60!=0)
983  {
984  hour+=min/60;
985  min=min%60;
986  }
987 
988  if(hour/24!=0)
989  {
990  day+=hour/24;
991  hour=hour%24;
992  }
993  return Duration(day,hour,min,sec,msec);
994  }
995  };
1007  std::ostream& operator<<(std::ostream &os,const Duration &a);
1008 
1009  using Milliseconds = std::chrono::duration<uint64_t,std::milli>;
1010  using Seconds=std::chrono::duration<uint64_t>;
1014  #define ISO8086A "yyyy-mm-ddThh:mi:ss"
1015 
1018  #define ISO8086B "yyyy-mm-ddThh:mi:ss.sss"
1019 
1020 
1027  class DateTime
1028  {
1029  private:
1030  static Duration& dTOD(const Milliseconds& d1,Duration &D1);
1031  static Milliseconds& DTOd(const Duration &D1,Milliseconds& d1);
1032  static std::string &toPGtimeFormat();
1033  static std::chrono::system_clock::time_point strToTimePoint(const std::string &timeStr,const std::string &format=ISO8086A);
1034  static std::string& timePointToStr(const std::chrono::system_clock::time_point &tp,std::string &timeStr,const std::string &format=ISO8086A);
1035  public:
1043  static std::string& getTime(std::string &timeStr,const std::string &format=ISO8086A);
1052  static bool convertFormat(std::string &timeStr,const std::string &oldFormat,const std::string &newFormat=ISO8086A);
1062  static Duration& calculateTime(const std::string &time1,const std::string &time2,Duration &result,const std::string &format1=ISO8086A,const std::string &format2=ISO8086A);
1073  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);
1083  static bool compareTime(const std::string &time1,const std::string &time2,const std::string &format1=ISO8086A,const std::string &format2=ISO8086A);
1084  private:
1085  Duration dt{-1,-1,-1,-1,-1};
1086  bool flag=false;
1087  std::chrono::steady_clock::time_point start;
1088  std::chrono::steady_clock::time_point end;
1089  public:
1094  bool startTiming();
1099  Duration checkTime();
1105  Duration endTiming();
1106  public:
1111  Duration getDt(){return dt;}
1116  bool isStart(){return flag;}
1117  };
1118  }
1119  namespace file
1120  {
1126  class LogFile:private time::DateTime,protected File
1127  {
1128  private:
1129  std::string timeFormat;
1130  std::string contentFormat;
1131  std::atomic<bool> consumerGuard{true};
1132  //std::mutex queueMutex;
1133  //std::condition_variable queueCV;
1135  std::thread consumerThread;
1136  public:
1157  LogFile(const size_t &logQueue_cap=8192):logQueue(logQueue_cap)
1158  {
1159  consumerGuard=true;
1160  consumerThread = std::thread([this]()->void
1161  {
1162  std::string content;
1163  content.reserve(1024);
1164  std::string time;
1165  content.reserve(1074);
1166  while(this->consumerGuard)
1167  {
1168  while(this->logQueue.pop(content))//非空则执行
1169  {
1170  getTime(time,timeFormat);
1171  time+=contentFormat;
1172  time+=content;
1173  this->appendLine(time);
1174  }
1175  std::this_thread::sleep_for(std::chrono::microseconds(500));
1176 
1177  }
1178  });
1179  }
1188  bool openFile(const std::string &fileName,const std::string &timeFormat=ISO8086A,const std::string &contentFormat=" ");
1193  bool isOpen(){return File::isOpen();}
1198  std::string getFileName(){return File::getFileName();}
1204  bool closeFile(const bool &del=false);
1209  void writeLog(const std::string &data);
1214  bool clearLog();
1222  bool deleteLogByTime(const std::string &date1="1",const std::string &date2="2");
1226  ~LogFile();
1227  };
1228  }
1234  namespace data
1235  {
1240  {
1241  public:
1252  static bool encryptSymmetric(const unsigned char *before,const size_t &length,const unsigned char *passwd,const unsigned char *iv,unsigned char *after);
1263  static bool decryptSymmetric(const unsigned char *before,const size_t &length,const unsigned char *passwd,const unsigned char *iv,unsigned char *after);
1276  static std::string& sha1(const std::string &ori_str,std::string &result);
1289  static std::string& sha11(const std::string &ori_str,std::string &result);
1290  };
1294  class BitUtil
1295  {
1296  public:
1304  static std::string& bitOutput(char input,std::string &result);
1312  static std::string& bitOutput(const std::string &input,std::string &result);
1321  static char& bitOutput_bit(char input,const int pos,char &result);
1329  static unsigned long& bitStrToNumber(const std::string &input,unsigned long &result);
1339  static unsigned long& bitToNumber(const std::string &input,unsigned long &result);
1347  static char& toBit(const std::string &input,char &result);
1355  static std::string& toBit(const std::string &input,std::string &result);
1356  };
1361  {
1362  public:
1370  static long getRandomNumber(const long &a,const long &b);
1377  static std::string& getRandomStr_base64(std::string &str,const int &length);
1391  static std::string& generateMask_4(std::string &mask);
1392  };
1397  {
1398  public:
1410  static unsigned long& htonl_ntohl_64(unsigned long &data);//64位无符号数转化为大/小端序(网络字节序)
1411  };
1412 
1417  {
1418  public:
1419 
1428  static std::string& getPreciesFloat(const float &number,const int &bit,std::string &str);
1436  static float& getPreciesFloat(float &number,const int &bit);
1445  static std::string& getPreciesDouble(const double &number,const int &bit,std::string &str);
1453  static double& getPreciesDouble(double &number,const int &bit);
1465  static float& getValidFloat(float &number,const int &bit);
1466  };
1472  {
1473  public:
1490  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);
1501  static std::string_view& get_value_str(const std::string_view& ori_str,std::string_view &str,const std::string& name);
1510  static std::string_view& get_value_header(const std::string_view& ori_str,std::string_view &str,const std::string& name);
1520  static std::string_view& get_location_str(const std::string_view& ori_str,std::string_view &str);
1530  static std::string_view& getLocPara(const std::string_view &url,std::string_view &locPara);
1539  static std::string_view& getPara(const std::string_view &url,std::string_view &para);
1540 
1541 
1558  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);
1569  static std::string& get_value_str(const std::string& ori_str,std::string &str,const std::string& name);
1578  static std::string& get_value_header(const std::string& ori_str,std::string &str,const std::string& name);
1588  static std::string& get_location_str(const std::string& ori_str,std::string &str);
1598  static std::string& getLocPara(const std::string &url,std::string &locPara);
1607  static std::string& getPara(const std::string &url,std::string &para);
1618  static std::string& getIP(const std::string &url,std::string &IP);
1629  static int& getPort(const std::string &url,int &port);
1639  static std::string createHeader(const std::string& first,const std::string& second);
1660  template<class... Args>
1661  static std::string createHeader(const std::string& first,const std::string& second,Args... args)
1662  {
1663  std::string cf=first+": "+second+"\r\n"+createHeader(args...);
1664  return cf;
1665  }
1666  };
1671  {
1672  public:
1684  static std::string& transfer_websocket_key(std::string &str);
1685  };
1690  {
1691  public:
1700  static int& toInt(const std::string_view&ori_str,int &result,const int &i=-1);
1707  static int& str16toInt(const std::string_view&ori_str,int &result,const int &i=-1);
1716  static long& toLong(const std::string_view&ori_str,long &result,const long &i=-1);
1725  static float& toFloat(const std::string&ori_str,float &result,const float &i=-1);
1734  static double& toDouble(const std::string&ori_str,double &result,const double &i=-1);
1742  static bool& toBool(const std::string_view&ori_str,bool &result);
1753  static std::string& strto16(const std::string &ori_str,std::string &result);//字符串转化为16进制字符串 (暂不需要)(待修复)
1754  };
1759  {
1760  public:
1769  static std::string base64_encode(const std::string &input);
1778  static std::string base64_decode(const std::string &input);
1790  static std::string& transfer_websocket_key(std::string &str);
1804  static std::string& generateMask_4(std::string &mask);
1815  static std::string& maskCalculate(std::string &data,const std::string &mask);
1816  };
1821  {
1822  public:
1835  static int getValue(const std::string &oriStr,std::string& result,const std::string &type="value",const std::string &name="a",const int &num=0);
1836 
1842  static std::string toString(const Json::Value &val);
1848  static Json::Value toJsonArray(const std::string & str);
1858  template<class T1,class T2>
1859  static std::string createJson(T1 first,T2 second)
1860  {
1861  Json::Value root;
1862  //root[first]=second;
1863  if constexpr (std::is_integral_v<T2>) {
1864  root[first] = Json::Value(static_cast<Json::Int64>(second));
1865  } else {
1866  root[first] = second;
1867  }
1868  Json::StreamWriterBuilder builder;
1869  std::string jsonString=Json::writeString(builder,root);
1870  return jsonString;
1871  }
1883  template<class T1,class T2,class... Args>
1884  static std::string createJson(T1 first,T2 second,Args... args)
1885  {
1886  Json::Value root;
1887  //root[first]=second;
1888  if constexpr (std::is_integral_v<T2>) {
1889  root[first] = Json::Value(static_cast<Json::Int64>(second));
1890  } else {
1891  root[first] = second;
1892  }
1893  std::string kk=createJson(args...);
1894  Json::StreamWriterBuilder builder;
1895  std::string jsonString=Json::writeString(builder,root);
1896  jsonString=jsonString.erase(jsonString.length()-2);
1897  kk=kk.substr(1);
1898  return jsonString+","+kk;
1899 
1900  }
1908  template<class T>
1909  static std::string createArray(T first)
1910  {
1911  Json::Value root(Json::arrayValue);
1912  root.append(first);
1913  Json::StreamWriterBuilder builder;
1914  std::string jsonString=Json::writeString(builder,root);
1915  return jsonString;
1916  }
1926  template<class T,class... Args>
1927  static std::string createArray(T first,Args... args)
1928  {
1929  Json::Value root(Json::arrayValue);
1930  root.append(first);
1931  std::string kk=createArray(args...);
1932  Json::StreamWriterBuilder builder;
1933  std::string jsonString=Json::writeString(builder,root);
1934  jsonString=jsonString.erase(jsonString.length()-2);
1935  kk=kk.substr(1);
1936  return jsonString+","+kk;
1937 
1938  }
1945  static std::string jsonAdd(const std::string &a,const std::string &b);
1952  static std::string& jsonFormatify(const std::string &a,std::string &b);
1959  static std::string& jsonToUTF8(const std::string &input,std::string &output);
1960  };
1961  }
1962 
1966  namespace security
1967  {
2012  enum class RateLimitType
2013  {
2014  Cooldown, // 连续触发惩罚:达到上限后进入冷却,需要安静 secs 才恢复
2015  FixedWindow, // 固定窗口计数:每 secs 一个窗口,窗口内最多 times 次
2016  SlidingWindow, // 滑动窗口:统计最近 secs 内的次数(队列时间戳)
2017  TokenBucket // 令牌桶:允许突发 + 控制长期平均速率(常用于 API/消息)
2018  };
2038  struct RateState
2039  {
2040  // 通用
2041  int counter = 0;
2042  int violations = 0; // 新增:触发限流的次数
2043  std::chrono::steady_clock::time_point lastTime{};
2044 
2045  // SlidingWindow
2046  std::deque<std::chrono::steady_clock::time_point> history;
2047 
2048  // TokenBucket
2049  double tokens = 0.0;
2050  std::chrono::steady_clock::time_point lastRefill{};
2051  };
2069  {
2070  int fd = -1;
2072  std::unordered_map<std::string, RateState> pathRate;
2073  std::chrono::steady_clock::time_point lastActivity{};
2074  };
2099  {
2100  int activeConnections = 0;
2102  int badScore = 0; //IP 风险评分(用于升级惩罚)
2103  std::unordered_map<int, ConnectionState> conns; // fd -> state
2104  };
2126  enum DefenseDecision : int
2127  {
2128  ALLOW = 0, // 正常通过
2129  DROP = 1, // 不回应(丢弃)
2130  CLOSE = 2 // 断连(可伴随封 IP)
2131  };
2132 
2221  {
2222  public:
2229  ConnectionLimiter(const int& maxConn = 20, const int& idleTimeout = 60) : maxConnections(maxConn),connectionTimeout(idleTimeout){}
2230 
2231  // ========== 策略设置 ==========
2238  void setConnectStrategy(const RateLimitType &type);
2245  void setRequestStrategy(const RateLimitType &type);
2252  void setPathStrategy(const RateLimitType &type);
2253 
2254  // ========== Path 配置 ==========
2267  void setPathLimit(const std::string &path, const int &times, const int &secs);
2268 
2269  // ========== 核心判断 ==========
2286  DefenseDecision allowConnect(const std::string &ip, const int &fd,const int &times, const int &secs);
2301  DefenseDecision allowRequest(const std::string &ip,const int &fd,const std::string_view &path,const int &times,const int &secs);
2302 
2303  // ========== 生命周期 ==========
2314  void clearIP(const std::string &ip,const int &fd);
2328  bool connectionDetect(const std::string &ip,const int &fd);
2359  void banIP(const std::string &ip,int banSeconds,const std::string &reasonCN,const std::string &reasonEN);
2363  void unbanIP(const std::string &ip);
2367  bool isBanned(const std::string &ip) const;
2368 
2369 
2370  private:
2371  // 核心判定
2372  bool allow(RateState &st,const RateLimitType &type,const int &times,const int &secs,const std::chrono::steady_clock::time_point &now);
2373 
2374  private:
2375  int maxConnections;
2376  int connectionTimeout;
2377 
2378  RateLimitType connectStrategy = RateLimitType::Cooldown;
2379  RateLimitType requestStrategy = RateLimitType::SlidingWindow;
2380  RateLimitType pathStrategy = RateLimitType::SlidingWindow;
2381 
2382  std::unordered_map<std::string, IPInformation> table;
2383  std::unordered_map<std::string, std::pair<int,int>> pathConfig;
2384  // IP -> 解封时间
2385  std::unordered_map<std::string,std::chrono::steady_clock::time_point> blacklist;
2386  inline void logSecurity(const std::string &msgCN,const std::string &msgEN);
2387  };
2388 
2389 
2390 
2391  }
2392 
2398  namespace network
2399  {
2404  {
2405  protected:
2406  int fd=-1;
2407  bool flag1=false;
2408  bool flag2=false;
2409  SSL *ssl=nullptr;
2410  int sec=-1;
2411  public:
2415  bool flag3=false;
2416  public:
2426  void setFD(const int &fd,SSL *ssl,const bool &flag1=false,const bool &flag2=false,const int &sec=-1);
2431  int getFD(){return fd;}
2436  SSL *getSSL(){return ssl;}
2441  void close(const bool &cle=true);
2446  void blockSet(const int &sec = -1);
2450  void unblockSet();
2454  bool multiUseSet();
2459  bool isConnect(){if(fd==-1)return false;else return true;}
2460  public:
2479  int sendData(const std::string &data,const bool &block=true);
2499  int sendData(const char *data,const uint64_t &length,const bool &block=true);
2515  int recvDataByLength(std::string &data,const uint64_t &length,const int &sec=2);
2531  int recvDataByLength(char *data,const uint64_t &length,const int &sec=2);
2544  int recvData(std::string &data,const uint64_t &length);
2557  int recvData(char *data,const uint64_t &length);
2558  };
2559 
2565  {
2566  private:
2567  std::string serverIP="";
2568  int serverPort=-1;
2569  bool flag=false;
2570  bool TLS;
2571  SSL_CTX *ctx=nullptr;
2572  const char *ca;
2573  const char *cert;
2574  const char *key;
2575  const char *passwd;
2576  private:
2577  bool createFD();
2578  void closeAndUnCreate();
2579  bool initCTX(const char *ca,const char *cert="",const char *key="",const char *passwd="");
2580  public:
2593  TcpClient(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd="");
2600  bool connect(const std::string &ip,const int &port);
2614  void resetCTX(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd="");
2619  bool close();
2623  ~TcpClient(){closeAndUnCreate();}
2624  public:
2629  std::string getServerIP(){return serverIP;}
2634  int getServerPort(){return serverPort;}
2639  bool isConnect(){return flag;}
2640  };
2641 
2649  class HttpClient:private TcpClient
2650  {
2651  private:
2652  bool flag=false;
2653  public:
2666  HttpClient(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd=""):TcpClient(TLS,ca,cert,key,passwd){}
2667  public:
2680  bool getRequest(const std::string &url,const std::string &header="",const std::string &header1="Connection: keep-alive",const int &sec=-1);
2694  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);
2709  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);
2725  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);
2726  public:
2731  bool isReturn(){return flag;}
2735  std::string header="";
2739  std::string body="";
2740  };
2741 
2746  {
2747  private:
2748  int fd;
2749  bool flag=true;
2750  std::function<bool(const int &fd)> fc=[](const int &fd)->bool
2751  {return true;};
2752  std::function<void(const int &fd)> fcEnd=[](const int &fd)->void
2753  {};
2754  std::function<bool(const int &fd)> fcTimeOut=[](const int &fd)->bool
2755  {return true;};
2756  bool flag1=true;
2757  bool flag2=false;
2758  time::Duration dt{0,20,0,0,0};
2759  bool flag3=false;
2760  time::Duration t;
2761  private:
2762  void epolll();
2763  public:
2770  void startListen(const int &fd,const bool &flag=true,const time::Duration &dt=time::Duration{0,0,20,0,0});
2771  public:
2776  bool isListen(){return flag2;}
2786  void setFunction(std::function<bool(const int &fd)> fc){this->fc=fc;}
2794  void setEndFunction(std::function<void(const int &fd)> fcEnd){this->fcEnd=fcEnd;};
2804  void setTimeOutFunction(std::function<bool(const int &fd)> fcTimeOut){this->fcTimeOut=fcTimeOut;};
2810  bool endListen();
2815  void endListenWithSignal(){flag1=false;}
2821  void waitAndQuit(const time::Duration &t=time::Duration{0,0,0,10,10}){flag3=true;this->t=t;}
2826  ~EpollSingle(){endListen();}
2827  };
2828 
2835  {
2836  private:
2837  bool flag4=false;
2838  std::function<bool(const std::string &message,WebSocketClient &k)> fc=[](const std::string &message,WebSocketClient &k)->bool
2839  {std::cout<<"收到: "<<message<<std::endl;return true;};
2840  std::string url;
2841  EpollSingle k;
2842  bool flag5=false;
2843  private:
2844  bool close1();
2845  public:
2858  WebSocketClient(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd=""):TcpClient(TLS,ca,cert,key,passwd){}
2869  void setFunction(std::function<bool(const std::string &message,WebSocketClient &k)> fc){this->fc=fc;}
2876  bool connect(const std::string &url,const int &min=20);
2899  bool sendMessage(const std::string &message,const std::string &type="0001");
2909  void close(const std::string &closeCodeAndMessage,const bool &wait=true);
2927  void close(const short &code=1000,const std::string &message="bye",const bool &wait=true);
2928  public:
2933  bool isConnect(){return flag4;}
2938  std::string getUrl(){return url;}
2943  std::string getServerIp(){return TcpClient::getServerIP();}
2948  std::string getServerPort(){return TcpClient::getServerIP();}
2952  ~WebSocketClient();
2953  };
2954 
2959  {
2963  int fd;
2971  std::string type;
2975  std::string locPara;
2979  std::string loc;
2983  std::string para;
2987  std::string header;
2991  std::string body;
2995  std::string body_chunked;
2999  std::unordered_map<std::string,std::any> ctx;
3000  };
3001 
3002  struct TcpFDInf;
3008  {
3009  public:
3017  void setFD(const int &fd,SSL *ssl=nullptr,const bool &flag1=false,const bool &flag2=true){TcpFDHandler::setFD(fd,ssl,flag1,flag2);}
3033  int solveRequest(TcpFDInf &TcpInf,HttpRequestInformation &HttpInf,const unsigned long &buffer_size,const int &times=1);
3042  bool sendBack(const std::string &data,const std::string &header="",const std::string &code="200 OK",const std::string &header1="");
3055  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);
3056  };
3061  {
3065  int fd;
3077  std::string locPara;
3081  std::string header;
3085  time_t HBTime=0;
3089  time_t response;
3093  size_t recv_length;
3105  std::string message="";
3109  bool fin;
3113  std::string mask;
3117  std::unordered_map<std::string,std::any> ctx;
3122  };
3123 
3128  {
3132  int fd;
3140  std::string data;
3144  std::unordered_map<std::string,std::any> ctx;
3145  };
3146 
3147  enum class TLSState : uint8_t {
3148  NONE = 0, // 非 TLS 连接(普通 TCP)
3149  HANDSHAKING, // TLS 握手中(SSL_accept 还没完成)
3150  ESTABLISHED, // TLS 已建立,可以 SSL_read / SSL_write
3151  ERROR // TLS 出错(可选)
3152  };
3153 
3157  struct TcpFDInf
3158  {
3162  int fd;
3170  std::string ip;
3174  std::string port;
3182  std::queue<std::any> pendindQueue;
3186  int status;
3190  std::string_view data;
3194  SSL* ssl;
3202  char *buffer;
3206  unsigned long p_buffer_now;
3207  };
3208 
3213  {
3217  int fd;
3221  int ret;
3222  };
3223 
3224 
3229  class TcpServer
3230  {
3231  protected:
3234  unsigned long buffer_size;
3235  unsigned long long maxFD;
3237  //std::unordered_map<int,TcpFDInf> clientfd;
3238  //std::mutex lc1;
3240  int flag1=true;
3241  //std::queue<QueueFD> *fdQueue;
3242  //std::mutex *lq1;
3243  //std::condition_variable cv1;
3244  //std::condition_variable *cv;
3245  //int consumerNum;
3246  //std::mutex lco1;
3247  bool unblock;
3248  SSL_CTX *ctx=nullptr;
3249  bool TLS=false;
3250  //std::unordered_map<int,SSL*> tlsfd;
3251  //std::mutex ltl1;
3253  //bool flag_detect;
3254  //bool flag_detect_status;
3256  int serverType; // 1 tcp 2 http 3 websocket
3263  private:
3264  std::function<void(const int &fd)> closeFun=[](const int &fd)->void
3265  {
3266 
3267  };
3268  std::function<void(TcpFDHandler &k,TcpInformation &inf)> securitySendBackFun=[](TcpFDHandler &k,TcpInformation &inf)->void
3269  {};
3270  std::function<bool(TcpFDHandler &k,TcpInformation &inf)> globalSolveFun=[](TcpFDHandler &k,TcpInformation &inf)->bool
3271  {return true;};
3272  std::unordered_map<std::string,std::vector<std::function<int(TcpFDHandler &k,TcpInformation &inf)>>> solveFun;
3273  std::function<int(TcpFDHandler &k,TcpInformation &inf)> parseKey=[](TcpFDHandler &k,TcpInformation &inf)->int
3274  {inf.ctx["key"]=inf.data;return 1;};
3275  int fd=-1;
3276  int port=-1;
3277  int flag=false;
3278  bool flag2=false;
3279  private:
3280  void epolll(const int &evsNum);
3281  //virtual void consumer(const int &threadID);
3282  virtual void handler_netevent(const int &fd);
3283  virtual void handler_workerevent(const int &fd,const int &ret);
3284  virtual void handleHeartbeat()=0;
3285  public:
3298  void putTask(const std::function<int(TcpFDHandler &k,TcpInformation &inf)> &fun,TcpFDHandler &k,TcpInformation &inf);
3327  TcpServer(const unsigned long long &maxFD=1000000,const int &buffer_size=256,const size_t &finishQueue_cap=65536,const bool &security_open=true,
3328  const int &connectionNumLimit=20,const int &connectionSecs=1,const int &connectionTimes=6,const int &requestSecs=1,const int &requestTimes=40,
3329  const int &checkFrequency=60,const int &connectionTimeout=60):maxFD(maxFD),buffer_size(buffer_size*1024),finishQueue(finishQueue_cap),security_open(security_open),connectionSecs(connectionSecs),connectionTimes(connectionTimes),requestSecs(requestSecs),requestTimes(requestTimes),
3330  connectionLimiter(connectionNumLimit,connectionTimeout),checkFrequency(checkFrequency){serverType=1;}
3337  bool startListen(const int &port,const int &threads=8);
3364  bool setTLS(const char *cert,const char *key,const char *passwd,const char *ca);
3368  void redrawTLS();
3378  void setSecuritySendBackFun(std::function<void(TcpFDHandler &k,TcpInformation &inf)> fc){this->securitySendBackFun=fc;}
3388  void setGlobalSolveFunction(std::function<bool(TcpFDHandler &k,TcpInformation &inf)> fc){this->globalSolveFun=fc;}
3399  void setFunction(const std::string &key,std::function<int(TcpFDHandler &k,TcpInformation &inf)> fc)
3400  {
3401  auto [it, inserted] = solveFun.try_emplace(key);
3402  it->second.push_back(std::move(fc));
3403  }
3413  void setGetKeyFunction(std::function<int(TcpFDHandler &k,TcpInformation &inf)> parseKeyFun){this->parseKey=parseKeyFun;}
3419  bool stopListen();
3426  bool close();
3432  virtual bool close(const int &fd);
3439  void setConnectStrategy(const stt::security::RateLimitType &type){this->connectionLimiter.setConnectStrategy(type);}
3446  void setRequestStrategy(const stt::security::RateLimitType &type){this->connectionLimiter.setRequestStrategy(type);}
3454  void setPathStrategy(const stt::security::RateLimitType &type){this->connectionLimiter.setPathStrategy(type);}
3468  void setPathLimit(const std::string &path, const int &times, const int &secs){this->connectionLimiter.setPathLimit(path,times,secs);}
3472  void setCloseFun(std::function<void(const int &fd)> closeFun){this->closeFun=closeFun;}
3473  public:
3478  bool isListen(){return flag;}
3483  SSL* getSSL(const int &fd);
3488  ~TcpServer(){close();}
3489  };
3490 
3491 
3492 
3497  class HttpServer:public TcpServer
3498  {
3499  private:
3500  std::function<void(HttpServerFDHandler &k,HttpRequestInformation &inf)> securitySendBackFun=[](HttpServerFDHandler &k,HttpRequestInformation &inf)->void
3501  {};
3502  std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>> globalSolveFun;
3503  //std::function<bool(HttpServerFDHandler &k,HttpRequestInformation &inf)> globalSolveFun={};
3504  std::unordered_map<std::string,std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>>> solveFun;
3505  std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> parseKey=[](HttpServerFDHandler &k,HttpRequestInformation &inf)->int
3506  {inf.ctx["key"]=inf.loc;return 1;};
3507  //std::function<bool(const HttpRequestInformation &inf,HttpServerFDHandler &k)> fc;
3508  //HttpRequestInformation *HttpInf;
3509  HttpRequestInformation *httpinf;
3510  private:
3511  //void consumer(const int &threadID);
3512  //inline void handler(const int &fd);
3513  void handler_netevent(const int &fd);
3514  void handler_workerevent(const int &fd,const int &ret);
3515  void handleHeartbeat(){}
3516  public:
3529  void putTask(const std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> &fun,HttpServerFDHandler &k,HttpRequestInformation &inf);
3530 
3559  HttpServer(const unsigned long long &maxFD=1000000,const int &buffer_size=256,const size_t &finishQueue_cap=65536,const bool &security_open=true,
3560  const int &connectionNumLimit=10,const int &connectionSecs=1,const int &connectionTimes=3,const int &requestSecs=1,const int &requestTimes=20,
3561  const int &checkFrequency=30,const int &connectionTimeout=30):TcpServer(
3562  maxFD,
3563  buffer_size,
3564  finishQueue_cap,
3565  security_open,
3566  connectionNumLimit,
3567  connectionSecs,
3568  connectionTimes,
3569  requestSecs,
3570  requestTimes,
3571  checkFrequency,
3572  connectionTimeout
3573  ){serverType=2;}
3583  void setSecuritySendBackFun(std::function<void(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc){this->securitySendBackFun=fc;}
3592  void setGlobalSolveFunction(std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc){globalSolveFun.push_back(std::move(fc));}
3619  void setFunction(const std::string &key,std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc)
3620  {
3621  auto [it, inserted] = solveFun.try_emplace(key);
3622  it->second.push_back(std::move(fc));
3623  }
3639  void setGetKeyFunction(std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> parseKeyFun){this->parseKey=parseKeyFun;}
3646  bool startListen(const int &port,const int &threads=8)
3647  {
3648  //HttpInf=new HttpRequestInformation[maxFD];
3649  httpinf=new HttpRequestInformation[maxFD];
3650  return TcpServer::startListen(port,threads);
3651  }
3656  {
3657  delete[] httpinf;
3658  }
3659  };
3665  {
3666  public:
3674  void setFD(const int &fd,SSL *ssl=nullptr,const bool &flag1=false,const bool &flag2=true){TcpFDHandler::setFD(fd,ssl,flag1,flag2);}
3697  int getMessage(TcpFDInf &Tcpinf,WebSocketFDInformation &Websocketinf,const unsigned long &buffer_size,const int &ii=1);
3712  bool sendMessage(const std::string &msg,const std::string &type="0001");
3713 
3714  };
3715 
3720  {
3721  private:
3722  std::unordered_map<int,WebSocketFDInformation> wbclientfd;
3723  std::function<void(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> securitySendBackFun=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->void
3724  {};
3725  //std::function<bool(const std::string &msg,WebSocketServer &k,const WebSocketFDInformation &inf)> fc=[](const std::string &message,WebSocketServer &k,const WebSocketFDInformation &inf)->bool
3726  //{std::cout<<"收到: "<<message<<std::endl;return true;};
3727  std::function<bool(WebSocketFDInformation &k)> fcc=[](WebSocketFDInformation &k)
3728  {return true;};
3729  std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fccc=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->bool
3730  {
3731  return true;
3732  };
3733  std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> globalSolveFun=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->bool
3734  {return true;};
3735  std::unordered_map<std::string,std::vector<std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)>>> solveFun;
3736  std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> parseKey=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->int
3737  {inf.ctx["key"]=inf.message;return 1;};
3738  int seca=20*60;
3739  int secb=30;
3740 
3741  private:
3742  void handler_netevent(const int &fd);
3743  void handler_workerevent(const int &fd,const int &ret);
3744  //void consumer(const int &threadID);
3745  //inline void handler(const int &fd);
3746  void closeAck(const int &fd,const std::string &closeCodeAndMessage);
3747  void closeAck(const int &fd,const short &code=1000,const std::string &message="bye");
3748 
3749  void handleHeartbeat();
3750  bool closeWithoutLock(const int &fd,const std::string &closeCodeAndMessage);
3751  bool closeWithoutLock(const int &fd,const short &code=1000,const std::string &message="bye");
3752  public:
3765  void putTask(const std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> &fun,WebSocketServerFDHandler &k,WebSocketFDInformation &inf);
3794  WebSocketServer(const unsigned long long &maxFD=1000000,const int &buffer_size=256,const size_t &finishQueue_cap=65536,const bool &security_open=true,
3795  const int &connectionNumLimit=5,const int &connectionSecs=10,const int &connectionTimes=3,const int &requestSecs=1,const int &requestTimes=10,
3796  const int &checkFrequency=60,const int &connectionTimeout=120):TcpServer(
3797  maxFD,
3798  buffer_size,
3799  finishQueue_cap,
3800  security_open,
3801  connectionNumLimit,
3802  connectionSecs,
3803  connectionTimes,
3804  requestSecs,
3805  requestTimes,
3806  checkFrequency,
3807  connectionTimeout
3808  ){serverType=3;}
3818  void setSecuritySendBackFun(std::function<void(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fc){this->securitySendBackFun=fc;}
3828  void setGlobalSolveFunction(std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fc){this->globalSolveFun=fc;}
3837  void setStartFunction(std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fccc){this->fccc=fccc;}
3847  void setJudgeFunction(std::function<bool(WebSocketFDInformation &k)> fcc){this->fcc=fcc;}
3864  void setFunction(const std::string &key,std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fc)
3865  {
3866  auto [it, inserted] = solveFun.try_emplace(key);
3867  it->second.push_back(std::move(fc));
3868  }
3884  void setGetKeyFunction(std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> parseKeyFun){this->parseKey=parseKeyFun;}
3885  //void setFunction(std::function<bool(const std::string &msg,WebSocketServer &k,const WebSocketFDInformation &inf)> fc){this->fc=fc;}
3890  void setTimeOutTime(const int &seca){this->seca=seca*60;}
3896  void setHBTimeOutTime(const int &secb){this->secb=secb;}
3908  bool closeFD(const int &fd,const std::string &closeCodeAndMessage);
3928  bool closeFD(const int &fd,const short &code=1000,const std::string &message="bye");
3952  bool sendMessage(const int &fd,const std::string &msg,const std::string &type="0001"){WebSocketServerFDHandler k;k.setFD(fd,getSSL(fd),unblock);return k.sendMessage(msg,type);}
3957  bool close();
3962  bool close(const int &fd);
3969  bool startListen(const int &port,const int &threads=8)
3970  {
3971  //std::thread(&WebSocketServer::HB,this).detach();
3972 
3973  return TcpServer::startListen(port,threads);
3974  }
3996  void sendMessage(const std::string &msg,const std::string &type="0001");
4002  };
4003 
4009  {
4010  protected:
4011  int fd=-1;
4012  bool flag1=false;
4013  bool flag2=false;
4014  int sec=-1;
4015  public:
4023  void setFD(const int &fd,const bool &flag1=false,const int &sec=-1,const bool &flag2=false);
4028  void blockSet(const int &sec=-1);
4032  void unblockSet();
4037  bool multiUseSet();
4041  int getFD(){return fd;}
4046  void close(const bool &cle=true);
4065  int sendData(const std::string &data,const std::string &ip,const int &port,const bool &block=true);
4085  int sendData(const char *data,const uint64_t &length,const std::string &ip,const int &port,const bool &block=true);
4100  int recvData(std::string &data,const uint64_t &length,std::string &ip,int &port);
4115  int recvData(char *data,const uint64_t &length,std::string &ip,int &port);
4116 
4117  };
4122  {
4123  public:
4129  UdpClient(const bool &flag1=false,const int &sec=-1);
4135  bool createFD(const bool &flag1=false,const int &sec=-1);
4139  ~UdpClient(){close();}
4140  };
4145  {
4146  public:
4153  UdpServer(const int &port,const bool &flag1=false,const int &sec=-1,const bool &flag2=true);
4160  bool createFD(const int &port,const bool &flag1=false,const int &sec=-1,const bool &flag2=true);
4164  ~UdpServer(){close();}
4165  };
4166  }
4172  namespace system
4173  {
4182  {
4183  public:
4191  static std::string language;
4192  private:
4193  static void signalterminated(){std::cout<<"未捕获的异常终止"<<std::endl;if(system::ServerSetting::logfile!=nullptr){if(system::ServerSetting::language=="Chinese")system::ServerSetting::logfile->writeLog("未捕获的异常终止");else system::ServerSetting::logfile->writeLog("end for uncaught exception");}kill(getpid(),15);}
4194  static void signalSIGSEGV(int signal){std::cout<<"SIGSEGV"<<std::endl;if(system::ServerSetting::logfile!=nullptr){if(system::ServerSetting::language=="Chinese")system::ServerSetting::logfile->writeLog("信号SIGSEGV");else system::ServerSetting::logfile->writeLog("signal SIGSEGV");}kill(getpid(),15);}
4195  static void signalSIGABRT(int signal){std::cout<<"SIGABRT"<<std::endl;if(system::ServerSetting::logfile!=nullptr){if(system::ServerSetting::language=="Chinese")system::ServerSetting::logfile->writeLog("信号SIGABRT");else system::ServerSetting::logfile->writeLog("signal SIGABRT");}kill(getpid(),15);}
4196  public:
4205  static void setExceptionHandling();
4213  static void setLogFile(file::LogFile *logfile=nullptr,const std::string &language="");
4219  static void init(file::LogFile *logfile=nullptr,const std::string &language="");
4220  };
4221 
4230  class csemp
4231  {
4232  private:
4238  union semun
4239  {
4240  int val;
4241  struct semid_ds *buf;
4242  unsigned short *arry;
4243  };
4244 
4245  int m_semid;
4246  short m_sem_flg;
4247 
4248  csemp(const csemp &) = delete;
4249  csemp &operator=(const csemp &) = delete;
4250 
4251  public:
4255  csemp():m_semid(-1){}
4256 
4267  bool init(key_t key, unsigned short value = 1, short sem_flg = SEM_UNDO);
4268 
4277  bool wait(short value = -1);
4278 
4287  bool post(short value = 1);
4288 
4294  int getvalue();
4295 
4303  bool destroy();
4304 
4308  ~csemp();
4309  };
4310 
4314  #define MAX_PROCESS_NAME 100
4315 
4318  #define MAX_PROCESS_INF 1000
4319 
4322  #define SHARED_MEMORY_KEY 0x5095
4323 
4326  #define SHARED_MEMORY_LOCK_KEY 0x5095
4327 
4331  struct ProcessInf
4332  {
4336  pid_t pid;
4340  time_t lastTime;
4344  char name[MAX_PROCESS_NAME];
4348  char argv0[20];
4352  char argv1[20];
4356  char argv2[20];
4357  };
4358 
4366  class HBSystem
4367  {
4368  private:
4369 
4370  static ProcessInf *p;
4371  static csemp plock;
4372  static bool isJoin;
4373  public:
4382  bool join(const char *name,const char *argv0="",const char *argv1="",const char *argv2="");
4387  bool renew();
4391  static void list();
4398  static bool HBCheck(const int &sec);
4403  bool deleteFromHBS();
4408  ~HBSystem();
4409  };
4410 
4414  class Process
4415  {
4416  public:
4417 
4418 
4439  template<class... Args>
4440  static bool startProcess(const std::string &name,const int &sec=-1,Args ...args)
4441  {
4442  std::vector<const char *> paramList={args...,nullptr};
4443  if(sec==-1)
4444  {
4445  pid_t pid=fork();
4446  if(pid==-1)
4447  return false;
4448  if(pid>0)
4449  return true;
4450  else
4451  {
4452  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4453  return false;
4454  }
4455  }
4456  for(int ii=1;ii<=64;ii++)
4457  signal(ii,SIG_IGN);
4458  pid_t pid=fork();
4459  if(pid==-1)
4460  return false;
4461  if(pid>0)
4462  {
4463  return true;
4464  }
4465  else
4466  {
4467  signal(SIGCHLD,SIG_DFL);
4468  signal(15,SIG_DFL);
4469  while(1)
4470  {
4471  pid=fork();
4472  if(fork()==0)
4473  {
4474  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4475  exit(0);
4476  }
4477  else if(pid>0)
4478  {
4479  int sts;
4480  wait(&sts);
4481  sleep(sec);
4482  }
4483  else
4484  continue;
4485  }
4486  }
4487  }
4509  template<class Fn,class... Args>
4510  static typename std::enable_if<!std::is_convertible<Fn, std::string>::value, bool>::type
4511  startProcess(Fn&& fn,const int &sec=-1,Args &&...args)
4512  {
4513  if(sec==-1)
4514  {
4515  pid_t pid=fork();
4516  if(pid==-1)
4517  return false;
4518  if(pid>0)
4519  return true;
4520  else
4521  {
4522  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4523  f();
4524  return true;
4525  }
4526  }
4527  for(int ii=1;ii<=64;ii++)
4528  signal(ii,SIG_IGN);
4529  pid_t pid=fork();
4530  if(pid==-1)
4531  return false;
4532  if(pid>0)
4533  {
4534  return true;
4535  }
4536  else
4537  {
4538  signal(SIGCHLD,SIG_DFL);
4539  signal(15,SIG_DFL);
4540  while(1)
4541  {
4542  pid=fork();
4543  if(pid==0)
4544  {
4545  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4546  f();
4547  return true;
4548  }
4549  else if(pid>0)
4550  {
4551  int sts;
4552  wait(&sts);
4553  sleep(sec);
4554  }
4555  else
4556  continue;
4557  }
4558  }
4559  }
4560  };
4561 
4562  using Task = std::function<void()>;
4588  class WorkerPool
4589  {
4590  public:
4598  explicit WorkerPool(size_t n):stop_(false)
4599  {
4600  for (size_t i = 0; i < n; ++i) {
4601  threads_.emplace_back([this] {
4602  this->workerLoop();
4603  });
4604  }
4605  }
4613  {
4614  stop();
4615  }
4623  void submit(Task task)
4624  {
4625  {
4626  std::lock_guard<std::mutex> lk(mtx_);
4627  tasks_.push(std::move(task));
4628  }
4629  cv_.notify_one();
4630  }
4641  void stop()
4642  {
4643  {
4644  std::lock_guard<std::mutex> lk(mtx_);
4645  stop_ = true;
4646  }
4647  cv_.notify_all();
4648  for (auto &t : threads_)
4649  {
4650  if (t.joinable()) t.join();
4651  }
4652  }
4653 
4654  private:
4665  void workerLoop()
4666  {
4667  while (true)
4668  {
4669  Task task;
4670  {
4671  std::unique_lock<std::mutex> lk(mtx_);
4672  cv_.wait(lk, [this] {
4673  return stop_ || !tasks_.empty();
4674  });
4675  if (stop_ && tasks_.empty())
4676  {
4677  return;
4678  }
4679  task = std::move(tasks_.front());
4680  tasks_.pop();
4681  }
4682  task(); // 执行任务
4683  }
4684  }
4685 
4686  private:
4687  std::vector<std::thread> threads_;
4688  std::queue<Task> tasks_;
4689  std::mutex mtx_;
4690  std::condition_variable cv_;
4691  bool stop_;
4692  };
4693  }
4694 
4695 }
4696 
4697 
4698 #endif
4699 
void setSecuritySendBackFun(std::function< void(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
设置违反信息安全策略时候的返回函数
Definition: sttnet.h:3583
void setStartFunction(std::function< bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fccc)
设置websocket连接成功后就执行的回调函数 注册一个回调函数
Definition: sttnet.h:3837
time_t response
上次收到信息的时间
Definition: sttnet.h:3089
统一的连接与请求安全裁决器(IP 级 + fd 级,多策略限流 + 黑名单)。
Definition: sttnet.h:2220
std::chrono::duration< uint64_t > Seconds
Definition: sttnet.h:1010
bool operator>(const Duration &b)
判断当前时间间隔是否大于另一个时间间隔。
Definition: sttnet.h:744
int getServerPort()
返回已连接的客户端的端口 return 已连接的服务端的端口
Definition: sttnet.h:2634
int fd
底层套接字
Definition: sttnet.h:3217
SSL * getSSL()
获取该对象的加密SSL句柄
Definition: sttnet.h:2436
Definition: sttnet.h:2128
int checkFrequency
Definition: sttnet.h:3261
bool isStart()
返回本对象计时状态
Definition: sttnet.h:1116
bool fin
fin的状态
Definition: sttnet.h:3109
std::string header
握手阶段的Http/Https请求头
Definition: sttnet.h:3081
TcpFDInf * clientfd
Definition: sttnet.h:3239
std::string getServerIp()
如果连接到了服务器 返回服务器ip
Definition: sttnet.h:2943
bool unblock
Definition: sttnet.h:3247
int ret
返回值 -2:失败并且要求关闭连接 -1:失败但不需要关闭连接 1:成功
Definition: sttnet.h:3221
void setFD(const int &fd, SSL *ssl=nullptr, const bool &flag1=false, const bool &flag2=true)
初始化对象,传入套接字等参数
Definition: sttnet.h:3017
tcp协议的套接字操作类
Definition: sttnet.h:2403
void setConnectStrategy(const stt::security::RateLimitType &type)
设置“连接速率限流”所使用的策略。
Definition: sttnet.h:3439
static std::string createJson(T1 first, T2 second, Args...args)
创建多个键值对组成的 JSON 字符串(递归变参模板)。
Definition: sttnet.h:1884
表示时间间隔的结构体,支持天、小时、分钟、秒和毫秒粒度。
Definition: sttnet.h:712
void setGlobalSolveFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
设置全局备用函数
Definition: sttnet.h:3592
WebSocket协议的操作类 仅传入套接字,然后使用这个类进行WebSocket的操作
Definition: sttnet.h:3664
bool isConnect()
判断对象是否有套接字绑定
Definition: sttnet.h:2459
时间操作、运算、计时的类
Definition: sttnet.h:1027
int getFD()
获取该对象的套接字
Definition: sttnet.h:2431
void waitAndQuit(const time::Duration &t=time::Duration{0, 0, 0, 10, 10})
开始退出epoll倒计时,直到套接字有新的消息 如果套接字倒计时结束还没有新的消息,那么退出epoll
Definition: sttnet.h:2821
bool operator<=(const Duration &b)
判断当前时间间隔是否小于等于另一个时间间隔。
Definition: sttnet.h:808
Http/HttpServer 服务端操作类
Definition: sttnet.h:3497
bool sendMessage(const int &fd, const std::string &msg, const std::string &type="0001")
发送 WebSocket 消息给某一个客户端
Definition: sttnet.h:3952
void setCloseFun(std::function< void(const int &fd)> closeFun)
设置关闭tcp连接之后调用的函数
Definition: sttnet.h:3472
std::string body_chunked
请求体(chunked)
Definition: sttnet.h:2995
工作现场完成任务后压入完成队列的数据结构
Definition: sttnet.h:3212
pid_t pid
进程id
Definition: sttnet.h:4336
WebSocketClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
WebSocketClient类的构造函数
Definition: sttnet.h:2858
Duration operator+(const Duration &b)
将两个时间间隔相加。
Definition: sttnet.h:824
Duration(long long a, int b, int c, int d, int e)
构造函数,传入天,时,分,秒,毫秒
Definition: sttnet.h:737
int getFD()
返回fd
Definition: sttnet.h:4041
单个 IP 的安全状态与连接集合。
Definition: sttnet.h:2098
std::string body
请求体
Definition: sttnet.h:2991
std::string loc
文件路径
Definition: sttnet.h:306
unsigned long p_buffer_now
接收空间位置指针
Definition: sttnet.h:3206
bool isConnect()
返回对象的连接状态
Definition: sttnet.h:2639
MPSCQueue & operator=(const MPSCQueue &)=delete
std::ostream & operator<<(std::ostream &os, const Duration &a)
将 Duration 对象以可读格式输出到流中。
LogFile(const size_t &logQueue_cap=8192)
构造函数,初始化消费者线程
Definition: sttnet.h:1157
int sec
Definition: sttnet.h:729
~TcpServer()
TcpServer 类的析构函数
Definition: sttnet.h:3488
double convertToMin()
将当前时间间隔转换为以“分钟”为单位的浮点数表示。
Definition: sttnet.h:931
int fd
底层的socket套接字
Definition: sttnet.h:2963
unsigned long buffer_size
Definition: sttnet.h:3234
std::string getServerPort()
如果连接到了服务器 返回服务器端口
Definition: sttnet.h:2948
unsigned long long maxFD
Definition: sttnet.h:3235
int serverType
Definition: sttnet.h:3256
void setPathLimit(const std::string &path, const int &times, const int &secs)
设置某个路径的额外限流规则(path 级)。
Definition: sttnet.h:3468
void setTimeOutFunction(std::function< bool(const int &fd)> fcTimeOut)
设置epoll超时后出发的回调函数 注册一个回调函数
Definition: sttnet.h:2804
Duration recoverForm(const long long &t)
从给定的毫秒数恢复为标准的天-时-分-秒-毫秒格式。
Definition: sttnet.h:962
static std::string createArray(T first)
创建只包含一个元素的 JSON 数组字符串。
Definition: sttnet.h:1909
std::queue< std::any > pendindQueue
等待处理的队列
Definition: sttnet.h:3182
负责字符串和数字的转化
Definition: sttnet.h:1689
~EpollSingle()
EpollSingle的析构函数 调用eldListen阻塞退出epoll.
Definition: sttnet.h:2826
int threads
记录文件正在被多少个线程使用
Definition: sttnet.h:310
std::string para
url中的参数
Definition: sttnet.h:2983
void setFunction(const std::string &key, std::function< int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
设置key对应的收到客户端消息后的回调函数
Definition: sttnet.h:3864
static std::string language
系统的日志系统的语言选择,默认为English
Definition: sttnet.h:4191
负责进程心跳监控,调度的类 用于监控服务进程,保证服务进程持续有效运行 进程结束后,0x5095这一块共享内存和信号量都没有删掉 目前只支持最多三个参数的进程加入监控 应该自己手动在程序编写加入心跳监控...
Definition: sttnet.h:4366
std::deque< std::chrono::steady_clock::time_point > history
Definition: sttnet.h:2046
size_t getFileSize()
获取二进制打开的文件的大小
Definition: sttnet.h:450
Definition: sttnet.h:2130
Tcp服务端类
Definition: sttnet.h:3229
uint64_t connection_obj_fd
连接对象fd
Definition: sttnet.h:3166
stt::system::WorkerPool * workpool
Definition: sttnet.h:3233
static std::string createArray(T first, Args...args)
创建多个元素组成的 JSON 数组字符串(递归变参模板)。
Definition: sttnet.h:1927
static std::mutex l1
Definition: sttnet.h:332
std::string port
客户端端口
Definition: sttnet.h:3174
UDP操作的类 传入套接字进行UDP协议的操作
Definition: sttnet.h:4008
int requestTimes
Definition: sttnet.h:3260
size_t getSize1()
获取二进制打开的文件在内存中的大小
Definition: sttnet.h:459
static std::enable_if<!std::is_convertible< Fn, std::string >::value, bool >::type startProcess(Fn &&fn, const int &sec=-1, Args &&...args)
通过函数创建子进程(可选择是否定时重启)
Definition: sttnet.h:4511
uint64_t connection_obj_fd
Definition: sttnet.h:3262
~File()
析构函数
Definition: sttnet.h:417
std::string loc
url中的路径
Definition: sttnet.h:2979
HttpClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
HttpClient类的构造函数
Definition: sttnet.h:2666
bool push(const T &v) noexcept(std::is_nothrow_copy_constructible_v< T >)
Definition: sttnet.h:135
WebSocketServer服务端操作类
Definition: sttnet.h:3719
std::string locPara
握手阶段的Http/Https路径和参数
Definition: sttnet.h:3077
解析,响应Http/https请求的操作类 仅传入套接字,然后使用这个类进行Http的操作
Definition: sttnet.h:3007
void setGlobalSolveFunction(std::function< bool(TcpFDHandler &k, TcpInformation &inf)> fc)
设置全局备用函数
Definition: sttnet.h:3388
bool operator<(const Duration &b)
判断当前时间间隔是否小于另一个时间间隔。
Definition: sttnet.h:760
bool isConnect()
返回连接状态
Definition: sttnet.h:2933
负责加密,解密和哈希
Definition: sttnet.h:1239
负责浮点数精度处理
Definition: sttnet.h:1416
void stop()
停止线程池并等待所有线程退出
Definition: sttnet.h:4641
SSL_CTX * ctx
Definition: sttnet.h:3248
负责二进制数据,字符串之间的转化
Definition: sttnet.h:1294
json数据操作类
Definition: sttnet.h:1820
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.h:131
std::unordered_map< std::string, std::any > ctx
所需的数据仓库
Definition: sttnet.h:3144
~HttpServer()
析构函数
Definition: sttnet.h:3655
uint64_t connection_obj_fd
连接对象fd
Definition: sttnet.h:2967
int connectionTimes
Definition: sttnet.h:3258
MPSCQueue(std::size_t capacity_pow2)
Definition: sttnet.h:99
std::unordered_map< std::string, RateState > pathRate
Definition: sttnet.h:2072
进程信息的结构体
Definition: sttnet.h:4331
static std::unordered_map< std::string, FileThreadLock > fl2
Definition: sttnet.h:333
std::size_t approx_size() const noexcept
Approximate size (may be inaccurate under concurrency) 近似长度(并发下可能不精确)
Definition: sttnet.h:173
#define MAX_PROCESS_NAME
定义MAX_PROCESS_NAME这个宏为100,意思是进程信息中的进程名字长度不超过100个字节
Definition: sttnet.h:4314
tcp协议客户端操作类
Definition: sttnet.h:2564
负责Http字符串和URL解析 包括从 URL 或请求报文中提取参数、IP、端口、请求头字段等功能。
Definition: sttnet.h:1471
double convertToHour()
将当前时间间隔转换为以“小时”为单位的浮点数表示。
Definition: sttnet.h:921
void setGetKeyFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKeyFun)
设置解析出key的回调函数
Definition: sttnet.h:3639
csemp()
构造函数,初始化内部状态。
Definition: sttnet.h:4255
time_t lastTime
进程最后一次心跳时间,是时间戳
Definition: sttnet.h:4340
long long day
Definition: sttnet.h:717
void setGetKeyFunction(std::function< int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
设置解析出key的回调函数
Definition: sttnet.h:3413
void setSecuritySendBackFun(std::function< void(TcpFDHandler &k, TcpInformation &inf)> fc)
设置违反信息安全策略时候的返回函数
Definition: sttnet.h:3378
void setFunction(const std::string &key, std::function< int(TcpFDHandler &k, TcpInformation &inf)> fc)
设置key对应的收到客户端消息后的回调函数
Definition: sttnet.h:3399
std::mutex lock
此文件的锁
Definition: sttnet.h:314
int min
Definition: sttnet.h:725
void endListenWithSignal()
发送结束epoll的信号
Definition: sttnet.h:2815
保存HTTP/HTTPS请求信息的结构体
Definition: sttnet.h:2958
std::unordered_map< std::string, std::any > ctx
所需的数据仓库
Definition: sttnet.h:3117
WorkerPool(size_t n)
构造函数,创建指定数量的工作线程
Definition: sttnet.h:4598
Duration operator-(const Duration &b)
计算两个时间间隔的差值(当前对象减去参数 b)。
Definition: sttnet.h:868
Lock-free bounded MPSC queue (Multi-Producer Single-Consumer) 无锁有界多生产者单消费者队列(环形缓冲) ...
Definition: sttnet.h:97
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)
构造函数,默认是允许最大1000000个连接,每个连接接收缓冲区最大为256kb,启用安全模块。
Definition: sttnet.h:3794
RateState connectRate
Definition: sttnet.h:2101
double convertToSec()
将当前时间间隔转换为以“秒”为单位的浮点数表示。
Definition: sttnet.h:941
std::string getUrl()
如果连接到了服务器 返回url
Definition: sttnet.h:2938
static file::LogFile * logfile
系统的日志系统的读写日志对象的指针
Definition: sttnet.h:4187
TLSState
Definition: sttnet.h:3147
size_t recv_length
待接收的长度
Definition: sttnet.h:3093
static std::string createHeader(const std::string &first, const std::string &second, Args...args)
递归构造多个 HTTP 请求头字段。
Definition: sttnet.h:1661
用epoll监听单个句柄
Definition: sttnet.h:2745
int workerEventFD
Definition: sttnet.h:3255
int FDStatus
记录当前处理状态机到第几步了
Definition: sttnet.h:3178
std::string header
请求头
Definition: sttnet.h:2987
~WorkerPool()
析构函数
Definition: sttnet.h:4612
void setPathStrategy(const stt::security::RateLimitType &type)
设置“path 级请求限流”所使用的策略。
Definition: sttnet.h:3454
void setSecuritySendBackFun(std::function< void(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
设置违反信息安全策略时候的返回函数
Definition: sttnet.h:3818
bool sendMessage(const std::string &msg, const std::string &type="0001")
发送一条websocket信息
void setFD(const int &fd, SSL *ssl=nullptr, const bool &flag1=false, const bool &flag2=true)
初始化对象,传入套接字等参数
Definition: sttnet.h:3674
int connectionSecs
Definition: sttnet.h:3257
FileThreadLock(const std::string &loc, const int &threads)
这个结构体的构造函数
Definition: sttnet.h:320
bool operator>=(const Duration &b)
判断当前时间间隔是否大于等于另一个时间间隔。
Definition: sttnet.h:792
保存客户端WS/WSS请求信息的结构体
Definition: sttnet.h:3060
std::string getFileName()
获取打开的文件名字
Definition: sttnet.h:432
~TcpClient()
TcpClient的析构函数,会关闭释放套接字和其连接
Definition: sttnet.h:2623
void setEndFunction(std::function< void(const int &fd)> fcEnd)
设置epoll退出前的回调函数 注册一个回调函数
Definition: sttnet.h:2794
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.h:143
负责websocket协议有关字符串的操作
Definition: sttnet.h:1670
Duration getDt()
获取上一次计时的时间
Definition: sttnet.h:1111
数据编码解码,掩码处理等
Definition: sttnet.h:1758
std::function< void()> Task
Definition: sttnet.h:4562
~UdpServer()
析构函数,对象生命结束会会关闭套接字
Definition: sttnet.h:4164
bool startListen(const int &port, const int &threads=8)
打开Http服务器监听程序
Definition: sttnet.h:3646
保存Tcp客户端的信息
Definition: sttnet.h:3127
bool operator==(const Duration &b)
判断当前时间间隔是否等于另一个时间间隔。
Definition: sttnet.h:776
单一限流器的运行状态(可复用于多种限流策略)。
Definition: sttnet.h:2038
int message_type
消息类型
Definition: sttnet.h:3101
std::unordered_map< std::string, std::any > ctx
所需的数据仓库
Definition: sttnet.h:2999
char * buffer
接收空间指针
Definition: sttnet.h:3202
记录文件和线程关系的结构体
Definition: sttnet.h:301
int fd
套接字fd
Definition: sttnet.h:3132
int status
当前fd的接收状态,用于保存接收处理机逻辑
Definition: sttnet.h:3186
void writeLog(const std::string &data)
写一行日志
std::string locPara
url中的路径和参数
Definition: sttnet.h:2975
初始化服务系统的类
Definition: sttnet.h:4181
~UdpClient()
析构函数,对象生命结束会会关闭套接字
Definition: sttnet.h:4139
std::string data
裸数据
Definition: sttnet.h:3140
uint64_t getFileLine()
获取打开的文件的行数
Definition: sttnet.h:441
bool isOpen()
判断对象是否打开了文件
Definition: sttnet.h:422
bool isReturn()
获取服务器返回响应状态
Definition: sttnet.h:2731
int requestSecs
Definition: sttnet.h:3259
std::string_view data
保存收到的客户端传来的数据
Definition: sttnet.h:3190
std::chrono::duration< uint64_t, std::milli > Milliseconds
Definition: sttnet.h:1009
单个连接(fd)的安全与限流状态。
Definition: sttnet.h:2068
RateState requestRate
Definition: sttnet.h:2071
void setGetKeyFunction(std::function< int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> parseKeyFun)
设置解析出key的回调函数
Definition: sttnet.h:3884
void setRequestStrategy(const stt::security::RateLimitType &type)
设置“IP 级请求限流”所使用的策略。
Definition: sttnet.h:3446
std::string type
请求类型
Definition: sttnet.h:2971
TLSState tls_state
tls状态
Definition: sttnet.h:3198
uint64_t connection_obj_fd
连接对象fd
Definition: sttnet.h:3136
Websocket客户端操作的类 -如果需要重新设置TLS/Https加密的证书,目前需要销毁对象后重新构造 底层TCP默认是阻塞的
Definition: sttnet.h:2834
bool isBinary()
判断对象是否以二进制模式打开文件
Definition: sttnet.h:427
std::string getServerIP()
返回已连接的服务端的ip return 已连接的服务端的ip
Definition: sttnet.h:2629
uint64_t connection_obj_fd
连接对象fd
Definition: sttnet.h:3069
void submit(Task task)
向线程池提交一个任务
Definition: sttnet.h:4623
封装 System V 信号量的同步工具类。
Definition: sttnet.h:4230
std::string mask
mask
Definition: sttnet.h:3113
~MPSCQueue()
Definition: sttnet.h:121
RateLimitType
限流算法类型(策略)。
Definition: sttnet.h:2012
负责大小端字节序转换
Definition: sttnet.h:1396
~WebSocketServer()
WebSocketServer的析构函数
Definition: sttnet.h:4001
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)
构造函数,默认是允许最大1000000个连接,每个连接接收缓冲区最大为256kb,启用安全模块。
Definition: sttnet.h:3327
std::mutex che
Definition: sttnet.h:335
bool startListen(const int &port, const int &threads=8)
打开Websocket服务器监听程序
Definition: sttnet.h:3969
std::string getFileName()
获取对象打开的文件名
Definition: sttnet.h:1198
udp服务端的操作类
Definition: sttnet.h:4144
double convertToDay()
将当前时间间隔转换为以“天”为单位的浮点数表示。
Definition: sttnet.h:911
bool isListen()
返回epoll监听状态
Definition: sttnet.h:2776
Http/Https客户端操作类
Definition: sttnet.h:2649
bool closeflag
true:发送了关闭帧 false:没有发送关闭帧
Definition: sttnet.h:3073
int fd
套接字fd
Definition: sttnet.h:3162
size_t have_recv_length
已经接收的长度
Definition: sttnet.h:3097
bool security_open
Definition: sttnet.h:3252
HttpRequestInformation httpinf
握手阶段保存的http信息
Definition: sttnet.h:3121
进程管理的静态工具类
Definition: sttnet.h:4414
int hour
Definition: sttnet.h:721
long long convertToMsec()
将当前时间间隔转换为总毫秒数。
Definition: sttnet.h:951
void setFunction(std::function< bool(const int &fd)> fc)
设置epoll触发后的处理函数 注册一个回调函数
Definition: sttnet.h:2786
udp客户端的操作类
Definition: sttnet.h:4121
static std::string createJson(T1 first, T2 second)
创建仅包含一个键值对的 JSON 字符串。
Definition: sttnet.h:1859
void setGlobalSolveFunction(std::function< bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
设置全局备用函数
Definition: sttnet.h:3828
保存底层基础Tcp通道信息的结构体
Definition: sttnet.h:3157
void setFunction(const std::string &key, std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
设置key对应的收到客户端消息后的回调函数
Definition: sttnet.h:3619
security::ConnectionLimiter connectionLimiter
Definition: sttnet.h:3236
std::string ip
客户端ip
Definition: sttnet.h:3170
bool isOpen()
获取对象是否打开日志文件的状态
Definition: sttnet.h:1193
DefenseDecision
安全裁决结果(由 ConnectionLimiter 返回)。
Definition: sttnet.h:2126
int fd
底层的socket套接字
Definition: sttnet.h:3065
void setHBTimeOutTime(const int &secb)
设置发送心跳后的等待时间
Definition: sttnet.h:3896
提供文件操作的静态函数工具类
Definition: sttnet.h:259
ConnectionLimiter(const int &maxConn=20, const int &idleTimeout=60)
构造函数。
Definition: sttnet.h:2229
日志文件操作类
Definition: sttnet.h:1126
读写磁盘文件的类
Definition: sttnet.h:329
void setJudgeFunction(std::function< bool(WebSocketFDInformation &k)> fcc)
设置websocket握手阶段的检查函数,只有检查通过才执行后续握手 注册一个回调函数
Definition: sttnet.h:3847
int msec
毫秒
Definition: sttnet.h:733
随机数,字符串生成相关
Definition: sttnet.h:1360
SSL * ssl
如果加密了,存放加密句柄
Definition: sttnet.h:3194
bool isListen()
返回对象的监听状态
Definition: sttnet.h:3478
Definition: sttnet.h:2129
static bool startProcess(const std::string &name, const int &sec=-1, Args...args)
启动一个新进程(可选择是否定时重启)
Definition: sttnet.h:4440
#define ISO8086A
定义ISO8086A这个宏为&quot;yyyy-mm-ddThh:mi:ss&quot;
Definition: sttnet.h:1014
void setTimeOutTime(const int &seca)
设置心跳时间
Definition: sttnet.h:3890
void setFunction(std::function< bool(const std::string &message, WebSocketClient &k)> fc)
设置收到服务端消息后的回调函数 注册一个回调函数
Definition: sttnet.h:2869
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)
构造函数,默认是允许最大1000000个连接,每个连接接收缓冲区最大为256kb,启用安全模块。
Definition: sttnet.h:3559
system::MPSCQueue< WorkerMessage > finishQueue
Definition: sttnet.h:3232
固定大小的工作线程池
Definition: sttnet.h:4588
std::unordered_map< int, ConnectionState > conns
Definition: sttnet.h:2103