CSnmpClass.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. #include <signal.h>
  2. #include "json.h"
  3. #include "CSnmpClass.h"
  4. #include "CSnmptrap.h"
  5. #include "log.h"
  6. #include "TSysTime.h"
  7. //char* CSnmpClass::m_pDdefault_port = "udp:192.168.1.82:162";
  8. //char* CSnmpClass::m_pDdefault_port = "udp:192.168.12.10:162";
  9. char* CSnmpClass::m_pDdefault_port = "udp:162";
  10. char* CSnmpClass::m_pDefault_port = m_pDdefault_port;
  11. int CSnmpClass::m_nDofork = 1;
  12. void* CSnmpClass::m_pInstance = nullptr;
  13. CSnmpClass::CSnmpClass()
  14. {
  15. m_nAlarmStatus = 0;
  16. m_nPowerFlag = 0;
  17. m_nErpsFlag = 0;
  18. m_nPhyFlag = 0;
  19. m_nBoardFlag = 0;
  20. m_pOolInvoker = nullptr;
  21. m_pTrap1_fmt_str_remember = nullptr;
  22. m_nTrapd_status = SNMPTRAPD_STOPPED;
  23. m_pApp_name_long = "Net-SNMP Trap Handler";
  24. m_pApp_name = "snmptrapd";
  25. memset(m_bindip,0,100);
  26. AppLogConfigure(nullptr, "netsnmp", "netsnmp");
  27. m_pOolInvoker = new TSysThreadPool;
  28. m_pOolInvoker->Start(2);
  29. }
  30. CSnmpClass::~CSnmpClass()
  31. {
  32. Stop();
  33. std::vector <DEVICEINFO*>::iterator iter = m_pWhite_list.begin();
  34. for (; iter != m_pWhite_list.end();) {
  35. if (*iter) {
  36. delete (*iter);
  37. (*iter) = NULL;
  38. }
  39. iter = m_pWhite_list.erase(iter);
  40. }
  41. if (m_pOolInvoker) {
  42. delete m_pOolInvoker;
  43. m_pOolInvoker = nullptr;
  44. }
  45. TermHandler(1);
  46. BLOG_DEBUG("app closed");
  47. }
  48. RETSIGTYPE CSnmpClass::TermHandler(int sig)
  49. {
  50. netsnmp_running = 0;
  51. /*
  52. * In case of windows, select() in receive() function will not return
  53. * on signal. Thats why following function is called, which closes the
  54. * socket descriptors and causes the select() to return
  55. */
  56. snmp_close(main_session);
  57. }
  58. int CSnmpClass::PreParse(netsnmp_session * session, netsnmp_transport *transport, void *transport_data, int transport_data_length)
  59. {
  60. return 1;
  61. }
  62. netsnmp_session* CSnmpClass::SnmptrapdAddSession(netsnmp_transport *t)
  63. {
  64. netsnmp_session sess, *session = &sess, *rc = NULL;
  65. snmp_sess_init(session);
  66. session->peername = SNMP_DEFAULT_PEERNAME; /* Original code had NULL here */
  67. session->version = SNMP_DEFAULT_VERSION;
  68. session->community_len = SNMP_DEFAULT_COMMUNITY_LEN;
  69. session->retries = SNMP_DEFAULT_RETRIES;
  70. session->timeout = SNMP_DEFAULT_TIMEOUT;
  71. session->callback = snmp_input;
  72. session->callback_magic = (void *)t;
  73. session->authenticator = NULL;
  74. sess.isAuthoritative = SNMP_SESS_UNKNOWNAUTH;
  75. rc = snmp_add(session, t, PreParse, NULL);
  76. if (rc == NULL) {
  77. snmp_sess_perror("snmptrapd", session);
  78. }
  79. return rc;
  80. }
  81. void CSnmpClass::SnmptrapdCloseSessions(netsnmp_session * sess_list)
  82. {
  83. netsnmp_session *s = NULL, *next = NULL;
  84. for (s = sess_list; s != NULL; s = next) {
  85. next = s->next;
  86. snmp_close(s);
  87. }
  88. }
  89. void CSnmpClass::ParseTrapdAddress(const char *token, char *cptr)
  90. {
  91. char buf[BUFSIZ];
  92. char *p;
  93. cptr = copy_nword(cptr, buf, sizeof(buf));
  94. if (m_pDefault_port == m_pDdefault_port) {
  95. m_pDefault_port = strdup(buf);
  96. }
  97. else {
  98. p = (char*)malloc(strlen(buf) + 1 + strlen(m_pDefault_port) + 1);
  99. if (p) {
  100. strcpy(p, buf);
  101. strcat(p, ",");
  102. strcat(p, m_pDefault_port);
  103. }
  104. free(m_pDefault_port);
  105. m_pDefault_port = p;
  106. }
  107. }
  108. void CSnmpClass::FreeTrapdAddress(void)
  109. {
  110. if (m_pDefault_port != m_pDdefault_port) {
  111. free(m_pDefault_port);
  112. m_pDefault_port = m_pDdefault_port;
  113. }
  114. }
  115. void CSnmpClass::ParseConfigDoNotLogTraps(const char *token, char *cptr)
  116. {
  117. if (atoi(cptr) > 0)
  118. SyslogTrap++;
  119. }
  120. void CSnmpClass::ParseConfigDoNotFork(const char *token, char *cptr)
  121. {
  122. if (netsnmp_ds_parse_boolean(cptr) == 1)
  123. m_nDofork = 0;
  124. }
  125. void CSnmpClass::ParseConfigIgnoreAuthFailure(const char *token, char *cptr)
  126. {
  127. if (netsnmp_ds_parse_boolean(cptr) == 1)
  128. dropauth = 1;
  129. }
  130. void CSnmpClass::ParseConfigOutputOption(const char *token, char *cptr)
  131. {
  132. char *cp;
  133. cp = snmp_out_toggle_options(cptr);
  134. if (cp != NULL) {
  135. fprintf(stderr, "Unknown output option passed to -O: %c\n",
  136. *cp);
  137. }
  138. }
  139. void CSnmpClass::ParseConfigAddForwarderInfo(const char *token, char *cptr)
  140. {
  141. if (netsnmp_ds_parse_boolean(cptr) == 1) {
  142. netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
  143. NETSNMP_DS_LIB_ADD_FORWARDER_INFO, 1);
  144. }
  145. }
  146. void CSnmpClass::Action()
  147. {
  148. char custom[100] = "";
  149. memcpy(custom, m_send_bind_ip.c_str(), m_send_bind_ip.size());
  150. CSnmptrap* m_pTrap = new CSnmptrap;
  151. while (!IsAborted()) {
  152. Sleep(m_nMtime*1000);
  153. if (m_systemType == "h3c")
  154. continue;
  155. //m_Alarm.lock();
  156. int status = m_nAlarmStatus;
  157. std::vector<std::string>::iterator iter;
  158. for (iter = m_dst_ip.begin(); iter != m_dst_ip.end(); iter++) {
  159. m_pTrap->SendTrap2(status, *iter, m_sCommunity, "KTT Alarm", "1.3.6.1.4.1.2345", custom, m_needTime);
  160. BLOG_DEBUG(fmt::format("Action SendTrap:: ip:{},comunnity:{},KTT Alarm:{}", *iter, m_sCommunity, status));
  161. }
  162. //m_pTrap->SendTrap2(status, m_dst_ip, m_sCommunity, "KTT Alarm", "1.3.6.1.4.1.2345",custom, m_needTime);
  163. }
  164. delete m_pTrap;
  165. }
  166. std::string CSnmpClass::FindString(std::string a, std::string b)
  167. {
  168. if (a.size()>b.size())
  169. swap(a, b); //确保前面的一个字符串短;
  170. std::string str_m;
  171. for (int i = 0; i<a.size(); i++)
  172. {
  173. for (int j = i; j<a.size(); j++)
  174. {
  175. std::string temp = a.substr(i, j - i + 1);
  176. if (int(b.find(temp))<0)
  177. break;
  178. else if (str_m.size()<temp.size())
  179. str_m = temp;
  180. }
  181. }
  182. return str_m;
  183. }
  184. void CSnmpClass::SendStringH3c(int status, std::string comunnity, std::string buf)
  185. {
  186. CSnmptrap* m_pTrap = new CSnmptrap;
  187. //
  188. std::string m_sAlarmType = "ADB-;WVB-;EVB-;CTR-";
  189. std::string m_sResult = FindString(buf, m_sAlarmType);
  190. BLOG_DEBUG(fmt::format("Find The AlarmType :{}", m_sResult.c_str()));
  191. char m_cFirst = (m_sResult.c_str())[0];
  192. switch (m_cFirst)
  193. {
  194. case 'A':
  195. case 'W':
  196. case 'E':
  197. m_pTrap->SendTrapH3c(status, "10.1.101.21", comunnity, "TKO Alarm");
  198. m_pTrap->SendTrapH3c(status, "10.1.201.21", comunnity, "TKO Alarm");
  199. m_pTrap->SendTrapH3c(status, "10.1.101.22", comunnity, "TKO Alarm");
  200. m_pTrap->SendTrapH3c(status, "10.1.201.22", comunnity, "TKO Alarm");
  201. BLOG_DEBUG(fmt::format("SendTrap:: comunnity:{},TKO Alarm:{}", comunnity, status));
  202. break;
  203. case 'C':
  204. m_pTrap->SendTrapH3c(status, "10.4.101.21", comunnity, "CBL Alarm");
  205. m_pTrap->SendTrapH3c(status, "10.4.201.21", comunnity, "CBL Alarm");
  206. m_pTrap->SendTrapH3c(status, "10.4.101.22", comunnity, "CBL Alarm");
  207. m_pTrap->SendTrapH3c(status, "10.4.201.22", comunnity, "CBL Alarm");
  208. BLOG_DEBUG(fmt::format("SendTrap:: comunnity:{},CBL Alarm:{}", comunnity, status));
  209. break;
  210. default:
  211. break;
  212. }
  213. //
  214. delete m_pTrap;
  215. }
  216. void CSnmpClass::SendString(int status, std::string comunnity, std::string buf, std::string moduleIdentity, std::string power)
  217. {
  218. m_Alarm.lock();
  219. m_nAlarmStatus = status;
  220. m_Alarm.unlock();
  221. CSnmptrap* m_pTrap = new CSnmptrap;
  222. char custom[100] = "";
  223. memcpy(custom, m_send_bind_ip.c_str(), m_send_bind_ip.size());
  224. std::vector<std::string>::iterator iter;
  225. for (iter = m_dst_ip.begin(); iter != m_dst_ip.end(); iter++) {
  226. m_pTrap->SendTrap(status, *iter, comunnity, "KTT Alarm", moduleIdentity, power, custom, m_needTime);
  227. BLOG_DEBUG(fmt::format("SendTrap:: ip:{},comunnity:{},KTT Alarm:{}", *iter, comunnity, status));
  228. }
  229. //m_pTrap->SendTrap(status, m_dst_ip, comunnity, "KTT Alarm", moduleIdentity, power,custom, m_needTime);
  230. /*m_pTrap->SendTrap(status, "192.168.31.8:161", comunnity, "KTT Alarm", moduleIdentity, power);*/
  231. delete m_pTrap;
  232. }
  233. int CSnmpClass::ParsePtype(std::string buf,std::string upAnddown)
  234. {
  235. //POWER_FAILED
  236. //POWER_RECOVERED
  237. //PHY_UPDOWN
  238. int m_nResult = 1;
  239. if ("POWER_FAILED" == buf) {
  240. m_nPowerFlag = 1;
  241. m_nResult = 0;
  242. //SendString(1,buf);
  243. }
  244. if ("POWER_RECOVERED" == buf) {
  245. m_nPowerFlag = 0;
  246. m_nResult = 0;
  247. }
  248. if ("PHY_UPDOWN" == buf) {
  249. std::string::size_type m_nindex = upAnddown.find("changed to down");
  250. if (m_nindex != upAnddown.npos) {
  251. //buff = buff.substr(0, m_nindex);
  252. m_nPhyFlag = 1;
  253. }
  254. else {
  255. m_nPhyFlag = 0;
  256. }
  257. m_nResult = 0;
  258. }
  259. return m_nResult;
  260. }
  261. int CSnmpClass::ParseEtype(std::string buf, std::string upAnddown)
  262. {
  263. //ERPS_STATE_CHANGED
  264. int m_nResult = 1;
  265. if ("ERPS_STATE_CHANGED" == buf) {
  266. std::string::size_type m_nindex = upAnddown.find("changed state to Protection");
  267. if (m_nindex != upAnddown.npos) {
  268. BLOG_DEBUG("find changed state to Protection");
  269. m_nErpsFlag = 1;
  270. m_nResult = 0;
  271. }
  272. else {
  273. std::string::size_type m_nindex_2 = upAnddown.find("changed state to Idle");
  274. if (m_nindex_2 != upAnddown.npos) {
  275. //buff = buff.substr(0, m_nindex);
  276. BLOG_DEBUG("find changed state to Idle");
  277. m_nErpsFlag = 0;
  278. m_nResult = 0;
  279. }
  280. }
  281. }
  282. return m_nResult;
  283. }
  284. int CSnmpClass::ParseBtype(std::string buf)
  285. {
  286. int m_nResult = 1;
  287. //BOARD_STATE_FAULT
  288. //BOARD_STATE_NORMAL
  289. if ("BOARD_STATE_FAULT" == buf) {
  290. m_nBoardFlag = 1;
  291. m_nResult = 0;
  292. }
  293. if ("BOARD_STATE_NORMAL" == buf) {
  294. m_nBoardFlag = 0;
  295. m_nResult = 0;
  296. }
  297. return m_nResult;
  298. }
  299. void CSnmpClass::MoxaParseBuffer(std::string buf, std::string comunnity)
  300. {
  301. //printf("RECV:%s\n", buf.c_str());
  302. //std::string test = "{2022-03-23 13:52:51 192.168.12.253 [192.168.12.253] (via UDP: [192.168.1.82]:49990->[192.168.1.82]:162) TRAP, SNMP v1, community public \
  303. // SNMPv2 - SMI::enterprises.8691.7.7 Enterprise Specific Trap(2) Uptime: 0 : 03 : 57.68 \
  304. // SNMPv2 - SMI::enterprises.8691.7.7.2.2 = INTEGER : 3}";
  305. if (CheckPower(buf, comunnity) || CheckResetPower(buf, comunnity) || CheckNetwork(buf, comunnity))
  306. return;
  307. }
  308. void CSnmpClass::H3cParseBuffer(std::string buf, std::string comunnity)
  309. {
  310. //POWER_FAILED
  311. //POWER_RECOVERED
  312. //ERPS_STATE_CHANGED
  313. //PHY_UPDOWN
  314. //BOARD_STATE_FAULT
  315. //BOARD_STATE_NORMAL
  316. std::string m_sdata = "POWER_FAILED;POWER_RECOVERED;ERPS_STATE_CHANGED;PHY_UPDOWN;BOARD_STATE_FAULT;BOARD_STATE_NORMAL";
  317. #if 1
  318. std::string m_sResult = FindString(buf, m_sdata);
  319. #else
  320. std::string test1 = "2021-06-10 10:19:20 <UNKNOWN> [UDP: [10.2.100.1]:10703->[10.1.100.99]:162]:DISMAN - EVENT - MIB::sysUpTimeInstance = Timeticks: (1295968167) 149 days, 23 : 54 : 41.67SNMPv2 - MIB::snmpTrapOID.0 = OID : SNMPv2 - SMI::mib - 2.192.0.1SNMPv2 - SMI::mib - 2.192.1.2.1.2.1143 = INTEGER : 23SNMPv2 - SMI::mib - 2.192.1.2.1.3.1143 = INTEGER : 5SNMPv2 - SMI::mib - 2.192.1.2.1.4.1143 = Gauge32 : 1SNMPv2 - SMI::mib - 2.192.1.2.1.5.1143 = Hex - STRING : 07 E5 06 0A 0A 11 2E 00 00 00 2B 08 00SNMPv2 - SMI::mib - 2.192.1.2.1.6.1143 = STRING: \"WVB-COM-CSW\"SNMPv2 - SMI::mib - 2.192.1.2.1.7.1143 = STRING : \"DEV\"SNMPv2 - SMI::mib - 2.192.1.2.1.8.1143 = STRING : \"-\"SNMPv2 - SMI::mib - 2.192.1.2.1.9.1143 = STRING : \"BOARD_REBOOT\"SNMPv2 - SMI::mib - 2.192.1.2.1.10.1143 = Gauge32 : 3SNMPv2 - SMI::mib - 2.192.1.2.1.11.1143 = STRING : \"Physical state on the interface Ten-GigabitEthernet1/2/0/29 changed to up.\"SNMPv2 - SMI::mib - 2.192.1.3.1.4.1143.1.12.83.121.115.76.111.99.64.50.53.53.48.54.7.67.104.97.115.115.105.115 = STRING : \"1\"SNMPv2 - SMI::mib - 2.192.1.3.1.4.1143.2.12.83.121.115.76.111.99.64.50.53.53.48.54.4.83.108.111.116 = STRING : \"0\"SNMPv2 - SMI::mib - 2.192.1.3.1.4.1143.3.12.83.121.115.76.111.99.64.50.53.53.48.54.3.77.68.67 = STRING : \"1\"";
  321. std::string m_sResult = FindString(m_sdata, test1);
  322. buf = test1;
  323. #endif
  324. int m_nFlag = 0;
  325. char m_cFirst = (m_sResult.c_str())[0];
  326. switch (m_cFirst)
  327. {
  328. case 'P':
  329. m_nFlag = ParsePtype(m_sResult, buf);
  330. break;
  331. case 'E':
  332. m_nFlag = ParseEtype(m_sResult, buf);
  333. break;
  334. case 'B':
  335. m_nFlag = ParseBtype(m_sResult);
  336. break;
  337. default:
  338. m_nFlag = 1;
  339. break;
  340. }
  341. if (0 == m_nFlag) {
  342. printf("RECV:{%s}\n", m_sResult.c_str());
  343. BLOG_DEBUG(fmt::format("RECV:{}", m_sResult));
  344. BLOG_DEBUG(fmt::format("[comunnity::{}]m_nPowerFlag:{},m_nErpsFlag:{},m_nPhyFlag:{},m_nBoardFlag:{}", comunnity, m_nPowerFlag, m_nErpsFlag, m_nPhyFlag, m_nBoardFlag));
  345. if (m_nPowerFlag || m_nErpsFlag || m_nPhyFlag || m_nBoardFlag)
  346. {
  347. SendStringH3c(1, comunnity, buf);
  348. }
  349. else {
  350. SendStringH3c(0, comunnity, buf);
  351. }
  352. }
  353. }
  354. void CSnmpClass::ParseBuffer(std::string buf, std::string comunnity)
  355. {
  356. OutputDebugStringA(fmt::format("RECV:{}", buf).c_str());
  357. if (m_systemType == "moxa")
  358. MoxaParseBuffer(buf, comunnity);
  359. if (m_systemType == "h3c")
  360. H3cParseBuffer(buf, comunnity);
  361. }
  362. int CSnmpClass::RecvHandler(netsnmp_pdu* pdu, netsnmp_transport* transport, netsnmp_trapd_handler * handler)
  363. {
  364. #if 1
  365. u_char *rbuf = NULL;
  366. size_t r_len = 64, o_len = 0;
  367. int trunc = 0;
  368. DEBUGMSGTL(("snmptrapd", "print_handler\n"));
  369. /*
  370. * Don't bother logging authentication failures
  371. * XXX - can we handle this via suitable handler entries instead?
  372. */
  373. if (pdu->trap_type == SNMP_TRAP_AUTHFAIL && dropauth)
  374. return NETSNMPTRAPD_HANDLER_OK;
  375. if ((rbuf = (u_char *)calloc(r_len, 1)) == NULL) {
  376. snmp_log(LOG_ERR, "couldn't display trap -- malloc failed\n");
  377. return NETSNMPTRAPD_HANDLER_FAIL; /* Failed but keep going */
  378. }
  379. /*
  380. * If there's a format string registered for this trap, then use it.
  381. */
  382. if (handler && handler->format) {
  383. DEBUGMSGTL(("snmptrapd", "format = '%s'\n", handler->format));
  384. if (*handler->format) {
  385. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  386. handler->format, pdu, transport);
  387. }
  388. else {
  389. free(rbuf);
  390. return NETSNMPTRAPD_HANDLER_OK; /* A 0-length format string means don't log */
  391. }
  392. /*
  393. * Otherwise (i.e. a NULL handler format string),
  394. * use a standard output format setting
  395. * either configurable, or hardwired
  396. *
  397. * XXX - v1 traps use a different routine for hardwired output
  398. * Do we actually need this separate v1 routine?
  399. * Or would a suitable format string be sufficient?
  400. */
  401. }
  402. else {
  403. if (pdu->command == SNMP_MSG_TRAP) {
  404. if (print_format1) {
  405. DEBUGMSGTL(("snmptrapd", "print_format v1 = '%s'\n", print_format1));
  406. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  407. print_format1, pdu, transport);
  408. }
  409. else {
  410. DEBUGMSGTL(("snmptrapd", "v1 format\n"));
  411. trunc = !realloc_format_plain_trap(&rbuf, &r_len, &o_len, 1,
  412. pdu, transport);
  413. }
  414. }
  415. else {
  416. if (print_format2) {
  417. DEBUGMSGTL(("snmptrapd", "print_format v2 = '%s'\n", print_format2));
  418. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  419. print_format2, pdu, transport);
  420. }
  421. else {
  422. DEBUGMSGTL(("snmptrapd", "v2/3 format\n"));
  423. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  424. PRINT_V23_NOTIFICATION_FORMAT,
  425. pdu, transport);
  426. }
  427. }
  428. }
  429. //snmp_log(LOG_INFO, "%s%s", rbuf, (trunc ? " [TRUNCATED]\n" : ""));
  430. std::string m_sBuff = (char*)rbuf;
  431. BLOG_DEBUG(m_sBuff);
  432. //
  433. char* m_pCom = (char*)malloc(pdu->community_len + 1);
  434. memset(m_pCom,0, pdu->community_len + 1);
  435. memcpy(m_pCom, pdu->community, pdu->community_len);
  436. std::string Community = std::string(m_pCom);
  437. free(m_pCom);
  438. evpp::EventLoop* curr_loop = ((CSnmpClass*)m_pInstance)->m_pOolInvoker->GetNextLoop();
  439. if (!curr_loop) {
  440. //BLOG_DEBUG(fmt::format("[FAIL] find an executive for AcknowledgeEntityStatusEX"));
  441. }
  442. else {
  443. curr_loop->RunInLoop(std::bind(&CSnmpClass::ReadProcess, (CSnmpClass*)m_pInstance, m_sBuff, Community));
  444. }
  445. free(rbuf);
  446. #endif
  447. return NETSNMPTRAPD_HANDLER_OK;
  448. }
  449. int CSnmpClass::PrintHandler(netsnmp_pdu* pdu,netsnmp_transport* transport,netsnmp_trapd_handler * handler)
  450. {
  451. printf("print_handler\n");
  452. //std::string m_sBuff = (char*)rbuf;
  453. #if 0
  454. u_char *rbuf = NULL;
  455. size_t r_len = 64, o_len = 0;
  456. int trunc = 0;
  457. printf("print_handler\n");
  458. DEBUGMSGTL(("snmptrapd", "print_handler\n"));
  459. /*
  460. * Don't bother logging authentication failures
  461. * XXX - can we handle this via suitable handler entries instead?
  462. */
  463. if (pdu->trap_type == SNMP_TRAP_AUTHFAIL && dropauth)
  464. return NETSNMPTRAPD_HANDLER_OK;
  465. if ((rbuf = (u_char *)calloc(r_len, 1)) == NULL) {
  466. snmp_log(LOG_ERR, "couldn't display trap -- malloc failed\n");
  467. return NETSNMPTRAPD_HANDLER_FAIL; /* Failed but keep going */
  468. }
  469. /*
  470. * If there's a format string registered for this trap, then use it.
  471. */
  472. if (handler && handler->format) {
  473. DEBUGMSGTL(("snmptrapd", "format = '%s'\n", handler->format));
  474. if (*handler->format) {
  475. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  476. handler->format, pdu, transport);
  477. }
  478. else {
  479. free(rbuf);
  480. return NETSNMPTRAPD_HANDLER_OK; /* A 0-length format string means don't log */
  481. }
  482. /*
  483. * Otherwise (i.e. a NULL handler format string),
  484. * use a standard output format setting
  485. * either configurable, or hardwired
  486. *
  487. * XXX - v1 traps use a different routine for hardwired output
  488. * Do we actually need this separate v1 routine?
  489. * Or would a suitable format string be sufficient?
  490. */
  491. }
  492. else {
  493. if (pdu->command == SNMP_MSG_TRAP) {
  494. if (print_format1) {
  495. DEBUGMSGTL(("snmptrapd", "print_format v1 = '%s'\n", print_format1));
  496. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  497. print_format1, pdu, transport);
  498. }
  499. else {
  500. DEBUGMSGTL(("snmptrapd", "v1 format\n"));
  501. trunc = !realloc_format_plain_trap(&rbuf, &r_len, &o_len, 1,
  502. pdu, transport);
  503. }
  504. }
  505. else {
  506. if (print_format2) {
  507. DEBUGMSGTL(("snmptrapd", "print_format v2 = '%s'\n", print_format2));
  508. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  509. print_format2, pdu, transport);
  510. }
  511. else {
  512. DEBUGMSGTL(("snmptrapd", "v2/3 format\n"));
  513. trunc = !realloc_format_trap(&rbuf, &r_len, &o_len, 1,
  514. PRINT_V23_NOTIFICATION_FORMAT,
  515. pdu, transport);
  516. }
  517. }
  518. }
  519. snmp_log(LOG_INFO, "%s%s", rbuf, (trunc ? " [TRUNCATED]\n" : ""));
  520. std::string bufftest = (char*)rbuf;
  521. //SnmptrapdMainLoop();
  522. evpp::EventLoop* curr_loop = ((CSnmpClass*)m_pInstance)->m_pOolInvoker->GetNextLoop();
  523. if (!curr_loop) {
  524. //BLOG_DEBUG(fmt::format("[FAIL] find an executive for AcknowledgeEntityStatusEX"));
  525. }
  526. else {
  527. curr_loop->RunInLoop(std::bind(&CSnmpClass::ReadProcess, (CSnmpClass*)m_pInstance, bufftest));
  528. }
  529. free(rbuf);
  530. #endif
  531. return NETSNMPTRAPD_HANDLER_OK;
  532. }
  533. void CSnmpClass::ReadProcess(std::string buf, std::string comunnity)
  534. {
  535. //STRING:
  536. //INTEGER:
  537. m_sCommunity = comunnity;
  538. ParseBuffer(buf, comunnity);
  539. }
  540. void CSnmpClass::SnmptrapdMainLoop(void)
  541. {
  542. int count, numfds, block;
  543. fd_set readfds, writefds, exceptfds;
  544. struct timeval timeout;
  545. NETSNMP_SELECT_TIMEVAL timeout2;
  546. while (netsnmp_running) {
  547. numfds = 0;
  548. FD_ZERO(&readfds);
  549. FD_ZERO(&writefds);
  550. FD_ZERO(&exceptfds);
  551. block = 0;
  552. timerclear(&timeout);
  553. timeout.tv_sec = 5;
  554. snmp_select_info(&numfds, &readfds, &timeout, &block);
  555. #ifndef NETSNMP_FEATURE_REMOVE_FD_EVENT_MANAGER
  556. netsnmp_external_event_info(&numfds, &readfds, &writefds, &exceptfds);
  557. #endif /* NETSNMP_FEATURE_REMOVE_FD_EVENT_MANAGER */
  558. timeout2.tv_sec = timeout.tv_sec;
  559. timeout2.tv_usec = timeout.tv_usec;
  560. count = select(numfds, &readfds, &writefds, &exceptfds,
  561. !block ? &timeout2 : NULL);
  562. if (count > 0) {
  563. #ifndef NETSNMP_FEATURE_REMOVE_FD_EVENT_MANAGER
  564. netsnmp_dispatch_external_events(&count, &readfds, &writefds,
  565. &exceptfds);
  566. #endif /* NETSNMP_FEATURE_REMOVE_FD_EVENT_MANAGER */
  567. /* If there are any more events after external events, then
  568. * try SNMP events. */
  569. if (count > 0) {
  570. snmp_read(&readfds);
  571. }
  572. }
  573. else {
  574. switch (count) {
  575. case 0:
  576. snmp_timeout();
  577. break;
  578. case -1:
  579. if (errno == EINTR)
  580. continue;
  581. snmp_log_perror("select");
  582. netsnmp_running = 0;
  583. break;
  584. default:
  585. fprintf(stderr, "select returned %d\n", count);
  586. netsnmp_running = 0;
  587. }
  588. }
  589. run_alarms();
  590. }
  591. }
  592. /*******************************************************************-o-******
  593. * main - Non Windows
  594. * SnmpTrapdMain - Windows to support windows service
  595. *
  596. * Parameters:
  597. * argc
  598. * *argv[]
  599. *
  600. * Returns:
  601. * 0 Always succeeds. (?)
  602. *
  603. *
  604. * Setup and start the trap receiver daemon.
  605. *
  606. * Also successfully EXITs with zero for some options.
  607. */
  608. void CSnmpClass::InitNetsnmpTrapdAuth(void)
  609. {
  610. /* register our function as a authorization handler */
  611. netsnmp_trapd_handler *traph;
  612. //RecvHandler
  613. //traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_AUTH_HANDLER,netsnmp_trapd_auth);
  614. traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_AUTH_HANDLER, RecvHandler);
  615. traph->authtypes = TRAP_AUTH_NONE;
  616. #ifdef USING_MIBII_VACM_CONF_MODULE
  617. /* register our configuration tokens for VACM configs */
  618. init_vacm_config_tokens();
  619. #endif
  620. /* register a config token for turning off the authorization entirely */
  621. netsnmp_ds_register_config(ASN_BOOLEAN, "snmptrapd", "disableAuthorization",
  622. NETSNMP_DS_APPLICATION_ID,
  623. NETSNMP_DS_APP_NO_AUTHORIZATION);
  624. }
  625. int CSnmpClass::SnmpTrapdMain(int argc, char * argv[])
  626. {
  627. static const char options[] = "aAc:CdD::efF:g:hHI:L:m:M:no:O:Ptu:vx:X-:""p:";
  628. netsnmp_session *sess_list = NULL, *ss = NULL;
  629. netsnmp_transport *transport = NULL;
  630. int arg, i = 0;
  631. int uid = 0, gid = 0;
  632. int exit_code = 1;
  633. char *cp, *listen_ports = NULL;
  634. #if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
  635. int agentx_subagent = 1;
  636. #endif
  637. netsnmp_trapd_handler *traph;
  638. signal(SIGTERM,TermHandler);
  639. signal(SIGINT,TermHandler);
  640. /*
  641. * register our configuration handlers now so -H properly displays them
  642. */
  643. snmptrapd_register_configs();
  644. #ifdef NETSNMP_SECMOD_USM
  645. init_usm_conf("snmptrapd");
  646. #endif /* NETSNMP_SECMOD_USM */
  647. register_config_handler("snmptrapd", "snmpTrapdAddr",
  648. ParseTrapdAddress, FreeTrapdAddress, "string");
  649. register_config_handler("snmptrapd", "doNotLogTraps",
  650. ParseConfigDoNotLogTraps, NULL, "(1|yes|true|0|no|false)");
  651. register_config_handler("snmptrapd", "doNotFork",
  652. ParseConfigDoNotFork, NULL, "(1|yes|true|0|no|false)");
  653. register_config_handler("snmptrapd", "ignoreAuthFailure",
  654. ParseConfigIgnoreAuthFailure, NULL, "(1|yes|true|0|no|false)");
  655. register_config_handler("snmptrapd", "outputOption",
  656. ParseConfigOutputOption, NULL, "string");
  657. register_config_handler("snmptrapd", "addForwarderInfo",
  658. ParseConfigAddForwarderInfo, NULL,
  659. "(1|yes|true|0|no|false)");
  660. snmp_log_syslogname(m_pApp_name_long);
  661. /*
  662. * Now process options normally.
  663. */
  664. #if 1
  665. while ((arg = getopt(argc, argv, options)) != EOF) {
  666. switch (arg) {
  667. case 'c':
  668. if (optarg != NULL) {
  669. netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID,
  670. NETSNMP_DS_LIB_OPTIONALCONFIG, optarg);
  671. }
  672. else {
  673. return 1;
  674. }
  675. break;
  676. case 'C':
  677. netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
  678. NETSNMP_DS_LIB_DONT_READ_CONFIGS, 1);
  679. break;
  680. case 'd':
  681. netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
  682. NETSNMP_DS_LIB_DUMP_PACKET, 1);
  683. break;
  684. case 'D':
  685. debug_register_tokens(optarg);
  686. snmp_set_do_debugging(1);
  687. break;
  688. case 'f':
  689. m_nDofork = 0;
  690. break;
  691. case 'F':
  692. if (optarg != NULL) {
  693. if ((strncmp(optarg, "print", 5) == 0) ||
  694. (strncmp(optarg, "syslog", 6) == 0) ||
  695. (strncmp(optarg, "execute", 7) == 0)) {
  696. /* New style: "type=format" */
  697. m_pTrap1_fmt_str_remember = strdup(optarg);
  698. cp = strchr(m_pTrap1_fmt_str_remember, '=');
  699. if (cp)
  700. *cp = ' ';
  701. }
  702. else {
  703. /* Old style: implicitly "print=format" */
  704. m_pTrap1_fmt_str_remember = (char*)malloc(strlen(optarg) + 7);
  705. sprintf(m_pTrap1_fmt_str_remember, "print %s", optarg);
  706. }
  707. }
  708. else {
  709. return 1;
  710. }
  711. break;
  712. case 'L':
  713. if (snmp_log_options(optarg, argc, argv) < 0) {
  714. return 1;
  715. }
  716. break;
  717. }
  718. }
  719. #endif
  720. SOCK_STARTUP;
  721. /*
  722. * I'm being lazy here, and not checking the
  723. * return value from these registration calls.
  724. * Don't try this at home, children!
  725. */
  726. if (0 == snmp_get_do_logging()) {
  727. traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_PRE_HANDLER,
  728. syslog_handler);
  729. traph->authtypes = TRAP_AUTH_LOG;
  730. snmp_enable_syslog();
  731. }
  732. else {
  733. traph = netsnmp_add_global_traphandler(NETSNMPTRAPD_PRE_HANDLER,
  734. PrintHandler);
  735. traph->authtypes = TRAP_AUTH_LOG;
  736. }
  737. #if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
  738. /*
  739. * we're an agentx subagent?
  740. */
  741. if (agentx_subagent) {
  742. /*
  743. * make us a agentx client.
  744. */
  745. netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID,
  746. NETSNMP_DS_AGENT_ROLE, 1);
  747. }
  748. #endif
  749. /*
  750. * don't fail if we can't do agentx (ie, socket not there, or not root)
  751. */
  752. netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID,
  753. NETSNMP_DS_AGENT_NO_ROOT_ACCESS);
  754. /*
  755. * ignore any warning messages.
  756. */
  757. netsnmp_ds_toggle_boolean(NETSNMP_DS_APPLICATION_ID,
  758. NETSNMP_DS_AGENT_NO_CONNECTION_WARNINGS);
  759. /*
  760. * initialize the agent library
  761. */
  762. init_agent("snmptrapd");
  763. #if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
  764. #ifdef NETSNMP_FEATURE_CHECKING
  765. netsnmp_feature_require(register_snmpEngine_scalars_context)
  766. #endif /* NETSNMP_FEATURE_CHECKING */
  767. /*
  768. * initialize local modules
  769. */
  770. if (agentx_subagent) {
  771. subagent_init();
  772. #ifdef USING_SNMPV3_SNMPENGINE_MODULE
  773. /*
  774. * register scalars from SNMP-FRAMEWORK-MIB::snmpEngineID group;
  775. * allows engineID probes via the master agent under the
  776. * snmptrapd context
  777. */
  778. register_snmpEngine_scalars_context("snmptrapd");
  779. #endif
  780. }
  781. #endif /* USING_AGENTX_SUBAGENT_MODULE && !NETSNMP_SNMPTRAPD_DISABLE_AGENTX */
  782. /* register our authorization handler */
  783. InitNetsnmpTrapdAuth();
  784. #if defined(USING_AGENTX_SUBAGENT_MODULE) && !defined(NETSNMP_SNMPTRAPD_DISABLE_AGENTX)
  785. if (agentx_subagent) {
  786. #ifdef USING_SNMPV3_USMUSER_MODULE
  787. #ifdef NETSNMP_FEATURE_CHECKING
  788. netsnmp_feature_require(init_register_usmUser_context)
  789. #endif /* NETSNMP_FEATURE_CHECKING */
  790. /* register ourselves as having a USM user database */
  791. init_register_usmUser_context("snmptrapd");
  792. #endif
  793. #ifdef USING_AGENT_NSVACMACCESSTABLE_MODULE
  794. /* register net-snmp vacm extensions */
  795. init_register_nsVacm_context("snmptrapd");
  796. #endif
  797. #ifdef USING_TLSTM_MIB_SNMPTLSTMCERTTOTSNTABLE_MODULE
  798. init_snmpTlstmCertToTSNTable_context("snmptrapd");
  799. #endif
  800. }
  801. #endif
  802. /*
  803. * Initialize the world.
  804. */
  805. init_snmp("snmptrapd");
  806. if (m_pTrap1_fmt_str_remember) {
  807. parse_format(NULL, m_pTrap1_fmt_str_remember);
  808. }
  809. if (netsnmp_ds_get_boolean(NETSNMP_DS_APPLICATION_ID,
  810. NETSNMP_DS_AGENT_QUIT_IMMEDIATELY)) {
  811. /*
  812. * just starting up to process specific configuration and then
  813. * shutting down immediately.
  814. */
  815. netsnmp_running = 0;
  816. }
  817. /*
  818. * if no logging options on command line or in conf files, use syslog
  819. */
  820. if (0 == snmp_get_do_logging()) {
  821. snmp_enable_syslog_ident(m_pApp_name_long, LOG_DAEMON);
  822. }
  823. if (listen_ports)
  824. cp = listen_ports;
  825. else
  826. cp = m_pDefault_port;
  827. printf("%s\n", m_pDefault_port);
  828. while (cp != NULL) {
  829. char *sep = strchr(cp, ',');
  830. if (sep != NULL) {
  831. *sep = 0;
  832. }
  833. transport = netsnmp_transport_open_server("snmptrap", cp);
  834. if (transport == NULL) {
  835. snmp_log(LOG_ERR, "couldn't open %s -- errno %d (\"%s\")\n",
  836. cp, errno, strerror(errno));
  837. SnmptrapdCloseSessions(sess_list);
  838. goto sock_cleanup;
  839. }
  840. else {
  841. ss = SnmptrapdAddSession(transport);
  842. if (ss == NULL) {
  843. /*
  844. * Shouldn't happen? We have already opened the transport
  845. * successfully so what could have gone wrong?
  846. */
  847. SnmptrapdCloseSessions(sess_list);
  848. snmp_log(LOG_ERR, "couldn't open snmp - %s", strerror(errno));
  849. goto sock_cleanup;
  850. }
  851. else {
  852. ss->next = sess_list;
  853. sess_list = ss;
  854. }
  855. }
  856. /*
  857. * Process next listen address, if there is one.
  858. */
  859. if (sep != NULL) {
  860. *sep = ',';
  861. cp = sep + 1;
  862. }
  863. else {
  864. cp = NULL;
  865. }
  866. }
  867. SNMP_FREE(listen_ports); /* done with them */
  868. #ifdef NETSNMP_USE_MYSQL
  869. if (netsnmp_mysql_init()) {
  870. fprintf(stderr, "MySQL initialization failed\n");
  871. goto sock_cleanup;
  872. }
  873. #endif
  874. snmp_log(LOG_INFO, "NET-SNMP version %s\n", netsnmp_get_version());
  875. #ifdef WIN32SERVICE
  876. m_nTrapd_status = SNMPTRAPD_RUNNING;
  877. #endif
  878. SnmptrapdMainLoop();
  879. if (snmp_get_do_logging()) {
  880. struct tm *tm;
  881. time_t timer;
  882. time(&timer);
  883. tm = localtime(&timer);
  884. snmp_log(LOG_INFO,
  885. "%.4d-%.2d-%.2d %.2d:%.2d:%.2d NET-SNMP version %s Stopped.\n",
  886. tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour,
  887. tm->tm_min, tm->tm_sec, netsnmp_get_version());
  888. }
  889. snmp_log(LOG_INFO, "Stopping snmptrapd\n");
  890. #ifdef NETSNMP_EMBEDDED_PERL
  891. shutdown_perl();
  892. #endif
  893. SnmptrapdCloseSessions(sess_list);
  894. snmp_shutdown("snmptrapd");
  895. #ifdef WIN32SERVICE
  896. m_nTrapd_status = SNMPTRAPD_STOPPED;
  897. #endif
  898. snmp_disable_log();
  899. exit_code = 0;
  900. sock_cleanup:
  901. SOCK_CLEANUP;
  902. out:
  903. return exit_code;
  904. }
  905. void CSnmpClass::GetIdentity(std::string data)
  906. {
  907. //enterprises.8691.7.XXX.2对应着moxa的mib中的swTraps
  908. std::string buf = data;
  909. while(1) {
  910. std::string::size_type index = buf.find(",");
  911. if (index != std::string::npos) {
  912. /*std::string ff = buf.substr(0,index);*/
  913. std::string tmp = buf.substr(0, index);
  914. tmp = "enterprises.8691.7." + tmp;
  915. m_identity.emplace_back(tmp);
  916. buf = buf.substr(index + 1);
  917. }
  918. else {
  919. if (buf != "") {
  920. buf = "enterprises.8691.7." + buf;
  921. m_identity.emplace_back(buf);
  922. }
  923. break;
  924. }
  925. }
  926. return;
  927. }
  928. bool CSnmpClass::LoadDeviceInfo()
  929. {
  930. char* text = NULL;
  931. FILE *pf = fopen("deveice.config", "rb+");
  932. if (!pf) {
  933. printf("open deveice.config failed\n");
  934. return false;
  935. }
  936. fseek(pf, 0, SEEK_END);
  937. long lSize = ftell(pf);
  938. text = (char*)malloc(lSize);
  939. rewind(pf);
  940. fread(text, sizeof(char), lSize, pf);
  941. std::string filedata = std::string(text, lSize);
  942. free(text);
  943. fclose(pf);
  944. nlohmann::json j = nlohmann::json::parse(filedata);
  945. std::string system = j["system"];
  946. m_systemType = system;
  947. m_needTime = j["times"];
  948. m_nMtime = j["interval"];
  949. std::string receive_bind_ip = j["receive_bind_ip"];
  950. std::string send_bind_ip = j["send_bind_ip"];
  951. for (int i = 0; i < j["dst_ip"].size(); i++) {
  952. std::string dst_ip = j["dst_ip"][i];
  953. m_dst_ip.emplace_back(dst_ip);
  954. }
  955. m_receive_bind_ip = receive_bind_ip;
  956. if (send_bind_ip != "")
  957. m_send_bind_ip = send_bind_ip;
  958. else
  959. m_send_bind_ip = "0.0.0.0";
  960. memcpy(m_bindip, m_receive_bind_ip.c_str(), m_receive_bind_ip.size());
  961. m_pDdefault_port = m_bindip;
  962. m_pDefault_port = m_pDdefault_port;
  963. std::string data = j["module-identity"];
  964. GetIdentity(data);
  965. int sizeef = j["white_list"].size();
  966. for (int i = 0; i < sizeef; i++) {
  967. DEVICEINFO* point = new DEVICEINFO;
  968. std::string srcIp = j["white_list"][i]["ip"];
  969. std::string port = j["white_list"][i]["port_index"];
  970. point->srcip = srcIp;
  971. point->port_index = port;
  972. m_pWhite_list.emplace_back(point);
  973. }
  974. return true;
  975. }
  976. bool CSnmpClass::FindIntegerOrSend(std::string src, std::string comunnity, std::string moduleIdentity, std::string power)
  977. {
  978. bool re = false;
  979. std::string::size_type index = src.find("INTEGER:");
  980. if (index != std::string::npos) {
  981. int integer = std::stoi(src.substr(index + 8, src.size()));
  982. //printf("INTEGER=%d\n", integer);
  983. if (integer == 2) {
  984. OutputDebugStringA("Power Alarm");
  985. SendString(1, comunnity, src, moduleIdentity, power);
  986. re = true;
  987. }
  988. if (integer == 3) {
  989. OutputDebugStringA("Power Alarm Clear");
  990. SendString(0, comunnity, src, moduleIdentity, power);
  991. re = true;
  992. }
  993. }
  994. else {
  995. OutputDebugStringA("not find Power");
  996. }
  997. return re;
  998. }
  999. bool CSnmpClass::CheckResetPower(std::string buf, std::string comunnity)
  1000. {
  1001. bool result = false;
  1002. //std::string test = "SNMPv2-SMI::enterprises.8691.7.98 Cold Start Trap";
  1003. //buf = test;
  1004. std::string::size_type index = buf.find("Cold Start Trap");
  1005. if (index != std::string::npos) {
  1006. CSnmptrap* m_pTrap = new CSnmptrap;
  1007. std::vector <std::string>::iterator iter = m_identity.begin();
  1008. for (; iter != m_identity.end(); iter++) {
  1009. std::string::size_type index2 = buf.find(*iter);
  1010. if (index2 != std::string::npos) {
  1011. char custom[100] = "";
  1012. memcpy(custom, m_send_bind_ip.c_str(), m_send_bind_ip.size());
  1013. printf("%s,Reset sucess Alarm clear\n",(*iter).c_str());
  1014. std::vector<std::string>::iterator iter2;
  1015. for (iter2 = m_dst_ip.begin(); iter2 != m_dst_ip.end(); iter2++) {
  1016. m_pTrap->SendTrap2(0, *iter2, comunnity, "KTT Alarm", *iter2, custom, m_needTime);
  1017. BLOG_DEBUG(fmt::format("SendTrap:: ip:{},comunnity:{},KTT Alarm:{}", *iter2, comunnity, 0));
  1018. }
  1019. /*m_pTrap->SendTrap2(0, m_dst_ip, comunnity, "KTT Alarm", *iter,custom, m_needTime);*/
  1020. m_Alarm.lock();
  1021. m_nAlarmStatus = 0;
  1022. m_Alarm.unlock();
  1023. result = true;
  1024. break;
  1025. }
  1026. }
  1027. delete m_pTrap;
  1028. }
  1029. return result;
  1030. }
  1031. bool CSnmpClass::CheckPower(std::string buf, std::string comunnity)
  1032. {
  1033. bool result = false;
  1034. //std::string test = "2022-03-23 13:52:51 192.168.12.253 [192.168.12.253] (via UDP: [192.168.1.82]:49990->[192.168.1.82]:162) TRAP, SNMP v1, community public \
  1035. // SNMPv2 - SMI::enterprises.8691.7.7 Enterprise Specific Trap(2) Uptime: 0 : 03 : 57.68 \
  1036. // SNMPv2 - SMI::enterprises.8691.7.7.2.2=INTEGER: 3";
  1037. //buf = test;
  1038. std::vector <std::string>::iterator iter = m_identity.begin();
  1039. for (; iter != m_identity.end(); iter++) {
  1040. //enterprises.8691.7.XXX.2对应着moxa的mib中的swTraps
  1041. std::string power1 = (*iter) + ".2.2";
  1042. std::string power2 = (*iter) + ".2.3";
  1043. std::string::size_type index = buf.find(power1);
  1044. if (index != std::string::npos) {
  1045. OutputDebugStringA("power1");
  1046. result = FindIntegerOrSend(buf, comunnity, (*iter), power1);
  1047. break;
  1048. }
  1049. index = buf.find(power2);
  1050. if (index != std::string::npos) {
  1051. OutputDebugStringA("power2");
  1052. result = FindIntegerOrSend(buf, comunnity, (*iter), power2);
  1053. break;
  1054. }
  1055. }
  1056. return result;
  1057. }
  1058. bool CSnmpClass::CheckPort_index(std::string src, std::string port_index)
  1059. {
  1060. bool result = false;
  1061. std::string::size_type index2 = src.find("INTEGER:");
  1062. if (index2 != std::string::npos) {
  1063. int integer = std::stoi(src.substr(index2 + 8, src.size()));
  1064. char tmp[100] = "";
  1065. sprintf(tmp, "%d", integer);
  1066. std::string::size_type index = port_index.find(std::string(tmp));
  1067. if (index != std::string::npos) {
  1068. result = true;
  1069. }
  1070. }
  1071. return result;
  1072. }
  1073. bool CSnmpClass::FindNetAlarm(std::string buf, std::string comunnity, std::string moduleIdentity)
  1074. {
  1075. bool result = false;
  1076. int status = 2;
  1077. std::string::size_type link = buf.find("Link Down Trap");
  1078. if (link != std::string::npos) {
  1079. status = 1;
  1080. }
  1081. link = buf.find("Link Up Trap");
  1082. if (link != std::string::npos) {
  1083. status = 0;
  1084. }
  1085. if (status == 2)
  1086. return result;
  1087. std::vector <DEVICEINFO*>::iterator iter = m_pWhite_list.begin();
  1088. for (; iter != m_pWhite_list.end(); iter++) {
  1089. if ((*iter)->srcip == "")
  1090. continue;
  1091. std::string::size_type index = buf.find((*iter)->srcip);
  1092. //没在白名单的ip地址数据直接发送snmp
  1093. if (index == std::string::npos) {
  1094. char custom[100] = "";
  1095. memcpy(custom, m_send_bind_ip.c_str(), m_send_bind_ip.size());
  1096. CSnmptrap* m_pTrap = new CSnmptrap;
  1097. //printf("Link Alarm %d\n",status);
  1098. OutputDebugStringA(fmt::format("Link Alarm {}", status).c_str());
  1099. std::vector<std::string>::iterator iter2;
  1100. for (iter2 = m_dst_ip.begin(); iter2 != m_dst_ip.end(); iter2++) {
  1101. m_pTrap->SendTrap2(status, *iter2, comunnity, "KTT Alarm", moduleIdentity, custom, m_needTime);
  1102. BLOG_DEBUG(fmt::format("SendTrap:: ip:{},comunnity:{},KTT Alarm:{}", *iter2, comunnity, status));
  1103. }
  1104. /*m_pTrap->SendTrap2(status, m_dst_ip, comunnity, "KTT Alarm", moduleIdentity, custom, m_needTime);*/
  1105. result = true;
  1106. m_Alarm.lock();
  1107. m_nAlarmStatus = status;
  1108. m_Alarm.unlock();
  1109. delete m_pTrap;
  1110. }
  1111. else {
  1112. //white_list处理忽略port
  1113. CSnmptrap* m_pTrap = new CSnmptrap;
  1114. if (!CheckPort_index(buf, (*iter)->port_index)) {
  1115. char custom[100] = "";
  1116. memcpy(custom, m_send_bind_ip.c_str(), m_send_bind_ip.size());
  1117. m_Alarm.lock();
  1118. m_nAlarmStatus = status;
  1119. m_Alarm.unlock();
  1120. printf("white_list Link Alarm %d\n",status);
  1121. std::vector<std::string>::iterator iter2;
  1122. for (iter2 = m_dst_ip.begin(); iter2 != m_dst_ip.end(); iter2++) {
  1123. m_pTrap->SendTrap2(status, *iter2, comunnity, "KTT Alarm", moduleIdentity, custom, m_needTime);
  1124. BLOG_DEBUG(fmt::format("SendTrap:: ip:{},comunnity:{},KTT Alarm:{}", *iter2, comunnity, status));
  1125. }
  1126. /*m_pTrap->SendTrap2(status, m_dst_ip, comunnity, "KTT Alarm", moduleIdentity,custom, m_needTime);*/
  1127. result = true;
  1128. }
  1129. else {
  1130. printf("white_list port\n");
  1131. }
  1132. delete m_pTrap;
  1133. break;
  1134. }
  1135. }
  1136. return result;
  1137. }
  1138. bool CSnmpClass::CheckNetwork(std::string buf, std::string comunnity)
  1139. {
  1140. bool result = false;
  1141. //std::string test = "2022-03-23 14:04:21 192.168.12.253 [192.168.12.253] (via UDP: [192.168.1.82]:64451->[192.168.1.82]:162) TRAP, SNMP v1, community public \
  1142. // SNMPv2 - SMI::enterprises.8691.7.7 Link Down Trap(0) Uptime: 0 : 15 : 28.53 \
  1143. // IF - MIB::ifIndex.2 = INTEGER:3";
  1144. //buf = test;
  1145. std::vector <std::string>::iterator iter = m_identity.begin();
  1146. for (; iter != m_identity.end(); iter++) {
  1147. std::string::size_type identity = buf.find(*iter);
  1148. if (identity != std::string::npos) {
  1149. result = FindNetAlarm(buf,comunnity, *iter);
  1150. break;
  1151. }
  1152. }
  1153. return result;
  1154. }
  1155. int CSnmpClass::Init(std::string addr)
  1156. {
  1157. if (!LoadDeviceInfo())
  1158. return -1;
  1159. Start();
  1160. BLOG_DEBUG("application start");
  1161. m_sDeviceIp = addr;
  1162. m_pInstance = (void*)this;
  1163. char* argv2[] = { "netsnmp_ALL.exe","-Lo" };
  1164. return SnmpTrapdMain(2, argv2);
  1165. }
  1166. /*
  1167. * To stop Snmp Trap Receiver daemon
  1168. * This portion is still not working
  1169. */
  1170. void CSnmpClass::StopSnmpTrapd(void)
  1171. {
  1172. /*
  1173. * Shut Down Service
  1174. */
  1175. TermHandler(1);
  1176. /*
  1177. * Wait till trap receiver is completely stopped
  1178. */
  1179. while (m_nTrapd_status != SNMPTRAPD_STOPPED) {
  1180. Sleep(100);
  1181. }
  1182. }