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>
58 namespace stt
59 {
60 
61  namespace system
62  {
63  class WorkerPool;
64  }
70  namespace file
71  {
75  class FileTool
76  {
77  public:
85  static bool createDir(const std::string & ddir,const mode_t &mode=0775);
94  static bool copy(const std::string &sourceFile,const std::string &objectFile);
103  static bool createFile(const std::string &filePath,const mode_t &mode=0666);
110  static size_t get_file_size(const std::string &fileName);
111  };
112 
118  {
122  std::string loc;
126  int threads;
130  std::mutex lock;
136  FileThreadLock(const std::string &loc,const int &threads):loc(loc),threads(threads){};
137  };
138 
145  class File:private FileTool
146  {
147  protected:
148  static std::mutex l1;
149  static std::unordered_map<std::string,FileThreadLock> fl2;
150  protected:
151  std::mutex che;
152 
153  private:
154  void lockfl2();
155  void unlockfl2();
156  private:
157  std::ifstream fin;
158  std::vector<std::string> data;
159  std::vector<std::string> backUp;
160  char *data_binary=nullptr;
161  char *backUp_binary=nullptr;
162  size_t size1=0;
163  size_t size2=0;
164  int multiple=0;
165  size_t multiple_backup=0;
166  size_t malloced=0;
167  std::mutex fl1;
168 
169  std::ofstream fout;
170  std::string fileName;
171 
172  std::string fileNameTemp;
173  bool flag=false;
174  bool binary;
175  mode_t mode;
176  size_t size=0;
177  uint64_t totalLines=0;
178  private:
179  void toMemory();
180  bool toDisk();
181  public:
222  bool openFile(const std::string &fileName,const bool &create=true,const int &multiple=0,const size_t &size=0,const mode_t &mode=0666);
228  bool closeFile(const bool &del=false);
233  ~File(){closeFile(false);}
238  bool isOpen(){return flag;}
243  bool isBinary(){return binary;}
248  std::string getFileName(){return fileName;}
257  uint64_t getFileLine(){return totalLines;}
266  size_t getFileSize(){return size;}
275  size_t getSize1(){return size1;}
276  public:
282  bool lockMemory();
290  bool unlockMemory(const bool &rec=false);
291  public:
305  int findC(const std::string &targetString,const int linePos=1);
315  bool appendLineC(const std::string &data,const int &linePos=0);
324  bool deleteLineC(const int &linePos=0);
331  bool deleteAllC();
341  bool chgLineC(const std::string &data,const int &linePos=0);
351  bool readLineC(std::string &data,const int linePos);
361  std::string& readC(std::string &data,const int &linePos,const int &num);
368  std::string& readAllC(std::string &data);
384  bool readC(char *data,const size_t &pos,const size_t &size);
395  bool writeC(const char *data,const size_t &pos,const size_t &size);
400  void formatC();
402  public:
416  int find(const std::string &targetString,const int linePos=1);
426  bool appendLine(const std::string &data,const int &linePos=0);
435  bool deleteLine(const int &linePos=0);
442  bool deleteAll();
452  bool chgLine(const std::string &data,const int &linePos=0);
462  bool readLine(std::string &data,const int linePos);
472  std::string& read(std::string &data,const int &linePos,const int &num);
479  std::string& readAll(std::string &data);
495  bool read(char *data,const size_t &pos,const size_t &size);
506  bool write(const char *data,const size_t &pos,const size_t &size);
511  void format();
513  };
514  }
520  namespace time
521  {
528  struct Duration
529  {
533  long long day;
537  int hour;
541  int min;
545  int sec;
549  int msec;
553  Duration(long long a,int b,int c,int d,int e):day(a),hour(b),min(c),sec(d),msec(e){}
554  Duration()=default;
560  bool operator>(const Duration &b)
561  {
562  long long total;
563  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
564  long long totalB;
565  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
566  if(total>totalB)
567  return true;
568  else
569  return false;
570  }
576  bool operator<(const Duration &b)
577  {
578  long long total;
579  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
580  long long totalB;
581  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
582  if(total<totalB)
583  return true;
584  else
585  return false;
586  }
592  bool operator==(const Duration &b)
593  {
594  long long total;
595  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
596  long long totalB;
597  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
598  if(total==totalB)
599  return true;
600  else
601  return false;
602  }
608  bool operator>=(const Duration &b)
609  {
610  long long total;
611  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
612  long long totalB;
613  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
614  if(total>=totalB)
615  return true;
616  else
617  return false;
618  }
624  bool operator<=(const Duration &b)
625  {
626  long long total;
627  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
628  long long totalB;
629  totalB=b.day*24*60*60*1000+b.hour*60*60*1000+b.min*60*1000+b.sec*1000+b.msec;
630  if(total<=totalB)
631  return true;
632  else
633  return false;
634  }
641  {
642  long long dayy=day;
643  int hourr=hour;
644  int minn=min;
645  int secc=sec;
646  int msecc=msec;
647 
648  msecc+=b.msec;
649  secc+=b.sec;
650  minn+=b.min;
651  hourr+=b.hour;
652  dayy+=b.day;
653 
654  if(msecc/1000!=0)
655  {
656  secc+=msecc/1000;
657  msecc=msecc%1000;
658  }
659 
660  if(secc/60!=0)
661  {
662  minn+=secc/60;
663  secc=secc%60;
664  }
665 
666  if(minn/60!=0)
667  {
668  hourr+=minn/60;
669  minn=minn%60;
670  }
671 
672  if(hourr/24!=0)
673  {
674  dayy+=hourr/24;
675  hourr=hourr%24;
676  }
677  return Duration(dayy,hourr,minn,secc,msecc);
678  }
685  {
686  long long dayy=day;
687  int hourr=hour;
688  int minn=min;
689  int secc=sec;
690  int msecc=msec;
691 
692  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;
693  secc=0;
694  minn=0;
695  hourr=0;
696  dayy=0;
697 
698  if(msecc/1000!=0)
699  {
700  secc+=msecc/1000;
701  msecc=msecc%1000;
702  }
703 
704  if(secc/60!=0)
705  {
706  minn+=secc/60;
707  secc=secc%60;
708  }
709 
710  if(minn/60!=0)
711  {
712  hourr+=minn/60;
713  minn=minn%60;
714  }
715 
716  if(hourr/24!=0)
717  {
718  dayy+=hourr/24;
719  hourr=hourr%24;
720  }
721  return Duration(dayy,hourr,minn,secc,msecc);
722  }
723 
727  double convertToDay()
728  {
729  long long total;
730  total=hour*60*60*1000+min*60*1000+sec*1000+msec;
731  double k=day+total/86400000.0000;
732  return k;
733  }
737  double convertToHour()
738  {
739  long long total;
740  total=min*60*1000+sec*1000+msec;
741  double k=day*24+hour+total/36000000.0000;
742  return k;
743  }
747  double convertToMin()
748  {
749  long long total;
750  total=sec*1000+msec;
751  double k=day*24*60+hour*60+min+total/60000.0000;
752  return k;
753  }
757  double convertToSec()
758  {
759  long long total;
760  total=msec;
761  double k=day*24*60*60+hour*60*60+min*60+sec+total/1000.0000;
762  return k;
763  }
767  long long convertToMsec()
768  {
769  long long total;
770  total=day*24*60*60*1000+hour*60*60*1000+min*60*1000+sec*1000+msec;
771  return total;
772  }
778  Duration recoverForm(const long long &t)
779  {
780  msec=t;
781  sec=0;
782  min=0;
783  hour=0;
784  day=0;
785 
786  if(msec/1000!=0)
787  {
788  sec+=msec/1000;
789  msec=msec%1000;
790  }
791 
792  if(sec/60!=0)
793  {
794  min+=sec/60;
795  sec=sec%60;
796  }
797 
798  if(min/60!=0)
799  {
800  hour+=min/60;
801  min=min%60;
802  }
803 
804  if(hour/24!=0)
805  {
806  day+=hour/24;
807  hour=hour%24;
808  }
809  return Duration(day,hour,min,sec,msec);
810  }
811  };
823  std::ostream& operator<<(std::ostream &os,const Duration &a);
824 
825  using Milliseconds = std::chrono::duration<uint64_t,std::milli>;
826  using Seconds=std::chrono::duration<uint64_t>;
830  #define ISO8086A "yyyy-mm-ddThh:mi:ss"
831 
834  #define ISO8086B "yyyy-mm-ddThh:mi:ss.sss"
835 
836 
843  class DateTime
844  {
845  private:
846  static Duration& dTOD(const Milliseconds& d1,Duration &D1);
847  static Milliseconds& DTOd(const Duration &D1,Milliseconds& d1);
848  static std::string &toPGtimeFormat();
849  static std::chrono::system_clock::time_point strToTimePoint(const std::string &timeStr,const std::string &format=ISO8086A);
850  static std::string& timePointToStr(const std::chrono::system_clock::time_point &tp,std::string &timeStr,const std::string &format=ISO8086A);
851  public:
859  static std::string& getTime(std::string &timeStr,const std::string &format=ISO8086A);
868  static bool convertFormat(std::string &timeStr,const std::string &oldFormat,const std::string &newFormat=ISO8086A);
878  static Duration& calculateTime(const std::string &time1,const std::string &time2,Duration &result,const std::string &format1=ISO8086A,const std::string &format2=ISO8086A);
889  static std::string& calculateTime(const std::string &time1,const Duration &time2,std::string &result,const std::string &am,const std::string &format1=ISO8086A,const std::string &format2=ISO8086A);
899  static bool compareTime(const std::string &time1,const std::string &time2,const std::string &format1=ISO8086A,const std::string &format2=ISO8086A);
900  private:
901  Duration dt{-1,-1,-1,-1,-1};
902  bool flag=false;
903  std::chrono::steady_clock::time_point start;
904  std::chrono::steady_clock::time_point end;
905  public:
910  bool startTiming();
922  public:
927  Duration getDt(){return dt;}
932  bool isStart(){return flag;}
933  };
934  }
935  namespace file
936  {
941  class LogFile:private time::DateTime,protected File
942  {
943  private:
944  std::string timeFormat;
945  std::string contentFormat;
946  std::atomic<bool> consumerGuard{true};
947  std::mutex queueMutex;
948  std::condition_variable queueCV;
949  std::queue<std::string> logQueue;
950  std::thread consumerThread;
951  public:
955  LogFile();
964  bool openFile(const std::string &fileName,const std::string &timeFormat=ISO8086A,const std::string &contentFormat=" ");
969  bool isOpen(){return File::isOpen();}
974  std::string getFileName(){return File::getFileName();}
980  bool closeFile(const bool &del=false);
985  void writeLog(const std::string &data);
990  bool clearLog();
998  bool deleteLogByTime(const std::string &date1="1",const std::string &date2="2");
1002  ~LogFile();
1003  };
1004  }
1010  namespace data
1011  {
1016  {
1017  public:
1028  static bool encryptSymmetric(const unsigned char *before,const size_t &length,const unsigned char *passwd,const unsigned char *iv,unsigned char *after);
1039  static bool decryptSymmetric(const unsigned char *before,const size_t &length,const unsigned char *passwd,const unsigned char *iv,unsigned char *after);
1052  static std::string& sha1(const std::string &ori_str,std::string &result);
1065  static std::string& sha11(const std::string &ori_str,std::string &result);
1066  };
1070  class BitUtil
1071  {
1072  public:
1080  static std::string& bitOutput(char input,std::string &result);
1088  static std::string& bitOutput(const std::string &input,std::string &result);
1097  static char& bitOutput_bit(char input,const int pos,char &result);
1105  static unsigned long& bitStrToNumber(const std::string &input,unsigned long &result);
1115  static unsigned long& bitToNumber(const std::string &input,unsigned long &result);
1123  static char& toBit(const std::string &input,char &result);
1131  static std::string& toBit(const std::string &input,std::string &result);
1132  };
1137  {
1138  public:
1146  static long getRandomNumber(const long &a,const long &b);
1153  static std::string& getRandomStr_base64(std::string &str,const int &length);
1167  static std::string& generateMask_4(std::string &mask);
1168  };
1173  {
1174  public:
1186  static unsigned long& htonl_ntohl_64(unsigned long &data);//64位无符号数转化为大/小端序(网络字节序)
1187  };
1188 
1193  {
1194  public:
1195 
1204  static std::string& getPreciesFloat(const float &number,const int &bit,std::string &str);
1212  static float& getPreciesFloat(float &number,const int &bit);
1221  static std::string& getPreciesDouble(const double &number,const int &bit,std::string &str);
1229  static double& getPreciesDouble(double &number,const int &bit);
1241  static float& getValidFloat(float &number,const int &bit);
1242  };
1248  {
1249  public:
1266  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);
1277  static std::string_view& get_value_str(const std::string_view& ori_str,std::string_view &str,const std::string& name);
1286  static std::string_view& get_value_header(const std::string_view& ori_str,std::string_view &str,const std::string& name);
1296  static std::string_view& get_location_str(const std::string_view& ori_str,std::string_view &str);
1306  static std::string_view& getLocPara(const std::string_view &url,std::string_view &locPara);
1315  static std::string_view& getPara(const std::string_view &url,std::string_view &para);
1316 
1317 
1334  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);
1345  static std::string& get_value_str(const std::string& ori_str,std::string &str,const std::string& name);
1354  static std::string& get_value_header(const std::string& ori_str,std::string &str,const std::string& name);
1364  static std::string& get_location_str(const std::string& ori_str,std::string &str);
1374  static std::string& getLocPara(const std::string &url,std::string &locPara);
1383  static std::string& getPara(const std::string &url,std::string &para);
1394  static std::string& getIP(const std::string &url,std::string &IP);
1405  static int& getPort(const std::string &url,int &port);
1415  static std::string createHeader(const std::string& first,const std::string& second);
1436  template<class... Args>
1437  static std::string createHeader(const std::string& first,const std::string& second,Args... args)
1438  {
1439  std::string cf=first+": "+second+"\r\n"+createHeader(args...);
1440  return cf;
1441  }
1442  };
1447  {
1448  public:
1460  static std::string& transfer_websocket_key(std::string &str);
1461  };
1466  {
1467  public:
1476  static int& toInt(const std::string_view&ori_str,int &result,const int &i=-1);
1483  static int& str16toInt(const std::string_view&ori_str,int &result,const int &i=-1);
1492  static long& toLong(const std::string_view&ori_str,long &result,const long &i=-1);
1501  static float& toFloat(const std::string&ori_str,float &result,const float &i=-1);
1510  static double& toDouble(const std::string&ori_str,double &result,const double &i=-1);
1518  static bool& toBool(const std::string_view&ori_str,bool &result);
1529  static std::string& strto16(const std::string &ori_str,std::string &result);//字符串转化为16进制字符串 (暂不需要)(待修复)
1530  };
1535  {
1536  public:
1545  static std::string base64_encode(const std::string &input);
1554  static std::string base64_decode(const std::string &input);
1566  static std::string& transfer_websocket_key(std::string &str);
1580  static std::string& generateMask_4(std::string &mask);
1591  static std::string& maskCalculate(std::string &data,const std::string &mask);
1592  };
1597  {
1598  public:
1611  static int getValue(const std::string &oriStr,std::string& result,const std::string &type="value",const std::string &name="a",const int &num=0);
1612 
1618  static std::string toString(const Json::Value &val);
1624  static Json::Value toJsonArray(const std::string & str);
1634  template<class T1,class T2>
1635  static std::string createJson(T1 first,T2 second)
1636  {
1637  Json::Value root;
1638  //root[first]=second;
1639  if constexpr (std::is_integral_v<T2>) {
1640  root[first] = Json::Value(static_cast<Json::Int64>(second));
1641  } else {
1642  root[first] = second;
1643  }
1644  Json::StreamWriterBuilder builder;
1645  std::string jsonString=Json::writeString(builder,root);
1646  return jsonString;
1647  }
1659  template<class T1,class T2,class... Args>
1660  static std::string createJson(T1 first,T2 second,Args... args)
1661  {
1662  Json::Value root;
1663  //root[first]=second;
1664  if constexpr (std::is_integral_v<T2>) {
1665  root[first] = Json::Value(static_cast<Json::Int64>(second));
1666  } else {
1667  root[first] = second;
1668  }
1669  std::string kk=createJson(args...);
1670  Json::StreamWriterBuilder builder;
1671  std::string jsonString=Json::writeString(builder,root);
1672  jsonString=jsonString.erase(jsonString.length()-2);
1673  kk=kk.substr(1);
1674  return jsonString+","+kk;
1675 
1676  }
1684  template<class T>
1685  static std::string createArray(T first)
1686  {
1687  Json::Value root(Json::arrayValue);
1688  root.append(first);
1689  Json::StreamWriterBuilder builder;
1690  std::string jsonString=Json::writeString(builder,root);
1691  return jsonString;
1692  }
1702  template<class T,class... Args>
1703  static std::string createArray(T first,Args... args)
1704  {
1705  Json::Value root(Json::arrayValue);
1706  root.append(first);
1707  std::string kk=createArray(args...);
1708  Json::StreamWriterBuilder builder;
1709  std::string jsonString=Json::writeString(builder,root);
1710  jsonString=jsonString.erase(jsonString.length()-2);
1711  kk=kk.substr(1);
1712  return jsonString+","+kk;
1713 
1714  }
1721  static std::string jsonAdd(const std::string &a,const std::string &b);
1728  static std::string& jsonFormatify(const std::string &a,std::string &b);
1735  static std::string& jsonToUTF8(const std::string &input,std::string &output);
1736  };
1737  }
1738 
1742  namespace security
1743  {
1788  enum class RateLimitType
1789  {
1790  Cooldown, // 连续触发惩罚:达到上限后进入冷却,需要安静 secs 才恢复
1791  FixedWindow, // 固定窗口计数:每 secs 一个窗口,窗口内最多 times 次
1792  SlidingWindow, // 滑动窗口:统计最近 secs 内的次数(队列时间戳)
1793  TokenBucket // 令牌桶:允许突发 + 控制长期平均速率(常用于 API/消息)
1794  };
1814  struct RateState
1815  {
1816  // 通用
1817  int counter = 0;
1818  int violations = 0; // 新增:触发限流的次数
1819  std::chrono::steady_clock::time_point lastTime{};
1820 
1821  // SlidingWindow
1822  std::deque<std::chrono::steady_clock::time_point> history;
1823 
1824  // TokenBucket
1825  double tokens = 0.0;
1826  std::chrono::steady_clock::time_point lastRefill{};
1827  };
1845  {
1846  int fd = -1;
1848  std::unordered_map<std::string, RateState> pathRate;
1849  std::chrono::steady_clock::time_point lastActivity{};
1850  };
1875  {
1878  int badScore = 0; //IP 风险评分(用于升级惩罚)
1879  std::unordered_map<int, ConnectionState> conns; // fd -> state
1880  };
1902  enum DefenseDecision : int
1903  {
1904  ALLOW = 0, // 正常通过
1905  DROP = 1, // 不回应(丢弃)
1906  CLOSE = 2 // 断连(可伴随封 IP)
1907  };
1908 
1997  {
1998  public:
2005  ConnectionLimiter(const int& maxConn = 20, const int& idleTimeout = 60) : maxConnections(maxConn),connectionTimeout(idleTimeout){}
2006 
2007  // ========== 策略设置 ==========
2014  void setConnectStrategy(const RateLimitType &type);
2021  void setRequestStrategy(const RateLimitType &type);
2028  void setPathStrategy(const RateLimitType &type);
2029 
2030  // ========== Path 配置 ==========
2043  void setPathLimit(const std::string &path, const int &times, const int &secs);
2044 
2045  // ========== 核心判断 ==========
2062  DefenseDecision allowConnect(const std::string &ip, const int &fd,const int &times, const int &secs);
2077  DefenseDecision allowRequest(const std::string &ip,const int &fd,const std::string_view &path,const int &times,const int &secs);
2078 
2079  // ========== 生命周期 ==========
2090  void clearIP(const std::string &ip,const int &fd);
2104  bool connectionDetect(const std::string &ip,const int &fd);
2105  private:
2106  // 核心判定
2107  bool allow(RateState &st,const RateLimitType &type,const int &times,const int &secs,const std::chrono::steady_clock::time_point &now);
2108 
2109  private:
2110  int maxConnections;
2111  int connectionTimeout;
2112 
2113  RateLimitType connectStrategy = RateLimitType::Cooldown;
2114  RateLimitType requestStrategy = RateLimitType::SlidingWindow;
2116 
2117  std::unordered_map<std::string, IPInformation> table;
2118  std::unordered_map<std::string, std::pair<int,int>> pathConfig;
2119  // IP -> 解封时间
2120  std::unordered_map<std::string,std::chrono::steady_clock::time_point> blacklist;
2121  inline void logSecurity(const std::string &msgCN,const std::string &msgEN);
2122  };
2123 
2124 
2125 
2126  }
2127 
2133  namespace network
2134  {
2139  {
2140  protected:
2141  int fd=-1;
2142  bool flag1=false;
2143  bool flag2=false;
2144  SSL *ssl=nullptr;
2145  int sec=-1;
2146  public:
2150  bool flag3=false;
2151  public:
2161  void setFD(const int &fd,SSL *ssl,const bool &flag1=false,const bool &flag2=false,const int &sec=-1);
2166  int getFD(){return fd;}
2171  SSL *getSSL(){return ssl;}
2176  void close(const bool &cle=true);
2181  void blockSet(const int &sec = -1);
2185  void unblockSet();
2189  bool multiUseSet();
2194  bool isConnect(){if(fd==-1)return false;else return true;}
2195  public:
2214  int sendData(const std::string &data,const bool &block=true);
2234  int sendData(const char *data,const uint64_t &length,const bool &block=true);
2250  int recvDataByLength(std::string &data,const uint64_t &length,const int &sec=2);
2266  int recvDataByLength(char *data,const uint64_t &length,const int &sec=2);
2279  int recvData(std::string &data,const uint64_t &length);
2292  int recvData(char *data,const uint64_t &length);
2293  };
2294 
2300  {
2301  private:
2302  std::string serverIP="";
2303  int serverPort=-1;
2304  bool flag=false;
2305  bool TLS;
2306  SSL_CTX *ctx=nullptr;
2307  const char *ca;
2308  const char *cert;
2309  const char *key;
2310  const char *passwd;
2311  private:
2312  bool createFD();
2313  void closeAndUnCreate();
2314  bool initCTX(const char *ca,const char *cert="",const char *key="",const char *passwd="");
2315  public:
2328  TcpClient(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd="");
2335  bool connect(const std::string &ip,const int &port);
2349  void resetCTX(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd="");
2354  bool close();
2358  ~TcpClient(){closeAndUnCreate();}
2359  public:
2364  std::string getServerIP(){return serverIP;}
2369  int getServerPort(){return serverPort;}
2374  bool isConnect(){return flag;}
2375  };
2376 
2384  class HttpClient:private TcpClient
2385  {
2386  private:
2387  bool flag=false;
2388  public:
2401  HttpClient(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd=""):TcpClient(TLS,ca,cert,key,passwd){}
2402  public:
2415  bool getRequest(const std::string &url,const std::string &header="",const std::string &header1="Connection: keep-alive",const int &sec=-1);
2429  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);
2444  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);
2460  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);
2461  public:
2466  bool isReturn(){return flag;}
2470  std::string header="";
2474  std::string body="";
2475  };
2476 
2481  {
2482  private:
2483  int fd;
2484  bool flag=true;
2485  std::function<bool(const int &fd)> fc=[](const int &fd)->bool
2486  {return true;};
2487  std::function<void(const int &fd)> fcEnd=[](const int &fd)->void
2488  {};
2489  std::function<bool(const int &fd)> fcTimeOut=[](const int &fd)->bool
2490  {return true;};
2491  bool flag1=true;
2492  bool flag2=false;
2493  time::Duration dt{0,20,0,0,0};
2494  bool flag3=false;
2495  time::Duration t;
2496  private:
2497  void epolll();
2498  public:
2505  void startListen(const int &fd,const bool &flag=true,const time::Duration &dt=time::Duration{0,0,20,0,0});
2506  public:
2511  bool isListen(){return flag2;}
2521  void setFunction(std::function<bool(const int &fd)> fc){this->fc=fc;}
2529  void setEndFunction(std::function<void(const int &fd)> fcEnd){this->fcEnd=fcEnd;};
2539  void setTimeOutFunction(std::function<bool(const int &fd)> fcTimeOut){this->fcTimeOut=fcTimeOut;};
2545  bool endListen();
2550  void endListenWithSignal(){flag1=false;}
2556  void waitAndQuit(const time::Duration &t=time::Duration{0,0,0,10,10}){flag3=true;this->t=t;}
2562  };
2563 
2570  {
2571  private:
2572  bool flag4=false;
2573  std::function<bool(const std::string &message,WebSocketClient &k)> fc=[](const std::string &message,WebSocketClient &k)->bool
2574  {std::cout<<"收到: "<<message<<std::endl;return true;};
2575  std::string url;
2576  EpollSingle k;
2577  bool flag5=false;
2578  private:
2579  bool close1();
2580  public:
2593  WebSocketClient(const bool &TLS=false,const char *ca="",const char *cert="",const char *key="",const char *passwd=""):TcpClient(TLS,ca,cert,key,passwd){}
2604  void setFunction(std::function<bool(const std::string &message,WebSocketClient &k)> fc){this->fc=fc;}
2611  bool connect(const std::string &url,const int &min=20);
2634  bool sendMessage(const std::string &message,const std::string &type="0001");
2644  void close(const std::string &closeCodeAndMessage,const bool &wait=true);
2662  void close(const short &code=1000,const std::string &message="bye",const bool &wait=true);
2663  public:
2668  bool isConnect(){return flag4;}
2673  std::string getUrl(){return url;}
2678  std::string getServerIp(){return TcpClient::getServerIP();}
2683  std::string getServerPort(){return TcpClient::getServerIP();}
2687  ~WebSocketClient();
2688  };
2689 
2694  {
2698  int fd;
2702  std::string type;
2706  std::string locPara;
2710  std::string loc;
2714  std::string para;
2718  std::string header;
2722  std::string body;
2726  std::string body_chunked;
2730  std::unordered_map<std::string,std::any> ctx;
2731  };
2732 
2733  struct TcpFDInf;
2739  {
2740  public:
2748  void setFD(const int &fd,SSL *ssl=nullptr,const bool &flag1=false,const bool &flag2=true){TcpFDHandler::setFD(fd,ssl,flag1,flag2);}
2764  int solveRequest(TcpFDInf &TcpInf,HttpRequestInformation &HttpInf,const unsigned long &buffer_size,const int &times=1);
2773  bool sendBack(const std::string &data,const std::string &header="",const std::string &code="200 OK",const std::string &header1="");
2786  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);
2787  };
2792  {
2796  int fd;
2804  std::string locPara;
2808  std::string header;
2812  time_t HBTime=0;
2816  time_t response;
2820  size_t recv_length;
2832  std::string message="";
2836  bool fin;
2840  std::string mask;
2844  std::unordered_map<std::string,std::any> ctx;
2845  };
2846 
2851  {
2855  int fd;
2859  std::string data;
2863  std::unordered_map<std::string,std::any> ctx;
2864  };
2865 
2866  enum class TLSState : uint8_t {
2867  NONE = 0, // 非 TLS 连接(普通 TCP)
2868  HANDSHAKING, // TLS 握手中(SSL_accept 还没完成)
2869  ESTABLISHED, // TLS 已建立,可以 SSL_read / SSL_write
2870  ERROR // TLS 出错(可选)
2871  };
2872 
2876  struct TcpFDInf
2877  {
2881  int fd;
2885  std::string ip;
2889  std::string port;
2897  std::queue<std::any> pendindQueue;
2901  int status;
2905  std::string_view data;
2909  SSL* ssl;
2917  char *buffer;
2921  unsigned long p_buffer_now;
2922  };
2923 
2928  {
2932  int fd;
2936  int ret;
2937  };
2938 
2939 
2944  class TcpServer
2945  {
2946  protected:
2947  std::queue<WorkerMessage> finishQueue;
2949  unsigned long buffer_size;
2950  unsigned long long maxFD;
2952  //std::unordered_map<int,TcpFDInf> clientfd;
2953  //std::mutex lc1;
2955  int flag1=true;
2956  //std::queue<QueueFD> *fdQueue;
2957  //std::mutex *lq1;
2958  //std::condition_variable cv1;
2959  //std::condition_variable *cv;
2960  //int consumerNum;
2961  //std::mutex lco1;
2962  bool unblock;
2963  SSL_CTX *ctx=nullptr;
2964  bool TLS=false;
2965  //std::unordered_map<int,SSL*> tlsfd;
2966  //std::mutex ltl1;
2968  //bool flag_detect;
2969  //bool flag_detect_status;
2971  int serverType; // 1 tcp 2 http 3 websocket
2977  private:
2978  std::function<void(const int &fd)> closeFun=[](const int &fd)->void
2979  {
2980 
2981  };
2982  std::function<void(TcpFDHandler &k,TcpInformation &inf)> securitySendBackFun=[](TcpFDHandler &k,TcpInformation &inf)->void
2983  {};
2984  std::function<bool(TcpFDHandler &k,TcpInformation &inf)> globalSolveFun=[](TcpFDHandler &k,TcpInformation &inf)->bool
2985  {return true;};
2986  std::unordered_map<std::string,std::vector<std::function<int(TcpFDHandler &k,TcpInformation &inf)>>> solveFun;
2987  std::function<int(TcpFDHandler &k,TcpInformation &inf)> parseKey=[](TcpFDHandler &k,TcpInformation &inf)->int
2988  {inf.ctx["key"]=inf.data;return 1;};
2989  int fd=-1;
2990  int port=-1;
2991  int flag=false;
2992  bool flag2=false;
2993  private:
2994  void epolll(const int &evsNum);
2995  //virtual void consumer(const int &threadID);
2996  virtual void handler_netevent(const int &fd);
2997  virtual void handler_workerevent(const int &fd,const int &ret);
2998  virtual void handleHeartbeat()=0;
2999  public:
3011  void putTask(const std::function<int(TcpFDHandler &k,TcpInformation &inf)> &fun,TcpFDHandler &k,TcpInformation &inf);
3026  TcpServer(const unsigned long long &maxFD=1000000,const int &buffer_size=256,const bool &security_open=true,
3027  const int &connectionNumLimit=20,const int &connectionSecs=1,const int &connectionTimes=6,const int &requestSecs=1,const int &requestTimes=40,
3029  connectionLimiter(connectionNumLimit,connectionTimeout),checkFrequency(checkFrequency){serverType=1;}
3036  bool startListen(const int &port,const int &threads=8);
3063  bool setTLS(const char *cert,const char *key,const char *passwd,const char *ca);
3067  void redrawTLS();
3077  void setSecuritySendBackFun(std::function<void(TcpFDHandler &k,TcpInformation &inf)> fc){this->securitySendBackFun=fc;}
3087  void setGlobalSolveFunction(std::function<bool(TcpFDHandler &k,TcpInformation &inf)> fc){this->globalSolveFun=fc;}
3098  void setFunction(const std::string &key,std::function<int(TcpFDHandler &k,TcpInformation &inf)> fc)
3099  {
3100  auto [it, inserted] = solveFun.try_emplace(key);
3101  it->second.push_back(std::move(fc));
3102  }
3112  void setGetKeyFunction(std::function<int(TcpFDHandler &k,TcpInformation &inf)> parseKeyFun){this->parseKey=parseKeyFun;}
3118  bool stopListen();
3125  bool close();
3131  virtual bool close(const int &fd);
3167  void setPathLimit(const std::string &path, const int &times, const int &secs){this->connectionLimiter.setPathLimit(path,times,secs);}
3171  void setCloseFun(std::function<void(const int &fd)> closeFun){this->closeFun=closeFun;}
3172  public:
3177  bool isListen(){return flag;}
3182  SSL* getSSL(const int &fd);
3188  };
3189 
3190 
3191 
3196  class HttpServer:public TcpServer
3197  {
3198  private:
3199  std::function<void(HttpServerFDHandler &k,HttpRequestInformation &inf)> securitySendBackFun=[](HttpServerFDHandler &k,HttpRequestInformation &inf)->void
3200  {};
3201  std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>> globalSolveFun;
3202  //std::function<bool(HttpServerFDHandler &k,HttpRequestInformation &inf)> globalSolveFun={};
3203  std::unordered_map<std::string,std::vector<std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)>>> solveFun;
3204  std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> parseKey=[](HttpServerFDHandler &k,HttpRequestInformation &inf)->int
3205  {inf.ctx["key"]=inf.loc;return 1;};
3206  //std::function<bool(const HttpRequestInformation &inf,HttpServerFDHandler &k)> fc;
3207  //HttpRequestInformation *HttpInf;
3208  private:
3209  //void consumer(const int &threadID);
3210  //inline void handler(const int &fd);
3211  void handler_netevent(const int &fd);
3212  void handler_workerevent(const int &fd,const int &ret);
3213  void handleHeartbeat(){}
3214  public:
3226  void putTask(const std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> &fun,HttpServerFDHandler &k,HttpRequestInformation &inf);
3227 
3242  HttpServer(const unsigned long long &maxFD=1000000,const int &buffer_size=256,const bool &security_open=true,
3243  const int &connectionNumLimit=10,const int &connectionSecs=1,const int &connectionTimes=3,const int &requestSecs=1,const int &requestTimes=20,
3244  const int &checkFrequency=30,const int &connectionTimeout=30):TcpServer(
3245  maxFD,
3246  buffer_size,
3247  security_open,
3248  connectionNumLimit,
3251  requestSecs,
3252  requestTimes,
3254  connectionTimeout
3255  ){serverType=2;}
3265  void setSecuritySendBackFun(std::function<void(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc){this->securitySendBackFun=fc;}
3274  void setGlobalSolveFunction(std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc){globalSolveFun.push_back(std::move(fc));}
3301  void setFunction(const std::string &key,std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> fc)
3302  {
3303  auto [it, inserted] = solveFun.try_emplace(key);
3304  it->second.push_back(std::move(fc));
3305  }
3321  void setGetKeyFunction(std::function<int(HttpServerFDHandler &k,HttpRequestInformation &inf)> parseKeyFun){this->parseKey=parseKeyFun;}
3328  bool startListen(const int &port,const int &threads=8)
3329  {
3330  //HttpInf=new HttpRequestInformation[maxFD];
3331  return TcpServer::startListen(port,threads);
3332  }
3337  {
3338  //delete[] HttpInf;
3339  }
3340  };
3346  {
3347  public:
3355  void setFD(const int &fd,SSL *ssl=nullptr,const bool &flag1=false,const bool &flag2=true){TcpFDHandler::setFD(fd,ssl,flag1,flag2);}
3378  int getMessage(TcpFDInf &Tcpinf,WebSocketFDInformation &Websocketinf,const unsigned long &buffer_size,const int &ii=1);
3393  bool sendMessage(const std::string &msg,const std::string &type="0001");
3394 
3395  };
3396 
3401  {
3402  private:
3403  std::unordered_map<int,WebSocketFDInformation> wbclientfd;
3404  std::function<void(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> securitySendBackFun=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->void
3405  {};
3406  //std::function<bool(const std::string &msg,WebSocketServer &k,const WebSocketFDInformation &inf)> fc=[](const std::string &message,WebSocketServer &k,const WebSocketFDInformation &inf)->bool
3407  //{std::cout<<"收到: "<<message<<std::endl;return true;};
3408  std::function<bool(WebSocketFDInformation &k)> fcc=[](WebSocketFDInformation &k)
3409  {return true;};
3410  std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fccc=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->bool
3411  {
3412  return true;
3413  };
3414  std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> globalSolveFun=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->bool
3415  {return true;};
3416  std::unordered_map<std::string,std::vector<std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)>>> solveFun;
3417  std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> parseKey=[](WebSocketServerFDHandler &k,WebSocketFDInformation &inf)->int
3418  {inf.ctx["key"]=inf.message;return 1;};
3419  int seca=20*60;
3420  int secb=30;
3421 
3422  private:
3423  void handler_netevent(const int &fd);
3424  void handler_workerevent(const int &fd,const int &ret);
3425  //void consumer(const int &threadID);
3426  //inline void handler(const int &fd);
3427  void closeAck(const int &fd,const std::string &closeCodeAndMessage);
3428  void closeAck(const int &fd,const short &code=1000,const std::string &message="bye");
3429 
3430  void handleHeartbeat();
3431  bool closeWithoutLock(const int &fd,const std::string &closeCodeAndMessage);
3432  bool closeWithoutLock(const int &fd,const short &code=1000,const std::string &message="bye");
3433  public:
3445  void putTask(const std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> &fun,WebSocketServerFDHandler &k,WebSocketFDInformation &inf);
3460  WebSocketServer(const unsigned long long &maxFD=1000000,const int &buffer_size=256,const bool &security_open=true,
3461  const int &connectionNumLimit=5,const int &connectionSecs=10,const int &connectionTimes=3,const int &requestSecs=1,const int &requestTimes=10,
3462  const int &checkFrequency=60,const int &connectionTimeout=120):TcpServer(
3463  maxFD,
3464  buffer_size,
3465  security_open,
3466  connectionNumLimit,
3469  requestSecs,
3470  requestTimes,
3472  connectionTimeout
3473  ){serverType=3;}
3483  void setSecuritySendBackFun(std::function<void(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fc){this->securitySendBackFun=fc;}
3493  void setGlobalSolveFunction(std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fc){this->globalSolveFun=fc;}
3502  void setStartFunction(std::function<bool(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fccc){this->fccc=fccc;}
3512  void setJudgeFunction(std::function<bool(WebSocketFDInformation &k)> fcc){this->fcc=fcc;}
3529  void setFunction(const std::string &key,std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> fc)
3530  {
3531  auto [it, inserted] = solveFun.try_emplace(key);
3532  it->second.push_back(std::move(fc));
3533  }
3549  void setGetKeyFunction(std::function<int(WebSocketServerFDHandler &k,WebSocketFDInformation &inf)> parseKeyFun){this->parseKey=parseKeyFun;}
3550  //void setFunction(std::function<bool(const std::string &msg,WebSocketServer &k,const WebSocketFDInformation &inf)> fc){this->fc=fc;}
3555  void setTimeOutTime(const int &seca){this->seca=seca*60;}
3561  void setHBTimeOutTime(const int &secb){this->secb=secb;}
3573  bool closeFD(const int &fd,const std::string &closeCodeAndMessage);
3593  bool closeFD(const int &fd,const short &code=1000,const std::string &message="bye");
3617  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);}
3622  bool close();
3627  bool close(const int &fd);
3634  bool startListen(const int &port,const int &threads=8)
3635  {
3636  //std::thread(&WebSocketServer::HB,this).detach();
3637 
3638  return TcpServer::startListen(port,threads);
3639  }
3661  void sendMessage(const std::string &msg,const std::string &type="0001");
3667  };
3668 
3674  {
3675  protected:
3676  int fd=-1;
3677  bool flag1=false;
3678  bool flag2=false;
3679  int sec=-1;
3680  public:
3688  void setFD(const int &fd,const bool &flag1=false,const int &sec=-1,const bool &flag2=false);
3693  void blockSet(const int &sec=-1);
3697  void unblockSet();
3702  bool multiUseSet();
3706  int getFD(){return fd;}
3711  void close(const bool &cle=true);
3730  int sendData(const std::string &data,const std::string &ip,const int &port,const bool &block=true);
3750  int sendData(const char *data,const uint64_t &length,const std::string &ip,const int &port,const bool &block=true);
3765  int recvData(std::string &data,const uint64_t &length,std::string &ip,int &port);
3780  int recvData(char *data,const uint64_t &length,std::string &ip,int &port);
3781 
3782  };
3787  {
3788  public:
3794  UdpClient(const bool &flag1=false,const int &sec=-1);
3800  bool createFD(const bool &flag1=false,const int &sec=-1);
3805  };
3810  {
3811  public:
3818  UdpServer(const int &port,const bool &flag1=false,const int &sec=-1,const bool &flag2=true);
3825  bool createFD(const int &port,const bool &flag1=false,const int &sec=-1,const bool &flag2=true);
3830  };
3831  }
3837  namespace system
3838  {
3847  {
3848  public:
3856  static std::string language;
3857  private:
3858  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);}
3859  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);}
3860  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);}
3861  public:
3870  static void setExceptionHandling();
3878  static void setLogFile(file::LogFile *logfile=nullptr,const std::string &language="");
3884  static void init(file::LogFile *logfile=nullptr,const std::string &language="");
3885  };
3886 
3895  class csemp
3896  {
3897  private:
3903  union semun
3904  {
3905  int val;
3906  struct semid_ds *buf;
3907  unsigned short *arry;
3908  };
3909 
3910  int m_semid;
3911  short m_sem_flg;
3912 
3913  csemp(const csemp &) = delete;
3914  csemp &operator=(const csemp &) = delete;
3915 
3916  public:
3920  csemp():m_semid(-1){}
3921 
3932  bool init(key_t key, unsigned short value = 1, short sem_flg = SEM_UNDO);
3933 
3942  bool wait(short value = -1);
3943 
3952  bool post(short value = 1);
3953 
3959  int getvalue();
3960 
3968  bool destroy();
3969 
3973  ~csemp();
3974  };
3975 
3979  #define MAX_PROCESS_NAME 100
3980 
3983  #define MAX_PROCESS_INF 1000
3984 
3987  #define SHARED_MEMORY_KEY 0x5095
3988 
3991  #define SHARED_MEMORY_LOCK_KEY 0x5095
3992 
3996  struct ProcessInf
3997  {
4001  pid_t pid;
4005  time_t lastTime;
4013  char argv0[20];
4017  char argv1[20];
4021  char argv2[20];
4022  };
4023 
4031  class HBSystem
4032  {
4033  private:
4034 
4035  static ProcessInf *p;
4036  static csemp plock;
4037  static bool isJoin;
4038  public:
4047  bool join(const char *name,const char *argv0="",const char *argv1="",const char *argv2="");
4052  bool renew();
4056  static void list();
4063  static bool HBCheck(const int &sec);
4068  bool deleteFromHBS();
4073  ~HBSystem();
4074  };
4075 
4079  class Process
4080  {
4081  public:
4082 
4083 
4104  template<class... Args>
4105  static bool startProcess(const std::string &name,const int &sec=-1,Args ...args)
4106  {
4107  std::vector<const char *> paramList={args...,nullptr};
4108  if(sec==-1)
4109  {
4110  pid_t pid=fork();
4111  if(pid==-1)
4112  return false;
4113  if(pid>0)
4114  return true;
4115  else
4116  {
4117  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4118  return false;
4119  }
4120  }
4121  for(int ii=1;ii<=64;ii++)
4122  signal(ii,SIG_IGN);
4123  pid_t pid=fork();
4124  if(pid==-1)
4125  return false;
4126  if(pid>0)
4127  {
4128  return true;
4129  }
4130  else
4131  {
4132  signal(SIGCHLD,SIG_DFL);
4133  signal(15,SIG_DFL);
4134  while(1)
4135  {
4136  pid=fork();
4137  if(fork()==0)
4138  {
4139  execv(name.c_str(),const_cast<char* const*>(paramList.data()));
4140  exit(0);
4141  }
4142  else if(pid>0)
4143  {
4144  int sts;
4145  wait(&sts);
4146  sleep(sec);
4147  }
4148  else
4149  continue;
4150  }
4151  }
4152  }
4174  template<class Fn,class... Args>
4175  static typename std::enable_if<!std::is_convertible<Fn, std::string>::value, bool>::type
4176  startProcess(Fn&& fn,const int &sec=-1,Args &&...args)
4177  {
4178  if(sec==-1)
4179  {
4180  pid_t pid=fork();
4181  if(pid==-1)
4182  return false;
4183  if(pid>0)
4184  return true;
4185  else
4186  {
4187  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4188  f();
4189  return true;
4190  }
4191  }
4192  for(int ii=1;ii<=64;ii++)
4193  signal(ii,SIG_IGN);
4194  pid_t pid=fork();
4195  if(pid==-1)
4196  return false;
4197  if(pid>0)
4198  {
4199  return true;
4200  }
4201  else
4202  {
4203  signal(SIGCHLD,SIG_DFL);
4204  signal(15,SIG_DFL);
4205  while(1)
4206  {
4207  pid=fork();
4208  if(pid==0)
4209  {
4210  auto f=std::bind(std::forward<Fn>(fn),std::forward<Args>(args)...);
4211  f();
4212  return true;
4213  }
4214  else if(pid>0)
4215  {
4216  int sts;
4217  wait(&sts);
4218  sleep(sec);
4219  }
4220  else
4221  continue;
4222  }
4223  }
4224  }
4225  };
4226 
4227  using Task = std::function<void()>;
4253  class WorkerPool
4254  {
4255  public:
4263  explicit WorkerPool(size_t n):stop_(false)
4264  {
4265  for (size_t i = 0; i < n; ++i) {
4266  threads_.emplace_back([this] {
4267  this->workerLoop();
4268  });
4269  }
4270  }
4278  {
4279  stop();
4280  }
4288  void submit(Task task)
4289  {
4290  {
4291  std::lock_guard<std::mutex> lk(mtx_);
4292  tasks_.push(std::move(task));
4293  }
4294  cv_.notify_one();
4295  }
4306  void stop()
4307  {
4308  {
4309  std::lock_guard<std::mutex> lk(mtx_);
4310  stop_ = true;
4311  }
4312  cv_.notify_all();
4313  for (auto &t : threads_)
4314  {
4315  if (t.joinable()) t.join();
4316  }
4317  }
4318 
4319  private:
4330  void workerLoop()
4331  {
4332  while (true)
4333  {
4334  Task task;
4335  {
4336  std::unique_lock<std::mutex> lk(mtx_);
4337  cv_.wait(lk, [this] {
4338  return stop_ || !tasks_.empty();
4339  });
4340  if (stop_ && tasks_.empty())
4341  {
4342  return;
4343  }
4344  task = std::move(tasks_.front());
4345  tasks_.pop();
4346  }
4347  task(); // 执行任务
4348  }
4349  }
4350 
4351  private:
4352  std::vector<std::thread> threads_;
4353  std::queue<Task> tasks_;
4354  std::mutex mtx_;
4355  std::condition_variable cv_;
4356  bool stop_;
4357  };
4358 
4359 
4360  }
4361 
4362 }
4363 
4364 
4365 #endif
4366 
void setSecuritySendBackFun(std::function< void(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
设置违反信息安全策略时候的返回函数
Definition: sttnet.h:3265
void setStartFunction(std::function< bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fccc)
设置websocket连接成功后就执行的回调函数 注册一个回调函数
Definition: sttnet.h:3502
static std::string & transfer_websocket_key(std::string &str)
生成 WebSocket 握手响应中的 Sec-WebSocket-Accept 字段值。
time_t response
上次收到信息的时间
Definition: sttnet.h:2816
统一的连接与请求安全裁决器(IP 级 + fd 级,多策略限流 + 黑名单)。
Definition: sttnet.h:1996
int sendData(const std::string &data, const std::string &ip, const int &port, const bool &block=true)
向目标发送字符串数据。
std::chrono::duration< uint64_t > Seconds
Definition: sttnet.h:826
bool close()
关闭监听和所有连接
bool operator>(const Duration &b)
判断当前时间间隔是否大于另一个时间间隔。
Definition: sttnet.h:560
int getServerPort()
返回已连接的客户端的端口 return 已连接的服务端的端口
Definition: sttnet.h:2369
int fd
底层套接字
Definition: sttnet.h:2932
SSL * getSSL()
获取该对象的加密SSL句柄
Definition: sttnet.h:2171
int solveRequest(TcpFDInf &TcpInf, HttpRequestInformation &HttpInf, const unsigned long &buffer_size, const int &times=1)
解析Http/Https请求
Definition: sttnet.h:1904
int checkFrequency
Definition: sttnet.h:2976
bool isStart()
返回本对象计时状态
Definition: sttnet.h:932
bool fin
fin的状态
Definition: sttnet.h:2836
int fd
Definition: sttnet.h:2141
bool startTiming()
开始计时
bool connect(const std::string &ip, const int &port)
向服务端发起tcp连接
std::string header
握手阶段的Http/Https请求头
Definition: sttnet.h:2808
TcpFDInf * clientfd
Definition: sttnet.h:2954
~WebSocketClient()
WebSocketClient类的析构函数,销毁对象时候会优雅退出断开连接
std::string getServerIp()
如果连接到了服务器 返回服务器ip
Definition: sttnet.h:2678
bool unblock
Definition: sttnet.h:2962
int ret
返回值 -2:失败并且要求关闭连接 -1:失败但不需要关闭连接 1:成功
Definition: sttnet.h:2936
void setFD(const int &fd, SSL *ssl=nullptr, const bool &flag1=false, const bool &flag2=true)
初始化对象,传入套接字等参数
Definition: sttnet.h:2748
tcp协议的套接字操作类
Definition: sttnet.h:2138
void setConnectStrategy(const stt::security::RateLimitType &type)
设置“连接速率限流”所使用的策略。
Definition: sttnet.h:3138
bool readLine(std::string &data, const int linePos)
读取单行
static size_t get_file_size(const std::string &fileName)
获取文件大小
static std::string createJson(T1 first, T2 second, Args...args)
创建多个键值对组成的 JSON 字符串(递归变参模板)。
Definition: sttnet.h:1660
std::string & readAll(std::string &data)
读取全部
double tokens
Definition: sttnet.h:1825
表示时间间隔的结构体,支持天、小时、分钟、秒和毫秒粒度。
Definition: sttnet.h:528
std::string & readAllC(std::string &data)
读取全部
void setGlobalSolveFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
设置全局备用函数
Definition: sttnet.h:3274
WebSocket协议的操作类 仅传入套接字,然后使用这个类进行WebSocket的操作
Definition: sttnet.h:3345
static void setLogFile(file::LogFile *logfile=nullptr, const std::string &language="")
设置日志系统的日志文件对象 传入的日志文件对象如果是没初始化的空的对象,系统自动在程序目录下生成server_log文件夹并且根据当前时间生成一个日志文件记录服务程序的网络通信 如果传入的日志文件对象是...
static void init(file::LogFile *logfile=nullptr, const std::string &language="")
执行setExceptionHandling和setLogFile两个函数,完成初始化信号和日志系统
int badScore
Definition: sttnet.h:1878
DefenseDecision allowRequest(const std::string &ip, const int &fd, const std::string_view &path, const int &times, const int &secs)
对已建立连接的一次请求进行安全裁决。
bool isConnect()
判断对象是否有套接字绑定
Definition: sttnet.h:2194
void setPathLimit(const std::string &path, const int &times, const int &secs)
设置某个路径的额外限流规则(path 级)。
时间操作、运算、计时的类
Definition: sttnet.h:843
bool createFD(const int &port, const bool &flag1=false, const int &sec=-1, const bool &flag2=true)
销毁原来的套接字,重新创建一个服务端
int getFD()
获取该对象的套接字
Definition: sttnet.h:2166
static long getRandomNumber(const long &a, const long &b)
生成一个随机整数
static int & str16toInt(const std::string_view &ori_str, int &result, const int &i=-1)
16进制数字的字符串表示转化为10进制int类型数字
bool deleteLine(const int &linePos=0)
删除行
void waitAndQuit(const time::Duration &t=time::Duration{0, 0, 0, 10, 10})
开始退出epoll倒计时,直到套接字有新的消息 如果套接字倒计时结束还没有新的消息,那么退出epoll
Definition: sttnet.h:2556
bool connect(const std::string &url, const int &min=20)
连接到websocket服务器
bool operator<=(const Duration &b)
判断当前时间间隔是否小于等于另一个时间间隔。
Definition: sttnet.h:624
static std::string & sha11(const std::string &ori_str, std::string &result)
计算输入字符串的 SHA-1 哈希值,并以十六进制字符串形式返回。
Http/HttpServer 服务端操作类
Definition: sttnet.h:3196
int recvData(std::string &data, const uint64_t &length, std::string &ip, int &port)
接收一次数据到string字符串容器
int sendData(const std::string &data, const bool &block=true)
向已连接的套接字发送字符串数据。
bool sendMessage(const int &fd, const std::string &msg, const std::string &type="0001")
发送 WebSocket 消息给某一个客户端
Definition: sttnet.h:3617
void setCloseFun(std::function< void(const int &fd)> closeFun)
设置关闭tcp连接之后调用的函数
Definition: sttnet.h:3171
std::string body_chunked
请求体(chunked)
Definition: sttnet.h:2726
工作现场完成任务后压入完成队列的数据结构
Definition: sttnet.h:2927
pid_t pid
进程id
Definition: sttnet.h:4001
WebSocketClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
WebSocketClient类的构造函数
Definition: sttnet.h:2593
Duration operator+(const Duration &b)
将两个时间间隔相加。
Definition: sttnet.h:640
Duration(long long a, int b, int c, int d, int e)
构造函数,传入天,时,分,秒,毫秒
Definition: sttnet.h:553
int violations
Definition: sttnet.h:1818
bool post(short value=1)
V 操作(释放),尝试将信号量值加上 value。
int getFD()
返回fd
Definition: sttnet.h:3706
static unsigned long & htonl_ntohl_64(unsigned long &data)
将 64 位无符号整数的字节序反转(大端 &lt;-&gt; 小端)。
bool stopListen()
停止监听
Duration endTiming()
停止计时
char argv1[20]
进程第二个参数
Definition: sttnet.h:4017
bool writeC(const char *data, const size_t &pos, const size_t &size)
写数据块
单个 IP 的安全状态与连接集合。
Definition: sttnet.h:1874
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)
发送一个POST请求到服务器
std::string body
请求体
Definition: sttnet.h:2722
std::string loc
文件路径
Definition: sttnet.h:122
unsigned long p_buffer_now
接收空间位置指针
Definition: sttnet.h:2921
bool isConnect()
返回对象的连接状态
Definition: sttnet.h:2374
std::ostream & operator<<(std::ostream &os, const Duration &a)
将 Duration 对象以可读格式输出到流中。
int sec
Definition: sttnet.h:545
~TcpServer()
TcpServer 类的析构函数
Definition: sttnet.h:3187
double convertToMin()
将当前时间间隔转换为以“分钟”为单位的浮点数表示。
Definition: sttnet.h:747
void putTask(const std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> &fun, HttpServerFDHandler &k, HttpRequestInformation &inf)
把一个任务放入工作线程池由工作线程完成
int recvDataByLength(std::string &data, const uint64_t &length, const int &sec=2)
从已连接的套接字中阻塞接收指定长度的数据到字符串
static bool decryptSymmetric(const unsigned char *before, const size_t &length, const unsigned char *passwd, const unsigned char *iv, unsigned char *after)
AES-256-CBC模式对称解密函数
static std::string & generateMask_4(std::string &mask)
生成一个 32 位(4 字节)的随机掩码。
void clearIP(const std::string &ip, const int &fd)
在连接断开时回收对应 fd 的状态。
static long & toLong(const std::string_view &ori_str, long &result, const long &i=-1)
string转化为long类型
static std::string & getRandomStr_base64(std::string &str, const int &length)
生成一个规定长度的“Base64 字符集内的伪随机字符串”,并在末尾用 &#39;=&#39; 补齐至符合 Base64 字符串格式
int fd
底层的socket套接字
Definition: sttnet.h:2698
static float & toFloat(const std::string &ori_str, float &result, const float &i=-1)
string转化为float类型
unsigned long buffer_size
Definition: sttnet.h:2949
std::string getServerPort()
如果连接到了服务器 返回服务器端口
Definition: sttnet.h:2683
int counter
Definition: sttnet.h:1817
unsigned long long maxFD
Definition: sttnet.h:2950
bool closeFile(const bool &del=false)
关闭对象打开的日志文件
TcpClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
TcpClient类的构造函数
std::chrono::steady_clock::time_point lastActivity
Definition: sttnet.h:1849
int serverType
Definition: sttnet.h:2971
std::string message
消息
Definition: sttnet.h:2832
void setPathLimit(const std::string &path, const int &times, const int &secs)
设置某个路径的额外限流规则(path 级)。
Definition: sttnet.h:3167
void setTimeOutFunction(std::function< bool(const int &fd)> fcTimeOut)
设置epoll超时后出发的回调函数 注册一个回调函数
Definition: sttnet.h:2539
bool flag2
Definition: sttnet.h:2143
Duration recoverForm(const long long &t)
从给定的毫秒数恢复为标准的天-时-分-秒-毫秒格式。
Definition: sttnet.h:778
static std::string createArray(T first)
创建只包含一个元素的 JSON 数组字符串。
Definition: sttnet.h:1685
void close(const bool &cle=true)
置空对象,关闭套接字
UdpClient(const bool &flag1=false, const int &sec=-1)
构造函数
void putTask(const std::function< int(TcpFDHandler &k, TcpInformation &inf)> &fun, TcpFDHandler &k, TcpInformation &inf)
把一个任务放入工作线程池由工作线程完成
std::queue< std::any > pendindQueue
等待处理的队列
Definition: sttnet.h:2897
负责字符串和数字的转化
Definition: sttnet.h:1465
~EpollSingle()
EpollSingle的析构函数 调用eldListen阻塞退出epoll.
Definition: sttnet.h:2561
int threads
记录文件正在被多少个线程使用
Definition: sttnet.h:126
std::string para
url中的参数
Definition: sttnet.h:2714
static double & toDouble(const std::string &ori_str, double &result, const double &i=-1)
string转化为double类型
void setFunction(const std::string &key, std::function< int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
设置key对应的收到客户端消息后的回调函数
Definition: sttnet.h:3529
static std::string language
系统的日志系统的语言选择,默认为English
Definition: sttnet.h:3856
static std::string & getPreciesFloat(const float &number, const int &bit, std::string &str)
将浮点数格式化为指定小数位数的字符串表示。
负责进程心跳监控,调度的类 用于监控服务进程,保证服务进程持续有效运行 进程结束后,0x5095这一块共享内存和信号量都没有删掉 目前只支持最多三个参数的进程加入监控 应该自己手动在程序编写加入心跳监控...
Definition: sttnet.h:4031
bool flag1
Definition: sttnet.h:2142
std::deque< std::chrono::steady_clock::time_point > history
Definition: sttnet.h:1822
void startListen(const int &fd, const bool &flag=true, const time::Duration &dt=time::Duration{0, 0, 20, 0, 0})
开始监听
static bool createFile(const std::string &filePath, const mode_t &mode=0666)
新建一个文件
Duration checkTime()
计时过程中检查时间
void format()
格式化数据
size_t getFileSize()
获取二进制打开的文件的大小
Definition: sttnet.h:266
bool deleteAllC()
删除全部
Definition: sttnet.h:1906
Tcp服务端类
Definition: sttnet.h:2944
stt::system::WorkerPool * workpool
Definition: sttnet.h:2948
static std::string createArray(T first, Args...args)
创建多个元素组成的 JSON 数组字符串(递归变参模板)。
Definition: sttnet.h:1703
static std::mutex l1
Definition: sttnet.h:148
bool startListen(const int &port, const int &threads=8)
打开Tcp服务器监听程序
std::string port
客户端端口
Definition: sttnet.h:2889
UDP操作的类 传入套接字进行UDP协议的操作
Definition: sttnet.h:3673
void blockSet(const int &sec=-1)
设置对象中的套接字为阻塞模式
int requestTimes
Definition: sttnet.h:2975
int recvData(std::string &data, const uint64_t &length)
从已连接的套接字中接收一次数据到string字符串容器
bool flag1
Definition: sttnet.h:3677
size_t getSize1()
获取二进制打开的文件在内存中的大小
Definition: sttnet.h:275
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:4176
~File()
析构函数
Definition: sttnet.h:233
static std::string_view & get_location_str(const std::string_view &ori_str, std::string_view &str)
提取 URL 中 path 和 query 部分。
std::string loc
url中的路径
Definition: sttnet.h:2710
HttpClient(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
HttpClient类的构造函数
Definition: sttnet.h:2401
static std::string_view & getLocPara(const std::string_view &url, std::string_view &locPara)
提取 URL 的 path 部分(不含 query)。
WebSocketServer服务端操作类
Definition: sttnet.h:3400
std::string locPara
握手阶段的Http/Https路径和参数
Definition: sttnet.h:2804
解析,响应Http/https请求的操作类 仅传入套接字,然后使用这个类进行Http的操作
Definition: sttnet.h:2738
void setGlobalSolveFunction(std::function< bool(TcpFDHandler &k, TcpInformation &inf)> fc)
设置全局备用函数
Definition: sttnet.h:3087
bool closeFD(const int &fd, const std::string &closeCodeAndMessage)
发送关闭帧关闭对应套接字的 WebSocket 连接(简化方式)
bool chgLineC(const std::string &data, const int &linePos=0)
修改行
bool operator<(const Duration &b)
判断当前时间间隔是否小于另一个时间间隔。
Definition: sttnet.h:576
bool isConnect()
返回连接状态
Definition: sttnet.h:2668
static bool HBCheck(const int &sec)
检查心跳监控系统 如果上一次心跳更新的时间和现在的时候相差大于等于sec秒,则杀死进程 先发送信号15杀死进程 如果8秒后进程还存在 则发送信号9强制杀死
负责加密,解密和哈希
Definition: sttnet.h:1015
负责浮点数精度处理
Definition: sttnet.h:1192
static std::string & sha1(const std::string &ori_str, std::string &result)
计算输入字符串的 SHA-1 哈希值(原始二进制形式)。
void stop()
停止线程池并等待所有线程退出
Definition: sttnet.h:4306
SSL_CTX * ctx
Definition: sttnet.h:2963
bool deleteLogByTime(const std::string &date1="1", const std::string &date2="2")
删除指定时间区间内的日志
std::string & read(std::string &data, const int &linePos, const int &num)
读取行
static void list()
输出心跳监控系统的所有进程的信息
static std::string & jsonToUTF8(const std::string &input, std::string &output)
将 JSON 字符串中的 转换为 UTF-8 字符。
负责二进制数据,字符串之间的转化
Definition: sttnet.h:1070
static unsigned long & bitToNumber(const std::string &input, unsigned long &result)
将字符串转换为二进制,再转换为对应数值。
json数据操作类
Definition: sttnet.h:1596
static std::string & generateMask_4(std::string &mask)
生成一个 32 位(4 字节)的随机掩码。
static Duration & calculateTime(const std::string &time1, const std::string &time2, Duration &result, const std::string &format1=ISO8086A, const std::string &format2=ISO8086A)
计算两个用字符串表示的时间相减的差值
static Json::Value toJsonArray(const std::string &str)
解析 JSON 字符串为 Json::Value。
LogFile()
构造函数,初始化消费者线程
bool renew()
更新当前进程的心跳
std::unordered_map< std::string, std::any > ctx
所需的数据仓库
Definition: sttnet.h:2863
~HttpServer()
析构函数
Definition: sttnet.h:3336
std::chrono::steady_clock::time_point lastTime
Definition: sttnet.h:1819
int connectionTimes
Definition: sttnet.h:2973
~csemp()
析构函数,不自动销毁信号量。
std::unordered_map< std::string, RateState > pathRate
Definition: sttnet.h:1848
进程信息的结构体
Definition: sttnet.h:3996
std::string & readC(std::string &data, const int &linePos, const int &num)
读取行
static std::unordered_map< std::string, FileThreadLock > fl2
Definition: sttnet.h:149
void resetCTX(const bool &TLS=false, const char *ca="", const char *cert="", const char *key="", const char *passwd="")
重新或第一次设置TLS加密参数
bool getRequest(const std::string &url, const std::string &header="", const std::string &header1="Connection: keep-alive", const int &sec=-1)
发送一个GET请求到服务器
static std::string base64_encode(const std::string &input)
对字符串进行 Base64 编码。
bool deleteLineC(const int &linePos=0)
删除行
bool multiUseSet()
设置SO_REUSEADDR模式
#define MAX_PROCESS_NAME
定义MAX_PROCESS_NAME这个宏为100,意思是进程信息中的进程名字长度不超过100个字节
Definition: sttnet.h:3979
static std::string createHeader(const std::string &first, const std::string &second)
创建一个 HTTP 请求头字段字符串。
int getvalue()
获取信号量当前的值。
tcp协议客户端操作类
Definition: sttnet.h:2299
负责Http字符串和URL解析 包括从 URL 或请求报文中提取参数、IP、端口、请求头字段等功能。
Definition: sttnet.h:1247
double convertToHour()
将当前时间间隔转换为以“小时”为单位的浮点数表示。
Definition: sttnet.h:737
void setGetKeyFunction(std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> parseKeyFun)
设置解析出key的回调函数
Definition: sttnet.h:3321
csemp()
构造函数,初始化内部状态。
Definition: sttnet.h:3920
time_t lastTime
进程最后一次心跳时间,是时间戳
Definition: sttnet.h:4005
long long day
Definition: sttnet.h:533
static int & getPort(const std::string &url, int &port)
从 URL 中提取端口号。
int sec
Definition: sttnet.h:3679
static void setExceptionHandling()
设置系统的信号
bool chgLine(const std::string &data, const int &linePos=0)
修改行
void setGetKeyFunction(std::function< int(TcpFDHandler &k, TcpInformation &inf)> parseKeyFun)
设置解析出key的回调函数
Definition: sttnet.h:3112
static std::string & strto16(const std::string &ori_str, std::string &result)
将普通字符串转化为对应的十六进制表示字符串(hex string)。
void redrawTLS()
撤销TLS加密,ca证书等
bool close()
如果对象有套接字连接,关闭和释放这个连接和套接字,并且重新新建一个套接字。
void setSecuritySendBackFun(std::function< void(TcpFDHandler &k, TcpInformation &inf)> fc)
设置违反信息安全策略时候的返回函数
Definition: sttnet.h:3077
void setFunction(const std::string &key, std::function< int(TcpFDHandler &k, TcpInformation &inf)> fc)
设置key对应的收到客户端消息后的回调函数
Definition: sttnet.h:3098
std::mutex lock
此文件的锁
Definition: sttnet.h:130
int min
Definition: sttnet.h:541
void endListenWithSignal()
发送结束epoll的信号
Definition: sttnet.h:2550
static float & getValidFloat(float &number, const int &bit)
根据数值动态调整小数精度,保留指定数量的有效数字。
保存HTTP/HTTPS请求信息的结构体
Definition: sttnet.h:2693
bool unlockMemory(const bool &rec=false)
把数据从内存写入磁盘
std::unordered_map< std::string, std::any > ctx
所需的数据仓库
Definition: sttnet.h:2844
WorkerPool(size_t n)
构造函数,创建指定数量的工作线程
Definition: sttnet.h:4263
SSL * ssl
Definition: sttnet.h:2144
Duration operator-(const Duration &b)
计算两个时间间隔的差值(当前对象减去参数 b)。
Definition: sttnet.h:684
bool readLineC(std::string &data, const int linePos)
读取单行
static bool & toBool(const std::string_view &ori_str, bool &result)
string转化为bool类型
static char & toBit(const std::string &input, char &result)
将最多 8 位的 &quot;01&quot; 字符串压缩成 1 个字节(char)。
void setConnectStrategy(const RateLimitType &type)
设置“连接速率限流”所使用的策略。
bool createFD(const bool &flag1=false, const int &sec=-1)
销毁原来的套接字,重新创建一个客户端
char argv2[20]
进程第三个参数
Definition: sttnet.h:4021
UdpServer(const int &port, const bool &flag1=false, const int &sec=-1, const bool &flag2=true)
构造函数
static std::string toString(const Json::Value &val)
将 Json::Value 转换为字符串。
bool write(const char *data, const size_t &pos, const size_t &size)
写数据块
bool TLS
Definition: sttnet.h:2964
RateState connectRate
Definition: sttnet.h:1877
HttpServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=10, const int &connectionSecs=1, const int &connectionTimes=3, const int &requestSecs=1, const int &requestTimes=20, const int &checkFrequency=30, const int &connectionTimeout=30)
构造函数,默认是允许最大1000000个连接,每个连接接收缓冲区最大为256kb,启用安全模块。
Definition: sttnet.h:3242
double convertToSec()
将当前时间间隔转换为以“秒”为单位的浮点数表示。
Definition: sttnet.h:757
static std::string base64_decode(const std::string &input)
对 Base64 编码的字符串进行解码。
std::string getUrl()
如果连接到了服务器 返回url
Definition: sttnet.h:2673
static file::LogFile * logfile
系统的日志系统的读写日志对象的指针
Definition: sttnet.h:3852
TLSState
Definition: sttnet.h:2866
bool connectionDetect(const std::string &ip, const int &fd)
检测并清理僵尸连接(fd 级)。
size_t recv_length
待接收的长度
Definition: sttnet.h:2820
static std::string createHeader(const std::string &first, const std::string &second, Args...args)
递归构造多个 HTTP 请求头字段。
Definition: sttnet.h:1437
用epoll监听单个句柄
Definition: sttnet.h:2480
TcpServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=20, const int &connectionSecs=1, const int &connectionTimes=6, const int &requestSecs=1, const int &requestTimes=40, const int &checkFrequency=60, const int &connectionTimeout=60)
构造函数,默认是允许最大1000000个连接,每个连接接收缓冲区最大为256kb,启用安全模块。
Definition: sttnet.h:3026
static std::string & transfer_websocket_key(std::string &str)
生成 WebSocket 握手响应中的 Sec-WebSocket-Accept 字段值。
int workerEventFD
Definition: sttnet.h:2970
int FDStatus
记录当前处理状态机到第几步了
Definition: sttnet.h:2893
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)
从tcp套接字发送一个GET请求到服务器
std::string header
请求头
Definition: sttnet.h:2718
void setPathStrategy(const RateLimitType &type)
设置“path 级请求限流”所使用的策略。
bool sendMessage(const std::string &message, const std::string &type="0001")
发送 WebSocket 消息
~WorkerPool()
析构函数
Definition: sttnet.h:4277
bool flag3
如果sendData的block=true,如果发送过程中连接断开,这个标志位会置为true
Definition: sttnet.h:2150
void setPathStrategy(const stt::security::RateLimitType &type)
设置“path 级请求限流”所使用的策略。
Definition: sttnet.h:3153
void setSecuritySendBackFun(std::function< void(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
设置违反信息安全策略时候的返回函数
Definition: sttnet.h:3483
WebSocketServer(const unsigned long long &maxFD=1000000, const int &buffer_size=256, const bool &security_open=true, const int &connectionNumLimit=5, const int &connectionSecs=10, const int &connectionTimes=3, const int &requestSecs=1, const int &requestTimes=10, const int &checkFrequency=60, const int &connectionTimeout=120)
构造函数,默认是允许最大1000000个连接,每个连接接收缓冲区最大为256kb,启用安全模块。
Definition: sttnet.h:3460
bool lockMemory()
把数据从磁盘读入内存
bool sendMessage(const std::string &msg, const std::string &type="0001")
发送一条websocket信息
static std::string & bitOutput(char input, std::string &result)
将单个字符转换为其对应的 8 位二进制字符串。
void setFD(const int &fd, SSL *ssl=nullptr, const bool &flag1=false, const bool &flag2=true)
初始化对象,传入套接字等参数
Definition: sttnet.h:3355
int connectionSecs
Definition: sttnet.h:2972
FileThreadLock(const std::string &loc, const int &threads)
这个结构体的构造函数
Definition: sttnet.h:136
bool operator>=(const Duration &b)
判断当前时间间隔是否大于等于另一个时间间隔。
Definition: sttnet.h:608
保存客户端WS/WSS请求信息的结构体
Definition: sttnet.h:2791
bool wait(short value=-1)
P 操作(等待),尝试将信号量值减去 value。
bool destroy()
销毁当前信号量。
int fd
Definition: sttnet.h:3676
static bool copy(const std::string &sourceFile, const std::string &objectFile)
复制文件
std::string getFileName()
获取打开的文件名字
Definition: sttnet.h:248
~TcpClient()
TcpClient的析构函数,会关闭释放套接字和其连接
Definition: sttnet.h:2358
static std::string_view & getPara(const std::string_view &url, std::string_view &para)
获取 URL 中的查询参数字符串(包括 ?)。
void setEndFunction(std::function< void(const int &fd)> fcEnd)
设置epoll退出前的回调函数 注册一个回调函数
Definition: sttnet.h:2529
std::string body
服务器返回响应体
Definition: sttnet.h:2474
static std::string & getIP(const std::string &url, std::string &IP)
从 URL 中提取主机 IP 或域名。
~HBSystem()
HBSystem的析构函数
负责websocket协议有关字符串的操作
Definition: sttnet.h:1446
Duration getDt()
获取上一次计时的时间
Definition: sttnet.h:927
数据编码解码,掩码处理等
Definition: sttnet.h:1534
int activeConnections
Definition: sttnet.h:1876
int findC(const std::string &targetString, const int linePos=1)
查找行
std::function< void()> Task
Definition: sttnet.h:4227
~UdpServer()
析构函数,对象生命结束会会关闭套接字
Definition: sttnet.h:3829
bool startListen(const int &port, const int &threads=8)
打开Http服务器监听程序
Definition: sttnet.h:3328
保存Tcp客户端的信息
Definition: sttnet.h:2850
bool operator==(const Duration &b)
判断当前时间间隔是否等于另一个时间间隔。
Definition: sttnet.h:592
bool appendLineC(const std::string &data, const int &linePos=0)
插入行
static bool createDir(const std::string &ddir, const mode_t &mode=0775)
新建一个目录
单一限流器的运行状态(可复用于多种限流策略)。
Definition: sttnet.h:1814
int message_type
消息类型
Definition: sttnet.h:2828
bool deleteFromHBS()
把当前进程从心跳系统中删除
bool join(const char *name, const char *argv0="", const char *argv1="", const char *argv2="")
把进程加入到心跳系统
std::unordered_map< std::string, std::any > ctx
所需的数据仓库
Definition: sttnet.h:2730
void close(const bool &cle=true)
关闭对象
char * buffer
接收空间指针
Definition: sttnet.h:2917
static unsigned long & bitStrToNumber(const std::string &input, unsigned long &result)
将 &quot;01&quot; 字符串(二进制字符串)转换为无符号整数。
记录文件和线程关系的结构体
Definition: sttnet.h:117
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)
从原始字符串中提取两个标记之间的子串。
int fd
套接字fd
Definition: sttnet.h:2855
int status
当前fd的接收状态,用于保存接收处理机逻辑
Definition: sttnet.h:2901
void writeLog(const std::string &data)
写一行日志
std::string locPara
url中的路径和参数
Definition: sttnet.h:2706
bool init(key_t key, unsigned short value=1, short sem_flg=SEM_UNDO)
初始化信号量。
int sec
Definition: sttnet.h:2145
time_t HBTime
发送心跳的时间(没有发送过就填0) (检查完又要清空为0)
Definition: sttnet.h:2812
static bool convertFormat(std::string &timeStr, const std::string &oldFormat, const std::string &newFormat=ISO8086A)
转化时间字符串的格式
初始化服务系统的类
Definition: sttnet.h:3846
~UdpClient()
析构函数,对象生命结束会会关闭套接字
Definition: sttnet.h:3804
std::string data
裸数据
Definition: sttnet.h:2859
bool close()
关闭监听和所有已连接的套接字
bool deleteAll()
删除全部
uint64_t getFileLine()
获取打开的文件的行数
Definition: sttnet.h:257
void setFD(const int &fd, const bool &flag1=false, const int &sec=-1, const bool &flag2=false)
设置fd
~LogFile()
析构函数 写完日志 关闭消费者线程
bool isOpen()
判断对象是否打开了文件
Definition: sttnet.h:238
DefenseDecision allowConnect(const std::string &ip, const int &fd, const int &times, const int &secs)
对新建立的连接进行安全裁决(IP 级)。
int flag1
Definition: sttnet.h:2955
bool isReturn()
获取服务器返回响应状态
Definition: sttnet.h:2466
int requestSecs
Definition: sttnet.h:2974
std::string_view data
保存收到的客户端传来的数据
Definition: sttnet.h:2905
int getMessage(TcpFDInf &Tcpinf, WebSocketFDInformation &Websocketinf, const unsigned long &buffer_size, const int &ii=1)
获取一条websocket消息
std::chrono::duration< uint64_t, std::milli > Milliseconds
Definition: sttnet.h:825
bool flag2
Definition: sttnet.h:3678
单个连接(fd)的安全与限流状态。
Definition: sttnet.h:1844
int fd
Definition: sttnet.h:1846
RateState requestRate
Definition: sttnet.h:1847
void setGetKeyFunction(std::function< int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> parseKeyFun)
设置解析出key的回调函数
Definition: sttnet.h:3549
static std::string & jsonFormatify(const std::string &a, std::string &b)
将格式化后的 JSON 字符串去除缩进、空格等变成紧凑格式。
std::string header
服务器返回响应头
Definition: sttnet.h:2470
void setRequestStrategy(const stt::security::RateLimitType &type)
设置“IP 级请求限流”所使用的策略。
Definition: sttnet.h:3145
bool openFile(const std::string &fileName, const bool &create=true, const int &multiple=0, const size_t &size=0, const mode_t &mode=0666)
打开文件
std::string type
请求类型
Definition: sttnet.h:2702
static std::string & maskCalculate(std::string &data, const std::string &mask)
使用给定的 4 字节掩码对字符串进行异或操作(XOR Masking)。
TLSState tls_state
tls状态
Definition: sttnet.h:2913
Websocket客户端操作的类 -如果需要重新设置TLS/Https加密的证书,目前需要销毁对象后重新构造 底层TCP默认是阻塞的
Definition: sttnet.h:2569
bool isBinary()
判断对象是否以二进制模式打开文件
Definition: sttnet.h:243
void blockSet(const int &sec=-1)
设置为阻塞模式
void setFD(const int &fd, SSL *ssl, const bool &flag1=false, const bool &flag2=false, const int &sec=-1)
传入套接字初始化对象
std::string getServerIP()
返回已连接的服务端的ip return 已连接的服务端的ip
Definition: sttnet.h:2364
static std::string & getPreciesDouble(const double &number, const int &bit, std::string &str)
将双精度浮点数格式化为指定小数位数的字符串表示。
void submit(Task task)
向线程池提交一个任务
Definition: sttnet.h:4288
封装 System V 信号量的同步工具类。
Definition: sttnet.h:3895
std::string mask
mask
Definition: sttnet.h:2840
bool openFile(const std::string &fileName, const std::string &timeFormat=ISO8086A, const std::string &contentFormat=" ")
打开一个日志文件
RateLimitType
限流算法类型(策略)。
Definition: sttnet.h:1788
bool clearLog()
清空所有日志
负责大小端字节序转换
Definition: sttnet.h:1172
static bool encryptSymmetric(const unsigned char *before, const size_t &length, const unsigned char *passwd, const unsigned char *iv, unsigned char *after)
AES-256-CBC模式对称加密函数
~WebSocketServer()
WebSocketServer的析构函数
Definition: sttnet.h:3666
void setRequestStrategy(const RateLimitType &type)
设置“IP 级请求限流”所使用的策略。
std::mutex che
Definition: sttnet.h:151
bool startListen(const int &port, const int &threads=8)
打开Websocket服务器监听程序
Definition: sttnet.h:3634
std::string getFileName()
获取对象打开的文件名
Definition: sttnet.h:974
udp服务端的操作类
Definition: sttnet.h:3809
double convertToDay()
将当前时间间隔转换为以“天”为单位的浮点数表示。
Definition: sttnet.h:727
bool isListen()
返回epoll监听状态
Definition: sttnet.h:2511
Http/Https客户端操作类
Definition: sttnet.h:2384
bool closeflag
true:发送了关闭帧 false:没有发送关闭帧
Definition: sttnet.h:2800
char argv0[20]
进程第一个参数
Definition: sttnet.h:4013
int fd
套接字fd
Definition: sttnet.h:2881
size_t have_recv_length
已经接收的长度
Definition: sttnet.h:2824
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)
发送一个POST请求到服务器
bool security_open
Definition: sttnet.h:2967
bool setTLS(const char *cert, const char *key, const char *passwd, const char *ca)
启用 TLS 加密并配置服务器端证书与密钥
void formatC()
格式化数据
进程管理的静态工具类
Definition: sttnet.h:4079
static std::string_view & get_value_str(const std::string_view &ori_str, std::string_view &str, const std::string &name)
从 URL 查询参数中提取指定 key 的值。
bool sendBack(const std::string &data, const std::string &header="", const std::string &code="200 OK", const std::string &header1="")
发送Http/Https响应
static std::string_view & get_value_header(const std::string_view &ori_str, std::string_view &str, const std::string &name)
从 HTTP 请求头中提取指定字段的值。
static int getValue(const std::string &oriStr, std::string &result, const std::string &type="value", const std::string &name="a", const int &num=0)
提取 JSON 字符串中指定字段的值或嵌套结构。
int hour
Definition: sttnet.h:537
long long convertToMsec()
将当前时间间隔转换为总毫秒数。
Definition: sttnet.h:767
void setFunction(std::function< bool(const int &fd)> fc)
设置epoll触发后的处理函数 注册一个回调函数
Definition: sttnet.h:2521
udp客户端的操作类
Definition: sttnet.h:3786
static int & toInt(const std::string_view &ori_str, int &result, const int &i=-1)
string转化为int类型
static std::string createJson(T1 first, T2 second)
创建仅包含一个键值对的 JSON 字符串。
Definition: sttnet.h:1635
void setGlobalSolveFunction(std::function< bool(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> fc)
设置全局备用函数
Definition: sttnet.h:3493
保存底层基础Tcp通道信息的结构体
Definition: sttnet.h:2876
static std::string jsonAdd(const std::string &a, const std::string &b)
将两个 JSON 字符串拼接为一个有效的 JSON(适用于对象或数组拼接)。
static bool compareTime(const std::string &time1, const std::string &time2, const std::string &format1=ISO8086A, const std::string &format2=ISO8086A)
比较两个时间字符串表示的时间的大小
void setFunction(const std::string &key, std::function< int(HttpServerFDHandler &k, HttpRequestInformation &inf)> fc)
设置key对应的收到客户端消息后的回调函数
Definition: sttnet.h:3301
security::ConnectionLimiter connectionLimiter
Definition: sttnet.h:2951
bool closeFile(const bool &del=false)
关闭已打开了的文件
bool appendLine(const std::string &data, const int &linePos=0)
插入行
std::string ip
客户端ip
Definition: sttnet.h:2885
bool isOpen()
获取对象是否打开日志文件的状态
Definition: sttnet.h:969
DefenseDecision
安全裁决结果(由 ConnectionLimiter 返回)。
Definition: sttnet.h:1902
int fd
底层的socket套接字
Definition: sttnet.h:2796
void setHBTimeOutTime(const int &secb)
设置发送心跳后的等待时间
Definition: sttnet.h:3561
void putTask(const std::function< int(WebSocketServerFDHandler &k, WebSocketFDInformation &inf)> &fun, WebSocketServerFDHandler &k, WebSocketFDInformation &inf)
把一个任务放入工作线程池由工作线程完成
提供文件操作的静态函数工具类
Definition: sttnet.h:75
ConnectionLimiter(const int &maxConn=20, const int &idleTimeout=60)
构造函数。
Definition: sttnet.h:2005
日志文件操作类
Definition: sttnet.h:941
读写磁盘文件的类
Definition: sttnet.h:145
void setJudgeFunction(std::function< bool(WebSocketFDInformation &k)> fcc)
设置websocket握手阶段的检查函数,只有检查通过才执行后续握手 注册一个回调函数
Definition: sttnet.h:3512
int msec
毫秒
Definition: sttnet.h:549
std::queue< WorkerMessage > finishQueue
Definition: sttnet.h:2947
随机数,字符串生成相关
Definition: sttnet.h:1136
int find(const std::string &targetString, const int linePos=1)
查找行
static char & bitOutput_bit(char input, const int pos, char &result)
获取字符 input 的从左向右第 pos 位(二进制)并返回 &#39;1&#39; 或 &#39;0&#39;。
bool endListen()
结束epoll监听 会阻塞直到epoll退出完成
void unblockSet()
设置对象中的套接字为非阻塞模式
SSL * ssl
如果加密了,存放加密句柄
Definition: sttnet.h:2909
bool isListen()
返回对象的监听状态
Definition: sttnet.h:3177
bool multiUseSet()
设置对象中的套接字为SO_REUSEADDR模式
char name[MAX_PROCESS_NAME]
进程名字
Definition: sttnet.h:4009
Definition: sttnet.h:1905
static bool startProcess(const std::string &name, const int &sec=-1, Args...args)
启动一个新进程(可选择是否定时重启)
Definition: sttnet.h:4105
SSL * getSSL(const int &fd)
查询和服务端的连接,传入套接字,返回加密的SSL句柄
void unblockSet()
设置为非阻塞模式
static std::string & getTime(std::string &timeStr, const std::string &format=ISO8086A)
获取当前时间
#define ISO8086A
定义ISO8086A这个宏为&quot;yyyy-mm-ddThh:mi:ss&quot;
Definition: sttnet.h:830
void setTimeOutTime(const int &seca)
设置心跳时间
Definition: sttnet.h:3555
void setFunction(std::function< bool(const std::string &message, WebSocketClient &k)> fc)
设置收到服务端消息后的回调函数 注册一个回调函数
Definition: sttnet.h:2604
std::chrono::steady_clock::time_point lastRefill
Definition: sttnet.h:1826
固定大小的工作线程池
Definition: sttnet.h:4253
std::unordered_map< int, ConnectionState > conns
Definition: sttnet.h:1879