Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3553 lines
81 KiB

  1. /*++
  2. Copyright (c) 1997 Microsoft Corporation
  3. Module Name:
  4. mgmtapi.c
  5. Abstract:
  6. SNMP Management API (wrapped around WinSNMP API).
  7. Environment:
  8. User Mode - Win32
  9. Revision History:
  10. 05-Feb-1997 DonRyan
  11. Rewrote functions to be wrappers around WinSNMP.
  12. --*/
  13. ///////////////////////////////////////////////////////////////////////////////
  14. // //
  15. // Include Files //
  16. // //
  17. ///////////////////////////////////////////////////////////////////////////////
  18. #include <nt.h>
  19. #include <ntrtl.h>
  20. #include <nturtl.h>
  21. #include <windows.h>
  22. #include <wsipx.h>
  23. #include <winsnmp.h>
  24. #include <mgmtapi.h>
  25. #include <oidconv.h>
  26. #include <snmputil.h>
  27. ///////////////////////////////////////////////////////////////////////////////
  28. // //
  29. // Private Definitions //
  30. // //
  31. ///////////////////////////////////////////////////////////////////////////////
  32. typedef struct _SNMP_MGR_SESSION {
  33. SOCKET UnusedSocket; // WARNING: Previous versions of the
  34. struct sockaddr UnusedDestAddr; // MGMTAPI.H header file exposed the
  35. LPSTR UnusedCommunity; // SNMP_MGR_SESSION structure which
  36. INT UnusedTimeout; // unfortunately encouraged people to
  37. INT UnusedNumRetries; // muck with it. Since this structure
  38. AsnInteger UnusedRequestId; // has now changed we must protect it.
  39. CRITICAL_SECTION SessionLock; // multiple threads may share session
  40. HSNMP_SESSION hSnmpSession; // handle to winsnmp session
  41. HSNMP_ENTITY hAgentEntity; // handle to agent entity
  42. HSNMP_ENTITY hManagerEntity; // handle to manager entity
  43. HSNMP_CONTEXT hViewContext; // handle to view context
  44. HSNMP_PDU hPdu; // handle to snmp pdu
  45. HSNMP_VBL hVbl; // handle to snmp pdu
  46. HWND hWnd; // handle to window
  47. smiINT32 nPduType; // current pdu type
  48. smiINT32 nRequestId; // current request id
  49. smiINT32 nErrorIndex; // error index from pdu
  50. smiINT32 nErrorStatus; // error status from pdu
  51. smiINT32 nLastError; // last system error
  52. SnmpVarBindList * pVarBindList; // pointer to varbind list
  53. } SNMP_MGR_SESSION, *PSNMP_MGR_SESSION;
  54. typedef struct _TRAP_LIST_ENTRY {
  55. LIST_ENTRY Link; // linked-list link
  56. AsnObjectIdentifier EnterpriseOID; // generating enterprise
  57. AsnNetworkAddress AgentAddress; // generating agent addr
  58. AsnNetworkAddress SourceAddress; // generating network addr
  59. AsnInteger nGenericTrap; // generic trap type
  60. AsnInteger nSpecificTrap; // enterprise specific type
  61. AsnOctetString Community; // generating community
  62. AsnTimeticks TimeStamp; // time stamp
  63. SnmpVarBindList VarBindList; // variable bindings
  64. } TRAP_LIST_ENTRY, * PTRAP_LIST_ENTRY;
  65. #define IPADDRLEN 4
  66. #define IPXADDRLEN 10
  67. #define MAXENTITYSTRLEN 128
  68. #define MINVARBINDLEN 2
  69. #define SYSUPTIMEINDEX 0
  70. #define SNMPTRAPOIDINDEX 1
  71. #define DEFAULT_ADDRESS_IP "127.0.0.1"
  72. #define DEFAULT_ADDRESS_IPX "00000000.000000000000"
  73. #define NOTIFICATION_CLASS "MGMTAPI Notification Class"
  74. #define WM_WSNMP_INCOMING (WM_USER + 1)
  75. #define WM_WSNMP_DONE (WM_USER + 2)
  76. #define WSNMP_FAILED(s) ((s) == SNMPAPI_FAILURE)
  77. #define WSNMP_SUCCEEDED(s) ((s) != SNMPAPI_FAILURE)
  78. #define WSNMP_ASSERT(s) ASSERT((s))
  79. ///////////////////////////////////////////////////////////////////////////////
  80. // //
  81. // Global Variables //
  82. // //
  83. ///////////////////////////////////////////////////////////////////////////////
  84. HINSTANCE g_hDll; // module handle
  85. HANDLE g_hTrapEvent = NULL; // trap event handle
  86. HANDLE g_hTrapThread = NULL; // trap thread handle
  87. HANDLE g_hTrapRegisterdEvent = NULL; // event to sync. SnmpMgrTrapListen
  88. BOOL g_fIsSnmpStarted = FALSE; // indicates winsnmp inited
  89. BOOL g_fIsSnmpListening = FALSE; // indicates trap thread on
  90. BOOL g_fIsTrapRegistered = FALSE; // indicates trap registered
  91. DWORD g_dwRequestId = 1; // unique pdu request id
  92. LIST_ENTRY g_IncomingTraps; // incoming trap queue
  93. CRITICAL_SECTION g_GlobalLock; // process resource lock
  94. SNMP_MGR_SESSION g_TrapSMS; // process trap session
  95. ///////////////////////////////////////////////////////////////////////////////
  96. // //
  97. // Private Procedures //
  98. // //
  99. ///////////////////////////////////////////////////////////////////////////////
  100. DWORD
  101. GetRequestId(
  102. )
  103. /*++
  104. Routine Description:
  105. Retrieve next global request id.
  106. Arguments:
  107. None.
  108. Return Values:
  109. Returns request id.
  110. --*/
  111. {
  112. DWORD dwRequestId;
  113. // obtain exclusive access to request id
  114. EnterCriticalSection(&g_GlobalLock);
  115. // obtain copy of request id
  116. dwRequestId = g_dwRequestId++;
  117. // obtain exclusive access to request id
  118. LeaveCriticalSection(&g_GlobalLock);
  119. return dwRequestId;
  120. }
  121. BOOL
  122. TransferVb(
  123. PSNMP_MGR_SESSION pSMS,
  124. SnmpVarBind * pVarBind
  125. )
  126. /*++
  127. Routine Description:
  128. Transfer VarBind structure to WinSNMP structure.
  129. Arguments:
  130. pSMS - pointer to mgmtapi session structure.
  131. pVarBind - pointer to varbind to transfer.
  132. Return Values:
  133. Returns true if successful.
  134. --*/
  135. {
  136. BOOL fOk = FALSE;
  137. SNMPAPI_STATUS status;
  138. smiVALUE tmpValue;
  139. smiOID tmpOID;
  140. // validate session ptr
  141. WSNMP_ASSERT(pSMS != NULL);
  142. // validate pointers
  143. if ((pVarBind != NULL) &&
  144. (pVarBind->name.ids != NULL) &&
  145. (pVarBind->name.idLength != 0)) {
  146. // re-init
  147. fOk = TRUE;
  148. // transfer oid information
  149. tmpOID.len = pVarBind->name.idLength;
  150. tmpOID.ptr = pVarBind->name.ids;
  151. // only initialize value if set
  152. if (pSMS->nPduType == SNMP_PDU_SET) {
  153. // syntax values are equivalent
  154. tmpValue.syntax = (smiINT32)(BYTE)pVarBind->value.asnType;
  155. // determine type
  156. switch (pVarBind->value.asnType) {
  157. case ASN_INTEGER32:
  158. // transfer signed int
  159. tmpValue.value.sNumber = pVarBind->value.asnValue.number;
  160. break;
  161. case ASN_UNSIGNED32:
  162. case ASN_COUNTER32:
  163. case ASN_GAUGE32:
  164. case ASN_TIMETICKS:
  165. // transfer unsigned int
  166. tmpValue.value.uNumber = pVarBind->value.asnValue.unsigned32;
  167. break;
  168. case ASN_COUNTER64:
  169. // transfer 64-bit counter
  170. tmpValue.value.hNumber.lopart =
  171. pVarBind->value.asnValue.counter64.LowPart;
  172. tmpValue.value.hNumber.hipart =
  173. pVarBind->value.asnValue.counter64.HighPart;
  174. break;
  175. case ASN_OPAQUE:
  176. case ASN_IPADDRESS:
  177. case ASN_OCTETSTRING:
  178. case ASN_BITS:
  179. // transfer octet string
  180. tmpValue.value.string.len =
  181. pVarBind->value.asnValue.string.length;
  182. tmpValue.value.string.ptr =
  183. pVarBind->value.asnValue.string.stream;
  184. break;
  185. case ASN_OBJECTIDENTIFIER:
  186. // transfer object id
  187. tmpValue.value.oid.len =
  188. pVarBind->value.asnValue.object.idLength;
  189. tmpValue.value.oid.ptr =
  190. pVarBind->value.asnValue.object.ids;
  191. break;
  192. case ASN_NULL:
  193. case SNMP_EXCEPTION_NOSUCHOBJECT:
  194. case SNMP_EXCEPTION_NOSUCHINSTANCE:
  195. case SNMP_EXCEPTION_ENDOFMIBVIEW:
  196. // initialize empty byte
  197. tmpValue.value.empty = 0;
  198. break;
  199. default:
  200. // failure
  201. fOk = FALSE;
  202. break;
  203. }
  204. }
  205. if (fOk) {
  206. // register varbind
  207. status = SnmpSetVb(
  208. pSMS->hVbl,
  209. 0, // index
  210. &tmpOID,
  211. (pSMS->nPduType == SNMP_PDU_SET)
  212. ? &tmpValue
  213. : NULL
  214. );
  215. // validate return code
  216. if (WSNMP_FAILED(status)) {
  217. SNMPDBG((
  218. SNMP_LOG_ERROR,
  219. "MGMTAPI: SnmpSetVb returned %d.\n",
  220. SnmpGetLastError(pSMS->hSnmpSession)
  221. ));
  222. // failure
  223. fOk = FALSE;
  224. }
  225. }
  226. }
  227. return fOk;
  228. }
  229. BOOL
  230. AllocateVbl(
  231. PSNMP_MGR_SESSION pSMS
  232. )
  233. /*++
  234. Routine Description:
  235. Transfer VarBindList structure to WinSNMP structure.
  236. Arguments:
  237. pSMS - pointer to mgmtapi session structure.
  238. Return Values:
  239. Returns true if successful.
  240. --*/
  241. {
  242. BOOL fOk = FALSE;
  243. SNMPAPI_STATUS status;
  244. SnmpVarBind * pVarBind;
  245. DWORD cVarBind;
  246. // validate session ptr
  247. WSNMP_ASSERT(pSMS != NULL);
  248. // validate parameters
  249. WSNMP_ASSERT(pSMS->pVarBindList != NULL);
  250. WSNMP_ASSERT(pSMS->pVarBindList->len != 0);
  251. WSNMP_ASSERT(pSMS->pVarBindList->list != NULL);
  252. // allocate resources for variable bindings list
  253. pSMS->hVbl = SnmpCreateVbl(pSMS->hSnmpSession, NULL, NULL);
  254. // validate varbind handle
  255. if (WSNMP_SUCCEEDED(pSMS->hVbl)) {
  256. // re-init
  257. fOk = TRUE;
  258. // initialize varbind pointer
  259. pVarBind = pSMS->pVarBindList->list;
  260. // initialize varbind count
  261. cVarBind = pSMS->pVarBindList->len;
  262. // process each varbind
  263. while (fOk && cVarBind--) {
  264. // transfer variable binding
  265. fOk = TransferVb(pSMS, pVarBind++);
  266. }
  267. if (!fOk) {
  268. // release varbind list handle
  269. status = SnmpFreeVbl(pSMS->hVbl);
  270. // validate return code
  271. if (WSNMP_FAILED(status)) {
  272. SNMPDBG((
  273. SNMP_LOG_ERROR,
  274. "MGMTAPI: SnmpFreeVbl returned %d.\n",
  275. SnmpGetLastError(pSMS->hSnmpSession)
  276. ));
  277. }
  278. // re-initialize
  279. pSMS->hVbl = (HSNMP_VBL)NULL;
  280. }
  281. } else {
  282. SNMPDBG((
  283. SNMP_LOG_ERROR,
  284. "MGMTAPI: SnmpCreateVbl returned %d.\n",
  285. SnmpGetLastError(pSMS->hSnmpSession)
  286. ));
  287. }
  288. return fOk;
  289. }
  290. BOOL
  291. FreeVbl(
  292. PSNMP_MGR_SESSION pSMS
  293. )
  294. /*++
  295. Routine Description:
  296. Cleanup VarBind resources from WinSNMP structure.
  297. Arguments:
  298. pSMS - pointer to mgmtapi session structure.
  299. Return Values:
  300. Returns true if successful.
  301. --*/
  302. {
  303. BOOL fOk = TRUE;
  304. SNMPAPI_STATUS status;
  305. // validate session ptr
  306. WSNMP_ASSERT(pSMS != NULL);
  307. // validate handle
  308. if (pSMS->hVbl != (HSNMP_VBL)NULL) {
  309. // actually release vbl handle
  310. status = SnmpFreeVbl(pSMS->hVbl);
  311. // validate return code
  312. if (WSNMP_FAILED(status)) {
  313. SNMPDBG((
  314. SNMP_LOG_ERROR,
  315. "MGMTAPI: SnmpFreeVbl returned %d.\n",
  316. SnmpGetLastError(pSMS->hSnmpSession)
  317. ));
  318. // failure
  319. fOk = FALSE;
  320. }
  321. // re-initialize handle
  322. pSMS->hVbl = (HSNMP_VBL)NULL;
  323. }
  324. return fOk;
  325. }
  326. BOOL
  327. AllocatePdu(
  328. PSNMP_MGR_SESSION pSMS
  329. )
  330. /*++
  331. Routine Description:
  332. Initialize session structure for sending request.
  333. Arguments:
  334. pSMS - pointer to mgmtapi session structure.
  335. Return Values:
  336. Returns true if successful.
  337. --*/
  338. {
  339. BOOL fOk = FALSE;
  340. // validate session ptr
  341. WSNMP_ASSERT(pSMS != NULL);
  342. // transfer varbinds
  343. if (AllocateVbl(pSMS)) {
  344. // grab next shared request id
  345. pSMS->nRequestId = GetRequestId();
  346. // create request pdu
  347. pSMS->hPdu = SnmpCreatePdu(
  348. pSMS->hSnmpSession,
  349. pSMS->nPduType,
  350. pSMS->nRequestId,
  351. 0, // errorStatus
  352. 0, // errorIndex
  353. pSMS->hVbl
  354. );
  355. // validate return status
  356. if (WSNMP_SUCCEEDED(pSMS->hPdu)) {
  357. // success
  358. fOk = TRUE;
  359. } else {
  360. SNMPDBG((
  361. SNMP_LOG_ERROR,
  362. "MGMTAPI: SnmpCreatePdu returned %d.\n",
  363. SnmpGetLastError(pSMS->hSnmpSession)
  364. ));
  365. // free resources
  366. FreeVbl(pSMS);
  367. }
  368. }
  369. return fOk;
  370. }
  371. BOOL
  372. FreePdu(
  373. PSNMP_MGR_SESSION pSMS
  374. )
  375. /*++
  376. Routine Description:
  377. Cleanup session structure after processing response.
  378. Arguments:
  379. pSMS - pointer to mgmtapi session structure.
  380. Return Values:
  381. Returns true if successful.
  382. --*/
  383. {
  384. BOOL fOk = TRUE;
  385. SNMPAPI_STATUS status;
  386. // validate session ptr
  387. WSNMP_ASSERT(pSMS != NULL);
  388. // validate handle
  389. if (pSMS->hPdu != (HSNMP_PDU)NULL) {
  390. // free vbl
  391. FreeVbl(pSMS);
  392. // actually release pdu handle
  393. status = SnmpFreePdu(pSMS->hPdu);
  394. // validate return code
  395. if (WSNMP_FAILED(status)) {
  396. SNMPDBG((
  397. SNMP_LOG_ERROR,
  398. "MGMTAPI: SnmpFreePdu returned %d.\n",
  399. SnmpGetLastError(pSMS->hSnmpSession)
  400. ));
  401. // failure
  402. fOk = FALSE;
  403. }
  404. // re-initialize handle
  405. pSMS->hPdu = (HSNMP_PDU)NULL;
  406. }
  407. return fOk;
  408. }
  409. BOOL
  410. CopyOid(
  411. AsnObjectIdentifier * pDstOID,
  412. smiLPOID pSrcOID
  413. )
  414. /*++
  415. Routine Description:
  416. Copies object identifier from WinSNMP format to MGMTAPI format.
  417. Arguments:
  418. pDstOID - points to MGMTAPI structure to receive OID.
  419. pSrcOID - points to WinSNMP structure to copy.
  420. Return Values:
  421. Returns true if successful.
  422. --*/
  423. {
  424. BOOL fOk = FALSE;
  425. // validate pointers
  426. WSNMP_ASSERT(pDstOID != NULL);
  427. WSNMP_ASSERT(pSrcOID != NULL);
  428. WSNMP_ASSERT(pSrcOID->len != 0);
  429. WSNMP_ASSERT(pSrcOID->ptr != NULL);
  430. // store the number of subids
  431. pDstOID->idLength = pSrcOID->len;
  432. // allocate memory for subidentifiers
  433. pDstOID->ids = SnmpUtilMemAlloc(pDstOID->idLength * sizeof(DWORD));
  434. // validate pointer
  435. if (pDstOID->ids != NULL) {
  436. // transfer memory
  437. memcpy(pDstOID->ids,
  438. pSrcOID->ptr,
  439. pDstOID->idLength * sizeof(DWORD)
  440. );
  441. // success
  442. fOk = TRUE;
  443. }
  444. // now release memory for original oid
  445. SnmpFreeDescriptor(SNMP_SYNTAX_OID, (smiLPOPAQUE)pSrcOID);
  446. return fOk;
  447. }
  448. BOOL
  449. CopyOctets(
  450. AsnOctetString * pDstOctets,
  451. smiLPOCTETS pSrcOctets
  452. )
  453. /*++
  454. Routine Description:
  455. Copies octet string from WinSNMP format to MGMTAPI format.
  456. Arguments:
  457. pDstOctets - points to MGMTAPI structure to receive octets.
  458. pSrcOctets - points to WinSNMP structure to copy.
  459. Return Values:
  460. Returns true if successful.
  461. --*/
  462. {
  463. BOOL fOk = FALSE;
  464. SNMPAPI_STATUS status;
  465. // validate pointers
  466. WSNMP_ASSERT(pDstOctets != NULL);
  467. WSNMP_ASSERT(pSrcOctets != NULL);
  468. // it is legitimate that
  469. // 1. pSrcOctets->len == 0
  470. // 2. pSrcOctets->ptr == NULL
  471. if (pSrcOctets->len == 0 || pSrcOctets->ptr == NULL)
  472. {
  473. pDstOctets->dynamic = FALSE;
  474. pDstOctets->length = 0;
  475. pDstOctets->stream = NULL;
  476. fOk = TRUE;
  477. }
  478. else
  479. {
  480. // allocate memory for octet string
  481. pDstOctets->stream = SnmpUtilMemAlloc(pSrcOctets->len);
  482. // validate pointer
  483. if (pDstOctets->stream != NULL) {
  484. // octet string allocated
  485. pDstOctets->dynamic = TRUE;
  486. // store the number of bytes
  487. pDstOctets->length = pSrcOctets->len;
  488. // transfer memory
  489. memcpy(pDstOctets->stream,
  490. pSrcOctets->ptr,
  491. pDstOctets->length
  492. );
  493. // success
  494. fOk = TRUE;
  495. }
  496. }
  497. // now release memory for original string
  498. SnmpFreeDescriptor(SNMP_SYNTAX_OCTETS, (smiLPOPAQUE)pSrcOctets);
  499. return fOk;
  500. }
  501. CopyVb(
  502. PSNMP_MGR_SESSION pSMS,
  503. DWORD iVarBind,
  504. SnmpVarBind * pVarBind
  505. )
  506. /*++
  507. Routine Description:
  508. Copy variable binding from WinSNMP structure to MGMTAPI structure.
  509. Arguments:
  510. pSMS - pointer to mgmtapi session structure.
  511. iVarBind - index of varbind structure to copy.
  512. pVarBind - pointer to varbind structure.
  513. Return Values:
  514. Returns true if successful.
  515. --*/
  516. {
  517. BOOL fOk = FALSE;
  518. SNMPAPI_STATUS status;
  519. smiOID tmpOID;
  520. smiVALUE tmpValue;
  521. // validate session ptr
  522. WSNMP_ASSERT(pSMS != NULL);
  523. WSNMP_ASSERT(pVarBind != NULL);
  524. // attempt to retrieve varbind data from winsnmp structure
  525. status = SnmpGetVb(pSMS->hVbl, iVarBind, &tmpOID, &tmpValue);
  526. // validate return code
  527. if (WSNMP_SUCCEEDED(status)) {
  528. // transfer object identifier value
  529. fOk = CopyOid(&pVarBind->name, &tmpOID);
  530. // syntax values are equivalent
  531. pVarBind->value.asnType = (BYTE)(smiINT32)tmpValue.syntax;
  532. // determine syntax
  533. switch (tmpValue.syntax) {
  534. case SNMP_SYNTAX_INT32:
  535. // transfer signed int
  536. pVarBind->value.asnValue.number = tmpValue.value.sNumber;
  537. break;
  538. case SNMP_SYNTAX_UINT32:
  539. case SNMP_SYNTAX_CNTR32:
  540. case SNMP_SYNTAX_GAUGE32:
  541. case SNMP_SYNTAX_TIMETICKS:
  542. // transfer unsigned int
  543. pVarBind->value.asnValue.unsigned32 = tmpValue.value.uNumber;
  544. break;
  545. case SNMP_SYNTAX_CNTR64:
  546. // transfer 64-bit counter
  547. pVarBind->value.asnValue.counter64.LowPart =
  548. tmpValue.value.hNumber.lopart;
  549. pVarBind->value.asnValue.counter64.HighPart =
  550. tmpValue.value.hNumber.hipart;
  551. break;
  552. case SNMP_SYNTAX_OPAQUE:
  553. case SNMP_SYNTAX_IPADDR:
  554. case SNMP_SYNTAX_OCTETS:
  555. case SNMP_SYNTAX_BITS:
  556. // transfer octet string
  557. if (!CopyOctets(&pVarBind->value.asnValue.string,
  558. &tmpValue.value.string)) {
  559. // re-initialize
  560. pVarBind->value.asnType = ASN_NULL;
  561. // failure
  562. fOk = FALSE;
  563. }
  564. break;
  565. case SNMP_SYNTAX_OID:
  566. // transfer object identifier
  567. if (!CopyOid(&pVarBind->value.asnValue.object,
  568. &tmpValue.value.oid)) {
  569. // re-initialize
  570. pVarBind->value.asnType = ASN_NULL;
  571. // failure
  572. fOk = FALSE;
  573. }
  574. break;
  575. case SNMP_SYNTAX_NULL:
  576. case SNMP_SYNTAX_NOSUCHOBJECT:
  577. case SNMP_SYNTAX_NOSUCHINSTANCE:
  578. case SNMP_SYNTAX_ENDOFMIBVIEW:
  579. break; // do nothing...
  580. default:
  581. SNMPDBG((
  582. SNMP_LOG_ERROR,
  583. "MGMTAPI: SnmpGetVb returned invalid type.\n"
  584. ));
  585. // re-initialize
  586. pVarBind->value.asnType = ASN_NULL;
  587. // failure
  588. fOk = FALSE;
  589. break;
  590. }
  591. } else {
  592. SNMPDBG((
  593. SNMP_LOG_ERROR,
  594. "MGMTAPI: SnmpGetVb returned %d.\n",
  595. SnmpGetLastError(pSMS->hSnmpSession)
  596. ));
  597. }
  598. return fOk;
  599. }
  600. BOOL
  601. CopyVbl(
  602. PSNMP_MGR_SESSION pSMS,
  603. SnmpVarBindList * pVarBindList
  604. )
  605. /*++
  606. Routine Description:
  607. Copy variable bindings from WinSNMP structure to MGMTAPI structure.
  608. Arguments:
  609. pSMS - pointer to mgmtapi session structure.
  610. pVarBindList - pointer to varbind list structure.
  611. Return Values:
  612. Returns true if successful.
  613. --*/
  614. {
  615. BOOL fOk = TRUE;
  616. // validate session ptr
  617. WSNMP_ASSERT(pSMS != NULL);
  618. WSNMP_ASSERT(pVarBindList != NULL);
  619. // initialize
  620. pVarBindList->len = 0;
  621. pVarBindList->list = NULL;
  622. // validate varbind list handle
  623. if (pSMS->hVbl != (HSNMP_VBL)NULL) {
  624. // determine number of varbinds
  625. pVarBindList->len = SnmpCountVbl(pSMS->hVbl);
  626. // validate number of varbinds
  627. if (WSNMP_SUCCEEDED(pVarBindList->len)) {
  628. // allocate memory for varbinds
  629. pVarBindList->list = SnmpUtilMemAlloc(
  630. pVarBindList->len *
  631. sizeof(SnmpVarBind)
  632. );
  633. // validate pointer
  634. if (pVarBindList->list != NULL) {
  635. DWORD cVarBind = 1;
  636. SnmpVarBind * pVarBind;
  637. // save pointer to varbinds
  638. pVarBind = pVarBindList->list;
  639. // process varbinds in the list
  640. while (fOk && (cVarBind <= pVarBindList->len)) {
  641. // copy varbind from winsnmp to mgmtapi
  642. fOk = CopyVb(pSMS, cVarBind++, pVarBind++);
  643. }
  644. } else {
  645. SNMPDBG((
  646. SNMP_LOG_ERROR,
  647. "MGMTAPI: Could not allocate VBL.\n"
  648. ));
  649. // re-initialize
  650. pVarBindList->len = 0;
  651. // failure
  652. fOk = FALSE;
  653. }
  654. } else if (pVarBindList->len != SNMPAPI_NOOP) {
  655. SNMPDBG((
  656. SNMP_LOG_ERROR,
  657. "MGMTAPI: SnmpCountVbl returned %s.\n",
  658. SnmpGetLastError(pSMS->hSnmpSession)
  659. ));
  660. // re-initialize
  661. pVarBindList->len = 0;
  662. // failure
  663. fOk = FALSE;
  664. }
  665. }
  666. if (!fOk) {
  667. // cleanup any varbinds allocated
  668. SnmpUtilVarBindListFree(pVarBindList);
  669. }
  670. return fOk;
  671. }
  672. BOOL
  673. ParseVbl(
  674. PSNMP_MGR_SESSION pSMS,
  675. PTRAP_LIST_ENTRY pTLE
  676. )
  677. /*++
  678. Routine Description:
  679. Parse varbind list for trap-related varbinds.
  680. Arguments:
  681. pSMS - pointer to MGMTAPI session structure.
  682. pTLE - pointer to trap list entry.
  683. Return Values:
  684. Returns true if successful.
  685. --*/
  686. {
  687. BOOL fOk = FALSE;
  688. SnmpVarBind * pVarBind;
  689. AsnObjectIdentifier * pOID;
  690. AsnNetworkAddress * pAgentAddress = NULL;
  691. AsnObjectIdentifier * pEnterpriseOID = NULL;
  692. // object identifiers to convert snmpv2 trap format
  693. static UINT _sysUpTime[] = { 1, 3, 6, 1, 2, 1, 1, 3 };
  694. static UINT _snmpTrapOID[] = { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1 };
  695. static UINT _snmpAddress[] = { 1, 3, 6, 1, 3, 1057, 1 };
  696. static UINT _snmpTrapEnterprise[] = { 1, 3, 6, 1, 6, 3, 1, 1, 4, 3 };
  697. static UINT _snmpTraps[] = { 1, 3, 6, 1, 6, 3, 1, 1, 5 };
  698. static AsnObjectIdentifier sysUpTime = DEFINE_OID(_sysUpTime);
  699. static AsnObjectIdentifier snmpTrapOID = DEFINE_OID(_snmpTrapOID);
  700. static AsnObjectIdentifier snmpAddress = DEFINE_OID(_snmpAddress);
  701. static AsnObjectIdentifier snmpTrapEnterprise = DEFINE_OID(_snmpTrapEnterprise);
  702. static AsnObjectIdentifier snmpTraps = DEFINE_OID(_snmpTraps);
  703. // validate pointers
  704. WSNMP_ASSERT(pSMS != NULL);
  705. WSNMP_ASSERT(pTLE != NULL);
  706. // validate vbl have minimum entries
  707. if (pTLE->VarBindList.len >= MINVARBINDLEN) {
  708. // point to sysUpTime varbind structure
  709. pVarBind = &pTLE->VarBindList.list[SYSUPTIMEINDEX];
  710. // verify variable is sysUpTime
  711. if ((pVarBind->value.asnType == ASN_TIMETICKS) &&
  712. !SnmpUtilOidNCmp(&pVarBind->name,
  713. &sysUpTime,
  714. sysUpTime.idLength)) {
  715. // transfer sysUpTime value to trap entry
  716. pTLE->TimeStamp = pVarBind->value.asnValue.ticks;
  717. } else {
  718. SNMPDBG((
  719. SNMP_LOG_ERROR,
  720. "MGMTAPI: Could not find sysUpTime.\n"
  721. ));
  722. goto cleanup; // bail...
  723. }
  724. // see if any additional varbinds present
  725. if (pTLE->VarBindList.len > MINVARBINDLEN) {
  726. // point to snmpTrapEnterprise varbind structure (maybe)
  727. pVarBind = &pTLE->VarBindList.list[pTLE->VarBindList.len - 1];
  728. // verify variable is snmpTrapEnterprise
  729. if ((pVarBind->value.asnType == ASN_OBJECTIDENTIFIER) &&
  730. !SnmpUtilOidNCmp(&pVarBind->name,
  731. &snmpTrapEnterprise,
  732. snmpTrapEnterprise.idLength)) {
  733. // transfer enterprise oid to list entry
  734. pTLE->EnterpriseOID = pVarBind->value.asnValue.object;
  735. // store enterprise oid for later
  736. pEnterpriseOID = &pTLE->EnterpriseOID;
  737. // modify type to avoid deallocation
  738. pVarBind->value.asnType = ASN_NULL;
  739. } else {
  740. SNMPDBG((
  741. SNMP_LOG_TRACE,
  742. "MGMTAPI: Could not find snmpTrapEnterprise.\n"
  743. ));
  744. }
  745. }
  746. // see if the agent address is present
  747. if (pTLE->VarBindList.len > MINVARBINDLEN+1) {
  748. // point to snmpAddress varbind structure (maybe)
  749. pVarBind = &pTLE->VarBindList.list[pTLE->VarBindList.len - 2];
  750. // verify variable is snmpAddress
  751. if ((pVarBind->value.asnType == SNMP_SYNTAX_IPADDR) &&
  752. !SnmpUtilOidNCmp(&pVarBind->name,
  753. &snmpAddress,
  754. snmpAddress.idLength)) {
  755. // transfer agent address oid to list entry
  756. pTLE->AgentAddress = pVarBind->value.asnValue.address;
  757. // store agent address for later
  758. pAgentAddress = &pTLE->AgentAddress;
  759. // modify type to avoid deallocation
  760. pVarBind->value.asnType = ASN_NULL;
  761. } else {
  762. SNMPDBG((
  763. SNMP_LOG_TRACE,
  764. "MGMTAPI: Could not find snmpAddress.\n"
  765. ));
  766. }
  767. }
  768. // point to snmpTrapOID varbind structure
  769. pVarBind = &pTLE->VarBindList.list[SNMPTRAPOIDINDEX];
  770. // verify variable is snmpTrapOID
  771. if ((pVarBind->value.asnType == ASN_OBJECTIDENTIFIER) &&
  772. !SnmpUtilOidNCmp(&pVarBind->name,
  773. &snmpTrapOID,
  774. snmpTrapOID.idLength)) {
  775. // retrieve pointer to oid
  776. pOID = &pVarBind->value.asnValue.object;
  777. // check for generic trap
  778. if (!SnmpUtilOidNCmp(pOID,
  779. &snmpTraps,
  780. snmpTraps.idLength)) {
  781. // validate size is one greater than root
  782. if (pOID->idLength == (snmpTraps.idLength + 1)) {
  783. // retrieve trap id
  784. // --ft:10/01/98 (bug #231344): WINSNMP gives up the V2 syntax => pOID->ids[snmpTraps.idLength] = [1..6]
  785. // --ft:10/01/98 (bug #231344): as MGMTAPI turns back to V1, we need to decrement this value.
  786. pTLE->nGenericTrap = (pOID->ids[snmpTraps.idLength])-1;
  787. // re-initialize
  788. pTLE->nSpecificTrap = 0;
  789. } else {
  790. SNMPDBG((
  791. SNMP_LOG_ERROR,
  792. "MGMTAPI: Invalid snmpTrapOID.\n"
  793. ));
  794. goto cleanup; // bail...
  795. }
  796. // check for specific trap
  797. } else if ((pEnterpriseOID != NULL) &&
  798. !SnmpUtilOidNCmp(pOID,
  799. pEnterpriseOID,
  800. pEnterpriseOID->idLength)) {
  801. // validate size is two greater than root
  802. if (pOID->idLength == (pEnterpriseOID->idLength + 2)) {
  803. // validate separator sub-identifier
  804. WSNMP_ASSERT(pOID->ids[pEnterpriseOID->idLength] == 0);
  805. // retrieve trap id
  806. pTLE->nSpecificTrap = pOID->ids[pEnterpriseOID->idLength + 1];
  807. // re-initialize
  808. pTLE->nGenericTrap = SNMP_GENERICTRAP_ENTERSPECIFIC;
  809. } else {
  810. SNMPDBG((
  811. SNMP_LOG_ERROR,
  812. "MGMTAPI: Invalid snmpTrapOID.\n"
  813. ));
  814. goto cleanup; // bail...
  815. }
  816. } else {
  817. SNMPDBG((
  818. SNMP_LOG_ERROR,
  819. "MGMTAPI: Could not identify snmpTrapOID.\n"
  820. ));
  821. goto cleanup; // bail...
  822. }
  823. } else {
  824. SNMPDBG((
  825. SNMP_LOG_ERROR,
  826. "MGMTAPI: Could not find snmpTrapOID.\n"
  827. ));
  828. goto cleanup; // bail...
  829. }
  830. // check for enterprise oid
  831. if (pEnterpriseOID != NULL) {
  832. // release snmpTrapEnterprise varbind structure
  833. SnmpUtilVarBindFree(&pTLE->VarBindList.list[pTLE->VarBindList.len - 1]);
  834. // decrement the list length as the last varbind was freed
  835. pTLE->VarBindList.len--;
  836. }
  837. // check for agent address
  838. if (pAgentAddress != NULL) {
  839. // release snmpAgentAddress varbind structure
  840. SnmpUtilVarBindFree(&pTLE->VarBindList.list[pTLE->VarBindList.len - 1]);
  841. // decrement the list length as the last varbind was again freed
  842. pTLE->VarBindList.len--;
  843. }
  844. // release sysUpTime varbind structure
  845. SnmpUtilVarBindFree(&pTLE->VarBindList.list[SYSUPTIMEINDEX]);
  846. // release snmpTrapOID varbind structure
  847. SnmpUtilVarBindFree(&pTLE->VarBindList.list[SNMPTRAPOIDINDEX]);
  848. // subtract released varbinds
  849. pTLE->VarBindList.len -= MINVARBINDLEN;
  850. // check if all varbinds freed
  851. if (pTLE->VarBindList.len == 0) {
  852. // release memory for list
  853. SnmpUtilMemFree(pTLE->VarBindList.list);
  854. // re-initialize
  855. pTLE->VarBindList.list = NULL;
  856. } else {
  857. // shift varbind list up two spaces
  858. memmove((LPBYTE)(pTLE->VarBindList.list),
  859. (LPBYTE)(pTLE->VarBindList.list + MINVARBINDLEN),
  860. (pTLE->VarBindList.len * sizeof(SnmpVarBind))
  861. );
  862. }
  863. } else {
  864. SNMPDBG((
  865. SNMP_LOG_ERROR,
  866. "MGMTAPI: Too few subidentifiers.\n"
  867. ));
  868. }
  869. // success
  870. return TRUE;
  871. cleanup:
  872. // failure
  873. return FALSE;
  874. }
  875. BOOL
  876. FreeTle(
  877. PTRAP_LIST_ENTRY pTLE
  878. )
  879. /*++
  880. Routine Description:
  881. Release memory used for trap entry.
  882. Arguments:
  883. pTLE - pointer to trap list entry.
  884. Return Values:
  885. Returns true if successful.
  886. --*/
  887. {
  888. // validate pointer
  889. WSNMP_ASSERT(pTLE != NULL);
  890. // release memory for enterprise oid
  891. SnmpUtilOidFree(&pTLE->EnterpriseOID);
  892. // release memory for community string
  893. SnmpUtilMemFree(pTLE->Community.stream);
  894. // release memory used in varbind list
  895. SnmpUtilVarBindListFree(&pTLE->VarBindList);
  896. // release list entry
  897. SnmpUtilMemFree(pTLE);
  898. return TRUE;
  899. }
  900. BOOL
  901. AllocateTle(
  902. PSNMP_MGR_SESSION pSMS,
  903. PTRAP_LIST_ENTRY * ppTLE,
  904. HSNMP_ENTITY hAgentEntity,
  905. HSNMP_CONTEXT hViewContext
  906. )
  907. /*++
  908. Routine Description:
  909. Allocate memory for trap entry.
  910. Arguments:
  911. pSMS - pointer to MGMTAPI session structure.
  912. ppTLE - pointer to pointer to trap list entry.
  913. hAgentEntity - handle to agent sending trap.
  914. hViewContext - handle to view context of trap.
  915. Return Values:
  916. Returns true if successful.
  917. --*/
  918. {
  919. BOOL fOk = FALSE;
  920. PTRAP_LIST_ENTRY pTLE;
  921. SNMPAPI_STATUS status;
  922. smiOCTETS CommunityStr;
  923. CHAR SourceStrAddr[MAXENTITYSTRLEN+1];
  924. struct sockaddr SourceSockAddr;
  925. // validate pointers
  926. WSNMP_ASSERT(pSMS != NULL);
  927. WSNMP_ASSERT(ppTLE != NULL);
  928. // allocate memory from list entry
  929. pTLE = SnmpUtilMemAlloc(sizeof(TRAP_LIST_ENTRY));
  930. // validate pointer
  931. if (pTLE == NULL) {
  932. SNMPDBG((
  933. SNMP_LOG_ERROR,
  934. "MGMTAPI: Could not allocate trap entry.\n"
  935. ));
  936. return FALSE; // bail...
  937. }
  938. // initialize
  939. *ppTLE = NULL;
  940. // copy varbinds to trap list entry
  941. if (!CopyVbl(pSMS, &pTLE->VarBindList)) {
  942. goto cleanup; // bail...
  943. }
  944. // parse trap-related varbinds
  945. if (!ParseVbl(pSMS, pTLE)) {
  946. goto cleanup; // bail...
  947. }
  948. // check if source address is specified
  949. if (hAgentEntity != (HSNMP_ENTITY)NULL) {
  950. // convert addr to string
  951. status = SnmpEntityToStr(
  952. hAgentEntity,
  953. sizeof(SourceStrAddr),
  954. SourceStrAddr
  955. );
  956. // validate error code
  957. if (WSNMP_SUCCEEDED(status)) {
  958. DWORD AddrLen = 0;
  959. LPBYTE AddrPtr = NULL;
  960. // convert string to socket address structure
  961. SnmpSvcAddrToSocket(SourceStrAddr, &SourceSockAddr);
  962. // validate address family
  963. if (SourceSockAddr.sa_family == AF_INET) {
  964. // assign ip values
  965. AddrLen = IPADDRLEN;
  966. AddrPtr = (LPBYTE)&(((struct sockaddr_in *)
  967. (&SourceSockAddr))->sin_addr);
  968. } else if (SourceSockAddr.sa_family == AF_IPX) {
  969. // assign ipx values
  970. AddrLen = IPXADDRLEN;
  971. AddrPtr = (LPBYTE)&(((struct sockaddr_ipx *)
  972. (&SourceSockAddr))->sa_netnum);
  973. } else {
  974. SNMPDBG((
  975. SNMP_LOG_ERROR,
  976. "MGMTAPI: Ignoring invalid address.\n"
  977. ));
  978. goto cleanup; // bail...
  979. }
  980. // allocate address to return (if specified)
  981. pTLE->SourceAddress.stream = SnmpUtilMemAlloc(AddrLen);
  982. // validate pointer
  983. if (pTLE->SourceAddress.stream != NULL) {
  984. // initialize length values
  985. pTLE->SourceAddress.length = AddrLen;
  986. pTLE->SourceAddress.dynamic = TRUE;
  987. // transfer agent address information
  988. memcpy(pTLE->SourceAddress.stream, AddrPtr, AddrLen);
  989. }
  990. } else {
  991. SNMPDBG((
  992. SNMP_LOG_ERROR,
  993. "MGMTAPI: SnmpEntityToStr returned %d.\n",
  994. SnmpGetLastError((HSNMP_SESSION)NULL)
  995. ));
  996. goto cleanup; // bail...
  997. }
  998. }
  999. // check if community specified
  1000. if (hViewContext != (HSNMP_CONTEXT)NULL) {
  1001. // convert agent entity to string
  1002. status = SnmpContextToStr(hViewContext, &CommunityStr);
  1003. // validate error code
  1004. if (WSNMP_SUCCEEDED(status)) {
  1005. // copy octet string, memory allocated in CommunityStr is also freed
  1006. CopyOctets(&pTLE->Community, &CommunityStr);
  1007. } else {
  1008. SNMPDBG((
  1009. SNMP_LOG_ERROR,
  1010. "MGMTAPI: SnmpContextToStr returned %d.\n",
  1011. SnmpGetLastError((HSNMP_SESSION)NULL)
  1012. ));
  1013. goto cleanup; // bail...
  1014. }
  1015. }
  1016. // transfer
  1017. *ppTLE = pTLE;
  1018. // success
  1019. return TRUE;
  1020. cleanup:
  1021. // release
  1022. FreeTle(pTLE);
  1023. // failure
  1024. return FALSE;
  1025. }
  1026. BOOL
  1027. NotificationCallback(
  1028. PSNMP_MGR_SESSION pSMS
  1029. )
  1030. /*++
  1031. Routine Description:
  1032. Callback for processing notification messages.
  1033. Arguments:
  1034. pSMS - pointer to mgmtapi session structure.
  1035. Return Values:
  1036. Returns true if processing finished.
  1037. --*/
  1038. {
  1039. BOOL fDone = TRUE;
  1040. SNMPAPI_STATUS status;
  1041. HSNMP_ENTITY hAgentEntity = (HSNMP_ENTITY)NULL;
  1042. HSNMP_ENTITY hManagerEntity = (HSNMP_ENTITY)NULL;
  1043. HSNMP_CONTEXT hViewContext = (HSNMP_CONTEXT)NULL;
  1044. smiINT32 nPduType;
  1045. smiINT32 nRequestId;
  1046. // validate pointer
  1047. WSNMP_ASSERT(pSMS != NULL);
  1048. // retrieve message
  1049. status = SnmpRecvMsg(
  1050. pSMS->hSnmpSession,
  1051. &hAgentEntity,
  1052. &hManagerEntity,
  1053. &hViewContext,
  1054. &pSMS->hPdu
  1055. );
  1056. // validate return code
  1057. if (WSNMP_SUCCEEDED(status)) {
  1058. // retrieve pdu data
  1059. status = SnmpGetPduData(
  1060. pSMS->hPdu,
  1061. &nPduType,
  1062. &nRequestId,
  1063. &pSMS->nErrorStatus,
  1064. &pSMS->nErrorIndex,
  1065. &pSMS->hVbl
  1066. );
  1067. // validate return code
  1068. if (WSNMP_SUCCEEDED(status)) {
  1069. // process reponse to request
  1070. if (nPduType == SNMP_PDU_RESPONSE) {
  1071. // validate context information
  1072. if ((pSMS->nRequestId == nRequestId) &&
  1073. (pSMS->hViewContext == hViewContext) &&
  1074. (pSMS->hAgentEntity == hAgentEntity) &&
  1075. (pSMS->hManagerEntity == hManagerEntity)) {
  1076. // validate returned error status
  1077. if (pSMS->nErrorStatus == SNMP_ERROR_NOERROR) {
  1078. SnmpVarBindList VarBindList;
  1079. // copy variable binding list
  1080. if (CopyVbl(pSMS, &VarBindList)) {
  1081. // release existing varbind list
  1082. SnmpUtilVarBindListFree(pSMS->pVarBindList);
  1083. // manually copy new varbind list
  1084. *pSMS->pVarBindList = VarBindList;
  1085. } else {
  1086. // modify last error status
  1087. pSMS->nLastError = SNMPAPI_ALLOC_ERROR;
  1088. }
  1089. }
  1090. } else {
  1091. SNMPDBG((
  1092. SNMP_LOG_TRACE,
  1093. "MGMTAPI: Ignoring invalid context.\n"
  1094. ));
  1095. // continue
  1096. fDone = FALSE;
  1097. }
  1098. } else if (nPduType == SNMP_PDU_TRAP) {
  1099. PTRAP_LIST_ENTRY pTLE;
  1100. // allocate trap list entry (transfers varbinds etc.)
  1101. if (AllocateTle(pSMS, &pTLE, hAgentEntity, hViewContext)) {
  1102. // obtain exclusive access
  1103. EnterCriticalSection(&g_GlobalLock);
  1104. // insert new trap into the incoming queue
  1105. InsertTailList(&g_IncomingTraps, &pTLE->Link);
  1106. // alert user
  1107. SetEvent(g_hTrapEvent);
  1108. // release exclusive access
  1109. LeaveCriticalSection(&g_GlobalLock);
  1110. }
  1111. } else {
  1112. SNMPDBG((
  1113. SNMP_LOG_ERROR,
  1114. "MGMTAPI: Ignoring invalid pdu type %d.\n",
  1115. nPduType
  1116. ));
  1117. // continue
  1118. fDone = FALSE;
  1119. }
  1120. } else {
  1121. SNMPDBG((
  1122. SNMP_LOG_ERROR,
  1123. "MGMTAPI: SnmpGetPduData returned %d.\n",
  1124. SnmpGetLastError(pSMS->hSnmpSession)
  1125. ));
  1126. // retrieve last error status from winsnmp
  1127. pSMS->nLastError = SnmpGetLastError(pSMS->hSnmpSession);
  1128. }
  1129. // release temporary entity
  1130. SnmpFreeEntity(hAgentEntity);
  1131. // release temporary entity
  1132. SnmpFreeEntity(hManagerEntity);
  1133. // release temporary context
  1134. SnmpFreeContext(hViewContext);
  1135. } else {
  1136. SNMPDBG((
  1137. SNMP_LOG_ERROR,
  1138. "MGMTAPI: SnmpRecvMsg returned %d.\n",
  1139. SnmpGetLastError(pSMS->hSnmpSession)
  1140. ));
  1141. // retrieve last error status from winsnmp
  1142. pSMS->nLastError = SnmpGetLastError(pSMS->hSnmpSession);
  1143. }
  1144. // release pdu
  1145. FreePdu(pSMS);
  1146. return fDone;
  1147. }
  1148. LRESULT
  1149. CALLBACK
  1150. NotificationWndProc(
  1151. HWND hWnd,
  1152. UINT uMsg,
  1153. WPARAM wParam,
  1154. LPARAM lParam
  1155. )
  1156. /*++
  1157. Routine Description:
  1158. Callback that processes WinSNMP notifications.
  1159. Arguments:
  1160. hWnd - window handle.
  1161. uMsg - message identifier.
  1162. wParam - first message parameter.
  1163. lParam - second message parameter.
  1164. Return Values:
  1165. The return value is the result of the message processing and
  1166. depends on the message sent.
  1167. --*/
  1168. {
  1169. // check for winsnmp notification and transport timeout
  1170. if (uMsg == WM_WSNMP_INCOMING && wParam == SNMPAPI_TL_TIMEOUT) {
  1171. PSNMP_MGR_SESSION pSMS;
  1172. // retrieve mgmtapi session pointer from window
  1173. pSMS = (PSNMP_MGR_SESSION)GetWindowLongPtr(hWnd, 0);
  1174. // validate session ptr
  1175. WSNMP_ASSERT(pSMS != NULL);
  1176. // translate winsnmp error to mgmtapi error
  1177. pSMS->nLastError = SNMP_MGMTAPI_TIMEOUT;
  1178. // post message to break out of message pump
  1179. PostMessage(pSMS->hWnd, WM_WSNMP_DONE, (WPARAM)0, (LPARAM)0);
  1180. return (LRESULT)0;
  1181. }
  1182. // check for winsnmp notification
  1183. else if (uMsg == WM_WSNMP_INCOMING) {
  1184. PSNMP_MGR_SESSION pSMS;
  1185. // retrieve mgmtapi session pointer from window
  1186. pSMS = (PSNMP_MGR_SESSION)GetWindowLongPtr(hWnd, 0);
  1187. // validate session ptr
  1188. WSNMP_ASSERT(pSMS != NULL);
  1189. // process notification message
  1190. if (NotificationCallback(pSMS)) {
  1191. // post message to break out of message pump
  1192. PostMessage(pSMS->hWnd, WM_WSNMP_DONE, (WPARAM)0, (LPARAM)0);
  1193. }
  1194. return (LRESULT)0;
  1195. } else {
  1196. // forward all other messages to windows
  1197. return DefWindowProc(hWnd, uMsg, wParam, lParam);
  1198. }
  1199. }
  1200. BOOL
  1201. RegisterNotificationClass(
  1202. )
  1203. /*++
  1204. Routine Description:
  1205. Register notification class for sessions.
  1206. Arguments:
  1207. None.
  1208. Return Values:
  1209. Returns true if successful.
  1210. --*/
  1211. {
  1212. BOOL fOk;
  1213. WNDCLASS wc;
  1214. // initialize notification window class
  1215. wc.lpfnWndProc = (WNDPROC)NotificationWndProc;
  1216. wc.lpszClassName = NOTIFICATION_CLASS;
  1217. wc.lpszMenuName = NULL;
  1218. wc.hInstance = g_hDll;
  1219. wc.hIcon = NULL;
  1220. wc.hCursor = NULL;
  1221. wc.hbrBackground = NULL;
  1222. wc.cbWndExtra = sizeof(PSNMP_MGR_SESSION);
  1223. wc.cbClsExtra = 0;
  1224. wc.style = 0;
  1225. // register class
  1226. fOk = RegisterClass(&wc);
  1227. if (!fOk) {
  1228. SNMPDBG((
  1229. SNMP_LOG_ERROR,
  1230. "MGMTAPI: RegisterClass returned %d.\n",
  1231. GetLastError()
  1232. ));
  1233. }
  1234. return fOk;
  1235. }
  1236. BOOL
  1237. UnregisterNotificationClass(
  1238. )
  1239. /*++
  1240. Routine Description:
  1241. Unregister notification class.
  1242. Arguments:
  1243. None.
  1244. Return Values:
  1245. Returns true if successful.
  1246. --*/
  1247. {
  1248. BOOL fOk;
  1249. // unergister notification window class
  1250. fOk = UnregisterClass(NOTIFICATION_CLASS, g_hDll);
  1251. if (!fOk) {
  1252. SNMPDBG((
  1253. SNMP_LOG_ERROR,
  1254. "MGMTAPI: UnregisterClass returned %d.\n",
  1255. GetLastError()
  1256. ));
  1257. }
  1258. return fOk;
  1259. }
  1260. BOOL
  1261. StartSnmpIfNecessary(
  1262. )
  1263. /*++
  1264. Routine Description:
  1265. Initialize WinSNMP DLL if necessary.
  1266. Arguments:
  1267. None.
  1268. Return Values:
  1269. Returns true if successful.
  1270. --*/
  1271. {
  1272. BOOL fOk = TRUE;
  1273. // serialize access to startup code
  1274. EnterCriticalSection(&g_GlobalLock);
  1275. // see if already started
  1276. if (g_fIsSnmpStarted != TRUE) {
  1277. SNMPAPI_STATUS status;
  1278. // initialize start params
  1279. smiUINT32 nMajorVersion = 0;
  1280. smiUINT32 nMinorVersion = 0;
  1281. smiUINT32 nLevel = 0;
  1282. smiUINT32 nTranslateMode = 0;
  1283. smiUINT32 nRetransmitMode = 0;
  1284. // start winsnmp
  1285. status = SnmpStartup(
  1286. &nMajorVersion,
  1287. &nMinorVersion,
  1288. &nLevel,
  1289. &nTranslateMode,
  1290. &nRetransmitMode
  1291. );
  1292. // validate return code
  1293. if (WSNMP_SUCCEEDED(status)) {
  1294. SNMPDBG((
  1295. SNMP_LOG_TRACE,
  1296. "MGMTAPI: SnmpStartup succeeded:\n"
  1297. "MGMTAPI:\tnMajorVersion = %d\n"
  1298. "MGMTAPI:\tnMinorVersion = %d\n"
  1299. "MGMTAPI:\tnLevel = %d\n"
  1300. "MGMTAPI:\tnTranslateMode = %d\n"
  1301. "MGMTAPI:\tnRetransmitMode = %d\n",
  1302. nMajorVersion,
  1303. nMinorVersion,
  1304. nLevel,
  1305. nTranslateMode,
  1306. nRetransmitMode
  1307. ));
  1308. // allocate global trap available event
  1309. g_hTrapEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  1310. // allocate global event to sync. SnmpMgrTrapListen
  1311. g_hTrapRegisterdEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  1312. // make sure translate mode is snmp v1
  1313. SnmpSetTranslateMode(SNMPAPI_UNTRANSLATED_V1);
  1314. // make sure retransmit mode is on
  1315. SnmpSetRetransmitMode(SNMPAPI_ON);
  1316. // register notification class
  1317. RegisterNotificationClass();
  1318. // save new status
  1319. g_fIsSnmpStarted = TRUE;
  1320. // success
  1321. fOk = TRUE;
  1322. } else {
  1323. SNMPDBG((
  1324. SNMP_LOG_ERROR,
  1325. "MGMTAPI: SnmpStartup returned %d.\n",
  1326. SnmpGetLastError((HSNMP_SESSION)NULL)
  1327. ));
  1328. // failure
  1329. fOk = FALSE;
  1330. }
  1331. }
  1332. // serialize access to startup code
  1333. LeaveCriticalSection(&g_GlobalLock);
  1334. return fOk;
  1335. }
  1336. BOOL
  1337. CleanupIfNecessary(
  1338. )
  1339. /*++
  1340. Routine Description:
  1341. Cleanup WinSNMP DLL if necessary.
  1342. Arguments:
  1343. None.
  1344. Return Values:
  1345. Returns true if successful.
  1346. --*/
  1347. {
  1348. BOOL fOk = TRUE;
  1349. // serialize access to startup code
  1350. EnterCriticalSection(&g_GlobalLock);
  1351. // see if already started
  1352. if (g_fIsSnmpStarted == TRUE) {
  1353. SNMPAPI_STATUS status;
  1354. // shutdown winsnmp
  1355. status = SnmpCleanup();
  1356. // validate return code
  1357. if (WSNMP_FAILED(status)) {
  1358. SNMPDBG((
  1359. SNMP_LOG_ERROR,
  1360. "MGMTAPI: SnmpCleanup returned %d.\n",
  1361. SnmpGetLastError((HSNMP_SESSION)NULL)
  1362. ));
  1363. // failure
  1364. fOk = FALSE;
  1365. }
  1366. // unregister notification class
  1367. UnregisterNotificationClass();
  1368. // save new status
  1369. g_fIsSnmpStarted = FALSE;
  1370. }
  1371. // check trap handle
  1372. if (g_hTrapEvent != NULL) {
  1373. // close trap handle
  1374. CloseHandle(g_hTrapEvent);
  1375. // re-initialize
  1376. g_hTrapEvent = NULL;
  1377. }
  1378. // serialize access to startup code
  1379. LeaveCriticalSection(&g_GlobalLock);
  1380. return fOk;
  1381. }
  1382. BOOL
  1383. CreateNotificationWindow(
  1384. PSNMP_MGR_SESSION pSMS
  1385. )
  1386. /*++
  1387. Routine Description:
  1388. Create notification window for session.
  1389. Arguments:
  1390. pSMS - pointer to MGMTAPI session structure.
  1391. Return Values:
  1392. Returns true if successful.
  1393. --*/
  1394. {
  1395. BOOL fOk;
  1396. // validate session ptr
  1397. WSNMP_ASSERT(pSMS != NULL);
  1398. // create notification window
  1399. pSMS->hWnd = CreateWindow(
  1400. NOTIFICATION_CLASS,
  1401. NULL, // pointer to window name
  1402. 0, // window style
  1403. 0, // horizontal position of window
  1404. 0, // vertical position of window
  1405. 0, // window width
  1406. 0, // window height
  1407. NULL, // handle to parent or owner window
  1408. NULL, // handle to menu or child-window identifier
  1409. g_hDll, // handle to application instance
  1410. NULL // pointer to window-creation data
  1411. );
  1412. // validate window handle
  1413. if (pSMS->hWnd != NULL) {
  1414. // store pointer to session in window
  1415. SetWindowLongPtr(pSMS->hWnd, 0, (LONG_PTR)pSMS);
  1416. // success
  1417. fOk = TRUE;
  1418. } else {
  1419. SNMPDBG((
  1420. SNMP_LOG_ERROR,
  1421. "MGMTAPI: CreateWindow returned %d.\n",
  1422. GetLastError()
  1423. ));
  1424. // failure
  1425. fOk = FALSE;
  1426. }
  1427. return fOk;
  1428. }
  1429. BOOL
  1430. DestroyNotificationWindow(
  1431. HWND hWnd
  1432. )
  1433. /*++
  1434. Routine Description:
  1435. Destroy notification window for session.
  1436. Arguments:
  1437. hWnd - window handle for session.
  1438. Return Values:
  1439. Returns true if successful.
  1440. --*/
  1441. {
  1442. BOOL fOk;
  1443. // destroy notification window
  1444. fOk = DestroyWindow(hWnd);
  1445. if (!fOk) {
  1446. SNMPDBG((
  1447. SNMP_LOG_ERROR,
  1448. "MGMTAPI: DestroyWindow returned %d.\n",
  1449. GetLastError()
  1450. ));
  1451. }
  1452. return fOk;
  1453. }
  1454. BOOL
  1455. CloseSession(
  1456. PSNMP_MGR_SESSION pSMS
  1457. )
  1458. /*++
  1459. Routine Description:
  1460. Close WinSNMP session associated with MGMTAPI session.
  1461. Arguments:
  1462. pSMS - pointer to MGMTAPI session structure.
  1463. Return Values:
  1464. Returns true if successful.
  1465. --*/
  1466. {
  1467. BOOL fOk = TRUE;
  1468. SNMPAPI_STATUS status;
  1469. // validate session ptr
  1470. WSNMP_ASSERT(pSMS != NULL);
  1471. // check if window opened
  1472. if (pSMS->hWnd != (HWND)NULL) {
  1473. // destroy notification window
  1474. fOk = DestroyNotificationWindow(pSMS->hWnd);
  1475. }
  1476. // check if agent entity allocated
  1477. if (pSMS->hAgentEntity != (HSNMP_ENTITY)NULL) {
  1478. // close the entity handle
  1479. status = SnmpFreeEntity(pSMS->hAgentEntity);
  1480. // validate status
  1481. if (WSNMP_FAILED(status)) {
  1482. SNMPDBG((
  1483. SNMP_LOG_ERROR,
  1484. "MGMTAPI: SnmpFreeEntity returned %d.\n",
  1485. SnmpGetLastError((HSNMP_SESSION)NULL)
  1486. ));
  1487. // failure
  1488. fOk = FALSE;
  1489. }
  1490. // re-initialize
  1491. pSMS->hAgentEntity = (HSNMP_ENTITY)NULL;
  1492. }
  1493. // check if manager entity allocated
  1494. if (pSMS->hManagerEntity != (HSNMP_ENTITY)NULL) {
  1495. // close the entity handle
  1496. status = SnmpFreeEntity(pSMS->hManagerEntity);
  1497. // validate status
  1498. if (WSNMP_FAILED(status)) {
  1499. SNMPDBG((
  1500. SNMP_LOG_ERROR,
  1501. "MGMTAPI: SnmpFreeEntity returned %d.\n",
  1502. SnmpGetLastError((HSNMP_SESSION)NULL)
  1503. ));
  1504. // failure
  1505. fOk = FALSE;
  1506. }
  1507. // re-initialize
  1508. pSMS->hManagerEntity = (HSNMP_ENTITY)NULL;
  1509. }
  1510. // check if session allocated
  1511. if (pSMS->hSnmpSession != (HSNMP_SESSION)NULL) {
  1512. // close the winsnmp session
  1513. status = SnmpClose(pSMS->hSnmpSession);
  1514. // validate status
  1515. if (WSNMP_FAILED(status)) {
  1516. SNMPDBG((
  1517. SNMP_LOG_ERROR,
  1518. "MGMTAPI: SnmpClose returned %d.\n",
  1519. SnmpGetLastError((HSNMP_SESSION)NULL)
  1520. ));
  1521. // failure
  1522. fOk = FALSE;
  1523. }
  1524. // re-initialize
  1525. pSMS->hSnmpSession = (HSNMP_SESSION)NULL;
  1526. }
  1527. return fOk;
  1528. }
  1529. //SNMPAPI_STATUS SNMPAPI_CALL
  1530. // SnmpConveyAgentAddress (SNMPAPI_STATUS mode);
  1531. BOOL
  1532. OpenSession(
  1533. PSNMP_MGR_SESSION pSMS,
  1534. LPSTR pAgentAddress,
  1535. LPSTR pAgentCommunity,
  1536. INT nTimeOut,
  1537. INT nRetries
  1538. )
  1539. /*++
  1540. Routine Description:
  1541. Open WinSNMP session and associate with MGMTAPI session.
  1542. Arguments:
  1543. pSMS - pointer to MGMTAPI session structure.
  1544. pAgentAddress - points to a null-terminated string specifying either a
  1545. dotted-decimal IP address or a host name that can be resolved to an
  1546. IP address, an IPX address (in 8.12 notation), or an ethernet address.
  1547. pAgentCommunity - points to a null-terminated string specifying the
  1548. SNMP community name used when communicating with the agent specified
  1549. in the lpAgentAddress parameter
  1550. nTimeOut - specifies the communications time-out in milliseconds.
  1551. nRetries - specifies the communications retry count.
  1552. Return Values:
  1553. Returns true if successful.
  1554. --*/
  1555. {
  1556. BOOL fOk;
  1557. struct sockaddr AgentSockAddr;
  1558. CHAR AgentStrAddr[MAXENTITYSTRLEN+1];
  1559. smiOCTETS smiCommunity;
  1560. // validate session ptr
  1561. WSNMP_ASSERT(pSMS != NULL);
  1562. // initialize notification window
  1563. if (!CreateNotificationWindow(pSMS)) {
  1564. return FALSE; // bail...
  1565. }
  1566. // open a winsnmp session which corresponds to mgmtapi session
  1567. pSMS->hSnmpSession = SnmpOpen(pSMS->hWnd, WM_WSNMP_INCOMING);
  1568. // --ft
  1569. // we need to turn this on in order to have WINSNMP to pass back not
  1570. // only the entity standing for the source Ip address but also the
  1571. // agent address as it was sent into the V1 Trap Pdu. Without it,
  1572. // SnmpMgrGetTrapEx() will return a NULL address for the pSourceAddress
  1573. // paramter. However, SnmpMgrGetTrapEx() is not documented!!!
  1574. //SnmpConveyAgentAddress(SNMPAPI_ON); // Move this into wsnmp_cf.c:SnmpStartup
  1575. // to avoid missing entry point problem when wsnmp32.dll is from other vendors
  1576. // validate session handle returned
  1577. if (WSNMP_FAILED(pSMS->hSnmpSession)) {
  1578. SNMPDBG((
  1579. SNMP_LOG_ERROR,
  1580. "MGMTAPI: SnmpOpen returned %d.\n",
  1581. SnmpGetLastError((HSNMP_SESSION)NULL)
  1582. ));
  1583. // re-initialize
  1584. pSMS->hSnmpSession = (HSNMP_SESSION)NULL;
  1585. goto cleanup; // bail...
  1586. }
  1587. // validate pointer
  1588. if (pAgentAddress != NULL) {
  1589. // use snmpapi.dll to do convert to sockets structure
  1590. if (!SnmpSvcAddrToSocket(pAgentAddress, &AgentSockAddr)) {
  1591. goto cleanup; // bail...
  1592. }
  1593. // check address family of agent
  1594. if (AgentSockAddr.sa_family == AF_INET) {
  1595. LPSTR pAgentStrAddr;
  1596. struct sockaddr_in * pAgentSockAddr;
  1597. // cast generic socket address structure to inet
  1598. pAgentSockAddr = (struct sockaddr_in *)&AgentSockAddr;
  1599. // obtain exclusive access to api
  1600. EnterCriticalSection(&g_GlobalLock);
  1601. // attempt to convert address into string
  1602. pAgentStrAddr = inet_ntoa(pAgentSockAddr->sin_addr);
  1603. // copy to stack variable
  1604. strcpy(AgentStrAddr, pAgentStrAddr);
  1605. // release exclusive access to api
  1606. LeaveCriticalSection(&g_GlobalLock);
  1607. } else if (AgentSockAddr.sa_family == AF_IPX) {
  1608. // simply copy original string
  1609. strcpy(AgentStrAddr, pAgentAddress);
  1610. } else {
  1611. SNMPDBG((
  1612. SNMP_LOG_ERROR,
  1613. "MGMTAPI: Incorrect address family.\n"
  1614. ));
  1615. goto cleanup; // bail...
  1616. }
  1617. // create remote agent entity
  1618. pSMS->hAgentEntity = SnmpStrToEntity(
  1619. pSMS->hSnmpSession,
  1620. AgentStrAddr
  1621. );
  1622. // validate agent entity returned
  1623. if (WSNMP_FAILED(pSMS->hAgentEntity)) {
  1624. SNMPDBG((
  1625. SNMP_LOG_ERROR,
  1626. "MGMTAPI: SnmpStrToEntity returned %d.\n",
  1627. SnmpGetLastError(pSMS->hSnmpSession)
  1628. ));
  1629. // re-initialize
  1630. pSMS->hAgentEntity = (HSNMP_ENTITY)NULL;
  1631. goto cleanup; // bail...
  1632. }
  1633. // attach timeout specified with agent
  1634. SnmpSetTimeout(pSMS->hAgentEntity, nTimeOut / 10);
  1635. // attach retries specified with agent
  1636. SnmpSetRetry(pSMS->hAgentEntity, nRetries);
  1637. // create local manager entity
  1638. pSMS->hManagerEntity = SnmpStrToEntity(
  1639. pSMS->hSnmpSession,
  1640. (AgentSockAddr.sa_family == AF_INET)
  1641. ? DEFAULT_ADDRESS_IP
  1642. : DEFAULT_ADDRESS_IPX
  1643. );
  1644. // validate manager entity returned
  1645. if (WSNMP_FAILED(pSMS->hManagerEntity)) {
  1646. SNMPDBG((
  1647. SNMP_LOG_ERROR,
  1648. "MGMTAPI: SnmpStrToEntity returned %d.\n",
  1649. SnmpGetLastError(pSMS->hSnmpSession)
  1650. ));
  1651. // re-initialize
  1652. pSMS->hManagerEntity = (HSNMP_ENTITY)NULL;
  1653. goto cleanup; // bail...
  1654. }
  1655. // attach timeout specified with manager
  1656. SnmpSetTimeout(pSMS->hManagerEntity, nTimeOut / 10);
  1657. // attach retries specified with manager
  1658. SnmpSetRetry(pSMS->hManagerEntity, nRetries);
  1659. }
  1660. // validate pointer
  1661. if (pAgentCommunity != NULL) {
  1662. // transfer community string
  1663. smiCommunity.ptr = (smiLPBYTE)pAgentCommunity;
  1664. smiCommunity.len = pAgentCommunity ? lstrlen(pAgentCommunity) : 0;
  1665. // obtain context from community string
  1666. pSMS->hViewContext = SnmpStrToContext(
  1667. pSMS->hSnmpSession,
  1668. &smiCommunity
  1669. );
  1670. // validate context handle
  1671. if (WSNMP_FAILED(pSMS->hViewContext)) {
  1672. SNMPDBG((
  1673. SNMP_LOG_ERROR,
  1674. "MGMTAPI: SnmpStrToContext returned %d.\n",
  1675. SnmpGetLastError(pSMS->hSnmpSession)
  1676. ));
  1677. // re-initialize
  1678. pSMS->hViewContext = (HSNMP_CONTEXT)NULL;
  1679. goto cleanup; // bail...
  1680. }
  1681. }
  1682. // success
  1683. return TRUE;
  1684. cleanup:
  1685. // cleanup resources
  1686. CloseSession(pSMS);
  1687. // failure
  1688. return FALSE;
  1689. }
  1690. BOOL
  1691. AllocateSession(
  1692. PSNMP_MGR_SESSION * ppSMS
  1693. )
  1694. /*++
  1695. Routine Description:
  1696. Allocate mgmtapi session structure.
  1697. Arguments:
  1698. ppSMS - pointer to session pointer to return.
  1699. Return Values:
  1700. Returns true if successful.
  1701. --*/
  1702. {
  1703. PSNMP_MGR_SESSION pSMS = NULL;
  1704. __try
  1705. {
  1706. // allocate new session table entry
  1707. pSMS = SnmpUtilMemAlloc(sizeof(SNMP_MGR_SESSION));
  1708. // validate pointer
  1709. if (pSMS != NULL) {
  1710. // initialize session level lock
  1711. InitializeCriticalSection(&pSMS->SessionLock);
  1712. } else {
  1713. SNMPDBG((
  1714. SNMP_LOG_ERROR,
  1715. "MGMTAPI: Could not allocate session.\n"
  1716. ));
  1717. // notify application of error
  1718. SetLastError(SNMP_MEM_ALLOC_ERROR);
  1719. }
  1720. // transfer
  1721. *ppSMS = pSMS;
  1722. }
  1723. __except(EXCEPTION_EXECUTE_HANDLER)
  1724. {
  1725. if (pSMS != NULL)
  1726. {
  1727. SnmpUtilMemFree(pSMS);
  1728. pSMS = NULL;
  1729. }
  1730. }
  1731. // return status
  1732. return (pSMS != NULL);
  1733. }
  1734. VOID
  1735. FreeSession(
  1736. PSNMP_MGR_SESSION pSMS
  1737. )
  1738. /*++
  1739. Routine Description:
  1740. Frees mgmtapi session structure.
  1741. Arguments:
  1742. pSMS - pointer to mgmtapi session structure.
  1743. Return Values:
  1744. None.
  1745. --*/
  1746. {
  1747. // is session valid?
  1748. if (pSMS != NULL) {
  1749. // destroy the session level lock
  1750. DeleteCriticalSection(&pSMS->SessionLock);
  1751. // free session object
  1752. SnmpUtilMemFree(pSMS);
  1753. }
  1754. }
  1755. BOOL
  1756. ProcessAgentResponse(
  1757. PSNMP_MGR_SESSION pSMS
  1758. )
  1759. /*++
  1760. Routine Description:
  1761. Message pump for notification window.
  1762. Arguments:
  1763. pSMS - pointer to MGMTAPI session structure.
  1764. Return Values:
  1765. Returns true if agent responded.
  1766. --*/
  1767. {
  1768. MSG msg;
  1769. BOOL fOk = FALSE;
  1770. BOOL fRet;
  1771. // validate session ptr
  1772. WSNMP_ASSERT(pSMS != NULL);
  1773. // get the next message for this session
  1774. while ((fRet = GetMessage(&msg, pSMS->hWnd, 0, 0))) {
  1775. if (fRet == -1) {
  1776. // If there is an error, GetMessage returns -1
  1777. pSMS->nLastError = SNMPAPI_OTHER_ERROR;
  1778. SNMPDBG((
  1779. SNMP_LOG_ERROR,
  1780. "MGMTAPI: ProcessAgentResponse: GetMessage returns -1.\n"
  1781. ));
  1782. break;
  1783. }
  1784. // check for private message
  1785. if (msg.message != WM_WSNMP_DONE) {
  1786. // translate message
  1787. TranslateMessage(&msg);
  1788. // dispatch message
  1789. DispatchMessage(&msg);
  1790. } else {
  1791. // success
  1792. fOk = TRUE;
  1793. break;
  1794. }
  1795. }
  1796. return fOk;
  1797. }
  1798. DWORD
  1799. WINAPI
  1800. TrapThreadProc(
  1801. LPVOID lpParam
  1802. )
  1803. /*++
  1804. Routine Description:
  1805. Trap processing procedure.
  1806. Arguments:
  1807. lpParam - unused thread parameter.
  1808. Return Values:
  1809. Returns NOERROR if successful.
  1810. --*/
  1811. {
  1812. SNMPAPI_STATUS status;
  1813. PSNMP_MGR_SESSION pSMS;
  1814. SNMPDBG((
  1815. SNMP_LOG_TRACE,
  1816. "MGMTAPI: Trap thread starting...\n"
  1817. ));
  1818. // obtain pointer
  1819. pSMS = &g_TrapSMS;
  1820. // re-initialize
  1821. pSMS->nLastError = 0;
  1822. g_fIsTrapRegistered = FALSE; // init to failure. Note that there will
  1823. // be only 1 instance of this thread
  1824. // initialize winsnmp trap session
  1825. if (OpenSession(pSMS, NULL, NULL, 0, 0))
  1826. {
  1827. // register
  1828. status = SnmpRegister(
  1829. pSMS->hSnmpSession,
  1830. (HSNMP_ENTITY)NULL, // hAgentEntity
  1831. (HSNMP_ENTITY)NULL, // hManagerEntity
  1832. (HSNMP_CONTEXT)NULL, // hViewContext
  1833. (smiLPCOID)NULL, // notification
  1834. SNMPAPI_ON
  1835. );
  1836. // validate return code
  1837. if (WSNMP_SUCCEEDED(status))
  1838. {
  1839. // signal main thread that Trap has been registered with WinSNMP
  1840. g_fIsTrapRegistered = TRUE;
  1841. SetEvent(g_hTrapRegisterdEvent);
  1842. // loop processing responses
  1843. while (ProcessAgentResponse(pSMS))
  1844. {
  1845. //
  1846. // processing done in window procedure...
  1847. //
  1848. }
  1849. }
  1850. else
  1851. {
  1852. SNMPDBG((
  1853. SNMP_LOG_ERROR,
  1854. "MGMTAPI: SnmpRegister returned %d.\n",
  1855. SnmpGetLastError(pSMS->hSnmpSession)
  1856. ));
  1857. // transfer last error to global structure
  1858. pSMS->nLastError = SnmpGetLastError(pSMS->hSnmpSession);
  1859. // signal main thread that there is an error
  1860. // in registering Trap with WinSNMP
  1861. SetEvent(g_hTrapRegisterdEvent);
  1862. }
  1863. }
  1864. else
  1865. {
  1866. // transfer last error to global structure
  1867. pSMS->nLastError = SnmpGetLastError((HSNMP_SESSION)NULL);
  1868. // signal main thread that there is an error
  1869. // in registering Trap with WinSNMP
  1870. SetEvent(g_hTrapRegisterdEvent);
  1871. }
  1872. // free session
  1873. CloseSession(pSMS);
  1874. // obtain exclusive access
  1875. EnterCriticalSection(&g_GlobalLock);
  1876. // signal successful start
  1877. g_fIsSnmpListening = FALSE;
  1878. // release exclusive access
  1879. LeaveCriticalSection(&g_GlobalLock);
  1880. SNMPDBG((
  1881. SNMP_LOG_TRACE,
  1882. "MGMTAPI: Trap thread exiting...\n"
  1883. ));
  1884. // success
  1885. return NOERROR;
  1886. }
  1887. BOOL
  1888. StartTrapsIfNecessary(
  1889. HANDLE * phTrapAvailable
  1890. )
  1891. /*++
  1892. Routine Description:
  1893. Initializes global structures for trap listening.
  1894. Arguments:
  1895. phTrapAvailable - pointer to event for signalling traps.
  1896. Return Values:
  1897. Returns true if successful (must be called only once).
  1898. --*/
  1899. {
  1900. BOOL fOk = FALSE;
  1901. DWORD dwTrapThreadId;
  1902. DWORD dwWaitTrapRegisterd;
  1903. // validate pointer
  1904. if (phTrapAvailable != NULL)
  1905. {
  1906. // obtain exclusive access
  1907. EnterCriticalSection(&g_GlobalLock);
  1908. // transfer trap event to app
  1909. *phTrapAvailable = g_hTrapEvent;
  1910. // only start listening once
  1911. if (g_fIsSnmpListening == FALSE)
  1912. {
  1913. // spawn client trap thread
  1914. g_hTrapThread = CreateThread(
  1915. NULL, // lpThreadAttributes
  1916. 0, // dwStackSize
  1917. TrapThreadProc,
  1918. NULL, // lpParameter
  1919. 0, // dwCreationFlags
  1920. &dwTrapThreadId
  1921. );
  1922. // signal successful start
  1923. g_fIsSnmpListening = TRUE;
  1924. // release exclusive access
  1925. LeaveCriticalSection(&g_GlobalLock);
  1926. // WinSE bug 6182
  1927. // wait for TrapThreadProc to signal sucessful or failure
  1928. dwWaitTrapRegisterd = WaitForSingleObject(g_hTrapRegisterdEvent, INFINITE);
  1929. if (dwWaitTrapRegisterd == WAIT_OBJECT_0)
  1930. {
  1931. if (g_fIsTrapRegistered == TRUE)
  1932. fOk = TRUE; // success
  1933. else
  1934. {
  1935. SetLastError(SNMP_MGMTAPI_TRAP_ERRORS);
  1936. SNMPDBG((
  1937. SNMP_LOG_ERROR,
  1938. "MGMTAPI: Traps are not accessible.\n"
  1939. ));
  1940. }
  1941. }
  1942. else
  1943. {
  1944. SetLastError(SNMP_MGMTAPI_TRAP_ERRORS);
  1945. SNMPDBG((
  1946. SNMP_LOG_ERROR,
  1947. "MGMTAPI: Traps are not accessible.\n"
  1948. ));
  1949. }
  1950. }
  1951. else
  1952. {
  1953. // whine about having called this before
  1954. SetLastError(SNMP_MGMTAPI_TRAP_DUPINIT);
  1955. SNMPDBG((
  1956. SNMP_LOG_ERROR,
  1957. "MGMTAPI: Duplicate registration detected.\n"
  1958. ));
  1959. // release exclusive access
  1960. LeaveCriticalSection(&g_GlobalLock);
  1961. }
  1962. }
  1963. return fOk;
  1964. }
  1965. ///////////////////////////////////////////////////////////////////////////////
  1966. // //
  1967. // Dll Entry Point //
  1968. // //
  1969. ///////////////////////////////////////////////////////////////////////////////
  1970. BOOL
  1971. DllMain(
  1972. HANDLE hDll,
  1973. DWORD dwReason,
  1974. LPVOID lpReserved
  1975. )
  1976. /*++
  1977. Routine Description:
  1978. Dll entry point.
  1979. Arguments:
  1980. hDll - module handle.
  1981. dwReason - reason DllMain is being called.
  1982. lpReserved - unused.
  1983. Return Values:
  1984. None.
  1985. --*/
  1986. {
  1987. BOOL bOk = TRUE;
  1988. __try
  1989. {
  1990. // determine reason for being called
  1991. if (dwReason == DLL_PROCESS_ATTACH)
  1992. {
  1993. // initialize startup critical section
  1994. InitializeCriticalSection(&g_GlobalLock);
  1995. // initialize list of incoming traps
  1996. InitializeListHead(&g_IncomingTraps);
  1997. // optimize thread startup
  1998. DisableThreadLibraryCalls(hDll);
  1999. // save handle
  2000. g_hDll = hDll;
  2001. }
  2002. else if (dwReason == DLL_PROCESS_DETACH)
  2003. {
  2004. // cleanup winsnmp
  2005. CleanupIfNecessary();
  2006. // nuke startup critical section
  2007. DeleteCriticalSection(&g_GlobalLock);
  2008. }
  2009. }
  2010. __except(EXCEPTION_EXECUTE_HANDLER)
  2011. {
  2012. bOk = FALSE;
  2013. }
  2014. return bOk;
  2015. }
  2016. ///////////////////////////////////////////////////////////////////////////////
  2017. // //
  2018. // Public Procedures //
  2019. // //
  2020. ///////////////////////////////////////////////////////////////////////////////
  2021. LPSNMP_MGR_SESSION
  2022. SNMP_FUNC_TYPE
  2023. SnmpMgrOpen(
  2024. LPSTR pAgentAddress,
  2025. LPSTR pAgentCommunity,
  2026. INT nTimeOut,
  2027. INT nRetries
  2028. )
  2029. /*++
  2030. Routine Description:
  2031. Initializes resources necessary for communication with specified agent.
  2032. Arguments:
  2033. pAgentAddress - points to a null-terminated string specifying either a
  2034. dotted-decimal IP address or a host name that can be resolved to an
  2035. IP address, an IPX address (in 8.12 notation), or an ethernet address.
  2036. pAgentCommunity - points to a null-terminated string specifying the
  2037. SNMP community name used when communicating with the agent specified
  2038. in the lpAgentAddress parameter
  2039. nTimeOut - specifies the communications time-out in milliseconds.
  2040. nRetries - specifies the communications retry count.
  2041. Return Values:
  2042. Returns session handle if successful.
  2043. --*/
  2044. {
  2045. PSNMP_MGR_SESSION pSMS = NULL;
  2046. // initialize winsnmp
  2047. if (StartSnmpIfNecessary()) {
  2048. // allocate mgmtapi session
  2049. if (AllocateSession(&pSMS)) {
  2050. // open session
  2051. if (!OpenSession(
  2052. pSMS,
  2053. pAgentAddress,
  2054. pAgentCommunity,
  2055. nTimeOut,
  2056. nRetries)) {
  2057. // free session
  2058. FreeSession(pSMS);
  2059. // reset
  2060. pSMS = NULL;
  2061. }
  2062. }
  2063. }
  2064. // return opaque pointer
  2065. return (LPSNMP_MGR_SESSION)pSMS;
  2066. }
  2067. BOOL
  2068. SNMP_FUNC_TYPE
  2069. SnmpMgrCtl(
  2070. LPSNMP_MGR_SESSION session, // pointer to the MGMTAPI session
  2071. DWORD dwCtlCode, // control code for the command requested
  2072. LPVOID lpvInBuffer, // buffer with the input parameters for the operation
  2073. DWORD cbInBuffer, // size of lpvInBuffer in bytes
  2074. LPVOID lpvOUTBuffer, // buffer for all the output parameters of the command
  2075. DWORD cbOUTBuffer, // size of lpvOUTBuffer
  2076. LPDWORD lpcbBytesReturned // space used from lpvOutBuffer
  2077. )
  2078. /*++
  2079. Routine Description:
  2080. Operates several control operations over the MGMTAPI session
  2081. Arguments:
  2082. pSession - pointer to the session to
  2083. Return Values:
  2084. --*/
  2085. {
  2086. BOOL bOk = FALSE;
  2087. PSNMP_MGR_SESSION pSMS = (PSNMP_MGR_SESSION)session;
  2088. switch(dwCtlCode)
  2089. {
  2090. case MGMCTL_SETAGENTPORT:
  2091. if (pSMS == NULL)
  2092. SetLastError(SNMP_MGMTAPI_INVALID_SESSION);
  2093. else if (lpvInBuffer == NULL || cbInBuffer < sizeof(UINT))
  2094. SetLastError(SNMP_MGMTAPI_INVALID_BUFFER);
  2095. else if (WSNMP_FAILED(SnmpSetPort(pSMS->hAgentEntity, *(UINT*)lpvInBuffer)))
  2096. SetLastError(SnmpGetLastError(pSMS->hSnmpSession));
  2097. else
  2098. bOk = TRUE;
  2099. break;
  2100. default:
  2101. SetLastError(SNMP_MGMTAPI_INVALID_CTL);
  2102. break;
  2103. }
  2104. return bOk;
  2105. }
  2106. BOOL
  2107. SNMP_FUNC_TYPE
  2108. SnmpMgrClose(
  2109. LPSNMP_MGR_SESSION session
  2110. )
  2111. /*++
  2112. Routine Description:
  2113. Cleanups resources needed for communication with specified agent.
  2114. Arguments:
  2115. session - points to an internal structure that specifies
  2116. which session to close.
  2117. Return Values:
  2118. Returns true if successful.
  2119. --*/
  2120. {
  2121. PSNMP_MGR_SESSION pSMS = (PSNMP_MGR_SESSION)session;
  2122. // validate pointer
  2123. if (pSMS != NULL) {
  2124. // close session
  2125. CloseSession(pSMS);
  2126. // free session
  2127. FreeSession(pSMS);
  2128. }
  2129. return TRUE;
  2130. }
  2131. SNMPAPI
  2132. SNMP_FUNC_TYPE
  2133. SnmpMgrRequest(
  2134. LPSNMP_MGR_SESSION session,
  2135. BYTE requestType,
  2136. SnmpVarBindList * pVarBindList,
  2137. AsnInteger * pErrorStatus,
  2138. AsnInteger * pErrorIndex
  2139. )
  2140. /*++
  2141. Routine Description:
  2142. Requests the specified operation be performed with the specified agent.
  2143. Arguments:
  2144. session - points to an internal structure that specifies the session
  2145. that will perform the request.
  2146. requestType - specifies the SNMP request type.
  2147. pVarBindList - points to the variable bindings list
  2148. pErrorStatus - points to a variable in which the error status result
  2149. will be returned.
  2150. pErrorIndex - points to a variable in which the error index result
  2151. will be returned.
  2152. Return Values:
  2153. Returns true if successful.
  2154. --*/
  2155. {
  2156. BOOL fOk = FALSE;
  2157. SNMPAPI_STATUS status;
  2158. PSNMP_MGR_SESSION pSMS = (PSNMP_MGR_SESSION)session;
  2159. // validate pointers
  2160. if ((pSMS != NULL) &&
  2161. (pErrorIndex != NULL) &&
  2162. (pErrorStatus != NULL) &&
  2163. (pVarBindList != NULL) &&
  2164. (pVarBindList->len != 0) &&
  2165. (pVarBindList->list != NULL)) {
  2166. // obtain exclusive access to session
  2167. EnterCriticalSection(&pSMS->SessionLock);
  2168. // initialize session structure
  2169. pSMS->pVarBindList = pVarBindList;
  2170. pSMS->nPduType = (smiINT32)(BYTE)requestType;
  2171. pSMS->hVbl = (HSNMP_VBL)NULL;
  2172. pSMS->hPdu = (HSNMP_PDU)NULL;
  2173. pSMS->nErrorStatus = 0;
  2174. pSMS->nErrorIndex = 0;
  2175. pSMS->nLastError = 0;
  2176. // allocate resources
  2177. if (AllocatePdu(pSMS)) {
  2178. // actually send
  2179. status = SnmpSendMsg(
  2180. pSMS->hSnmpSession,
  2181. pSMS->hManagerEntity,
  2182. pSMS->hAgentEntity,
  2183. pSMS->hViewContext,
  2184. pSMS->hPdu
  2185. );
  2186. // release now
  2187. FreePdu(pSMS);
  2188. // validate return code
  2189. if (WSNMP_SUCCEEDED(status)) {
  2190. // process agent response
  2191. if (ProcessAgentResponse(pSMS) &&
  2192. (pSMS->nLastError == SNMP_ERROR_NOERROR)) {
  2193. // update error status and index
  2194. *pErrorStatus = pSMS->nErrorStatus;
  2195. *pErrorIndex = pSMS->nErrorIndex;
  2196. // success
  2197. fOk = TRUE;
  2198. } else {
  2199. // set error to winsnmp error
  2200. SetLastError(pSMS->nLastError);
  2201. // failure
  2202. fOk = FALSE;
  2203. }
  2204. } else {
  2205. SNMPDBG((
  2206. SNMP_LOG_ERROR,
  2207. "MGMTAPI: SnmpSendMsg returned %d.\n",
  2208. SnmpGetLastError(pSMS->hSnmpSession)
  2209. ));
  2210. }
  2211. }
  2212. // release exclusive access to session
  2213. LeaveCriticalSection(&pSMS->SessionLock);
  2214. }
  2215. return fOk;
  2216. }
  2217. BOOL
  2218. SNMP_FUNC_TYPE
  2219. SnmpMgrStrToOid(
  2220. LPSTR pString,
  2221. AsnObjectIdentifier * pOID
  2222. )
  2223. /*++
  2224. Routine Description:
  2225. Converts a string object identifier or object descriptor representation
  2226. to an internal object identifier.
  2227. Arguments:
  2228. pString - points to a null-terminated string to be converted.
  2229. pOID - points to an object identifier variable that will receive the
  2230. converted value.
  2231. Return Values:
  2232. Returns true if successful.
  2233. --*/
  2234. {
  2235. // validate pointer to oid and string
  2236. if ((pOID != NULL) && (pString != NULL)) {
  2237. // forward to mibcc code for now
  2238. return SnmpMgrText2Oid(pString, pOID);
  2239. }
  2240. return FALSE;
  2241. }
  2242. BOOL
  2243. SNMP_FUNC_TYPE
  2244. SnmpMgrOidToStr(
  2245. AsnObjectIdentifier * pOID,
  2246. LPSTR * ppString
  2247. )
  2248. /*++
  2249. Routine Description:
  2250. Converts an internal object identifier to a string object identifier or
  2251. object descriptor representation.
  2252. Arguments:
  2253. pOID - pointers to object identifier to be converted.
  2254. ppString - points to string pointer to receive converted value.
  2255. Return Values:
  2256. Returns true if successful.
  2257. --*/
  2258. {
  2259. // validate pointer to oid and string
  2260. if ((pOID != NULL) && (ppString != NULL)) {
  2261. // forward to mibcc code for now
  2262. return SnmpMgrOid2Text(pOID, ppString);
  2263. }
  2264. return FALSE;
  2265. }
  2266. BOOL
  2267. SNMP_FUNC_TYPE
  2268. SnmpMgrTrapListen(
  2269. HANDLE * phTrapAvailable
  2270. )
  2271. /*++
  2272. Routine Description:
  2273. Registers the ability of a manager application to receive SNMP traps.
  2274. Arguments:
  2275. phTrapAvailable - points to an event handle that will be used to indicate
  2276. that there are traps available
  2277. Return Values:
  2278. Returns true if successful.
  2279. --*/
  2280. {
  2281. BOOL fOk = FALSE;
  2282. // startup winsnmp
  2283. if (StartSnmpIfNecessary()) {
  2284. // spawn only one trap client thread
  2285. if (StartTrapsIfNecessary(phTrapAvailable)) {
  2286. // success
  2287. fOk = TRUE;
  2288. }
  2289. }
  2290. return fOk;
  2291. }
  2292. BOOL
  2293. SNMP_FUNC_TYPE
  2294. SnmpMgrGetTrap(
  2295. AsnObjectIdentifier * pEnterpriseOID,
  2296. AsnNetworkAddress * pAgentAddress,
  2297. AsnInteger * pGenericTrap,
  2298. AsnInteger * pSpecificTrap,
  2299. AsnTimeticks * pTimeStamp,
  2300. SnmpVarBindList * pVarBindList
  2301. )
  2302. /*++
  2303. Routine Description:
  2304. Returns outstanding trap data that the caller has not received if
  2305. trap reception is enabled.
  2306. Arguments:
  2307. pEnterpriseOID - points to an object identifier that specifies the
  2308. enterprise that generated the SNMP trap
  2309. pAgentAddress - points to the address of the agent that generated the
  2310. SNMP trap (retrieved from PDU).
  2311. pGenericTrap - points to an indicator of the generic trap id.
  2312. pSpecificTrap - points to an indicator of the specific trap id.
  2313. pTimeStamp - points to a variable to receive the time stamp.
  2314. pVarBindList - points to the associated variable bindings.
  2315. Return Values:
  2316. Returns true if successful.
  2317. --*/
  2318. {
  2319. // forward to new api
  2320. return SnmpMgrGetTrapEx(
  2321. pEnterpriseOID,
  2322. pAgentAddress,
  2323. NULL,
  2324. pGenericTrap,
  2325. pSpecificTrap,
  2326. NULL,
  2327. pTimeStamp,
  2328. pVarBindList
  2329. );
  2330. }
  2331. BOOL
  2332. SNMP_FUNC_TYPE
  2333. SnmpMgrGetTrapEx(
  2334. AsnObjectIdentifier * pEnterpriseOID,
  2335. AsnNetworkAddress * pAgentAddress,
  2336. AsnNetworkAddress * pSourceAddress,
  2337. AsnInteger * pGenericTrap,
  2338. AsnInteger * pSpecificTrap,
  2339. AsnOctetString * pCommunity,
  2340. AsnTimeticks * pTimeStamp,
  2341. SnmpVarBindList * pVarBindList
  2342. )
  2343. /*++
  2344. Routine Description:
  2345. Returns outstanding trap data that the caller has not received if
  2346. trap reception is enabled.
  2347. Arguments:
  2348. pEnterpriseOID - points to an object identifier that specifies the
  2349. enterprise that generated the SNMP trap
  2350. pAgentAddress - points to the address of the agent that generated the
  2351. SNMP trap (retrieved from PDU).
  2352. pSourceAddress - points to the address of the agent that generated the
  2353. SNMP trap (retrieved from network transport).
  2354. pGenericTrap - points to an indicator of the generic trap id.
  2355. pSpecificTrap - points to an indicator of the specific trap id.
  2356. pCommunity - points to structure to receive community string.
  2357. pTimeStamp - points to a variable to receive the time stamp.
  2358. pVarBindList - points to the associated variable bindings.
  2359. Return Values:
  2360. Returns true if successful.
  2361. --*/
  2362. {
  2363. BOOL fOk = FALSE;
  2364. PLIST_ENTRY pLE = NULL;
  2365. PTRAP_LIST_ENTRY pTLE = NULL;
  2366. smiINT32 nLastError;
  2367. // obtain exclusive access
  2368. EnterCriticalSection(&g_GlobalLock);
  2369. // make sure list has entries
  2370. if (!IsListEmpty(&g_IncomingTraps)) {
  2371. // remove first item from list
  2372. pLE = RemoveHeadList(&g_IncomingTraps);
  2373. } else {
  2374. // check for trap thread failure
  2375. nLastError = g_TrapSMS.nLastError;
  2376. }
  2377. // release exclusive access
  2378. LeaveCriticalSection(&g_GlobalLock);
  2379. // validate pointer
  2380. if (pLE != NULL) {
  2381. // retrieve pointer to trap list entry
  2382. pTLE = CONTAINING_RECORD(pLE, TRAP_LIST_ENTRY, Link);
  2383. // validate pointer
  2384. if (pEnterpriseOID != NULL) {
  2385. // manually copy enterprise oid
  2386. *pEnterpriseOID = pTLE->EnterpriseOID;
  2387. // re-initialize list entry
  2388. pTLE->EnterpriseOID.ids = NULL;
  2389. pTLE->EnterpriseOID.idLength = 0;
  2390. }
  2391. // validate pointer
  2392. if (pCommunity != NULL) {
  2393. // transfer string info
  2394. *pCommunity = pTLE->Community;
  2395. // re-initialize list entry
  2396. pTLE->Community.length = 0;
  2397. pTLE->Community.stream = NULL;
  2398. pTLE->Community.dynamic = FALSE;
  2399. }
  2400. // validate pointer
  2401. if (pVarBindList != NULL) {
  2402. // transfer varbindlist
  2403. *pVarBindList = pTLE->VarBindList;
  2404. // re-initialize list entry
  2405. pTLE->VarBindList.len = 0;
  2406. pTLE->VarBindList.list = NULL;
  2407. }
  2408. // validate pointer
  2409. if (pAgentAddress != NULL) {
  2410. // copy structure
  2411. memcpy(pAgentAddress,
  2412. &pTLE->AgentAddress,
  2413. sizeof(pTLE->AgentAddress)
  2414. );
  2415. }
  2416. // validate pointer
  2417. if (pSourceAddress != NULL) {
  2418. // copy structure
  2419. memcpy(pSourceAddress,
  2420. &pTLE->SourceAddress,
  2421. sizeof(pTLE->SourceAddress)
  2422. );
  2423. }
  2424. // validate pointer
  2425. if (pGenericTrap != NULL) {
  2426. // transfer generic trap info
  2427. *pGenericTrap = pTLE->nGenericTrap;
  2428. }
  2429. // validate pointer
  2430. if (pSpecificTrap != NULL) {
  2431. // transfer generic trap info
  2432. *pSpecificTrap = pTLE->nSpecificTrap;
  2433. }
  2434. // validate pointer
  2435. if (pTimeStamp != NULL) {
  2436. // transfer time info
  2437. *pTimeStamp = pTLE->TimeStamp;
  2438. }
  2439. // release
  2440. FreeTle(pTLE);
  2441. // success
  2442. fOk = TRUE;
  2443. } else if (nLastError != NOERROR) {
  2444. // indicate there was an thread error
  2445. SetLastError(SNMP_MGMTAPI_TRAP_ERRORS);
  2446. } else {
  2447. // indicate there are no traps
  2448. SetLastError(SNMP_MGMTAPI_NOTRAPS);
  2449. }
  2450. return fOk;
  2451. }
  2452. VOID
  2453. serverTrapThread(
  2454. LPVOID pUnused
  2455. )
  2456. /*++
  2457. Routine Description:
  2458. Old thread procedure used by the SNMP Trap Service.
  2459. Arguments:
  2460. pUnused - unused parameter.
  2461. Return Values:
  2462. None.
  2463. --*/
  2464. {
  2465. //
  2466. // do nothing here...
  2467. //
  2468. }