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.

7851 lines
259 KiB

  1. /*++
  2. Copyright (c) 1990-2000 Microsoft Corporation
  3. Module Name:
  4. IPROUTE.C
  5. Abstract:
  6. This file contains all the route table manipulation code
  7. Author:
  8. [Environment:]
  9. kernel mode only
  10. [Notes:]
  11. optional-notes
  12. Revision History:
  13. --*/
  14. //*** iproute.c - IP routing routines.
  15. //
  16. // This file contains all the routines related to IP routing, including
  17. // routing table lookup and management routines.
  18. #include "precomp.h"
  19. #include "info.h"
  20. #include "iproute.h"
  21. #include "iprtdef.h"
  22. #include "lookup.h"
  23. #include "ipxmit.h"
  24. #include "igmp.h"
  25. #include "mdlpool.h"
  26. #include "pplasl.h"
  27. #include "tcpipbuf.h"
  28. extern uint LoopIndex;
  29. extern uint IPSecStatus;
  30. typedef struct ChangeNotifyEvent {
  31. CTEEvent cne_event;
  32. IPNotifyOutput cne_info;
  33. LIST_ENTRY *cne_queue;
  34. void *cne_lock;
  35. } ChangeNotifyEvent;
  36. void ChangeNotifyAsync(CTEEvent *Event, PVOID Context);
  37. void InvalidateRCEChain(RouteTableEntry * RTE);
  38. extern IPAddr g_ValidAddr;
  39. extern uint TotalFreeInterfaces;
  40. extern uint MaxFreeInterfaces;
  41. extern Interface *FrontFreeList;
  42. extern Interface *RearFreeList;
  43. RouteCacheEntry *RCEFreeList = NULL;
  44. extern void DampCheck(void);
  45. #if IPMCAST
  46. #define MCAST_STARTED 1
  47. extern uint g_dwMcastState;
  48. extern BOOLEAN IPMForwardAfterRcv(NetTableEntry *PrimarySrcNTE,
  49. IPHeader UNALIGNED *Header, uint HeaderLength,
  50. PVOID Data, uint BufferLength,
  51. NDIS_HANDLE LContext1, uint LContext2,
  52. uchar DestType, LinkEntry *LinkCtxt);
  53. extern BOOLEAN IPMForwardAfterRcvPkt(NetTableEntry *PrimarySrcNTE,
  54. IPHeader UNALIGNED *Header,
  55. uint HeaderLength,
  56. PVOID Data, uint BufferLength,
  57. NDIS_HANDLE LContext1, uint LContext2,
  58. uchar DestType, uint MacHeaderSize,
  59. PNDIS_BUFFER NdisBuffer,
  60. uint* pClientCnt, LinkEntry * LinkCtxt);
  61. #endif
  62. ulong DbgNumPktFwd = 0;
  63. ulong UnConnected = 0;
  64. RouteCacheEntry *UnConnectedRCE;
  65. ulong Rcefailures = 0;
  66. extern NetTableEntry **NewNetTableList; // hash table for NTEs
  67. extern uint NET_TABLE_SIZE;
  68. extern NetTableEntry *DHCPNTE; // Pointer to NTE being DHCP'd.
  69. extern NetTableEntry *LoopNTE; // Pointer to loopback NTE.
  70. extern Interface LoopInterface; // Pointer to loopback interface.
  71. extern IP_STATUS SendICMPErr(IPAddr, IPHeader UNALIGNED *, uchar, uchar, ulong);
  72. extern IP_STATUS SendICMPIPSecErr(IPAddr, IPHeader UNALIGNED *, uchar, uchar, ulong);
  73. extern uchar ParseRcvdOptions(IPOptInfo *, OptIndex *);
  74. extern void ULMTUNotify(IPAddr Dest, IPAddr Src, uchar Prot, void *Ptr,
  75. uint NewMTU);
  76. void EnableRouter();
  77. void DisableRouter();
  78. IPHeader *GetFWPacket(PNDIS_PACKET *ReturnedPacket);
  79. void FreeFWPacket(PNDIS_PACKET Packet);
  80. PNDIS_BUFFER GetFWBufferChain(uint DataLength, PNDIS_PACKET Packet,
  81. PNDIS_BUFFER *TailPointer);
  82. BOOLEAN InitForwardingPools();
  83. PVOID
  84. NTAPI
  85. FwPacketAllocate (
  86. IN POOL_TYPE PoolType,
  87. IN SIZE_T NumberOfBytes,
  88. IN ULONG Tag
  89. );
  90. VOID
  91. NTAPI
  92. FwPacketFree (
  93. IN PVOID Buffer
  94. );
  95. extern Interface *IFList;
  96. extern NDIS_HANDLE BufferPool;
  97. extern CTEBlockStruc TcpipUnloadBlock; // Structure for blocking at time of unload
  98. extern BOOLEAN fRouteTimerStopping;
  99. void IPDelNTE(NetTableEntry * NTE, CTELockHandle * RouteTableHandle);
  100. CACHE_LINE_KSPIN_LOCK RouteTableLock;
  101. LIST_ENTRY RtChangeNotifyQueue;
  102. LIST_ENTRY RtChangeNotifyQueueEx;
  103. extern HANDLE IpHeaderPool;
  104. NDIS_HANDLE IpForwardPacketPool;
  105. HANDLE IpForwardLargePool;
  106. HANDLE IpForwardSmallPool;
  107. // Buffer size calculation: Based on the MDL pool's implementation:
  108. // sizeof(POOL_HEADER) + N * ALIGN_UP(sizeof(MDL) + BufSize, PVOID) == PAGE_SIZE
  109. // N is the number of buffers per page.
  110. // Choose BufSize to minimize wasted space per page
  111. //
  112. #ifdef _WIN64
  113. // Chosen to get 5 buffers per pool page with minimal space wasted.
  114. #define BUFSIZE_LARGE_POOL 1576
  115. // Chosen to get 9 buffers per pool page with no space wasted.
  116. #define BUFSIZE_SMALL_POOL 856
  117. #else
  118. // Chosen to get 3 buffers per pool page with 8 bytes wasted.
  119. #define BUFSIZE_LARGE_POOL 1320
  120. // Chosen to get 8 buffers per pool page with no space wasted.
  121. #define BUFSIZE_SMALL_POOL 476
  122. #endif
  123. #define PACKET_POOL_SIZE 16*1024
  124. uchar ForwardBCast; // Flag indicating if we should forward bcasts.
  125. uchar ForwardPackets; // Flag indicating whether we should forward.
  126. uchar RouterConfigured; // TRUE if we were initially configured as a
  127. // router.
  128. int IPEnableRouterRefCount; // Tracks enables/disables of
  129. // routing by various services
  130. RouteSendQ *BCastRSQ;
  131. uint DefGWConfigured; // Number of default gateways configed.
  132. uint DefGWActive; // Number of def. gateways active.
  133. uint DeadGWDetect;
  134. uint PMTUDiscovery;
  135. ProtInfo *RtPI = NULL;
  136. IPMask IPMaskTable[] =
  137. {
  138. CLASSA_MASK,
  139. CLASSA_MASK,
  140. CLASSA_MASK,
  141. CLASSA_MASK,
  142. CLASSA_MASK,
  143. CLASSA_MASK,
  144. CLASSA_MASK,
  145. CLASSA_MASK,
  146. CLASSB_MASK,
  147. CLASSB_MASK,
  148. CLASSB_MASK,
  149. CLASSB_MASK,
  150. CLASSC_MASK,
  151. CLASSC_MASK,
  152. CLASSD_MASK,
  153. CLASSE_MASK};
  154. extern void TransmitFWPacket(PNDIS_PACKET, uint);
  155. uint MTUTable[] =
  156. {
  157. 65535 - sizeof(IPHeader),
  158. 32000 - sizeof(IPHeader),
  159. 17914 - sizeof(IPHeader),
  160. 8166 - sizeof(IPHeader),
  161. 4352 - sizeof(IPHeader),
  162. 2002 - sizeof(IPHeader),
  163. 1492 - sizeof(IPHeader),
  164. 1006 - sizeof(IPHeader),
  165. 508 - sizeof(IPHeader),
  166. 296 - sizeof(IPHeader),
  167. MIN_VALID_MTU - sizeof(IPHeader)
  168. };
  169. uint DisableIPSourceRouting = 1;
  170. CTETimer IPRouteTimer;
  171. // Pointer to callout routine for dial on demand.
  172. IPMapRouteToInterfacePtr DODCallout;
  173. // Packet filter control variables
  174. IPPacketFilterPtr ForwardFilterPtr = NULL;
  175. BOOLEAN ForwardFilterEnabled = FALSE;
  176. uint ForwardFilterRefCount = 0;
  177. CTEBlockStruc ForwardFilterBlock;
  178. IPRtChangePtr pIPRtChangePtr;
  179. RouteInterface DummyInterface; // Dummy interface.
  180. #if FFP_SUPPORT
  181. ULONG FFPRegFastForwardingCacheSize; // FFP Configuration Params
  182. ULONG FFPRegControlFlags; // from the System Registry
  183. ULONG FFPFlushRequired; // Whether an FFP Cache Flush is needed
  184. #endif // if FFP_SUPPORT
  185. ULONG RouteTimerTicks; // To simulate 2 timers with different granularity
  186. ULONG FlushIFTimerTicks; // To simulate 2 timers with different granularity
  187. #ifdef ALLOC_PRAGMA
  188. //
  189. // Make init code disposable.
  190. //
  191. int InitRouting(IPConfigInfo * ci);
  192. #pragma alloc_text(INIT, InitRouting)
  193. #endif // ALLOC_PRAGMA
  194. // this macro is called whenever we delete the route: takes care of routes on links
  195. #define CleanupP2MP_RTE(_RTE) { \
  196. if ((_RTE)->rte_link){ \
  197. LinkEntry *Link; \
  198. RouteTableEntry *PrvRte, *tmpRte; \
  199. Link = (_RTE)->rte_link; \
  200. PrvRte = Link->link_rte; \
  201. tmpRte = Link->link_rte; \
  202. while (tmpRte){ \
  203. if (tmpRte == (_RTE)) break; \
  204. PrvRte = tmpRte; \
  205. tmpRte = tmpRte->rte_nextlinkrte; \
  206. } \
  207. if (tmpRte) { \
  208. if (PrvRte == tmpRte) { \
  209. Link->link_rte = (_RTE)->rte_nextlinkrte; \
  210. } else { \
  211. PrvRte->rte_nextlinkrte = (_RTE)->rte_nextlinkrte; \
  212. } \
  213. } else { \
  214. ASSERT((FALSE)); \
  215. } \
  216. } \
  217. }
  218. //** GetIfConstraint - Decide whether to constrain a lookup
  219. //
  220. // Arguments: Dest - destination address
  221. // Src - source address
  222. // OptInfo - options to use for a lookup
  223. // fIpsec - IPsec reinjected packet
  224. //
  225. // Returns: IfIndex to constrain lookup to,
  226. // 0 if unconstrained
  227. // INVALID_IF_INDEX if constrained by source address only
  228. //
  229. uint
  230. GetIfConstraint(IPAddr Dest, IPAddr Src, IPOptInfo *OptInfo, BOOLEAN fIpsec)
  231. {
  232. uint ConstrainIF=0;
  233. if (CLASSD_ADDR(Dest)) {
  234. ConstrainIF = (OptInfo)? OptInfo->ioi_mcastif : 0;
  235. if (!ConstrainIF && Src && !fIpsec) {
  236. ConstrainIF = INVALID_IF_INDEX;
  237. }
  238. } else {
  239. ConstrainIF = (OptInfo)? OptInfo->ioi_ucastif : 0;
  240. }
  241. return ConstrainIF;
  242. }
  243. //** DummyFilterPtr - Dummy filter-driver callout-routine
  244. //
  245. // A dummy routine installed while a real callout is in the process of being
  246. // deregistered.
  247. //
  248. // Entry: no arguments used.
  249. //
  250. // Returns: FORWARD.
  251. //
  252. FORWARD_ACTION
  253. DummyFilterPtr(struct IPHeader UNALIGNED* PacketHeader,
  254. uchar* Packet, uint PacketLength,
  255. uint RecvInterfaceIndex, uint SendInterfaceIndex,
  256. IPAddr RecvLinkNextHop, IPAddr SendLinkNextHop)
  257. {
  258. return FORWARD;
  259. }
  260. //** SetDummyFilterPtr - filter-driver callout installation routine
  261. //
  262. // A type-safe routine to install the dummy packet-filter routine as the
  263. // packet-filter callout.
  264. //
  265. // Entry: FilterPtr - the new packet-filter callout.
  266. //
  267. // Returns: Nothing.
  268. //
  269. void
  270. SetDummyFilterPtr(IPPacketFilterPtr FilterPtr)
  271. {
  272. InterlockedExchangePointer((PVOID*)&ForwardFilterPtr, DummyFilterPtr);
  273. }
  274. //** DerefFilterPtr - dereference the filter-driver callout-routine
  275. //
  276. // Drops the reference-count on the filter-driver callout and, if necessary,
  277. // signals anyone blocked on the callout.
  278. //
  279. // Entry: Nothing.
  280. //
  281. // Returns: Nothing.
  282. //
  283. void
  284. DerefFilterPtr(void)
  285. {
  286. if (CTEInterlockedDecrementLong(&ForwardFilterRefCount) == 0)
  287. CTESignal(&ForwardFilterBlock, NDIS_STATUS_SUCCESS);
  288. }
  289. //** NotifyFilterOfDiscard - notify the filter before discarding a packet
  290. //
  291. // Called when a packet is to be dropped before the filtering step is done.
  292. // This allows the dropped packet to be logged, if necessary.
  293. //
  294. // Entry: NTE - receiving NTE
  295. // IPH - header of dropped packet
  296. // Data - payload of dropped packet
  297. // DataSize - length of bytes at 'Data'.
  298. //
  299. // Returns: TRUE if IP filter-driver returned 'FORWARD', FALSE otherwise.
  300. //
  301. BOOLEAN
  302. NotifyFilterOfDiscard(NetTableEntry* NTE, IPHeader UNALIGNED* IPH, uchar* Data,
  303. uint DataSize)
  304. {
  305. FORWARD_ACTION Action;
  306. CTEInterlockedIncrementLong(&ForwardFilterRefCount);
  307. Action = (*ForwardFilterPtr)(IPH, Data, DataSize, NTE->nte_if->if_index,
  308. INVALID_IF_INDEX, IPADDR_LOCAL, NULL_IP_ADDR);
  309. DerefFilterPtr();
  310. return Action == FORWARD;
  311. }
  312. //** DuumyXmit - Dummy interface transmit handler.
  313. //
  314. // A dummy routine that should never be called.
  315. //
  316. // Entry: Context - NULL.
  317. // Packet - Pointer to packet to be transmitted.
  318. // Dest - Destination addres of packet.
  319. // RCE - Pointer to RCE (should be NULL).
  320. //
  321. // Returns: NDIS_STATUS_PENDING
  322. //
  323. NDIS_STATUS
  324. __stdcall
  325. DummyXmit(void *Context, PNDIS_PACKET *PacketArray, uint NumberOfPackets,
  326. IPAddr Dest, RouteCacheEntry * RCE, void *LinkCtxt)
  327. {
  328. ASSERT(FALSE);
  329. return NDIS_STATUS_SUCCESS;
  330. }
  331. //* DummyXfer - Dummy interface transfer data routine.
  332. //
  333. // A dummy routine that should never be called.
  334. //
  335. // Entry: Context - NULL.
  336. // TDContext - Original packet that was sent.
  337. // Dummy - Unused
  338. // Offset - Offset in frame from which to start copying.
  339. // BytesToCopy - Number of bytes to copy.
  340. // DestPacket - Packet describing buffer to copy into.
  341. // BytesCopied - Place to return bytes copied.
  342. //
  343. // Returns: NDIS_STATUS_SUCCESS
  344. //
  345. NDIS_STATUS
  346. __stdcall
  347. DummyXfer(void *Context, NDIS_HANDLE TDContext, uint Dummy, uint Offset, uint BytesToCopy,
  348. PNDIS_PACKET DestPacket, uint * BytesCopied)
  349. {
  350. ASSERT(FALSE);
  351. return NDIS_STATUS_FAILURE;
  352. }
  353. //* DummyClose - Dummy close routine.
  354. //
  355. // A dummy routine that should never be called.
  356. //
  357. // Entry: Context - Unused.
  358. //
  359. // Returns: Nothing.
  360. //
  361. void
  362. __stdcall
  363. DummyClose(void *Context)
  364. {
  365. ASSERT(FALSE);
  366. }
  367. //* DummyInvalidate - .
  368. //
  369. // A dummy routine that should never be called.
  370. //
  371. // Entry: Context - Unused.
  372. // RCE - Pointer to RCE to be invalidated.
  373. //
  374. // Returns: Nothing.
  375. //
  376. void
  377. __stdcall
  378. DummyInvalidate(void *Context, RouteCacheEntry * RCE)
  379. {
  380. }
  381. //* DummyQInfo - Dummy query information handler.
  382. //
  383. // A dummy routine that should never be called.
  384. //
  385. // Input: IFContext - Interface context (unused).
  386. // ID - TDIObjectID for object.
  387. // Buffer - Buffer to put data into.
  388. // Size - Pointer to size of buffer. On return, filled with
  389. // bytes copied.
  390. // Context - Pointer to context block.
  391. //
  392. // Returns: Status of attempt to query information.
  393. //
  394. int
  395. __stdcall
  396. DummyQInfo(void *IFContext, TDIObjectID * ID, PNDIS_BUFFER Buffer, uint * Size,
  397. void *Context)
  398. {
  399. ASSERT(FALSE);
  400. return TDI_INVALID_REQUEST;
  401. }
  402. //* DummySetInfo - Dummy query information handler.
  403. //
  404. // A dummy routine that should never be called.
  405. //
  406. // Input: IFContext - Interface context (unused).
  407. // ID - TDIObjectID for object.
  408. // Buffer - Buffer to put data into.
  409. // Size - Pointer to size of buffer. On return, filled with
  410. // bytes copied.
  411. //
  412. // Returns: Status of attempt to query information.
  413. //
  414. int
  415. __stdcall
  416. DummySetInfo(void *IFContext, TDIObjectID * ID, void *Buffer, uint Size)
  417. {
  418. ASSERT(FALSE);
  419. return TDI_INVALID_REQUEST;
  420. }
  421. //* DummyAddAddr - Dummy add address routine.
  422. //
  423. // Called at init time when we need to initialize ourselves.
  424. //
  425. uint
  426. __stdcall
  427. DummyAddAddr(void *Context, uint Type, IPAddr Address, IPMask Mask,
  428. void *Context2)
  429. {
  430. ASSERT(FALSE);
  431. return TRUE;
  432. }
  433. //* DummyDelAddr - Dummy del address routine.
  434. //
  435. // Called at init time when we need to initialize ourselves.
  436. //
  437. uint
  438. __stdcall
  439. DummyDelAddr(void *Context, uint Type, IPAddr Address, IPMask Mask)
  440. {
  441. ASSERT(FALSE);
  442. return TRUE;
  443. }
  444. //* DummyGetEList - Dummy get entity list.
  445. //
  446. // A dummy routine that should never be called.
  447. //
  448. // Input: Context - Unused.
  449. // EntityList - Pointer to entity list to be filled in.
  450. // Count - Pointer to number of entries in the list.
  451. //
  452. // Returns Status of attempt to get the info.
  453. //
  454. int
  455. __stdcall
  456. DummyGetEList(void *Context, TDIEntityID * EntityList, uint * Count)
  457. {
  458. ASSERT(FALSE);
  459. return FALSE;
  460. }
  461. //* DummyDoNdisReq - Dummy send NDIS request
  462. //
  463. // A dummy routine that should never be called.
  464. //
  465. // Input: Context - Interface context (unused).
  466. // RT - NDIS Request Type
  467. // OID - NDIS Request OID
  468. // Info - Information Buffer.
  469. // Length - Pointer to size of buffer
  470. // Needed - Pointer to required size
  471. // Blocking - Call is Sync or Async
  472. //
  473. // Returns Status of attempt to get the info.
  474. //
  475. uint
  476. __stdcall
  477. DummyDoNdisReq(void *Context, NDIS_REQUEST_TYPE RT,
  478. NDIS_OID OID, void *Info, uint Length,
  479. uint * Needed, BOOLEAN Blocking)
  480. {
  481. ASSERT(FALSE);
  482. return FALSE;
  483. }
  484. #if FFP_SUPPORT
  485. // Max number of FFP enabled NIC drivers in the system at any time
  486. // Note that this serves to limit total cache memory for FFP support
  487. //
  488. #define MAXFFPDRVS 8
  489. //* IPGetFFPDriverList - Lists unique FFP enabled drivers in the system
  490. //
  491. // Called by functions that dispatch requests to FFP enabled drivers
  492. //
  493. // Input: arrIF - Array of IFs to reach all FFP enabled drivers
  494. //
  495. // Returns: Number of FFP enabled drivers in the system
  496. //
  497. uint
  498. IPGetFFPDriverList(Interface ** arrIF)
  499. {
  500. ULONG numIF;
  501. Interface *IF;
  502. UINT i, j;
  503. CTELockHandle Handle;
  504. CTEGetLock(&RouteTableLock.Lock, &Handle);
  505. numIF = 0;
  506. // Take a lock to protect the list of all interfaces
  507. // Go over the interface list to pick FFP drivers
  508. for (IF = IFList; IF != NULL; IF = IF->if_next) {
  509. // Does this interface's driver support FFP ?
  510. if (IF->if_ffpversion == 0)
  511. continue;
  512. // FFP supported; was driver already picked ?
  513. for (i = 0; i < numIF; i++) {
  514. if (IF->if_ffpdriver == arrIF[i]->if_ffpdriver)
  515. break;
  516. }
  517. if (i == numIF) {
  518. ASSERT(numIF < MAXFFPDRVS);
  519. arrIF[numIF++] = IF;
  520. }
  521. }
  522. // Release lock to protect the list of all interfaces
  523. CTEFreeLock(&RouteTableLock.Lock, Handle);
  524. return numIF;
  525. }
  526. //* IPReclaimRequestMem - Post processing upon request completion
  527. //
  528. // ARP calls back upon completion of async requests IP sends ARP
  529. //
  530. // Input: pRequestInfo - Points to request IP sends ARP
  531. //
  532. // Returns: None
  533. //
  534. void
  535. IPReclaimRequestMem(PVOID pRequestInfo)
  536. {
  537. // Decrement ref count, and reclaim memory if it drops to zero
  538. if (InterlockedDecrement(&((ReqInfoBlock *) pRequestInfo)->RequestRefs) == 0) {
  539. // TCPTRACE(("IPReclaimRequestMem: Freeing mem at pReqInfo = %08X\n",
  540. // pRequestInfo));
  541. CTEFreeMem(pRequestInfo);
  542. }
  543. }
  544. //* IPFlushFFPCaches - Flush all FFP Caches
  545. //
  546. // Call ARP to flush FFP caches in layer 2
  547. //
  548. // Input: None
  549. //
  550. // Returns None
  551. //
  552. void
  553. IPFlushFFPCaches(void)
  554. {
  555. Interface *arrIF[MAXFFPDRVS];
  556. ULONG numIF;
  557. CTELockHandle lhandle;
  558. ReqInfoBlock *pRequestInfo;
  559. FFPFlushParams *pFlushInfo;
  560. UINT i, j;
  561. // Check if any requests need to be posted at all
  562. if (numIF = IPGetFFPDriverList(arrIF)) {
  563. // Allocate the request block - For General and Request Specific Parts
  564. pRequestInfo = CTEAllocMemNBoot(sizeof(ReqInfoBlock) + sizeof(FFPFlushParams), '7iCT');
  565. // TCPTRACE(("IPFlushFFPCaches: Allocated mem at pReqInfo = %08X\n",
  566. // pRequestInfo));
  567. if (pRequestInfo == NULL) {
  568. return;
  569. }
  570. // Prepare the params for the request [ Part common to all requests ]
  571. pRequestInfo->RequestType = OID_FFP_FLUSH;
  572. pRequestInfo->ReqCompleteCallback = IPReclaimRequestMem;
  573. // Prepare the params for the request [ Part specific to this request ]
  574. pRequestInfo->RequestLength = sizeof(FFPFlushParams);
  575. pFlushInfo = (FFPFlushParams *) pRequestInfo->RequestInfo;
  576. pFlushInfo->NdisProtocolType = NDIS_PROTOCOL_ID_TCP_IP;
  577. // Assign Initial Ref Count to total num of requests
  578. pRequestInfo->RequestRefs = numIF;
  579. // CTEGetLock(&FFPIFsLock, &lhandle);
  580. for (i = 0; i < numIF; i++) {
  581. // Dispatch the request block to the ARP layer
  582. ASSERT(arrIF[i]->if_dondisreq != NULL);
  583. arrIF[i]->if_dondisreq(arrIF[i]->if_lcontext,
  584. NdisRequestSetInformation,
  585. OID_FFP_FLUSH,
  586. pRequestInfo->RequestInfo,
  587. pRequestInfo->RequestLength,
  588. NULL, FALSE);
  589. }
  590. // CTEFreeLock(&FFPIFsLock, lhandle);
  591. }
  592. }
  593. //* IPSetInFFPCaches - Set an entry in all FFP Caches
  594. //
  595. // Call ARP to set -ve FFP entries in caches, (or)
  596. // Invalidate existing +ve or -ve FFP cache entries
  597. //
  598. // Input: PacketHeader - Header of the IP Packet
  599. // Packet - Rest of the IP Packet
  600. // PacketLength - Length of "Packet" param
  601. // CacheEntryType - DISCARD (-ve) or INVALID
  602. //
  603. // Returns None
  604. //
  605. void
  606. IPSetInFFPCaches(struct IPHeader UNALIGNED * PacketHeader, uchar * Packet,
  607. uint PacketLength, ulong CacheEntryType)
  608. {
  609. Interface *arrIF[MAXFFPDRVS];
  610. ULONG numIF;
  611. CTELockHandle lhandle;
  612. ReqInfoBlock *pRequestInfo;
  613. FFPDataParams *pSetInInfo;
  614. UINT i, j;
  615. // Check if any requests need to be posted at all
  616. if (numIF = IPGetFFPDriverList(arrIF)) {
  617. if (PacketLength < sizeof(ULONG)) {
  618. return;
  619. }
  620. // Allocate the request block - For General and Request Specific Parts
  621. pRequestInfo = CTEAllocMemNBoot(sizeof(ReqInfoBlock) + sizeof(FFPDataParams), '8iCT');
  622. // TCPTRACE(("IPSetInFFPCaches: Allocated mem at pReqInfo = %08X\n",
  623. // pRequestInfo));
  624. if (pRequestInfo == NULL) {
  625. return;
  626. }
  627. // Prepare the params for the request [ Part common to all requests ]
  628. pRequestInfo->RequestType = OID_FFP_DATA;
  629. pRequestInfo->ReqCompleteCallback = IPReclaimRequestMem;
  630. // Prepare the params for the request [ Part specific to this request ]
  631. pRequestInfo->RequestLength = sizeof(FFPDataParams);
  632. pSetInInfo = (FFPDataParams *) pRequestInfo->RequestInfo;
  633. pSetInInfo->NdisProtocolType = NDIS_PROTOCOL_ID_TCP_IP;
  634. pSetInInfo->CacheEntryType = CacheEntryType;
  635. pSetInInfo->HeaderSize = sizeof(IPHeader) + sizeof(ULONG);
  636. RtlCopyMemory(&pSetInInfo->Header, PacketHeader, sizeof(IPHeader));
  637. pSetInInfo->IpHeader.DwordAfterHeader = *(ULONG *) Packet;
  638. // Assign Initial Ref Count to total num of requests
  639. pRequestInfo->RequestRefs = numIF;
  640. // CTEGetLock(&FFPIFsLock, &lhandle);
  641. for (i = 0; i < numIF; i++) {
  642. // Dispatch the request block to the ARP layer
  643. ASSERT(arrIF[i]->if_dondisreq != NULL);
  644. arrIF[i]->if_dondisreq(arrIF[i]->if_lcontext,
  645. NdisRequestSetInformation,
  646. OID_FFP_DATA,
  647. pRequestInfo->RequestInfo,
  648. pRequestInfo->RequestLength,
  649. NULL, FALSE);
  650. }
  651. // CTEFreeLock(&FFPIFsLock, lhandle);
  652. }
  653. }
  654. //* IPStatsFromFFPCaches - Sum Stats from all FFP Caches
  655. //
  656. // Call ARP to get FFP Stats in layer 2
  657. //
  658. // Input: Pointer to the buffer that is filled with statistics
  659. //
  660. // Returns None
  661. //
  662. void
  663. IPStatsFromFFPCaches(FFPDriverStats * pCumulStats)
  664. {
  665. Interface *arrIF[MAXFFPDRVS];
  666. ULONG numIF;
  667. CTELockHandle lhandle;
  668. UINT i, j;
  669. FFPDriverStats DriverStatsInfo =
  670. {
  671. NDIS_PROTOCOL_ID_TCP_IP,
  672. 0, 0, 0, 0, 0, 0
  673. };
  674. RtlZeroMemory(pCumulStats, sizeof(FFPDriverStats));
  675. if (numIF = IPGetFFPDriverList(arrIF)) {
  676. // CTEGetLock(&FFPIFsLock, &lhandle);
  677. for (i = 0; i < numIF; i++) {
  678. // Dispatch the request block to the ARP layer
  679. ASSERT(arrIF[i]->if_dondisreq != NULL);
  680. if (arrIF[i]->if_dondisreq(arrIF[i]->if_lcontext,
  681. NdisRequestQueryInformation,
  682. OID_FFP_DRIVER_STATS,
  683. &DriverStatsInfo,
  684. sizeof(FFPDriverStats),
  685. NULL, TRUE) == NDIS_STATUS_SUCCESS) {
  686. // Consolidate results from all drivers
  687. pCumulStats->PacketsForwarded += DriverStatsInfo.PacketsForwarded;
  688. pCumulStats->OctetsForwarded += DriverStatsInfo.OctetsForwarded;
  689. pCumulStats->PacketsDiscarded += DriverStatsInfo.PacketsDiscarded;
  690. pCumulStats->OctetsDiscarded += DriverStatsInfo.OctetsDiscarded;
  691. pCumulStats->PacketsIndicated += DriverStatsInfo.PacketsIndicated;
  692. pCumulStats->OctetsIndicated += DriverStatsInfo.OctetsIndicated;
  693. }
  694. }
  695. // CTEFreeLock(&FFPIFsLock, lhandle);
  696. }
  697. }
  698. #endif // if FFP_SUPPORT
  699. //* DerefIF - Dereference an interface.
  700. //
  701. // Called when we need to dereference an interface. We decrement the
  702. // refcount, and if it goes to zero we signal whoever is blocked on
  703. // it.
  704. //
  705. // Input: IF - Interfaec to be dereferenced.
  706. //
  707. // Returns: Nothing.
  708. //
  709. #pragma optimize("", off)
  710. void
  711. DerefIF(Interface * IF)
  712. {
  713. uint Original;
  714. Original = DEREFERENCE_IF(IF);
  715. if (Original != 1) {
  716. return;
  717. } else {
  718. // We just decremented the last reference. Wake whoever is
  719. // blocked on it.
  720. ASSERT(IF->if_block != NULL);
  721. CTESignal(IF->if_block, NDIS_STATUS_SUCCESS);
  722. }
  723. }
  724. //* LockedDerefIF - Dereference an interface w/RouteTableLock held.
  725. //
  726. // Called when we need to dereference an interface. We decrement the
  727. // refcount, and if it goes to zero we signal whoever is blocked on
  728. // it. The difference here is that we assume the caller already holds
  729. // the RouteTableLock.
  730. //
  731. // Input: IF - Interfaec to be dereferenced.
  732. //
  733. // Returns: Nothing.
  734. //
  735. void
  736. LockedDerefIF(Interface * IF)
  737. {
  738. uint Original;
  739. LOCKED_DEREFERENCE_IF(IF);
  740. if (IF->if_refcount != 0) {
  741. return;
  742. } else {
  743. // We just decremented the last reference. Wake whoever is
  744. // blocked on it.
  745. ASSERT(IF->if_block != NULL);
  746. CTESignal(IF->if_block, NDIS_STATUS_SUCCESS);
  747. }
  748. }
  749. #pragma optimize("", on)
  750. //* DerefLink - Dereference the Link
  751. //
  752. // Called when we need to dereference a link. We decrement the
  753. // refcount, and if it goes to zero we free the link
  754. //
  755. // Input: Link - Link to be dereferenced.
  756. //
  757. // Returns: Nothing.
  758. //
  759. void
  760. DerefLink(LinkEntry * Link)
  761. {
  762. uint Original;
  763. Original = CTEInterlockedExchangeAdd(&Link->link_refcount, -1);
  764. if (Original != 1) {
  765. return;
  766. } else {
  767. // We just decremented the last reference.
  768. // Call CloseLink to Notify lower layer that link is going down
  769. ASSERT(Link->link_if);
  770. ASSERT(Link->link_if->if_closelink);
  771. #if DBG
  772. // P2MP stuff still needs to be cooked
  773. {
  774. Interface *IF = Link->link_if;
  775. LinkEntry *tmpLink = IF->if_link;
  776. while (tmpLink) {
  777. if (tmpLink == Link) {
  778. // freeing the Link without cleaning up??
  779. DbgBreakPoint();
  780. }
  781. tmpLink = tmpLink->link_next;
  782. }
  783. }
  784. #endif
  785. (*(Link->link_if->if_closelink)) (Link->link_if->if_lcontext, Link->link_arpctxt);
  786. // Free the link
  787. CTEFreeMem(Link);
  788. }
  789. }
  790. //** AddrOnIF - Check to see if a given address is local to an IF
  791. //
  792. // Called when we want to see if a given address is a valid local address
  793. // for an interface. We walk down the chain of NTEs in the interface, and
  794. // see if we get a match. We assume the caller holds the RouteTableLock
  795. // at this point.
  796. //
  797. // Input: IF - Interface to check.
  798. // Addr - Address to check.
  799. //
  800. // Returns: TRUE if Addr is an address for IF, FALSE otherwise.
  801. //
  802. uint
  803. AddrOnIF(Interface * IF, IPAddr Addr)
  804. {
  805. NetTableEntry *NTE;
  806. NTE = IF->if_nte;
  807. while (NTE != NULL) {
  808. if ((NTE->nte_flags & NTE_VALID) && IP_ADDR_EQUAL(NTE->nte_addr, Addr))
  809. return TRUE;
  810. else
  811. NTE = NTE->nte_ifnext;
  812. }
  813. return FALSE;
  814. }
  815. //** BestNTEForIF - Find the 'best match' NTE on a given interface.
  816. //
  817. // This is a utility function that takes an address and tries to find the
  818. // 'best match' NTE on a given interface. This is really only useful when we
  819. // have multiple IP addresses on a single interface.
  820. //
  821. // Input: Address - Source address of packet.
  822. // IF - Pointer to IF to be searched.
  823. //
  824. // Returns: The 'best match' NTE.
  825. //
  826. NetTableEntry *
  827. BestNTEForIF(IPAddr Address, Interface * IF)
  828. {
  829. NetTableEntry *CurrentNTE, *FoundNTE;
  830. uint i;
  831. if (IF->if_nte != NULL) {
  832. // Walk the list of NTEs, looking for a valid one.
  833. CurrentNTE = IF->if_nte;
  834. FoundNTE = NULL;
  835. do {
  836. if (CurrentNTE->nte_flags & NTE_VALID) {
  837. if (IP_ADDR_EQUAL(Address & CurrentNTE->nte_mask,
  838. CurrentNTE->nte_addr & CurrentNTE->nte_mask))
  839. return CurrentNTE;
  840. else if (FoundNTE == NULL)
  841. FoundNTE = CurrentNTE;
  842. }
  843. CurrentNTE = CurrentNTE->nte_ifnext;
  844. } while (CurrentNTE != NULL);
  845. // If we found a match, or we didn't and the destination is not
  846. // a broadcast, return the result. We have special case code to
  847. // handle broadcasts, since the interface doesn't really matter there.
  848. if (FoundNTE != NULL || (!IP_ADDR_EQUAL(Address, IP_LOCAL_BCST) &&
  849. !IP_ADDR_EQUAL(Address, IP_ZERO_BCST))) {
  850. return FoundNTE;
  851. }
  852. }
  853. // An 'anonymous' I/F, or the address we're reaching is a broadcast and the
  854. // first interface has no address. Find a valid (non-loopback, non-null ip,
  855. // non-uni) address.
  856. for (i = 0; i < NET_TABLE_SIZE; i++) {
  857. NetTableEntry *NetTableList = NewNetTableList[i];
  858. for (CurrentNTE = NetTableList; CurrentNTE != NULL;
  859. CurrentNTE = CurrentNTE->nte_next) {
  860. if (CurrentNTE != LoopNTE &&
  861. (CurrentNTE->nte_flags & NTE_VALID) &&
  862. !((CurrentNTE->nte_if->if_flags & IF_FLAGS_NOIPADDR) && IP_ADDR_EQUAL(CurrentNTE->nte_addr, NULL_IP_ADDR)) &&
  863. !(CurrentNTE->nte_if->if_flags & IF_FLAGS_UNI)) {
  864. return CurrentNTE;
  865. }
  866. }
  867. }
  868. return NULL;
  869. }
  870. //** IsBCastonNTE - Determine if the specified addr. is a bcast on a spec. NTE.
  871. //
  872. // This routine is called when we need to know if an address is a broadcast
  873. // on a particular net. We check in the order we expect to be most common - a
  874. // subnet bcast, an all ones broadcast, and then an all subnets broadcast. We
  875. // return the type of broadcast it is, or return DEST_LOCAL if it's not a
  876. // broadcast.
  877. //
  878. // Entry: Address - Address in question.
  879. // NTE - NetTableEntry to check Address against.
  880. //
  881. // Returns: Type of broadcast.
  882. //
  883. uchar
  884. IsBCastOnNTE(IPAddr Address, NetTableEntry * NTE)
  885. {
  886. IPMask Mask;
  887. IPAddr BCastAddr;
  888. if (NTE->nte_flags & NTE_VALID) {
  889. BCastAddr = NTE->nte_if->if_bcast;
  890. Mask = NTE->nte_mask;
  891. if (Mask != 0xFFFFFFFF) {
  892. if (IP_ADDR_EQUAL(Address,
  893. (NTE->nte_addr & Mask) | (BCastAddr & ~Mask)))
  894. return DEST_SN_BCAST;
  895. }
  896. // See if it's an all subnet's broadcast.
  897. if (!CLASSD_ADDR(Address)) {
  898. Mask = IPNetMask(Address);
  899. if (IP_ADDR_EQUAL(Address,
  900. (NTE->nte_addr & Mask) | (BCastAddr & ~Mask)))
  901. return DEST_BCAST;
  902. } else {
  903. // This is a class D address. If we're allowed to receive
  904. // mcast datagrams, check our list.
  905. return DEST_MCAST;
  906. }
  907. // A global bcast is certainly a bcast on this net.
  908. if (IP_ADDR_EQUAL(Address, BCastAddr))
  909. return DEST_BCAST;
  910. } else if (NTE == DHCPNTE) {
  911. BCastAddr = NTE->nte_if->if_bcast;
  912. if ((IP_ADDR_EQUAL(Address, BCastAddr))) {
  913. return (DEST_BCAST);
  914. }
  915. }
  916. return DEST_LOCAL;
  917. }
  918. //** InvalidSourceAddress - Check to see if a source address is invalid.
  919. //
  920. // This function takes an input address and checks to see if it is valid
  921. // if used as the source address of an incoming packet. An address is invalid
  922. // if it's 0, -1, a Class D or Class E address, is a net or subnet broadcast,
  923. // or has a 0 subnet or host part.
  924. //
  925. // Input: Address - Address to be check.
  926. //
  927. // Returns: FALSE if the address is not invalid, TRUE if it is invalid.
  928. //
  929. uint
  930. InvalidSourceAddress(IPAddr Address)
  931. {
  932. NetTableEntry *NTE; // Pointer to current NTE.
  933. IPMask Mask; // Mask for address.
  934. uchar Result; // Result of broadcast check.
  935. IPMask SNMask;
  936. IPAddr MaskedAddress;
  937. IPAddr LocalAddress;
  938. uint i;
  939. if (!CLASSD_ADDR(Address) &&
  940. !CLASSE_ADDR(Address) &&
  941. !IP_ADDR_EQUAL(Address, IP_ZERO_BCST) &&
  942. !IP_ADDR_EQUAL(Address, IP_LOCAL_BCST)
  943. ) {
  944. // It's not an obvious broadcast. See if it's an all subnets
  945. // broadcast, or has a zero host part.
  946. Mask = IPNetMask(Address);
  947. MaskedAddress = Address & Mask;
  948. if (!IP_ADDR_EQUAL(Address, MaskedAddress) &&
  949. !IP_ADDR_EQUAL(Address, (MaskedAddress | ~Mask))
  950. ) {
  951. // It's not an all subnet's broadcast, and it has a non-zero
  952. // host/subnet part. Walk our local IP addresses, and see if it's
  953. // a subnet broadcast.
  954. for (i = 0; i < NET_TABLE_SIZE; i++) {
  955. NetTableEntry *NetTableList = NewNetTableList[i];
  956. NTE = NetTableList;
  957. while (NTE) {
  958. LocalAddress = NTE->nte_addr;
  959. if ((NTE->nte_flags & NTE_VALID) &&
  960. !IP_LOOPBACK(LocalAddress)) {
  961. Mask = NTE->nte_mask;
  962. MaskedAddress = LocalAddress & Mask;
  963. if (!IP_ADDR_EQUAL(Mask, HOST_MASK)) {
  964. if (IP_ADDR_EQUAL(Address, MaskedAddress) ||
  965. IP_ADDR_EQUAL(Address,
  966. (MaskedAddress |
  967. (NTE->nte_if->if_bcast & ~Mask)))) {
  968. return TRUE;
  969. }
  970. }
  971. }
  972. NTE = NTE->nte_next;
  973. }
  974. }
  975. return FALSE;
  976. }
  977. }
  978. return TRUE;
  979. }
  980. // 8 regions of 31 cache elements.
  981. // Each region is indexed by the 3 most significant bits of the IP address.
  982. // Each cache element within a region is indexed by a hash of the IP address.
  983. // Each cache element is composed of 29 least significant bits of the IP
  984. // address plus the three bit address type code.
  985. // (31 is prime and works well with our hash.)
  986. //
  987. #define ATC_BITS 3
  988. #define ATC_ELEMENTS_PER_REGION 31
  989. #define ATC_REGIONS (1 << ATC_BITS)
  990. #define ATC_CODE_MASK (ULONG32)(ATC_REGIONS - 1)
  991. #define ATC_ADDR_MASK (ULONG32)(~ATC_CODE_MASK)
  992. // sanity check for 3 bits of address type code
  993. C_ASSERT(ATC_REGIONS == 8);
  994. C_ASSERT(ATC_CODE_MASK == 0x00000007);
  995. C_ASSERT(ATC_ADDR_MASK == 0xFFFFFFF8);
  996. // Each cache element is 32 bits to support atomic reading and writing.
  997. //
  998. ULONG32 AddrTypeCache [ATC_REGIONS * ATC_ELEMENTS_PER_REGION];
  999. #if DBG
  1000. ULONG DbgAddrTypeCacheHits;
  1001. ULONG DbgAddrTypeCacheMisses;
  1002. ULONG DbgAddrTypeCacheCollisions;
  1003. ULONG DbgAddrTypeCacheFlushes;
  1004. ULONG DbgAddrTypeCacheNoUpdates;
  1005. ULONG DbgAddrTypeCacheLastNoUpdateDestType;
  1006. #endif
  1007. // The following type codes must fit within ATC_BITS of information.
  1008. //
  1009. typedef enum _ADDRESS_TYPE_CODE {
  1010. ATC_LOCAL = 0,
  1011. ATC_BCAST,
  1012. ATC_MCAST,
  1013. ATC_REMOTE,
  1014. ATC_REMOTE_BCAST,
  1015. ATC_REMOTE_MCAST,
  1016. ATC_SUBNET_BCAST,
  1017. ATC_NUM_CODES
  1018. } ADDRESS_TYPE_CODE;
  1019. // The following array is indexed by ADDRESS_TYPE_CODE values.
  1020. //
  1021. const char MapAddrTypeCodeToDestType [] = {
  1022. DEST_LOCAL,
  1023. DEST_BCAST,
  1024. DEST_MCAST,
  1025. DEST_REMOTE,
  1026. DEST_REM_BCAST,
  1027. DEST_REM_MCAST,
  1028. DEST_SN_BCAST,
  1029. };
  1030. //** ComputeAddrTypeCacheIndex - Given an IP address, compute the index
  1031. // of its corresponding entry in the address type cache.
  1032. //
  1033. // Input: Address - IP Address to compute the index of.
  1034. //
  1035. // Returns: Valid index into the address type cache.
  1036. //
  1037. __forceinline
  1038. ULONG
  1039. ComputeAddrTypeCacheIndex(IPAddr Address)
  1040. {
  1041. ULONG Region;
  1042. ULONG Offset;
  1043. ULONG Index;
  1044. // Locate the region of the cache where this Address would reside.
  1045. //
  1046. Region = Address >> (32 - ATC_BITS);
  1047. ASSERT(Region < ATC_REGIONS);
  1048. // Locate the offset into the region where this address would reside.
  1049. // This is done by hashing the address.
  1050. //
  1051. Offset = (1103515245 * Address + 12345) % ATC_ELEMENTS_PER_REGION;
  1052. // Compute the cache index and return it.
  1053. //
  1054. Index = (Region * ATC_ELEMENTS_PER_REGION) + Offset;
  1055. ASSERT(Index < (sizeof(AddrTypeCache) / sizeof(AddrTypeCache[0])));
  1056. return Index;
  1057. }
  1058. //** AddrTypeCacheFlush - Flush the cache entry associated with an address.
  1059. //
  1060. // Input: Address - Address to remove from the cache.
  1061. //
  1062. // Returns: nothing.
  1063. //
  1064. void
  1065. AddrTypeCacheFlush(IPAddr Address)
  1066. {
  1067. ULONG CacheIndex;
  1068. CacheIndex = ComputeAddrTypeCacheIndex(Address);
  1069. AddrTypeCache [CacheIndex] = 0;
  1070. #if DBG
  1071. DbgAddrTypeCacheFlushes++;
  1072. #endif
  1073. }
  1074. //** AddrTypeCacheLookup - Lookup an address from the address type cache.
  1075. //
  1076. // Input: Address - Address to be lookup.
  1077. // Output: CacheIndex - Pointer to cache index corresponding to the Address.
  1078. // DestType - Pointer to destination type to be filled in if
  1079. // the address is found in the cache.
  1080. //
  1081. // Returns: TRUE if the address was found in the cache.
  1082. //
  1083. // N.B. The output parameter DestType is only initialized if TRUE is returned.
  1084. //
  1085. __forceinline
  1086. BOOLEAN
  1087. AddrTypeCacheLookup(IPAddr Address, ULONG *CacheIndex, uchar *DestType)
  1088. {
  1089. ULONG32 CacheValue;
  1090. // Read the value of the cache corresponding to this address.
  1091. //
  1092. *CacheIndex = ComputeAddrTypeCacheIndex(Address);
  1093. CacheValue = AddrTypeCache [*CacheIndex];
  1094. // If the cached value is non-zero and matches the relevent portion of
  1095. // the address, then get the type code and translate it to the proper
  1096. // destination type.
  1097. //
  1098. if ((CacheValue != 0) &&
  1099. (((Address << ATC_BITS) ^ CacheValue) & ATC_ADDR_MASK) == 0) {
  1100. ADDRESS_TYPE_CODE TypeCode = CacheValue & ATC_CODE_MASK;
  1101. ASSERT(TypeCode < ATC_NUM_CODES);
  1102. *DestType = MapAddrTypeCodeToDestType[TypeCode];
  1103. #if DBG
  1104. DbgAddrTypeCacheHits++;
  1105. #endif
  1106. return TRUE;
  1107. }
  1108. #if DBG
  1109. DbgAddrTypeCacheMisses++;
  1110. #endif
  1111. return FALSE;
  1112. }
  1113. //** AddrTypeCacheUpdate - Add or update the destination type for an Address.
  1114. // in the cache.
  1115. //
  1116. // Input: Address - Address to be add or update.
  1117. // CacheIndex - Cache index corresponding to the Address.
  1118. // DestType - Destination type to cache for the Address.
  1119. //
  1120. // Returns: nothing.
  1121. //
  1122. __forceinline
  1123. void
  1124. AddrTypeCacheUpdate(IPAddr Address, ULONG CacheIndex, uchar DestType)
  1125. {
  1126. ADDRESS_TYPE_CODE TypeCode;
  1127. BOOLEAN Update = TRUE;
  1128. ASSERT(CacheIndex < (sizeof(AddrTypeCache) / sizeof(AddrTypeCache[0])));
  1129. switch (DestType) {
  1130. case DEST_LOCAL:
  1131. TypeCode = ATC_LOCAL;
  1132. break;
  1133. case DEST_BCAST:
  1134. TypeCode = ATC_BCAST;
  1135. break;
  1136. case DEST_MCAST:
  1137. TypeCode = ATC_MCAST;
  1138. break;
  1139. case DEST_REMOTE:
  1140. TypeCode = ATC_REMOTE;
  1141. break;
  1142. case DEST_REM_BCAST:
  1143. TypeCode = ATC_REMOTE_BCAST;
  1144. break;
  1145. case DEST_REM_MCAST:
  1146. TypeCode = ATC_REMOTE_MCAST;
  1147. break;
  1148. case DEST_SN_BCAST:
  1149. TypeCode = ATC_SUBNET_BCAST;
  1150. break;
  1151. default:
  1152. Update = FALSE;
  1153. #if DBG
  1154. DbgAddrTypeCacheNoUpdates++;
  1155. DbgAddrTypeCacheLastNoUpdateDestType = DestType;
  1156. #endif
  1157. }
  1158. if (Update) {
  1159. #if DBG
  1160. ULONG32 CacheValue = AddrTypeCache [CacheIndex];
  1161. if (CacheValue != 0) {
  1162. DbgAddrTypeCacheCollisions++;
  1163. }
  1164. #endif
  1165. AddrTypeCache [CacheIndex] = (Address << ATC_BITS) | TypeCode;
  1166. }
  1167. }
  1168. //** GetAddrType - Return the destination type of a specified address.
  1169. //
  1170. // Input: Address - Address to get the destination type of.
  1171. //
  1172. // Returns: Destination type.
  1173. //
  1174. uchar
  1175. GetAddrType(IPAddr Address)
  1176. {
  1177. ULONG CacheIndex;
  1178. NetTableEntry *NTE; // Pointer to current NTE.
  1179. IPMask Mask; // Mask for address.
  1180. IPMask SNMask;
  1181. uint i;
  1182. uchar Result; // Result of broadcast check.
  1183. // Check the cache and return if we got a hit.
  1184. //
  1185. if (AddrTypeCacheLookup(Address, &CacheIndex, &Result)) {
  1186. return Result;
  1187. }
  1188. // We don't cache, nor do we need to cache, these types of invalid
  1189. // addresses.
  1190. //
  1191. if (CLASSE_ADDR(Address)) {
  1192. return DEST_INVALID;
  1193. }
  1194. // See if it's one of our local addresses, or a broadcast
  1195. // on a local address.
  1196. // optimize it for the DEST_LOCAL case
  1197. //
  1198. for (NTE = NewNetTableList[NET_TABLE_HASH(Address)];
  1199. NTE; NTE = NTE->nte_next) {
  1200. if (IP_ADDR_EQUAL(NTE->nte_addr, Address) &&
  1201. (NTE->nte_flags & NTE_VALID) &&
  1202. !((IP_ADDR_EQUAL(Address, NULL_IP_ADDR) && (NTE->nte_if->if_flags & IF_FLAGS_NOIPADDR)))) {
  1203. Result = DEST_LOCAL;
  1204. goto gat_exit;
  1205. }
  1206. }
  1207. // go thru the whole table for other cases
  1208. //
  1209. for (i = 0; i < NET_TABLE_SIZE; i++) {
  1210. for (NTE = NewNetTableList[i]; NTE; NTE = NTE->nte_next) {
  1211. if (!(NTE->nte_flags & NTE_VALID)) {
  1212. continue;
  1213. }
  1214. if ((Result = IsBCastOnNTE(Address, NTE)) != DEST_LOCAL) {
  1215. goto gat_exit;
  1216. }
  1217. // See if the destination has a valid host part.
  1218. SNMask = NTE->nte_mask;
  1219. if (IP_ADDR_EQUAL(Address & SNMask, NTE->nte_addr & SNMask)) {
  1220. // On this subnet. See if the host part is invalid.
  1221. if (IP_ADDR_EQUAL(Address & SNMask, Address)) {
  1222. Result = DEST_INVALID; // Invalid 0 host part.
  1223. goto gat_exit;
  1224. }
  1225. }
  1226. }
  1227. }
  1228. // It's not a local address, see if it's loopback.
  1229. if (IP_LOOPBACK(Address)) {
  1230. Result = DEST_LOCAL;
  1231. goto gat_exit;
  1232. }
  1233. // If we're doing IGMP, see if it's a Class D address. If it is,
  1234. // return that.
  1235. if (CLASSD_ADDR(Address)) {
  1236. if (IGMPLevel != 0) {
  1237. Result = DEST_REM_MCAST;
  1238. goto gat_exit;
  1239. } else {
  1240. Result = DEST_INVALID;
  1241. goto gat_exit;
  1242. }
  1243. }
  1244. Mask = IPNetMask(Address);
  1245. // Now check remote broadcast. When we get here we know that the
  1246. // address is not a global broadcast, a subnet broadcast for a subnet
  1247. // of which we're a member, or an all-subnets broadcast for a net of
  1248. // which we're a member. Since we're avoiding making assumptions about
  1249. // all subnet of a net having the same mask, we can't really check for
  1250. // a remote subnet broadcast. We'll use the net mask and see if it's
  1251. // a remote all-subnet's broadcast.
  1252. if (IP_ADDR_EQUAL(Address, (Address & Mask) | (IP_LOCAL_BCST & ~Mask))) {
  1253. Result = DEST_REM_BCAST;
  1254. goto gat_exit;
  1255. }
  1256. // Check for invalid 0 parts. All we can do from here is see if he's
  1257. // sending to a remote net with all zero subnet and host parts. We
  1258. // can't check to see if he's sending to a remote subnet with an all
  1259. // zero host part.
  1260. if (IP_ADDR_EQUAL(Address, NULL_IP_ADDR)) {
  1261. Result = DEST_INVALID;
  1262. goto gat_exit;
  1263. }
  1264. #if DBG
  1265. if (IP_ADDR_EQUAL(Address, Address & Mask)) {
  1266. //This is a remote address with null host part per classfull address
  1267. //But may be a supernetted address, where the prefix len is less than the
  1268. //class mask prefix len for the metid.
  1269. //We should let this address go out.
  1270. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," GAT: zero host part %x?\n", Address));
  1271. }
  1272. #endif
  1273. // Must be remote.
  1274. Result = DEST_REMOTE;
  1275. gat_exit:
  1276. AddrTypeCacheUpdate(Address, CacheIndex, Result);
  1277. return Result;
  1278. }
  1279. //** GetLocalNTE - Get the local NTE for an incoming packet.
  1280. //
  1281. // Called during receive processing to find a matching NTE for a packet.
  1282. // First we check against the NTE we received it on, then against any NTE.
  1283. //
  1284. // Input: Address - The dest. address of the packet.
  1285. // NTE - Pointer to NTE packet was received on - filled in on
  1286. // exit w/correct NTE.
  1287. //
  1288. // Returns: DEST_LOCAL if the packet is destined for this host,
  1289. // DEST_REMOTE if it needs to be routed,
  1290. // DEST_SN_BCAST or DEST_BCAST if it's some sort of a broadcast.
  1291. //
  1292. uchar
  1293. GetLocalNTE(IPAddr Address, NetTableEntry ** NTE)
  1294. {
  1295. NetTableEntry *LocalNTE = *NTE;
  1296. IPMask Mask;
  1297. uchar Result;
  1298. uint i;
  1299. Interface *LocalIF;
  1300. NetTableEntry *OriginalNTE;
  1301. // Quick check to see if it is for the NTE it came in on (the common case).
  1302. if (IP_ADDR_EQUAL(Address, LocalNTE->nte_addr) &&
  1303. (LocalNTE->nte_flags & NTE_VALID))
  1304. return DEST_LOCAL; // For us, just return.
  1305. // Now check to see if it's a broadcast of some sort on the interface it
  1306. // came in on.
  1307. if ((Result = IsBCastOnNTE(Address, LocalNTE)) != DEST_LOCAL)
  1308. return Result;
  1309. //Is this a mcast on a loop interface
  1310. if ((LocalNTE == LoopNTE) && CLASSD_ADDR(Address)) {
  1311. return DEST_MCAST;
  1312. }
  1313. // The common cases failed us. Loop through the NetTable and see if
  1314. // it is either a valid local address or is a broadcast on one of the NTEs
  1315. // on the incoming interface. We won't check the NTE we've already looked
  1316. // at. We look at all NTEs, including the loopback NTE, because a loopback
  1317. // frame could come through here. Also, frames from ourselves to ourselves
  1318. // will come in on the loopback NTE.
  1319. i = 0;
  1320. LocalIF = LocalNTE->nte_if;
  1321. OriginalNTE = LocalNTE;
  1322. // optimize it for the DEST_LOCAL case
  1323. LocalNTE = NewNetTableList[NET_TABLE_HASH(Address)];
  1324. while (LocalNTE) {
  1325. if (LocalNTE != OriginalNTE) {
  1326. if (IP_ADDR_EQUAL(Address, LocalNTE->nte_addr) &&
  1327. (LocalNTE->nte_flags & NTE_VALID) &&
  1328. !((IP_ADDR_EQUAL(Address, NULL_IP_ADDR) && (LocalNTE->nte_if->if_flags & IF_FLAGS_NOIPADDR)))) {
  1329. *NTE = LocalNTE;
  1330. return DEST_LOCAL; // For us, just return.
  1331. }
  1332. }
  1333. LocalNTE = LocalNTE->nte_next;
  1334. }
  1335. // go thru the whole table for other cases
  1336. for (i = 0; i < NET_TABLE_SIZE; i++) {
  1337. NetTableEntry *NetTableList = NewNetTableList[i];
  1338. LocalNTE = NetTableList;
  1339. while (LocalNTE) {
  1340. if (LocalNTE != OriginalNTE) {
  1341. // If this NTE is on the same interface as the NTE it arrived on,
  1342. // see if it's a broadcast.
  1343. if (LocalIF == LocalNTE->nte_if)
  1344. if ((Result = IsBCastOnNTE(Address, LocalNTE)) != DEST_LOCAL) {
  1345. *NTE = LocalNTE;
  1346. return Result;
  1347. }
  1348. }
  1349. LocalNTE = LocalNTE->nte_next;
  1350. }
  1351. }
  1352. // It's not a local address, see if it's loopback.
  1353. if (IP_LOOPBACK(Address)) {
  1354. *NTE = LoopNTE;
  1355. return DEST_LOCAL;
  1356. }
  1357. // If it's a class D address and we're receiveing multicasts, handle it
  1358. // here.
  1359. if (CLASSD_ADDR(Address)) {
  1360. if (IGMPLevel != 0)
  1361. return DEST_REM_MCAST;
  1362. else
  1363. return DEST_INVALID;
  1364. }
  1365. // It's not local. Check to see if maybe it's a net broadcast for a net
  1366. // of which we're not a member. If so, return remote bcast. We can't check
  1367. // for subnet broadcast of subnets for which we're not a member, since we're
  1368. // not making assumptions about all subnets of a single net having the
  1369. // same mask. If we're here it's not a subnet broadcast for a net of which
  1370. // we're a member, so we don't know a subnet mask for it. We'll just use
  1371. // the net mask.
  1372. Mask = IPNetMask(Address);
  1373. if (((*NTE)->nte_flags & NTE_VALID) &&
  1374. (IP_ADDR_EQUAL(Address, (Address & Mask) |
  1375. ((*NTE)->nte_if->if_bcast & ~Mask))))
  1376. return DEST_REM_BCAST;
  1377. // If it's to the 0 address, or a Class E address, or has an all-zero
  1378. // subnet and net part, it's invalid.
  1379. if (IP_ADDR_EQUAL(Address, IP_ZERO_BCST) ||
  1380. IP_ADDR_EQUAL(Address, (Address & Mask)) ||
  1381. CLASSE_ADDR(Address))
  1382. return DEST_INVALID;
  1383. // If we're DHCPing the interface on which this came in we'll accept this.
  1384. // If it came in as a broadcast a check in IPRcv() will reject it. If it's
  1385. // a unicast to us we'll pass it up.
  1386. if ((*NTE)->nte_flags & NTE_DHCP) {
  1387. ASSERT(!((*NTE)->nte_flags & NTE_VALID));
  1388. return DEST_LOCAL;
  1389. }
  1390. return DEST_REMOTE;
  1391. }
  1392. //** IsRouteICMP - This function is used by Router Discovery to determine
  1393. // how we learned about the route. We are not allowed to update or timeout
  1394. // routes that were not learned about via icmp. If the route is new then
  1395. // we treat it as icmp and add a new entry.
  1396. // Input: Dest - Destination to search for.
  1397. // Mask - Mask for destination.
  1398. // FirstHop - FirstHop to Dest.
  1399. // OutIF - Pointer to outgoing interface structure.
  1400. //
  1401. // Returns: TRUE if learned via ICMP, FALSE otherwise.
  1402. //
  1403. uint
  1404. IsRouteICMP(IPAddr Dest, IPMask Mask, IPAddr FirstHop, Interface * OutIF)
  1405. {
  1406. RouteTableEntry *RTE;
  1407. RouteTableEntry *TempRTE;
  1408. RTE = FindSpecificRTE(Dest, Mask, FirstHop, OutIF, &TempRTE, FALSE);
  1409. if (RTE == NULL)
  1410. return (TRUE);
  1411. if (RTE->rte_proto == IRE_PROTO_ICMP) {
  1412. return (TRUE);
  1413. } else {
  1414. return (FALSE);
  1415. }
  1416. }
  1417. void
  1418. UpdateDeadGWState( )
  1419. {
  1420. uint Active = 0;
  1421. uint Configured = 0;
  1422. RouteTableEntry* RTE;
  1423. RTE = GetDefaultGWs(&RTE);
  1424. while (RTE) {
  1425. ++Configured;
  1426. if (RTE->rte_flags & RTE_VALID)
  1427. ++Active;
  1428. RTE = RTE->rte_next;
  1429. }
  1430. DefGWActive = Active;
  1431. DefGWConfigured = Configured;
  1432. }
  1433. //* ValidateDefaultGWs - Mark all default gateways as valid.
  1434. //
  1435. // Called to one or all of our default gateways as up. The caller specifies
  1436. // the IP address of the one to mark as up, or NULL_IP_ADDR if they're all
  1437. // supposed to be marked up. We return a count of how many we marked as
  1438. // valid.
  1439. //
  1440. // Input: IP address of G/W to mark as up.
  1441. //
  1442. // Returns: Count of gateways marked as up.
  1443. //
  1444. uint
  1445. ValidateDefaultGWs(IPAddr Addr)
  1446. {
  1447. RouteTableEntry *RTE;
  1448. uint Count = 0;
  1449. uint Now = CTESystemUpTime() / 1000L;
  1450. RTE = GetDefaultGWs(&RTE);
  1451. while (RTE != NULL) {
  1452. if (RTE->rte_mask == DEFAULT_MASK && !(RTE->rte_flags & RTE_VALID) &&
  1453. (IP_ADDR_EQUAL(Addr, NULL_IP_ADDR) ||
  1454. IP_ADDR_EQUAL(Addr, RTE->rte_addr))) {
  1455. RTE->rte_flags |= RTE_VALID;
  1456. RTE->rte_valid = Now;
  1457. Count++;
  1458. }
  1459. RTE->rte_todg = RTE->rte_fromdg = NULL;
  1460. // To ensure that RCEs get switched to a lower-metric gateway
  1461. // if one exists, invalidate all RCEs on this RTE.
  1462. InvalidateRCEChain(RTE);
  1463. RTE = RTE->rte_next;
  1464. }
  1465. DefGWActive += Count;
  1466. UpdateDeadGWState();
  1467. return Count;
  1468. }
  1469. //* InvalidateRCE - Invalidate an RCE.
  1470. //
  1471. // Called to invalidate the RCE
  1472. //
  1473. //
  1474. // Input: RCE
  1475. //
  1476. // Returns: usecnt on the RCE.
  1477. //
  1478. uint
  1479. InvalidateRCE(RouteCacheEntry * CurrentRCE)
  1480. {
  1481. CTELockHandle RCEHandle; // Lock handle for RCE being updated.
  1482. Interface *OutIF;
  1483. RouteTableEntry *RTE;
  1484. RouteCacheEntry *PrevRCE;
  1485. uint RCE_usecnt = 0;
  1486. if (CurrentRCE != NULL) {
  1487. CTEGetLock(&CurrentRCE->rce_lock, &RCEHandle);
  1488. RCE_usecnt = CurrentRCE->rce_usecnt;
  1489. if ((CurrentRCE->rce_flags & RCE_VALID) && !(CurrentRCE->rce_flags & RCE_LINK_DELETED)) {
  1490. ASSERT(CurrentRCE->rce_rte != NULL);
  1491. OutIF = CurrentRCE->rce_rte->rte_if;
  1492. RTE = CurrentRCE->rce_rte;
  1493. CurrentRCE->rce_rte->rte_rces -= CurrentRCE->rce_cnt;
  1494. CurrentRCE->rce_flags &= ~RCE_VALID;
  1495. CurrentRCE->rce_rte = (RouteTableEntry *) OutIF;
  1496. if ((CurrentRCE->rce_flags & RCE_CONNECTED) &&
  1497. (RCE_usecnt == 0)) {
  1498. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"InvalidateRCE %x\n", CurrentRCE));
  1499. (*(OutIF->if_invalidate)) (OutIF->if_lcontext, CurrentRCE);
  1500. if (CurrentRCE->rce_flags & RCE_REFERENCED) {
  1501. LockedDerefIF(OutIF);
  1502. CurrentRCE->rce_flags &= ~RCE_REFERENCED;
  1503. }
  1504. }
  1505. PrevRCE = STRUCT_OF(RouteCacheEntry, &RTE->rte_rcelist, rce_next);
  1506. // Walk down the list until we find him.
  1507. while (PrevRCE != NULL) {
  1508. if (PrevRCE->rce_next == CurrentRCE)
  1509. break;
  1510. PrevRCE = PrevRCE->rce_next;
  1511. }
  1512. //ASSERT(PrevRCE != NULL);
  1513. if (PrevRCE != NULL) {
  1514. PrevRCE->rce_next = CurrentRCE->rce_next;
  1515. }
  1516. }
  1517. CTEFreeLock(&CurrentRCE->rce_lock, RCEHandle);
  1518. }
  1519. return RCE_usecnt;
  1520. }
  1521. //* InvalidateRCEChain - Invalidate the RCEs on an RCE.
  1522. //
  1523. // Called to invalidate the RCE chain on an RTE. We assume the caller holds
  1524. // the route table lock.
  1525. //
  1526. // Input: RTE - RTE on which to invalidate RCEs.
  1527. //
  1528. // Returns: Nothing.
  1529. //
  1530. void
  1531. InvalidateRCEChain(RouteTableEntry * RTE)
  1532. {
  1533. CTELockHandle RCEHandle; // Lock handle for RCE being updated.
  1534. RouteCacheEntry *TempRCE, *CurrentRCE;
  1535. Interface *OutIF;
  1536. OutIF = RTE->rte_if;
  1537. // If there is an RCE chain on this RCE, invalidate the RCEs on it. We still
  1538. // hold the RouteTableLock, so RCE closes can't happen.
  1539. CurrentRCE = RTE->rte_rcelist;
  1540. RTE->rte_rcelist = NULL;
  1541. // Walk down the list, nuking each RCE.
  1542. while (CurrentRCE != NULL) {
  1543. CTEGetLock(&CurrentRCE->rce_lock, &RCEHandle);
  1544. if ((CurrentRCE->rce_flags & RCE_VALID) && !(CurrentRCE->rce_flags & RCE_LINK_DELETED)) {
  1545. ASSERT(CurrentRCE->rce_rte == RTE);
  1546. RTE->rte_rces -= CurrentRCE->rce_cnt;
  1547. CurrentRCE->rce_flags &= ~RCE_VALID;
  1548. CurrentRCE->rce_rte = (RouteTableEntry *) OutIF;
  1549. if ((CurrentRCE->rce_flags & RCE_CONNECTED) &&
  1550. CurrentRCE->rce_usecnt == 0) {
  1551. (*(OutIF->if_invalidate)) (OutIF->if_lcontext, CurrentRCE);
  1552. if (CurrentRCE->rce_flags & RCE_REFERENCED) {
  1553. LockedDerefIF(OutIF);
  1554. CurrentRCE->rce_flags &= ~RCE_REFERENCED;
  1555. }
  1556. }
  1557. } else
  1558. ASSERT(FALSE);
  1559. TempRCE = CurrentRCE->rce_next;
  1560. CTEFreeLock(&CurrentRCE->rce_lock, RCEHandle);
  1561. CurrentRCE = TempRCE;
  1562. }
  1563. }
  1564. //* InvalidateRCELinks - Invalidate the RCEs on RTE when the link goes away
  1565. //
  1566. // Called to invalidate the RCE chain on an RTE. We assume the caller holds
  1567. // the route table lock.
  1568. //
  1569. // Input: RTE - RTE on which to invalidate RCEs.
  1570. //
  1571. // Returns: Nothing.
  1572. //
  1573. void
  1574. InvalidateRCELinks(RouteTableEntry * RTE)
  1575. {
  1576. CTELockHandle RCEHandle; // Lock handle for RCE being updated.
  1577. RouteCacheEntry *TempRCE, *CurrentRCE;
  1578. Interface *OutIF;
  1579. InvalidateRCEChain(RTE);
  1580. OutIF = RTE->rte_if;
  1581. ASSERT(OutIF->if_flags & IF_FLAGS_P2MP);
  1582. ASSERT(RTE->rte_link);
  1583. // If there is an RCE chain on this RCE, invalidate the RCEs on it. We still
  1584. // hold the RouteTableLock, so RCE closes can't happen.
  1585. CurrentRCE = RTE->rte_rcelist;
  1586. RTE->rte_rcelist = NULL;
  1587. // Walk down the list, nuking each RCE.
  1588. while (CurrentRCE != NULL) {
  1589. CTEGetLock(&CurrentRCE->rce_lock, &RCEHandle);
  1590. // mark the RCE as link deleted so that this rce is not selected in iptransmit
  1591. CurrentRCE->rce_flags |= RCE_LINK_DELETED;
  1592. TempRCE = CurrentRCE->rce_next;
  1593. CTEFreeLock(&CurrentRCE->rce_lock, RCEHandle);
  1594. CurrentRCE = TempRCE;
  1595. }
  1596. }
  1597. //* GetNextHopForRTE - determines the next-hop address for a route.
  1598. //
  1599. // Called when we need an actual next-hop for a route, typically so
  1600. // we can pass it to an external client. For local routes that have
  1601. // an rte_addr field set to IPADDR_LOCAL, this means figuring out
  1602. // the source NTE for the route and using its IP address.
  1603. //
  1604. // Entry: RTE - the entry whose next-hop is required
  1605. //
  1606. // Returns: IPAddr containing the next-hop
  1607. //
  1608. IPAddr
  1609. GetNextHopForRTE(RouteTableEntry* RTE)
  1610. {
  1611. if (IP_ADDR_EQUAL(RTE->rte_addr, IPADDR_LOCAL)) {
  1612. Interface *IF = RTE->rte_if;
  1613. NetTableEntry *SrcNTE = BestNTEForIF(RTE->rte_dest, IF);
  1614. if (IF->if_nte != NULL && SrcNTE != NULL)
  1615. return SrcNTE->nte_addr;
  1616. else
  1617. return RTE->rte_dest;
  1618. }
  1619. return RTE->rte_addr;
  1620. }
  1621. //** FindValidIFForRTE - Find a valid inteface for an RTE.
  1622. //
  1623. // Called when we're going to send a packet out a route that currently marked
  1624. // as disconnected. If we have a valid callout routine we'll call it to find
  1625. // the outgoing interface index, and set up the RTE to point at that interface.
  1626. // This routine is called with the RouteTableLock held.
  1627. //
  1628. // Input: RTE - A pointer to the RTE for the route being used.
  1629. // Destination - Destination IP address we're trying to reach.
  1630. // Source - Source IP address we're sending from.
  1631. // Protocol - Protocol type of packet that caused send.
  1632. // Buffer - Pointer to first part of packet that caused send.
  1633. // Length - Length of buffer.
  1634. // HdrSrc - Src Address in header
  1635. //
  1636. // Returns: A pointer to the RTE, or NULL if that RTE couldn't be connected.
  1637. //
  1638. RouteTableEntry *
  1639. FindValidIFForRTE(RouteTableEntry * RTE, IPAddr Destination, IPAddr Source,
  1640. uchar Protocol, uchar * Buffer, uint Length, IPAddr HdrSrc)
  1641. {
  1642. uint NewIFIndex;
  1643. Interface *NewIF;
  1644. NetTableEntry *NewNTE;
  1645. if (DODCallout != NULL) {
  1646. // There is a callout. See if it can help us.
  1647. NewIFIndex = (*DODCallout) (RTE->rte_context, Destination, Source,
  1648. Protocol, Buffer, Length, HdrSrc);
  1649. if (NewIFIndex != INVALID_IF_INDEX) {
  1650. // We got what should be a valid index. Walk our interface table list
  1651. // and see if we can find a matching interface structure.
  1652. for (NewIF = IFList; NewIF != NULL; NewIF = NewIF->if_next) {
  1653. if (NewIF->if_index == NewIFIndex) {
  1654. // Found one.
  1655. break;
  1656. }
  1657. }
  1658. if ((NewIF != NULL) && (NewIF->if_ntecount)) {
  1659. // We found a matching structure. Set the RTE interface to point
  1660. // to this, and mark as connected.
  1661. if (RTE->rte_addr != IPADDR_LOCAL) {
  1662. // See if the first hop of the route is a local address on this
  1663. // new interface. If it is, mark it as local.
  1664. for (NewNTE = NewIF->if_nte; NewNTE != NULL;
  1665. NewNTE = NewNTE->nte_ifnext) {
  1666. // Don't look at him if he's not valid.
  1667. if (!(NewNTE->nte_flags & NTE_VALID)) {
  1668. continue;
  1669. }
  1670. // See if the first hop in the RTE is equal to this IP
  1671. // address.
  1672. if (IP_ADDR_EQUAL(NewNTE->nte_addr, RTE->rte_addr)) {
  1673. // It is, so mark as local and quit looking.
  1674. RTE->rte_addr = IPADDR_LOCAL;
  1675. RTE->rte_type = IRE_TYPE_DIRECT;
  1676. break;
  1677. }
  1678. }
  1679. }
  1680. // Set the RTE to the new interface, and mark him as valid.
  1681. RTE->rte_if = NewIF;
  1682. RTE->rte_flags |= RTE_IF_VALID;
  1683. SortRoutesInDestByRTE(RTE);
  1684. RTE->rte_mtu = NewIF->if_mtu - sizeof(IPHeader);
  1685. return RTE;
  1686. } else {
  1687. // ASSERT(FALSE);
  1688. return NULL;
  1689. }
  1690. }
  1691. }
  1692. // Either the callout is NULL, or the callout couldn't map a inteface index.
  1693. return NULL;
  1694. }
  1695. //* GetRouteContext - Routine to get the route context for a specific route.
  1696. //
  1697. // Called when we need to get the route context for a path, usually when we're
  1698. // adding a route derived from an existing route. We return the route context
  1699. // for the existing route, or NULL if we can't find one.
  1700. //
  1701. // Input: Destination - Destination address of path.
  1702. // Source - Source address of path.
  1703. //
  1704. // Returns: A ROUTE_CONTEXT, or 0.
  1705. //
  1706. ROUTE_CONTEXT
  1707. GetRouteContext(IPAddr Destination, IPAddr Source)
  1708. {
  1709. CTELockHandle Handle;
  1710. RouteTableEntry *RTE;
  1711. ROUTE_CONTEXT Context;
  1712. CTEGetLock(&RouteTableLock.Lock, &Handle);
  1713. RTE = LookupRTE(Destination, Source, HOST_ROUTE_PRI, FALSE);
  1714. if (RTE != NULL) {
  1715. Context = RTE->rte_context;
  1716. } else
  1717. Context = 0;
  1718. CTEFreeLock(&RouteTableLock.Lock, Handle);
  1719. return (Context);
  1720. }
  1721. //** LookupNextHop - Look up the next hop
  1722. //
  1723. // Called when we need to find the next hop on our way to a destination. We
  1724. // call LookupRTE to find it, and return the appropriate information.
  1725. //
  1726. // In a PnP build, the interface is referenced here.
  1727. //
  1728. // Entry: Destination - IP address we're trying to reach.
  1729. // Src - Source address of datagram being routed.
  1730. // NextHop - Pointer to IP address of next hop (returned).
  1731. // MTU - Pointer to where to return max MTU used on the
  1732. // route.
  1733. //
  1734. // Returns: Pointer to outgoing interface if we found one, NULL otherwise.
  1735. //
  1736. Interface *
  1737. LookupNextHop(IPAddr Destination, IPAddr Src, IPAddr * NextHop, uint * MTU)
  1738. {
  1739. CTELockHandle TableLock; // Lock handle for routing table.
  1740. RouteTableEntry *Route; // Pointer to route table entry for route.
  1741. Interface *IF;
  1742. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  1743. Route = LookupRTE(Destination, Src, HOST_ROUTE_PRI, FALSE);
  1744. if (Route != (RouteTableEntry *) NULL) {
  1745. IF = Route->rte_if;
  1746. // If this is a direct route, send straight to the destination.
  1747. *NextHop = IP_ADDR_EQUAL(Route->rte_addr, IPADDR_LOCAL) ? Destination :
  1748. Route->rte_addr;
  1749. // if the route is on a P2MP interface get the mtu from the link associated with the route
  1750. if (Route->rte_link)
  1751. *MTU = Route->rte_link->link_mtu;
  1752. else
  1753. *MTU = Route->rte_mtu;
  1754. LOCKED_REFERENCE_IF(IF);
  1755. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1756. return IF;
  1757. } else { // Couldn't find a route.
  1758. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1759. return NULL;
  1760. }
  1761. }
  1762. //** LookupNextHopWithBuffer - Look up the next hop, with packet information.
  1763. //
  1764. // Called when we need to find the next hop on our way to a destination and we
  1765. // have packet information that we may use for dial on demand support. We call
  1766. // LookupRTE to find it, and return the appropriate information. We may bring
  1767. // up the link if neccessary.
  1768. //
  1769. // In a PnP build, the interface is referenced here.
  1770. //
  1771. // Entry: Destination - IP address we're trying to reach.
  1772. // Src - Source address of datagram being routed.
  1773. // NextHop - Pointer to IP address of next hop (returned).
  1774. // MTU - Pointer to where to return max MTU used on the
  1775. // route.
  1776. // Protocol - Protocol type for packet that's causing this
  1777. // lookup.
  1778. // Buffer - Pointer to first part of packet causing lookup.
  1779. // Length - Length of Buffer.
  1780. // HdrSrc - source addres from header
  1781. // UnicastIf - Iface to constrain lookup to, 0 if unconstrained
  1782. //
  1783. // Returns: Pointer to outgoing interface if we found one, NULL otherwise.
  1784. //
  1785. Interface *
  1786. LookupNextHopWithBuffer(IPAddr Destination, IPAddr Src, IPAddr *NextHop,
  1787. uint * MTU, uchar Protocol, uchar *Buffer, uint Length,
  1788. RouteCacheEntry **fwdRCE, LinkEntry **Link,
  1789. IPAddr HdrSrc, uint UnicastIf)
  1790. {
  1791. CTELockHandle TableLock; // Lock handle for routing table.
  1792. RouteTableEntry *Route; // Pointer to route table entry for route.
  1793. Interface *IF;
  1794. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  1795. Route = LookupRTE(Destination, Src, HOST_ROUTE_PRI, UnicastIf);
  1796. if (Route != (RouteTableEntry *) NULL) {
  1797. // If this is a direct route, send straight to the destination.
  1798. *NextHop = IP_ADDR_EQUAL(Route->rte_addr, IPADDR_LOCAL) ? Destination :
  1799. Route->rte_addr;
  1800. // If this is an indirect route, we can use the forwarding RCE
  1801. if (fwdRCE) {
  1802. #if REM_OPT
  1803. *fwdRCE = IP_ADDR_EQUAL(Route->rte_addr, IPADDR_LOCAL) ? NULL :
  1804. #else
  1805. *fwdRCE =
  1806. #endif
  1807. (RouteCacheEntry *) STRUCT_OF(RouteCacheEntry,
  1808. &Route->rte_arpcontext,
  1809. rce_context);
  1810. }
  1811. // See if the route we found is connected. If not, try to connect it.
  1812. if (!(Route->rte_flags & RTE_IF_VALID)) {
  1813. Route = FindValidIFForRTE(Route, Destination, Src, Protocol, Buffer,
  1814. Length, HdrSrc);
  1815. if (Route == NULL) {
  1816. // Couldn't bring it up.
  1817. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1818. return NULL;
  1819. } else
  1820. IF = Route->rte_if;
  1821. } else
  1822. IF = Route->rte_if;
  1823. // if the route is on a P2MP interface get the mtu from the
  1824. // link associated with the route
  1825. if (Route->rte_link)
  1826. *MTU = Route->rte_link->link_mtu;
  1827. else
  1828. *MTU = Route->rte_mtu;
  1829. if (Link) {
  1830. *Link = Route->rte_link;
  1831. if (Route->rte_link) {
  1832. CTEInterlockedIncrementLong(&Route->rte_link->link_refcount);
  1833. }
  1834. }
  1835. LOCKED_REFERENCE_IF(IF);
  1836. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1837. return IF;
  1838. } else { // Couldn't find a route.
  1839. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1840. return NULL;
  1841. }
  1842. }
  1843. //** LookupForwardingNextHop - Look up the next hop on which to forward packet on.
  1844. //
  1845. // Called when we need to find the next hop on our way to a destination and we
  1846. // have packet information that we may use for dial on demand support. We call
  1847. // LookupRTE to find it, and return the appropriate information. We may bring
  1848. // up the link if neccessary.
  1849. //
  1850. // In a PnP build, the interface is referenced here.
  1851. //
  1852. // Entry: Destination - IP address we're trying to reach.
  1853. // Src - Source address of datagram being routed.
  1854. // NextHop - Pointer to IP address of next hop (returned).
  1855. // MTU - Pointer to where to return max MTU used on the
  1856. // route.
  1857. // Protocol - Protocol type for packet that's causing this
  1858. // lookup.
  1859. // Buffer - Pointer to first part of packet causing lookup.
  1860. // Length - Length of Buffer.
  1861. // HdrSrc - source addres from header
  1862. //
  1863. // Returns: Pointer to outgoing interface if we found one, NULL otherwise.
  1864. //
  1865. Interface *
  1866. LookupForwardingNextHop(IPAddr Destination, IPAddr Src, IPAddr *NextHop,
  1867. uint * MTU, uchar Protocol, uchar *Buffer, uint Length,
  1868. RouteCacheEntry **fwdRCE, LinkEntry **Link,
  1869. IPAddr HdrSrc)
  1870. {
  1871. CTELockHandle TableLock; // Lock handle for routing table.
  1872. RouteTableEntry *Route; // Pointer to route table entry for route.
  1873. Interface *IF;
  1874. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  1875. Route = LookupForwardRTE(Destination, Src, TRUE);
  1876. if (Route != (RouteTableEntry *) NULL) {
  1877. // If this is a direct route, send straight to the destination.
  1878. *NextHop = IP_ADDR_EQUAL(Route->rte_addr, IPADDR_LOCAL) ? Destination :
  1879. Route->rte_addr;
  1880. // If this is an indirect route, we can use the forwarding RCE
  1881. if (fwdRCE) {
  1882. #if REM_OPT
  1883. *fwdRCE = IP_ADDR_EQUAL(Route->rte_addr, IPADDR_LOCAL) ? NULL :
  1884. #else
  1885. *fwdRCE =
  1886. #endif
  1887. (RouteCacheEntry *) STRUCT_OF(RouteCacheEntry,
  1888. &Route->rte_arpcontext,
  1889. rce_context);
  1890. }
  1891. // See if the route we found is connected. If not, try to connect it.
  1892. if (!(Route->rte_flags & RTE_IF_VALID)) {
  1893. Route = FindValidIFForRTE(Route, Destination, Src, Protocol, Buffer,
  1894. Length, HdrSrc);
  1895. if (Route == NULL) {
  1896. // Couldn't bring it up.
  1897. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1898. return NULL;
  1899. } else
  1900. IF = Route->rte_if;
  1901. } else
  1902. IF = Route->rte_if;
  1903. // if the route is on a P2MP interface get the mtu from the
  1904. // link associated with the route
  1905. if (Route->rte_link)
  1906. *MTU = Route->rte_link->link_mtu;
  1907. else
  1908. *MTU = Route->rte_mtu;
  1909. if (Link) {
  1910. *Link = Route->rte_link;
  1911. if (Route->rte_link) {
  1912. CTEInterlockedIncrementLong(&Route->rte_link->link_refcount);
  1913. }
  1914. }
  1915. LOCKED_REFERENCE_IF(IF);
  1916. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1917. return IF;
  1918. } else { // Couldn't find a route.
  1919. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  1920. return NULL;
  1921. }
  1922. }
  1923. //* RTReadNext - Read the next route in the table.
  1924. //
  1925. // Called by the GetInfo code to read the next route in the table. We assume
  1926. // the context passed in is valid, and the caller has the RouteTableLock.
  1927. //
  1928. // Input: Context - Pointer to a RouteEntryContext.
  1929. // Buffer - Pointer to an IPRouteEntry structure.
  1930. //
  1931. // Returns: TRUE if more data is available to be read, FALSE is not.
  1932. //
  1933. uint
  1934. RTReadNext(void *Context, void *Buffer)
  1935. {
  1936. RouteEntryContext *REContext = (RouteEntryContext *) Context;
  1937. IPRouteEntry *IPREntry = (IPRouteEntry *) Buffer;
  1938. RouteTableEntry *CurrentRTE=NULL;
  1939. uint i;
  1940. uint Now = CTESystemUpTime() / 1000L;
  1941. Interface *IF;
  1942. NetTableEntry *SrcNTE;
  1943. UINT retVal = GetNextRoute(Context, &CurrentRTE);
  1944. // Should always have the rte because we don't have empty route tables.
  1945. //
  1946. ASSERT(CurrentRTE);
  1947. // Fill in the buffer.
  1948. IF = CurrentRTE->rte_if;
  1949. IPREntry->ire_dest = CurrentRTE->rte_dest;
  1950. IPREntry->ire_index = IF->if_index;
  1951. IPREntry->ire_metric1 = CurrentRTE->rte_metric;
  1952. IPREntry->ire_metric2 = IRE_METRIC_UNUSED;
  1953. IPREntry->ire_metric3 = IRE_METRIC_UNUSED;
  1954. IPREntry->ire_metric4 = IRE_METRIC_UNUSED;
  1955. IPREntry->ire_metric5 = IRE_METRIC_UNUSED;
  1956. IPREntry->ire_nexthop = GetNextHopForRTE(CurrentRTE);
  1957. IPREntry->ire_type = (CurrentRTE->rte_flags & RTE_VALID ?
  1958. CurrentRTE->rte_type : IRE_TYPE_INVALID);
  1959. IPREntry->ire_proto = CurrentRTE->rte_proto;
  1960. IPREntry->ire_age = Now - CurrentRTE->rte_valid;
  1961. IPREntry->ire_mask = CurrentRTE->rte_mask;
  1962. IPREntry->ire_context = CurrentRTE->rte_context;
  1963. return retVal;
  1964. }
  1965. //* RTRead - Read the next route in the table.
  1966. //
  1967. // Called by the GetInfo code to read the next route in the table. We assume
  1968. // the context passed in is valid, and the caller has the RouteTableLock.
  1969. //
  1970. // Input: Context - Pointer to a RouteEntryContext.
  1971. // Buffer - Pointer to an IPRouteEntry structure.
  1972. //
  1973. // Returns:
  1974. //
  1975. //* RtRead - Read a route
  1976. //
  1977. // Returns: Status of attempt to add route.
  1978. //
  1979. uint
  1980. RTRead(void *pContext, void *pBuffer)
  1981. {
  1982. IPRouteLookupData *pRLData = (IPRouteLookupData *) pContext;
  1983. IPRouteEntry *pIPREntry = (IPRouteEntry *) pBuffer;
  1984. RouteTableEntry *pCurrentRTE;
  1985. uint i;
  1986. uint Now = CTESystemUpTime() / 1000L;
  1987. Interface *pIF;
  1988. NetTableEntry *pSrcNTE;
  1989. ASSERT((pContext != NULL) && (pBuffer != NULL));
  1990. pCurrentRTE = LookupRTE(pRLData->DestAdd, pRLData->SrcAdd,
  1991. HOST_ROUTE_PRI, FALSE);
  1992. if (pCurrentRTE == NULL) {
  1993. pIPREntry->ire_index = 0xffffffff;
  1994. return TDI_DEST_HOST_UNREACH;
  1995. }
  1996. // Fill in the buffer.
  1997. pIF = pCurrentRTE->rte_if;
  1998. pIPREntry->ire_dest = pCurrentRTE->rte_dest;
  1999. pIPREntry->ire_index = pIF->if_index;
  2000. pIPREntry->ire_metric1 = pCurrentRTE->rte_metric;
  2001. pIPREntry->ire_metric2 = IRE_METRIC_UNUSED;
  2002. pIPREntry->ire_metric3 = IRE_METRIC_UNUSED;
  2003. pIPREntry->ire_metric4 = IRE_METRIC_UNUSED;
  2004. pIPREntry->ire_metric5 = IRE_METRIC_UNUSED;
  2005. pIPREntry->ire_nexthop = GetNextHopForRTE(pCurrentRTE);
  2006. pIPREntry->ire_type = (pCurrentRTE->rte_flags & RTE_VALID ?
  2007. pCurrentRTE->rte_type : IRE_TYPE_INVALID);
  2008. pIPREntry->ire_proto = pCurrentRTE->rte_proto;
  2009. pIPREntry->ire_age = Now - pCurrentRTE->rte_valid;
  2010. pIPREntry->ire_mask = pCurrentRTE->rte_mask;
  2011. pIPREntry->ire_context = pCurrentRTE->rte_context;
  2012. return TDI_SUCCESS;
  2013. }
  2014. void
  2015. LookupRoute(IPRouteLookupData * pRLData, IPRouteEntry * pIpRTE)
  2016. {
  2017. CTELockHandle Handle;
  2018. CTEGetLock(&RouteTableLock.Lock, &Handle);
  2019. RTRead(pRLData, pIpRTE);
  2020. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2021. return;
  2022. }
  2023. NTSTATUS
  2024. LookupRouteInformation(void *pRouteLookupData, void *pIpRTE,
  2025. IPROUTEINFOCLASS RouteInfoClass, void *RouteInformation,
  2026. uint * RouteInfoLength)
  2027. {
  2028. return LookupRouteInformationWithBuffer(pRouteLookupData, NULL, 0, pIpRTE,
  2029. RouteInfoClass, RouteInformation,
  2030. RouteInfoLength);
  2031. }
  2032. NTSTATUS
  2033. LookupRouteInformationWithBuffer(void *pRouteLookupData, uchar * Buffer,
  2034. uint Length, void *pIpRTE,
  2035. IPROUTEINFOCLASS RouteInfoClass,
  2036. void *RouteInformation, uint * RouteInfoLength)
  2037. {
  2038. IPRouteLookupData *pRLData = (IPRouteLookupData *) pRouteLookupData;
  2039. IPRouteEntry *pIPREntry = (IPRouteEntry *) pIpRTE;
  2040. RouteTableEntry *pCurrentRTE;
  2041. uint i;
  2042. uint Now = CTESystemUpTime() / 1000L;
  2043. Interface *pIF;
  2044. NetTableEntry *pSrcNTE;
  2045. CTELockHandle Handle;
  2046. CTEGetLock(&RouteTableLock.Lock, &Handle);
  2047. ASSERT(pRouteLookupData != NULL);
  2048. pCurrentRTE = LookupRTE(pRLData->DestAdd, pRLData->SrcAdd, HOST_ROUTE_PRI, FALSE);
  2049. if (pCurrentRTE == NULL) {
  2050. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2051. return STATUS_UNSUCCESSFUL;
  2052. }
  2053. // see if the RTE is for a demand-dial route,
  2054. if (!(pCurrentRTE->rte_flags & RTE_IF_VALID)) {
  2055. pCurrentRTE = FindValidIFForRTE(pCurrentRTE, pRLData->DestAdd,
  2056. pRLData->SrcAdd, pRLData->Info[0],
  2057. Buffer, Length, pRLData->SrcAdd);
  2058. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2059. if (pCurrentRTE == NULL) {
  2060. // Couldn't bring it up.
  2061. return STATUS_UNSUCCESSFUL;
  2062. }
  2063. return STATUS_PENDING;
  2064. }
  2065. // Fill in the buffer.
  2066. pIF = pCurrentRTE->rte_if;
  2067. if (pIPREntry) {
  2068. pIPREntry->ire_dest = pCurrentRTE->rte_dest;
  2069. pIPREntry->ire_index = pIF->if_index;
  2070. pIPREntry->ire_metric1 = pCurrentRTE->rte_metric;
  2071. pIPREntry->ire_metric2 = IRE_METRIC_UNUSED;
  2072. pIPREntry->ire_metric3 = IRE_METRIC_UNUSED;
  2073. pIPREntry->ire_metric4 = IRE_METRIC_UNUSED;
  2074. pIPREntry->ire_metric5 = IRE_METRIC_UNUSED;
  2075. pIPREntry->ire_nexthop = GetNextHopForRTE(pCurrentRTE);
  2076. pIPREntry->ire_type = (pCurrentRTE->rte_flags & RTE_VALID ?
  2077. pCurrentRTE->rte_type : IRE_TYPE_INVALID);
  2078. pIPREntry->ire_proto = pCurrentRTE->rte_proto;
  2079. pIPREntry->ire_age = Now - pCurrentRTE->rte_valid;
  2080. pIPREntry->ire_mask = pCurrentRTE->rte_mask;
  2081. pIPREntry->ire_context = pCurrentRTE->rte_context;
  2082. }
  2083. switch (RouteInfoClass) {
  2084. case IPRouteOutgoingFirewallContext:
  2085. *(PULONG) RouteInformation = pIF->if_index;
  2086. *(PULONG) RouteInfoLength = sizeof(PVOID);
  2087. break;
  2088. case IPRouteOutgoingFilterContext:
  2089. *(PVOID *) RouteInformation = NULL;
  2090. *(PULONG) RouteInfoLength = sizeof(PVOID);
  2091. break;
  2092. }
  2093. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2094. return STATUS_SUCCESS;
  2095. }
  2096. //* DeleteRTE - Delete an RTE.
  2097. //
  2098. // Called when we need to delete an RTE. We assume the caller has the
  2099. // RouteTableLock. We'll splice out the RTE, invalidate his RCEs, and
  2100. // free the memory.
  2101. //
  2102. // Input: PrevRTE - RTE in 'front' of one being deleted.
  2103. // RTE - RTE to be deleted.
  2104. //
  2105. // Returns: Nothing.
  2106. //
  2107. void
  2108. DeleteRTE(RouteTableEntry * PrevRTE, RouteTableEntry * RTE)
  2109. {
  2110. IPSInfo.ipsi_numroutes--;
  2111. if (RTE->rte_mask == DEFAULT_MASK) {
  2112. // We're deleting a default route.
  2113. DefGWConfigured--;
  2114. if (RTE->rte_flags & RTE_VALID)
  2115. DefGWActive--;
  2116. UpdateDeadGWState();
  2117. if (DefGWActive == 0)
  2118. ValidateDefaultGWs(NULL_IP_ADDR);
  2119. }
  2120. if (RTE->rte_todg) {
  2121. RTE->rte_todg->rte_fromdg = NULL;
  2122. }
  2123. if (RTE->rte_fromdg) {
  2124. RTE->rte_fromdg->rte_todg = NULL;
  2125. }
  2126. {
  2127. RouteTableEntry *tmpRTE = NULL;
  2128. tmpRTE = GetDefaultGWs(&tmpRTE);
  2129. while (tmpRTE) {
  2130. if (tmpRTE->rte_todg == RTE) {
  2131. tmpRTE->rte_todg = NULL;
  2132. }
  2133. tmpRTE = tmpRTE->rte_next;
  2134. }
  2135. }
  2136. InvalidateRCEChain(RTE);
  2137. // Make sure RTE's IF is valid
  2138. ASSERT(RTE->rte_if != NULL);
  2139. // Invalidate the fwding rce
  2140. if (RTE->rte_if != (Interface *) & DummyInterface) {
  2141. (*(RTE->rte_if->if_invalidate)) (RTE->rte_if->if_lcontext,
  2142. (RouteCacheEntry *) STRUCT_OF(RouteCacheEntry,
  2143. &RTE->rte_arpcontext,
  2144. rce_context));
  2145. }
  2146. // Free the old route.
  2147. FreeRoute(RTE);
  2148. }
  2149. //* DeleteRTEOnIF - Delete all address-dependent RTEs on a particular IF.
  2150. //
  2151. // A function called by RTWalk when we want to delete all RTEs on a particular
  2152. // inteface, except those that are present for the lifetime of the interface.
  2153. // We just check the I/F of each RTE, and if it matches we return FALSE.
  2154. //
  2155. // Input: RTE - RTE to check.
  2156. // Context - Interface on which we're deleting.
  2157. //
  2158. // Returns: FALSE if we want to delete it, TRUE otherwise.
  2159. //
  2160. uint
  2161. DeleteRTEOnIF(RouteTableEntry * RTE, void *Context, void *Context1)
  2162. {
  2163. Interface *IF = (Interface *) Context;
  2164. if (RTE->rte_if == IF && !IP_ADDR_EQUAL(RTE->rte_dest, IF->if_bcast))
  2165. return FALSE;
  2166. else
  2167. return TRUE;
  2168. }
  2169. //* DeleteAllRTEOnIF - Delete all RTEs on a particular IF.
  2170. //
  2171. // A function called by RTWalk when we want to delete all RTEs on a particular
  2172. // inteface. We just check the I/F of each RTE, and if it matches we return
  2173. // FALSE.
  2174. //
  2175. // Input: RTE - RTE to check.
  2176. // Context - Interface on which we're deleting.
  2177. //
  2178. // Returns: FALSE if we want to delete it, TRUE otherwise.
  2179. //
  2180. uint
  2181. DeleteAllRTEOnIF(RouteTableEntry * RTE, void *Context, void *Context1)
  2182. {
  2183. Interface *IF = (Interface *) Context;
  2184. if (RTE->rte_if == IF)
  2185. return FALSE;
  2186. else
  2187. return TRUE;
  2188. }
  2189. //* InvalidateRCEOnIF - Invalidate all RCEs on a particular IF.
  2190. //
  2191. // A function called by RTWalk when we want to invalidate all RCEs on a
  2192. // particular inteface. We just check the I/F of each RTE, and if it
  2193. // matches we call InvalidateRCEChain to invalidate the RCEs.
  2194. //
  2195. // Input: RTE - RTE to check.
  2196. // Context - Interface on which we're invalidating.
  2197. //
  2198. // Returns: TRUE.
  2199. //
  2200. uint
  2201. InvalidateRCEOnIF(RouteTableEntry * RTE, void *Context, void *Context1)
  2202. {
  2203. Interface *IF = (Interface *) Context;
  2204. if (RTE->rte_if == IF)
  2205. InvalidateRCEChain(RTE);
  2206. return TRUE;
  2207. }
  2208. //* SetMTUOnIF - Set the MTU on an interface.
  2209. //
  2210. // Called when we need to set the MTU on an interface.
  2211. //
  2212. // Input: RTE - RTE to check.
  2213. // Context - Pointer to a context.
  2214. // Context1 - Pointer to the new MTU.
  2215. //
  2216. // Returns: TRUE.
  2217. //
  2218. uint
  2219. SetMTUOnIF(RouteTableEntry * RTE, void *Context, void *Context1)
  2220. {
  2221. uint NewMTU = *(uint *) Context1;
  2222. Interface *IF = (Interface *) Context;
  2223. if (RTE->rte_if == IF)
  2224. RTE->rte_mtu = NewMTU;
  2225. return TRUE;
  2226. }
  2227. //* SetMTUToAddr - Set the MTU to a specific address.
  2228. //
  2229. // Called when we need to set the MTU to a specific address. We set the MTU
  2230. // for all routes that use the specified address as a first hop to the new
  2231. // MTU.
  2232. //
  2233. // Input: RTE - RTE to check.
  2234. // Context - Pointer to a context.
  2235. // Context1 - Pointer to the new MTU.
  2236. //
  2237. // Returns: TRUE.
  2238. //
  2239. uint
  2240. SetMTUToAddr(RouteTableEntry * RTE, void *Context, void *Context1)
  2241. {
  2242. uint NewMTU = *(uint *) Context1;
  2243. IPAddr Addr = *(IPAddr *) Context;
  2244. if (IP_ADDR_EQUAL(RTE->rte_addr, Addr))
  2245. RTE->rte_mtu = NewMTU;
  2246. return TRUE;
  2247. }
  2248. //** FreeRtChangeList - Frees a route-change notification list.
  2249. //
  2250. // Called to clean up a list of route-change notifications in the failure path
  2251. // of 'RTWalk' and 'IPRouteTimeout'.
  2252. //
  2253. // Entry: RtChangeList - The list to be freed.
  2254. //
  2255. // Returns: Nothing.
  2256. //
  2257. void
  2258. FreeRtChangeList(RtChangeList* CurrentRtChangeList)
  2259. {
  2260. RtChangeList *TmpRtChangeList;
  2261. while (CurrentRtChangeList) {
  2262. TmpRtChangeList = CurrentRtChangeList->rt_next;
  2263. CTEFreeMem(CurrentRtChangeList);
  2264. CurrentRtChangeList = TmpRtChangeList;
  2265. }
  2266. }
  2267. //* RTWalk - Routine to walk the route table.
  2268. //
  2269. // This routine walks the route table, calling the specified function
  2270. // for each entry. If the called function returns FALSE, the RTE is
  2271. // deleted.
  2272. //
  2273. // Input: CallFunc - Function to call for each entry.
  2274. // Context - Context value to pass to each call.
  2275. //
  2276. // Returns: Nothing.
  2277. //
  2278. void
  2279. RTWalk(uint(*CallFunc) (struct RouteTableEntry *, void *, void *),
  2280. void *Context, void *Context1)
  2281. {
  2282. uint i;
  2283. CTELockHandle Handle;
  2284. RouteTableEntry *RTE, *PrevRTE;
  2285. RouteTableEntry *pOldBestRTE, *pNewBestRTE;
  2286. UINT IsDataLeft, IsValid;
  2287. UCHAR IteratorContext[CONTEXT_SIZE];
  2288. RtChangeList *CurrentRtChangeList = NULL;
  2289. CTEGetLock(&RouteTableLock.Lock, &Handle);
  2290. // Zero the context the first time it is used
  2291. RtlZeroMemory(IteratorContext, CONTEXT_SIZE);
  2292. // Do we have any routes in the table ?
  2293. IsDataLeft = RTValidateContext(IteratorContext, &IsValid);
  2294. if (IsDataLeft) {
  2295. // Get the first route in the table
  2296. IsDataLeft = GetNextRoute(IteratorContext, &RTE);
  2297. while (IsDataLeft) {
  2298. // Keep copy of current route and advance to next
  2299. PrevRTE = RTE;
  2300. // Read next route, before operating on current
  2301. IsDataLeft = GetNextRoute(IteratorContext, &RTE);
  2302. // Work on current route (already got next one)
  2303. if (!(*CallFunc) (PrevRTE, Context, Context1)) {
  2304. IPRouteNotifyOutput RNO = {0};
  2305. RtChangeList *NewRtChange;
  2306. // Retrieve information about the route for change-notification
  2307. // before proceeding with deletion.
  2308. RNO.irno_dest = PrevRTE->rte_dest;
  2309. RNO.irno_mask = PrevRTE->rte_mask;
  2310. RNO.irno_nexthop = GetNextHopForRTE(PrevRTE);
  2311. RNO.irno_proto = PrevRTE->rte_proto;
  2312. RNO.irno_ifindex = PrevRTE->rte_if->if_index;
  2313. RNO.irno_metric = PrevRTE->rte_metric;
  2314. RNO.irno_flags = IRNO_FLAG_DELETE;
  2315. // Delete the route and perform cleanup.
  2316. DelRoute(PrevRTE->rte_dest, PrevRTE->rte_mask,
  2317. PrevRTE->rte_addr, PrevRTE->rte_if, MATCH_FULL,
  2318. &PrevRTE, &pOldBestRTE, &pNewBestRTE);
  2319. CleanupP2MP_RTE(PrevRTE);
  2320. CleanupRTE(PrevRTE);
  2321. // Allocate, initialize and queue a change-notification entry
  2322. // for the deleted route.
  2323. NewRtChange = CTEAllocMemNBoot(sizeof(RtChangeList), '9iCT');
  2324. if (NewRtChange != NULL) {
  2325. NewRtChange->rt_next = CurrentRtChangeList;
  2326. NewRtChange->rt_info = RNO;
  2327. CurrentRtChangeList = NewRtChange;
  2328. }
  2329. #if FFP_SUPPORT
  2330. FFPFlushRequired = TRUE;
  2331. #endif
  2332. }
  2333. }
  2334. // Work on last route [it was not processed in the loop]
  2335. PrevRTE = RTE;
  2336. if (!(*CallFunc) (PrevRTE, Context, Context1)) {
  2337. IPRouteNotifyOutput RNO = {0};
  2338. RtChangeList *NewRtChange;
  2339. // Retrieve information about the route for change-notification
  2340. // before proceeding with deletion.
  2341. RNO.irno_dest = PrevRTE->rte_dest;
  2342. RNO.irno_mask = PrevRTE->rte_mask;
  2343. RNO.irno_nexthop = GetNextHopForRTE(PrevRTE);
  2344. RNO.irno_proto = PrevRTE->rte_proto;
  2345. RNO.irno_ifindex = PrevRTE->rte_if->if_index;
  2346. RNO.irno_metric = PrevRTE->rte_metric;
  2347. RNO.irno_flags = IRNO_FLAG_DELETE;
  2348. // Delete the route and perform cleanup.
  2349. DelRoute(PrevRTE->rte_dest, PrevRTE->rte_mask, PrevRTE->rte_addr,
  2350. PrevRTE->rte_if, MATCH_FULL, &PrevRTE, &pOldBestRTE,
  2351. &pNewBestRTE);
  2352. CleanupP2MP_RTE(PrevRTE);
  2353. CleanupRTE(PrevRTE);
  2354. // Allocate, initialize and queue a change-notification entry
  2355. // for the deleted route.
  2356. NewRtChange = CTEAllocMemNBoot(sizeof(RtChangeList), '0iCT');
  2357. if (NewRtChange != NULL) {
  2358. NewRtChange->rt_next = CurrentRtChangeList;
  2359. NewRtChange->rt_info = RNO;
  2360. CurrentRtChangeList = NewRtChange;
  2361. }
  2362. #if FFP_SUPPORT
  2363. FFPFlushRequired = TRUE;
  2364. #endif
  2365. }
  2366. }
  2367. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2368. // Call RtChangeNotify for each of the entries in the change-notification
  2369. // list that we've built up so far. In the process, free each entry.
  2370. if (CurrentRtChangeList) {
  2371. RtChangeList *TmpRtChangeList;
  2372. do {
  2373. TmpRtChangeList = CurrentRtChangeList->rt_next;
  2374. RtChangeNotify(&CurrentRtChangeList->rt_info);
  2375. CTEFreeMem(CurrentRtChangeList);
  2376. CurrentRtChangeList = TmpRtChangeList;
  2377. } while(CurrentRtChangeList);
  2378. }
  2379. }
  2380. uint
  2381. AttachRCEToNewRTE(RouteTableEntry *NewRTE, RouteCacheEntry *RCE,
  2382. RouteTableEntry *OldRTE)
  2383. {
  2384. CTELockHandle TableHandle, RCEHandle;
  2385. RouteCacheEntry *tempRCE, *CurrentRCE;
  2386. NetTableEntry *NTE;
  2387. uint Status = 1;
  2388. uint RCE_usecnt;
  2389. if (RCE == NULL) {
  2390. CurrentRCE = OldRTE->rte_rcelist;
  2391. } else {
  2392. CurrentRCE = RCE;
  2393. }
  2394. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AttachRCETonewRTE %x %x %x\n", NewRTE, RCE, OldRTE));
  2395. // OldRTE = RCE->rce_rte;
  2396. //associate all the RCEs with this RTE
  2397. while (CurrentRCE != NULL) {
  2398. RCE_usecnt = InvalidateRCE(CurrentRCE);
  2399. CTEGetLock(&CurrentRCE->rce_lock, &RCEHandle);
  2400. tempRCE = CurrentRCE->rce_next;
  2401. // if no one is using this go ahead and
  2402. // mark this as valid
  2403. if (RCE_usecnt == 0) {
  2404. //Make sure that the src address for RCE is valid
  2405. //for this RTE
  2406. NTE = NewRTE->rte_if->if_nte;
  2407. while (NTE) {
  2408. if ((NTE->nte_flags & NTE_VALID) &&
  2409. IP_ADDR_EQUAL(CurrentRCE->rce_src, NTE->nte_addr))
  2410. break;
  2411. NTE = NTE->nte_ifnext;
  2412. }
  2413. if (NTE != NULL) {
  2414. if (CurrentRCE->rce_flags & RCE_CONNECTED) {
  2415. Interface *IF = (Interface*)CurrentRCE->rce_rte;
  2416. (*(IF->if_invalidate))(IF->if_lcontext, CurrentRCE);
  2417. if (CurrentRCE->rce_flags & RCE_REFERENCED) {
  2418. LockedDerefIF(IF);
  2419. CurrentRCE->rce_flags &= ~RCE_REFERENCED;
  2420. }
  2421. } else {
  2422. ASSERT(!(CurrentRCE->rce_flags & RCE_REFERENCED));
  2423. }
  2424. // Link the RCE on the RTE, and set up the back pointer.
  2425. CurrentRCE->rce_rte = NewRTE;
  2426. CurrentRCE->rce_flags |= RCE_VALID;
  2427. CurrentRCE->rce_next = NewRTE->rte_rcelist;
  2428. NewRTE->rte_rcelist = CurrentRCE;
  2429. NewRTE->rte_rces += CurrentRCE->rce_cnt;
  2430. if ((NewRTE->rte_flags & RTE_IF_VALID)) {
  2431. CurrentRCE->rce_flags |= (RCE_CONNECTED | RCE_REFERENCED);
  2432. LOCKED_REFERENCE_IF(NewRTE->rte_if);
  2433. } else {
  2434. ASSERT(FALSE);
  2435. CurrentRCE->rce_flags &= ~RCE_CONNECTED;
  2436. Status = FALSE;
  2437. }
  2438. } //if NTE!=NULL
  2439. } else {
  2440. // In use. Mark it as in dead gw transit mmode
  2441. // so that attachtorte will do the right thing
  2442. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AttachRCETonewRTE RCE busy\n"));
  2443. // CurrentRCE->rce_rte = NewRTE;
  2444. CurrentRCE->rce_flags |= RCE_DEADGW;
  2445. } //in use
  2446. CTEFreeLock(&CurrentRCE->rce_lock, RCEHandle);
  2447. //if there is only one RCE to be switched, break.
  2448. if (RCE)
  2449. break;
  2450. CurrentRCE = tempRCE;
  2451. } //while
  2452. return (Status);
  2453. }
  2454. //** AttachRCEToRTE - Attach an RCE to an RTE.
  2455. //
  2456. // This procedure takes an RCE, finds the appropriate RTE, and attaches it.
  2457. // We check to make sure that the source address is still valid.
  2458. //
  2459. // Entry: RCE - RCE to be attached.
  2460. // Protocol - Protocol type for packet causing this call.
  2461. // Buffer - Pointer to buffer for packet causing this
  2462. // call.
  2463. // Length - Length of buffer.
  2464. //
  2465. // Returns: TRUE if we attach it, false if we don't.
  2466. //
  2467. uint
  2468. AttachRCEToRTE(RouteCacheEntry *RCE, uchar Protocol, uchar *Buffer, uint Length)
  2469. {
  2470. CTELockHandle TableHandle, RCEHandle;
  2471. RouteTableEntry *RTE;
  2472. NetTableEntry *NTE;
  2473. uint Status;
  2474. NetTableEntry *NetTableList;
  2475. CTEGetLock(&RouteTableLock.Lock, &TableHandle);
  2476. NetTableList = NewNetTableList[NET_TABLE_HASH(RCE->rce_src)];
  2477. for (NTE = NetTableList; NTE != NULL; NTE = NTE->nte_next)
  2478. if ((NTE->nte_flags & NTE_VALID) &&
  2479. IP_ADDR_EQUAL(RCE->rce_src, NTE->nte_addr))
  2480. break;
  2481. if (NTE == NULL) {
  2482. // Didn't find a match.
  2483. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  2484. return FALSE;
  2485. }
  2486. if ((RCE->rce_flags == RCE_VALID) && (RCE->rce_rte->rte_flags != RTE_IF_VALID)) {
  2487. RTE = RCE->rce_rte;
  2488. } else {
  2489. RTE = LookupRTE(RCE->rce_dest, RCE->rce_src, HOST_ROUTE_PRI, FALSE);
  2490. }
  2491. if (RTE == NULL) {
  2492. // No route! Fail the call.
  2493. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  2494. return FALSE;
  2495. }
  2496. // Check if this RCE is in transition (usecnt did not permit
  2497. // to swicthover earlier)
  2498. if ((RCE->rce_flags & RCE_DEADGW) && (RCE->rce_rte != RTE)) {
  2499. RouteTableEntry *tmpRTE = NULL;
  2500. // Scan through DefaultGWs checking
  2501. // for a GW that is in the process of
  2502. // taking over from the current one.
  2503. if (RTE->rte_todg) {
  2504. tmpRTE = GetDefaultGWs(&tmpRTE);
  2505. while (tmpRTE) {
  2506. if (tmpRTE == RTE->rte_todg) {
  2507. break;
  2508. }
  2509. tmpRTE = tmpRTE->rte_next;
  2510. }
  2511. }
  2512. if (tmpRTE) {
  2513. // Remove references to GW
  2514. // in transition and the current one
  2515. ASSERT(tmpRTE->rte_fromdg == RTE);
  2516. tmpRTE->rte_fromdg = NULL;
  2517. RTE->rte_todg = NULL;
  2518. }
  2519. Rcefailures++;
  2520. }
  2521. Status = TRUE;
  2522. // Yep, we found one. Get the lock on the RCE, and make sure he's
  2523. // not pointing at an RTE already. We also need to make sure that the usecnt
  2524. // is 0, so that we can invalidate the RCE at the low level. If we set valid
  2525. // to TRUE without doing this we may get into a wierd situation where we
  2526. // link the RCE onto an RTE but the lower layer information is wrong, so we
  2527. // send to IP address X at mac address Y. So to be safe we don't set valid
  2528. // to TRUE until both usecnt is 0 and valid is FALSE. We'll keep coming
  2529. // through this routine on every send until that happens.
  2530. CTEGetLock(&RCE->rce_lock, &RCEHandle);
  2531. if (RCE->rce_usecnt == 0) {
  2532. // Nobody is using him, so we can link him up.
  2533. if (!(RCE->rce_flags & RCE_VALID)) {
  2534. Interface *IF, *tmpIF;
  2535. // He's not valid. Invalidate the lower layer info, just in
  2536. // case. Make sure he's connected before we try to do this. If
  2537. // he's not marked as connected, don't bother to try and invalidate
  2538. // him as there is no interface.
  2539. if (RCE->rce_flags & RCE_CONNECTED) {
  2540. IF = (Interface *) RCE->rce_rte;
  2541. // invalidating this IF can fail in PNP world. An invalid RCE can not be found on on RTE list
  2542. // to be invalidated if Interface decides to take off!
  2543. // So, check the sanity of the interface
  2544. for (tmpIF = IFList; tmpIF != NULL; tmpIF = tmpIF->if_next) {
  2545. if (tmpIF == IF)
  2546. break;
  2547. }
  2548. if (tmpIF) {
  2549. (*(IF->if_invalidate)) (IF->if_lcontext, RCE);
  2550. } else {
  2551. RtlZeroMemory(RCE->rce_context, RCE_CONTEXT_SIZE);
  2552. }
  2553. if (RCE->rce_flags & RCE_REFERENCED) {
  2554. if (tmpIF)
  2555. LockedDerefIF(IF);
  2556. RCE->rce_flags &= ~RCE_REFERENCED;
  2557. }
  2558. } else {
  2559. ASSERT(!(RCE->rce_flags & RCE_REFERENCED));
  2560. }
  2561. // Link the RCE on the RTE, and set up the back pointer.
  2562. RCE->rce_rte = RTE;
  2563. RCE->rce_flags |= RCE_VALID;
  2564. RCE->rce_next = RTE->rte_rcelist;
  2565. RTE->rte_rcelist = RCE;
  2566. RTE->rte_rces += RCE->rce_cnt;
  2567. RCE->rce_flags &= ~RCE_DEADGW;
  2568. // Make sure the RTE is connected. If not, try to connect him.
  2569. if (!(RTE->rte_flags & RTE_IF_VALID)) {
  2570. // Not connected. Try to connect him.
  2571. RTE = FindValidIFForRTE(RTE, RCE->rce_dest, RCE->rce_src,
  2572. Protocol, Buffer, Length, RCE->rce_src);
  2573. if (RTE != NULL) {
  2574. // Got one, so mark as connected.
  2575. ASSERT(!(RCE->rce_flags & RCE_REFERENCED));
  2576. RCE->rce_flags |= (RCE_CONNECTED | RCE_REFERENCED);
  2577. LOCKED_REFERENCE_IF(RTE->rte_if);
  2578. } else {
  2579. // Couldn't get a valid i/f. Mark the RCE as not connected,
  2580. // and set up to fail this call.
  2581. RCE->rce_flags &= ~RCE_CONNECTED;
  2582. Status = FALSE;
  2583. }
  2584. } else {
  2585. // The RTE is connected, mark the RCE as connected.
  2586. ASSERT(!(RCE->rce_flags & RCE_REFERENCED));
  2587. RCE->rce_flags |= (RCE_CONNECTED | RCE_REFERENCED);
  2588. LOCKED_REFERENCE_IF(RTE->rte_if);
  2589. }
  2590. } else {
  2591. // The RCE is valid. See if it's connected.
  2592. if (!(RCE->rce_flags & RCE_CONNECTED)) {
  2593. // Not connected, try to get a valid i/f.
  2594. if (!(RTE->rte_flags & RTE_IF_VALID)) {
  2595. RTE = FindValidIFForRTE(RTE, RCE->rce_dest, RCE->rce_src,
  2596. Protocol, Buffer, Length, RCE->rce_src);
  2597. if (RTE != NULL) {
  2598. RCE->rce_flags |= RCE_CONNECTED;
  2599. ASSERT(!(RCE->rce_flags & RCE_REFERENCED));
  2600. ASSERT(RTE == RCE->rce_rte);
  2601. RCE->rce_flags |= RCE_REFERENCED;
  2602. LOCKED_REFERENCE_IF(RTE->rte_if);
  2603. } else {
  2604. // Couldn't connect, so fail.
  2605. Status = FALSE;
  2606. }
  2607. } else { // Already connected, just mark as valid.
  2608. RCE->rce_flags |= RCE_CONNECTED;
  2609. if (!(RCE->rce_flags & RCE_REFERENCED)) {
  2610. RCE->rce_flags |= RCE_REFERENCED;
  2611. LOCKED_REFERENCE_IF(RTE->rte_if);
  2612. }
  2613. }
  2614. }
  2615. }
  2616. }
  2617. // Free the locks and we're done.
  2618. CTEFreeLock(&RCE->rce_lock, RCEHandle);
  2619. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  2620. return Status;
  2621. }
  2622. //** IPGetPInfo - Get information..
  2623. //
  2624. // Called by an upper layer to get information about a path. We return the
  2625. // MTU of the path and the maximum link speed to be expected on the path.
  2626. //
  2627. // Input: Dest - Destination address.
  2628. // Src - Src address.
  2629. // NewMTU - Where to store path MTU (may be NULL).
  2630. // MaxPathSpeed - Where to store maximum path speed (may be NULL).
  2631. // RCE - RCE to be used to find the route
  2632. //
  2633. // Returns: Status of attempt to get new MTU.
  2634. //
  2635. IP_STATUS
  2636. IPGetPInfo(IPAddr Dest, IPAddr Src, uint * NewMTU, uint *MaxPathSpeed,
  2637. RouteCacheEntry *RCE)
  2638. {
  2639. CTELockHandle Handle;
  2640. RouteTableEntry *RTE = NULL;
  2641. IP_STATUS Status;
  2642. if (RCE) {
  2643. CTEGetLock(&RCE->rce_lock, &Handle);
  2644. if (RCE->rce_flags == RCE_ALL_VALID) {
  2645. RTE = RCE->rce_rte;
  2646. }
  2647. CTEFreeLock(&RCE->rce_lock, Handle);
  2648. }
  2649. CTEGetLock(&RouteTableLock.Lock, &Handle);
  2650. if (!RTE) {
  2651. RTE = LookupRTE(Dest, Src, HOST_ROUTE_PRI, FALSE);
  2652. }
  2653. if (RTE != NULL) {
  2654. if (NewMTU != NULL) {
  2655. // if the route is on a P2MP interface get the mtu from the link associated with the route
  2656. if (RTE->rte_link)
  2657. *NewMTU = RTE->rte_link->link_mtu;
  2658. else
  2659. *NewMTU = RTE->rte_mtu;
  2660. }
  2661. if (MaxPathSpeed != NULL)
  2662. *MaxPathSpeed = RTE->rte_if->if_speed;
  2663. Status = IP_SUCCESS;
  2664. } else
  2665. Status = IP_DEST_HOST_UNREACHABLE;
  2666. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2667. return Status;
  2668. }
  2669. //** IPCheckRoute - Check that a route is valid.
  2670. //
  2671. // Called by an upper layer when it believes a route might be invalid.
  2672. // We'll check if we can. If the upper layer is getting there through a
  2673. // route derived via ICMP (presumably a redirect) we'll check to see
  2674. // if it's been learned within the last minute. If it has, it's assumed
  2675. // to still be valid. Otherwise, we'll mark it as down and try to find
  2676. // another route there. If we can, we'll delete the old route. Otherwise
  2677. // we'll leave it. If the route is through a default gateway we'll switch
  2678. // to another one if we can. Otherwise, we'll just leave - we don't mess
  2679. // with manually configured routes.
  2680. //
  2681. // Input: Dest - Destination to be reached.
  2682. // Src - Src we're sending from.
  2683. // RCE - route-cache-entry to be updated.
  2684. // OptInfo - options to use if recreating the RCE
  2685. // CheckRouteFlag - modifies this routine's behavior
  2686. //
  2687. // Returns: Nothing.
  2688. //
  2689. void
  2690. IPCheckRoute(IPAddr Dest, IPAddr Src, RouteCacheEntry * RCE, IPOptInfo *OptInfo,
  2691. uint CheckRouteFlag)
  2692. {
  2693. RouteTableEntry *RTE;
  2694. RouteTableEntry *NewRTE;
  2695. RouteTableEntry *TempRTE;
  2696. CTELockHandle Handle;
  2697. uint Now = CTESystemUpTime() / 1000L;
  2698. if (DeadGWDetect) {
  2699. uint UnicastIf;
  2700. // We are doing dead G/W detection. Get the lock, and try and
  2701. // find the route.
  2702. // Decide whether to do a strong or weak host lookup.
  2703. UnicastIf = GetIfConstraint(Dest, Src, OptInfo, FALSE);
  2704. CTEGetLock(&RouteTableLock.Lock, &Handle);
  2705. RTE = LookupRTE(Dest, Src, HOST_ROUTE_PRI, UnicastIf);
  2706. if (RTE != NULL && ((Now - RTE->rte_valid) > MIN_RT_VALID)) {
  2707. // Found a route, and it's older than the minimum valid time. If it
  2708. // goes through a G/W, and is a route we learned via ICMP or is a
  2709. // default route, do something with it.
  2710. if (!IP_ADDR_EQUAL(RTE->rte_addr, IPADDR_LOCAL)) {
  2711. // It is through a G/W.
  2712. if (RTE->rte_proto == IRE_PROTO_ICMP) {
  2713. // Came from ICMP. Mark as invalid, and then make sure
  2714. // we have another route there.
  2715. RTE->rte_flags &= ~RTE_VALID;
  2716. NewRTE = LookupRTE(Dest, Src, HOST_ROUTE_PRI, UnicastIf);
  2717. if (NewRTE == NULL) {
  2718. // Can't get there any other way so leave this
  2719. // one alone.
  2720. RTE->rte_flags |= RTE_VALID;
  2721. // Re validate all the other gateways
  2722. InvalidateRCEChain(RTE);
  2723. ValidateDefaultGWs(NULL_IP_ADDR);
  2724. }
  2725. // The discovered route under the
  2726. // NTE is not cleaned up.
  2727. // Since deleting the route itself does not serve any purpose and
  2728. // the route will time out eventually, let us leave this
  2729. // as invalid.
  2730. } else {
  2731. if (RTE->rte_mask == DEFAULT_MASK) {
  2732. // This is a default gateway. If we have more than one
  2733. // configured move to the next one.
  2734. if (DefGWConfigured > 1) {
  2735. // Have more than one. Try the next one. First
  2736. // invalidate any RCEs on this G/W.
  2737. if (DefGWActive == 1) {
  2738. // No more active. Revalidate all of them,
  2739. // and try again.
  2740. ValidateDefaultGWs(NULL_IP_ADDR);
  2741. // ASSERT(DefGWActive == DefGWConfigured);
  2742. } else {
  2743. //Make sure that we do not switch all the
  2744. //connections just because of a spurious
  2745. //dead gate way event.
  2746. //switch only when % of number of connections are
  2747. // failed over to the other gateway.
  2748. // if we have already found the next default gateway
  2749. // check if it is time to switch all the connections
  2750. // to it.
  2751. if (RTE->rte_todg) {
  2752. #if DBG
  2753. {
  2754. RouteTableEntry *tmpRTE = NULL;
  2755. tmpRTE = GetDefaultGWs(&tmpRTE);
  2756. while (tmpRTE) {
  2757. if (tmpRTE == RTE->rte_todg) {
  2758. break;
  2759. }
  2760. tmpRTE = tmpRTE->rte_next;
  2761. }
  2762. if (tmpRTE == NULL) {
  2763. DbgBreakPoint();
  2764. }
  2765. }
  2766. #endif
  2767. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"to todg %lx\n", RTE));
  2768. // If the alternate gateway now has 25%
  2769. // as many as the active gateway
  2770. // and the caller has not requested
  2771. // a switch for this RCE only,
  2772. // invalidate the active gateway and
  2773. // select the alternate as the new default.
  2774. if ((RTE->rte_rcelist == RCE &&
  2775. RCE->rce_next == NULL) ||
  2776. (RTE->rte_todg->rte_rces >=
  2777. (RTE->rte_rces >> 2) &&
  2778. !(CheckRouteFlag & CHECK_RCE_ONLY))) {
  2779. //Switch every one.
  2780. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," Switching every one %x to %x\n", RTE->rte_todg, RTE));
  2781. --DefGWActive;
  2782. RTE->rte_flags &= ~RTE_VALID;
  2783. UpdateDeadGWState();
  2784. RTE->rte_todg->rte_fromdg = NULL;
  2785. RTE->rte_todg = NULL;
  2786. if (RTE->rte_fromdg) {
  2787. RTE->rte_fromdg->rte_todg = NULL;
  2788. }
  2789. RTE->rte_fromdg = NULL;
  2790. InvalidateRCEChain(RTE);
  2791. //ASSERT(RTE->rte_rces == 0);
  2792. } else {
  2793. //Switch this particular connection to the new one.
  2794. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," attaching RCE %x to newrte %x\n", RCE, RTE->rte_todg));
  2795. AttachRCEToNewRTE(RTE->rte_todg, RCE, RTE);
  2796. }
  2797. } else if (RTE->rte_fromdg) {
  2798. // find if there are any other gateways other than
  2799. // fromdg and switch to that.
  2800. // Note that if we have more than 3 default gateways
  2801. // configured, this algorithm does not do a god job
  2802. RouteTableEntry *OldRTE = RTE;
  2803. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"GW %x goofed. RTEfromdg %x\n",RTE,RTE->rte_fromdg));
  2804. --DefGWActive;
  2805. UpdateDeadGWState();
  2806. // turn on dead gw flag to tell findrte not to consider this rte
  2807. RTE->rte_flags |= RTE_DEADGW;
  2808. RTE->rte_fromdg->rte_flags |= RTE_DEADGW;
  2809. RTE = FindRTE(Dest, Src, 0,
  2810. DEFAULT_ROUTE_PRI,
  2811. DEFAULT_ROUTE_PRI, UnicastIf);
  2812. OldRTE->rte_flags &= ~RTE_DEADGW;
  2813. OldRTE->rte_fromdg->rte_flags &= ~RTE_DEADGW;
  2814. if (RTE == NULL) {
  2815. // No more default gateways! This is bad.
  2816. //ASSERT(FALSE);
  2817. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"No more def routes!\n"));
  2818. OldRTE->rte_fromdg->rte_todg = NULL;
  2819. OldRTE->rte_fromdg->rte_fromdg = NULL;
  2820. OldRTE->rte_fromdg = NULL;
  2821. OldRTE->rte_todg = NULL;
  2822. ValidateDefaultGWs(NULL_IP_ADDR);
  2823. //ASSERT(DefGWActive == DefGWConfigured);
  2824. } else {
  2825. // we have a third gateway to try!
  2826. // ASSERT(RTE->rte_mask == DEFAULT_MASK);
  2827. //Treat OldRTE as dead!
  2828. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Trying next def route %x\n",RTE));
  2829. OldRTE->rte_flags &= ~RTE_VALID;
  2830. RTE->rte_fromdg = OldRTE->rte_fromdg;
  2831. RTE->rte_fromdg->rte_todg = RTE;
  2832. if (OldRTE->rte_todg)
  2833. OldRTE->rte_todg->rte_fromdg = NULL;
  2834. OldRTE->rte_todg = NULL;
  2835. OldRTE->rte_fromdg = NULL;
  2836. //Attach all the RCEs to the new one
  2837. AttachRCEToNewRTE(RTE, NULL, OldRTE);
  2838. RTE->rte_valid = Now;
  2839. }
  2840. } else {
  2841. //find the next potential default gateway
  2842. RouteTableEntry *OldRTE = RTE;
  2843. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Finding potential GW\n" ));
  2844. OldRTE->rte_flags |= RTE_DEADGW;
  2845. RTE = FindRTE(Dest, Src, 0,
  2846. DEFAULT_ROUTE_PRI,
  2847. DEFAULT_ROUTE_PRI, UnicastIf);
  2848. OldRTE->rte_flags &= ~RTE_DEADGW;
  2849. if (RTE == NULL) {
  2850. // No more default gateways! This is bad.
  2851. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," ---No more def routes!\n"));
  2852. // ASSERT(FALSE);
  2853. ValidateDefaultGWs(NULL_IP_ADDR);
  2854. //ASSERT(DefGWActive == DefGWConfigured);
  2855. } else {
  2856. ASSERT(RTE->rte_mask == DEFAULT_MASK);
  2857. //remember the new gw until we transition fully
  2858. OldRTE->rte_todg = RTE;
  2859. RTE->rte_fromdg = OldRTE;
  2860. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"FoundGW %x\n",RTE));
  2861. //Attach this RCE to use the new RTE
  2862. AttachRCEToNewRTE(RTE, RCE, OldRTE);
  2863. RTE->rte_valid = Now;
  2864. }
  2865. }
  2866. }
  2867. }
  2868. }
  2869. }
  2870. }
  2871. }
  2872. CTEFreeLock(&RouteTableLock.Lock, Handle);
  2873. }
  2874. }
  2875. //** FindRCE - Find an RCE on an RTE.
  2876. //
  2877. // A routine to find an RCE that's chained on an RTE. We assume the lock
  2878. // is held on the RTE.
  2879. //
  2880. // Entry: RTE - RTE to search.
  2881. // Dest - Destination address of RTE to find.
  2882. // Src - Source address of RTE to find.
  2883. //
  2884. // Returns: Pointer to RTE found, or NULL.
  2885. //
  2886. RouteCacheEntry *
  2887. FindRCE(RouteTableEntry * RTE, IPAddr Dest, IPAddr Src)
  2888. {
  2889. RouteCacheEntry *CurrentRCE;
  2890. ASSERT(!IP_ADDR_EQUAL(Src, NULL_IP_ADDR));
  2891. for (CurrentRCE = RTE->rte_rcelist; CurrentRCE != NULL;
  2892. CurrentRCE = CurrentRCE->rce_next) {
  2893. if (IP_ADDR_EQUAL(CurrentRCE->rce_dest, Dest) &&
  2894. IP_ADDR_EQUAL(CurrentRCE->rce_src, Src)) {
  2895. break;
  2896. }
  2897. }
  2898. return CurrentRCE;
  2899. }
  2900. //** OpenRCE - Open an RCE for a specific route.
  2901. //
  2902. // Called by the upper layer to open an RCE. We look up the type of the address
  2903. // - if it's invalid, we return 'Destination invalid'. If not, we look up the
  2904. // route, fill in the RCE, and link it on the correct RTE.
  2905. //
  2906. // As an added bonus, this routine will return the local address to use
  2907. // to reach the destination.
  2908. //
  2909. // Entry: Address - Address for which we are to open an RCE.
  2910. // Src - Source address we'll be using.
  2911. // RCE - Pointer to where to return pointer to RCE.
  2912. // Type - Pointer to where to return destination type.
  2913. // MSS - Pointer to where to return MSS for route.
  2914. // OptInfo - Pointer to option information, such as TOS and
  2915. // any source routing info.
  2916. //
  2917. // Returns: Source IP address to use. This will be NULL_IP_ADDR if the
  2918. // specified destination is unreachable for any reason.
  2919. //
  2920. IPAddr
  2921. OpenRCE(IPAddr Address, IPAddr Src, RouteCacheEntry ** RCE, uchar * Type,
  2922. ushort * MSS, IPOptInfo * OptInfo)
  2923. {
  2924. RouteTableEntry *RTE; // Pointer to RTE to put RCE on.
  2925. CTELockHandle TableLock;
  2926. uchar LocalType;
  2927. NetTableEntry *RealNTE = NULL;
  2928. uint ConstrainIF = 0;
  2929. if (!IP_ADDR_EQUAL(OptInfo->ioi_addr, NULL_IP_ADDR))
  2930. Address = OptInfo->ioi_addr;
  2931. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  2932. LocalType = GetAddrType(Address);
  2933. *Type = LocalType;
  2934. // If the specified address isn't invalid, continue.
  2935. if (LocalType != DEST_INVALID) {
  2936. RouteCacheEntry *NewRCE;
  2937. // If he's specified a source address, loop through the NTE table
  2938. // now and make sure it's valid.
  2939. if (!IP_ADDR_EQUAL(Src, NULL_IP_ADDR)) {
  2940. NetTableEntry *NTE;
  2941. NetTableEntry *NetTableList = NewNetTableList[NET_TABLE_HASH(Src)];
  2942. for (NTE = NetTableList; NTE != NULL; NTE = NTE->nte_next)
  2943. if ((NTE->nte_flags & NTE_VALID) &&
  2944. IP_ADDR_EQUAL(Src, NTE->nte_addr))
  2945. break;
  2946. if (NTE == NULL) {
  2947. // Didn't find a match.
  2948. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  2949. return NULL_IP_ADDR;
  2950. }
  2951. // Decide whether to do a strong or weak host lookup
  2952. // No need to do this in case of unidirectional adapter.
  2953. // On unidirectional adapter sends are not permitted.
  2954. // If this openrce is called before setting specific mcast
  2955. // Address (ioi_mcastif) GetIfConstraint for mcast will fail.
  2956. // For W9x backward compatibility reasons, we will let
  2957. // OpenRce succeed even if ioi_mcast if is not set, as an
  2958. // exception in the case of unidirectional adapter. Side effect
  2959. // of this will be - when a send is attempted on this endpoint
  2960. // with this cached rce, it will go out on a random interface.
  2961. //
  2962. if (!(NTE->nte_if->if_flags & IF_FLAGS_UNI)) {
  2963. ConstrainIF = GetIfConstraint(Address, Src, OptInfo, FALSE);
  2964. }
  2965. } else {
  2966. ConstrainIF = GetIfConstraint(Address, Src, OptInfo, FALSE);
  2967. }
  2968. // Find the route for this guy. If we can't find one, return NULL.
  2969. if (IP_LOOPBACK_ADDR(Src)) {
  2970. RTE = LookupRTE(Src, Src, HOST_ROUTE_PRI, ConstrainIF);
  2971. if (RTE) {
  2972. ASSERT(RTE->rte_if == &LoopInterface);
  2973. } else {
  2974. KdPrint(("No Loopback rte!\n"));
  2975. ASSERT(0);
  2976. }
  2977. } else {
  2978. RTE = LookupRTE(Address, Src, HOST_ROUTE_PRI, ConstrainIF);
  2979. }
  2980. if (RTE != (RouteTableEntry *) NULL) {
  2981. CTELockHandle RCEHandle;
  2982. RouteCacheEntry *OldRCE;
  2983. //
  2984. // Make sure interface is not shutting down. Should we also check for
  2985. // IF_FLAGS_DELETING?
  2986. //
  2987. if (IS_IF_INVALID(RTE->rte_if) && RTE->rte_if->if_ntecount) {
  2988. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  2989. return NULL_IP_ADDR;
  2990. }
  2991. if (OptInfo->ioi_uni) {
  2992. //LookupRTE returns first route n the chain of
  2993. //unnumbered ifs.
  2994. //if this is not the one desired, scan further
  2995. RouteTableEntry *tmpRTE = RTE;
  2996. while (tmpRTE && (tmpRTE->rte_if->if_index != OptInfo->ioi_uni)) {
  2997. tmpRTE = tmpRTE->rte_next;
  2998. }
  2999. if (!tmpRTE) {
  3000. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"OpenRCE:No matching unnumbered interface %d\n", OptInfo->ioi_uni));
  3001. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3002. return NULL_IP_ADDR;
  3003. } else
  3004. RTE = tmpRTE;
  3005. }
  3006. // We found one.
  3007. // if the route is on a P2MP interface get the mtu from the link associated with the route
  3008. if (RTE->rte_link)
  3009. *MSS = (ushort) RTE->rte_link->link_mtu;
  3010. else
  3011. *MSS = (ushort) RTE->rte_mtu; // Return the route MTU.
  3012. if (IP_LOOPBACK_ADDR(Src) && (RTE->rte_if != &LoopInterface)) {
  3013. // The upper layer is sending from a loopback address, but the
  3014. // destination isn't reachable through the loopback interface.
  3015. // Fail the request.
  3016. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3017. return NULL_IP_ADDR;
  3018. }
  3019. // We have the RTE. Fill in the RCE, and link it on the RTE.
  3020. if (!IP_ADDR_EQUAL(RTE->rte_addr, IPADDR_LOCAL))
  3021. *Type |= DEST_OFFNET_BIT; // Tell upper layer it's off
  3022. // net.
  3023. //
  3024. // If no source address was specified, then use the best address
  3025. // for the interface. This will generally prevent dynamic NTE's from
  3026. // being chosen as the source for wildcard binds.
  3027. //
  3028. if (IP_ADDR_EQUAL(Src, NULL_IP_ADDR)) {
  3029. if (LocalType == DEST_LOCAL) {
  3030. Src = Address;
  3031. RealNTE = LoopNTE;
  3032. } else {
  3033. NetTableEntry *SrcNTE;
  3034. if ((RTE->rte_if->if_flags & IF_FLAGS_NOIPADDR) && (IP_ADDR_EQUAL(RTE->rte_if->if_nte->nte_addr, NULL_IP_ADDR))) {
  3035. Src = g_ValidAddr;
  3036. if (IP_ADDR_EQUAL(Src, NULL_IP_ADDR)) {
  3037. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3038. return NULL_IP_ADDR;
  3039. }
  3040. } else {
  3041. SrcNTE = BestNTEForIF(
  3042. ADDR_FROM_RTE(RTE, Address),
  3043. RTE->rte_if
  3044. );
  3045. if (SrcNTE == NULL) {
  3046. // Can't find an address! Fail the request.
  3047. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3048. return NULL_IP_ADDR;
  3049. }
  3050. Src = SrcNTE->nte_addr;
  3051. }
  3052. }
  3053. }
  3054. // Now, see if an RCE already exists for this.
  3055. if (RCE == NULL) {
  3056. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Openrce with null RCE!! %x\n",Src));
  3057. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3058. return Src;
  3059. }
  3060. if ((OldRCE = FindRCE(RTE, Address, Src)) == NULL) {
  3061. // Don't have an existing RCE. See if we can get a new one,
  3062. // and fill it in.
  3063. NewRCE = CTEAllocMemNBoot(sizeof(RouteCacheEntry), 'AiCT');
  3064. *RCE = NewRCE;
  3065. if (NewRCE != NULL) {
  3066. RtlZeroMemory(NewRCE, sizeof(RouteCacheEntry));
  3067. NewRCE->rce_src = Src;
  3068. NewRCE->rce_dtype = LocalType;
  3069. NewRCE->rce_cnt = 1;
  3070. CTEInitLock(&NewRCE->rce_lock);
  3071. NewRCE->rce_dest = Address;
  3072. NewRCE->rce_rte = RTE;
  3073. NewRCE->rce_flags = RCE_VALID;
  3074. if (RTE->rte_flags & RTE_IF_VALID) {
  3075. NewRCE->rce_flags |= RCE_CONNECTED;
  3076. //* Update the ref. count for this interface.
  3077. NewRCE->rce_flags |= RCE_REFERENCED;
  3078. LOCKED_REFERENCE_IF(RTE->rte_if);
  3079. // We register the chksum capability of the interface
  3080. // associated with this RCE, because interface definitions
  3081. // are transparent to TCP or UDP.
  3082. if (!IPSecStatus) {
  3083. NewRCE->rce_OffloadFlags = RTE->rte_if->if_OffloadFlags;
  3084. } else {
  3085. NewRCE->rce_OffloadFlags = 0;
  3086. }
  3087. NewRCE->rce_TcpLargeSend.MaxOffLoadSize = RTE->rte_if->if_MaxOffLoadSize;
  3088. NewRCE->rce_TcpLargeSend.MinSegmentCount = RTE->rte_if->if_MaxSegments;
  3089. NewRCE->rce_TcpWindowSize = RTE->rte_if->if_TcpWindowSize;
  3090. NewRCE->rce_TcpInitialRTT = RTE->rte_if->if_TcpInitialRTT;
  3091. NewRCE->rce_TcpDelAckTicks = RTE->rte_if->if_TcpDelAckTicks;
  3092. NewRCE->rce_TcpAckFrequency = RTE->rte_if->if_TcpAckFrequency;
  3093. NewRCE->rce_mediaspeed = RTE->rte_if->if_speed;
  3094. } //RTE_IF_VALID
  3095. NewRCE->rce_next = RTE->rte_rcelist;
  3096. RTE->rte_rcelist = NewRCE;
  3097. RTE->rte_rces++;
  3098. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3099. return Src;
  3100. } else {
  3101. // alloc failed
  3102. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3103. return NULL_IP_ADDR;
  3104. }
  3105. } else {
  3106. // We have an existing RCE. We'll return his source as the
  3107. // valid source, bump the reference count, free the locks
  3108. // and return.
  3109. CTEGetLock(&OldRCE->rce_lock, &RCEHandle);
  3110. OldRCE->rce_cnt++;
  3111. *RCE = OldRCE;
  3112. if (OldRCE->rce_newmtu) {
  3113. *MSS = (USHORT) OldRCE->rce_newmtu;
  3114. }
  3115. OldRCE->rce_rte->rte_rces++;
  3116. CTEFreeLock(&OldRCE->rce_lock, RCEHandle);
  3117. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3118. return Src;
  3119. }
  3120. } else {
  3121. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3122. return NULL_IP_ADDR;
  3123. }
  3124. }
  3125. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3126. return NULL_IP_ADDR;
  3127. }
  3128. void
  3129. FreeRCEToList(RouteCacheEntry * RCE)
  3130. /*++
  3131. Routine Description:
  3132. Free RCE to the RCEFreeList (since the use_cnt on it is non zero)
  3133. Called with routetable lock held
  3134. Arguments:
  3135. RCE : RCE to free
  3136. Return Value:
  3137. None
  3138. --*/
  3139. {
  3140. // link this new interface at the front of the list
  3141. RCE->rce_next = RCEFreeList;
  3142. RCEFreeList = RCE;
  3143. return;
  3144. }
  3145. //* CloseRCE - Close an RCE.
  3146. //
  3147. // Called by the upper layer when it wants to close the RCE. We unlink it from
  3148. // the RTE.
  3149. //
  3150. // Entry: RCE - Pointer to the RCE to be closed.
  3151. //
  3152. // Exit: Nothing.
  3153. //
  3154. void
  3155. CloseRCE(RouteCacheEntry * RCE)
  3156. {
  3157. RouteTableEntry *RTE; // Route on which RCE is linked.
  3158. RouteCacheEntry *PrevRCE;
  3159. CTELockHandle TableLock; // Lock handles used.
  3160. CTELockHandle RCEHandle;
  3161. Interface *IF;
  3162. Interface *tmpif = NULL;
  3163. uint FreetoRCEFreeList = 0;
  3164. if (RCE != NULL) {
  3165. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  3166. CTEGetLock(&RCE->rce_lock, &RCEHandle);
  3167. if ((RCE->rce_flags & RCE_VALID) && !(RCE->rce_flags & RCE_LINK_DELETED)) {
  3168. RCE->rce_rte->rte_rces--;
  3169. }
  3170. if (--RCE->rce_cnt == 0) {
  3171. // ASSERT(RCE->rce_usecnt == 0);
  3172. ASSERT(*(int *)&(RCE->rce_usecnt) >= 0);
  3173. if ((RCE->rce_flags & RCE_VALID) && !(RCE->rce_flags & RCE_LINK_DELETED)) {
  3174. // The RCE is valid, so we have a valid RTE in the pointer
  3175. // field. Walk down the RTE rcelist, looking for this guy.
  3176. RTE = RCE->rce_rte;
  3177. tmpif = IF = RTE->rte_if;
  3178. PrevRCE = STRUCT_OF(RouteCacheEntry, &RTE->rte_rcelist,
  3179. rce_next);
  3180. // Walk down the list until we find him.
  3181. while (PrevRCE != NULL) {
  3182. if (PrevRCE->rce_next == RCE)
  3183. break;
  3184. PrevRCE = PrevRCE->rce_next;
  3185. }
  3186. ASSERT(PrevRCE != NULL);
  3187. if(PrevRCE) {
  3188. PrevRCE->rce_next = RCE->rce_next;
  3189. }
  3190. } else {
  3191. //Make sure if the interface pointed by RCE
  3192. //is still there
  3193. tmpif = IFList;
  3194. IF = (Interface *) RCE->rce_rte;
  3195. while (tmpif) {
  3196. if (tmpif == IF)
  3197. break;
  3198. tmpif = tmpif->if_next;
  3199. }
  3200. }
  3201. if (tmpif) {
  3202. if (RCE->rce_flags & RCE_CONNECTED) {
  3203. (*(IF->if_invalidate)) (IF->if_lcontext, RCE);
  3204. } else {
  3205. UnConnected++;
  3206. UnConnectedRCE = RCE;
  3207. (*(IF->if_invalidate)) (IF->if_lcontext, RCE);
  3208. }
  3209. if (RCE->rce_usecnt != 0) {
  3210. // free to the free list
  3211. // and check in timer if the usecnt has fallen to 0, if yes free it
  3212. FreetoRCEFreeList = 1;
  3213. } else {
  3214. if (RCE->rce_flags & RCE_REFERENCED) {
  3215. LockedDerefIF(IF);
  3216. }
  3217. }
  3218. CTEFreeLock(&RCE->rce_lock, RCEHandle);
  3219. if (FreetoRCEFreeList) {
  3220. RCE->rce_rte = (RouteTableEntry *) IF;
  3221. FreeRCEToList(RCE);
  3222. } else {
  3223. CTEFreeMem(RCE);
  3224. }
  3225. } else { //tmpif==NULL
  3226. CTEFreeLock(&RCE->rce_lock, RCEHandle);
  3227. }
  3228. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3229. } else {
  3230. CTEFreeLock(&RCE->rce_lock, RCEHandle);
  3231. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3232. }
  3233. }
  3234. }
  3235. //* LockedAddRoute - Add a route to the routing table.
  3236. //
  3237. // Called by AddRoute to add a route to the routing table. We assume the
  3238. // route table lock is already held. If the route to be added already exists
  3239. // we update it. Routes are identified by a (Destination, Mask, FirstHop,
  3240. // Interface) tuple. If an exact match exists we'll update the metric, which
  3241. // may cause us to promote RCEs from other RTEs, or we may be demoted in which
  3242. // case we'll invalidate our RCEs and let them be reassigned at transmission
  3243. // time.
  3244. //
  3245. // If we have to create a new RTE we'll do so, and find the best previous
  3246. // RTE, and promote RCEs from that one to the new one.
  3247. //
  3248. // The route table is an open hash structure. Within each hash chain the
  3249. // RTEs with the longest masks (the 'priority') come first, and within
  3250. // each priority the RTEs with the smallest metric come first.
  3251. //
  3252. // Entry: Destination - Destination address for which route is being added.
  3253. // Mask - Mask for destination.
  3254. // FirstHop - First hop for address. Could be IPADDR_LOCAL.
  3255. // OutIF - Pointer to outgoing I/F.
  3256. // MTU - Maximum MTU for this route.
  3257. // Metric - Metric for this route.
  3258. // Proto - Protocol type to store in route.
  3259. // AType - Administrative type of route.
  3260. // Context - context to be associated with the route
  3261. // SetWithRefcnt - indicates the route should be referenced
  3262. // on the creator's behalf.
  3263. // RNO - optionally supplies a route-notification structure
  3264. // to be filled on output with details for the new route
  3265. //
  3266. // Returns: Status of attempt to add route.
  3267. //
  3268. IP_STATUS
  3269. LockedAddRoute(IPAddr Destination, IPMask Mask, IPAddr FirstHop,
  3270. Interface * OutIF, uint MTU, uint Metric, uint Proto, uint AType,
  3271. ROUTE_CONTEXT Context, BOOLEAN SetWithRefcnt,
  3272. IPRouteNotifyOutput* RNO)
  3273. {
  3274. uint RouteType; // SNMP route type.
  3275. RouteTableEntry *NewRTE, *OldRTE; // Entries for new and previous RTEs.
  3276. RouteTableEntry *PrevRTE; // Pointer to previous RTE.
  3277. CTELockHandle RCEHandle; // Lock handle for RCEs.
  3278. uint OldMetric; // Previous metric in use.
  3279. uint OldPriority; // Priority of previous route to destination.
  3280. RouteCacheEntry *CurrentRCE; // Current RCE being examined.
  3281. RouteCacheEntry *PrevRCE; // Previous RCE examined.
  3282. Interface *IF; // Interface being added on.
  3283. uint Priority; // Priority of the route.
  3284. uint TempMask; // Temporary copy of the mask.
  3285. uint Now = CTESystemUpTime() / 1000L; // System up time,
  3286. // in seconds.
  3287. uint MoveAny; // TRUE if we'll move any RCE.
  3288. ushort OldFlags;
  3289. Interface *OldIF = NULL;
  3290. ULONG status;
  3291. ULONG matchFlags;
  3292. RouteTableEntry *pOldBestRTE;
  3293. RouteTableEntry *pNewBestRTE;
  3294. LinkEntry *Link;
  3295. IPAddr AllSNBCast;
  3296. IPMask TmpMask;
  3297. // OutIF is ref'd so it can't go away
  3298. Link = OutIF->if_link;
  3299. // If Metric is 0, set the metric to interface metric
  3300. if (Metric == 0) {
  3301. Metric = OutIF->if_metric;
  3302. }
  3303. // Do the following only if the interface is not a dummy interface
  3304. if (OutIF != (Interface *) & DummyInterface) {
  3305. // Check we are adding a multicast route
  3306. if (IP_ADDR_EQUAL(Destination, MCAST_DEST) &&
  3307. (OutIF->if_iftype & DONT_ALLOW_MCAST))
  3308. return IP_SUCCESS;
  3309. if (OutIF->if_iftype & DONT_ALLOW_UCAST) {
  3310. // Check whether we are adding a ucast route
  3311. TmpMask = IPNetMask(OutIF->if_nte->nte_addr);
  3312. AllSNBCast =
  3313. (OutIF->if_nte->nte_addr & TmpMask) |
  3314. (OutIF->if_bcast & ~TmpMask);
  3315. if (!(IP_ADDR_EQUAL(Destination, OutIF->if_bcast) ||
  3316. IP_ADDR_EQUAL(Destination, AllSNBCast) ||
  3317. IP_ADDR_EQUAL(Destination, MCAST_DEST))) {
  3318. // this is not a bcast/mcast route: this is a ucast route
  3319. return IP_SUCCESS;
  3320. }
  3321. }
  3322. }
  3323. // First do some consistency checks. Make sure that the Mask and
  3324. // Destination agree.
  3325. if (!IP_ADDR_EQUAL(Destination & Mask, Destination))
  3326. return IP_BAD_DESTINATION;
  3327. if (AType != ATYPE_PERM && AType != ATYPE_OVERRIDE && AType != ATYPE_TEMP)
  3328. return IP_BAD_REQ;
  3329. // If the interface is marked as going away, fail this.
  3330. if (OutIF->if_flags & IF_FLAGS_DELETING) {
  3331. return IP_BAD_REQ;
  3332. }
  3333. RouteType = IP_ADDR_EQUAL(FirstHop, IPADDR_LOCAL) ? IRE_TYPE_DIRECT :
  3334. IRE_TYPE_INDIRECT;
  3335. // If this is a route that is being added on an interface that has no
  3336. // IP address, mark this as IRE_TYPE_DIRECT. This is true only for
  3337. // P2P or P2MP interface, where route is plumbed and then address
  3338. // is added due to a perf reason.
  3339. if (((OutIF->if_flags & IF_FLAGS_P2P) ||
  3340. (OutIF->if_flags & IF_FLAGS_P2MP)) &&
  3341. OutIF->if_nte && (OutIF->if_nte->nte_flags & NTE_VALID) &&
  3342. (IP_ADDR_EQUAL(OutIF->if_nte->nte_addr,NULL_IP_ADDR))) {
  3343. RouteType = IRE_TYPE_DIRECT;
  3344. }
  3345. MTU = MAX(MTU, MIN_VALID_MTU);
  3346. // If the outgoing interface has NTEs attached but none are valid, fail
  3347. // this request unless it's a request to add the broadcast route.
  3348. if (OutIF != (Interface *) & DummyInterface) {
  3349. if (OutIF->if_ntecount == 0 && OutIF->if_nte != NULL &&
  3350. !IP_ADDR_EQUAL(Destination, OutIF->if_bcast) &&
  3351. !(OutIF->if_flags & IF_FLAGS_NOIPADDR)) {
  3352. // This interface has NTEs attached, but none are valid. Fail the
  3353. // request.
  3354. return IP_BAD_REQ;
  3355. }
  3356. }
  3357. if (OutIF->if_flags & IF_FLAGS_P2MP) {
  3358. while (Link) {
  3359. if ((Link->link_NextHop == FirstHop) ||
  3360. ((Link->link_NextHop == Destination) &&
  3361. (FirstHop == IPADDR_LOCAL))) {
  3362. break;
  3363. }
  3364. Link = Link->link_next;
  3365. }
  3366. if (!Link)
  3367. return IP_GENERAL_FAILURE;
  3368. }
  3369. DEBUGMSG(DBG_INFO && DBG_IP && DBG_ROUTE,
  3370. (DTEXT("LockedAddRoute: D = %08x, M = %08x, NH = %08x, IF = %08x\n")
  3371. DTEXT("\t\tMTU = %x, Met = %08x, Prot = %08x, AT = %08x, C = %08x\n"),
  3372. Destination, Mask, FirstHop, OutIF, MTU, Metric, Proto, AType,
  3373. Context));
  3374. // Insert the route in the proper place depending on the dest, metric
  3375. // Match next-hop (and interface if not a demand-dial route)
  3376. matchFlags = MATCH_NHOP;
  3377. if (!Context) {
  3378. matchFlags |= MATCH_INTF;
  3379. }
  3380. status = InsRoute(Destination, Mask, FirstHop, OutIF, Metric,
  3381. matchFlags, &NewRTE, &pOldBestRTE, &pNewBestRTE);
  3382. if (status != IP_SUCCESS) {
  3383. return status;
  3384. }
  3385. // Has a best route been replaced
  3386. if ((pOldBestRTE) && (pOldBestRTE != pNewBestRTE)) {
  3387. InvalidateRCEChain(pOldBestRTE);
  3388. // If the replaced route is a default gateway,
  3389. // we may need to switch connections to the new entry.
  3390. // To do so, we retrieve the current default gateway,
  3391. // invalidate all its RCEs, and revalidate all gateways
  3392. // to restart the dead-gateway detection procedure.
  3393. if (pOldBestRTE->rte_mask == DEFAULT_MASK) {
  3394. ValidateDefaultGWs(NULL_IP_ADDR);
  3395. }
  3396. }
  3397. // Copy old route's parameters now
  3398. OldFlags = NewRTE->rte_flags;
  3399. if (!(NewRTE->rte_flags & RTE_NEW)) {
  3400. OldMetric = NewRTE->rte_metric;
  3401. OldPriority = NewRTE->rte_priority;
  3402. OldIF = NewRTE->rte_if;
  3403. if (Metric >= OldMetric && (OldFlags & RTE_VALID)) {
  3404. InvalidateRCEChain(NewRTE);
  3405. }
  3406. if (SetWithRefcnt) {
  3407. ASSERT(NewRTE->rte_refcnt > 0);
  3408. NewRTE->rte_refcnt++;
  3409. }
  3410. } else {
  3411. // this is a new RTE
  3412. NewRTE->rte_refcnt = 1;
  3413. }
  3414. // If this is P2MP, chain this RTE on link
  3415. if (Link && (NewRTE->rte_link == NULL)) {
  3416. //
  3417. // This RTE is not on the link
  3418. // Insert the route in the linkrte chain
  3419. //
  3420. NewRTE->rte_nextlinkrte = Link->link_rte;
  3421. Link->link_rte = NewRTE;
  3422. NewRTE->rte_link = Link;
  3423. }
  3424. // Update fields in the new/old route
  3425. NewRTE->rte_addr = FirstHop;
  3426. NewRTE->rte_mtu = MTU;
  3427. NewRTE->rte_metric = Metric;
  3428. NewRTE->rte_type = (ushort) RouteType;
  3429. NewRTE->rte_if = OutIF;
  3430. NewRTE->rte_flags &= ~RTE_NEW;
  3431. NewRTE->rte_flags |= RTE_VALID;
  3432. NewRTE->rte_flags &= ~RTE_INCREASE;
  3433. if (OutIF != (Interface *) & DummyInterface) {
  3434. NewRTE->rte_flags |= RTE_IF_VALID;
  3435. SortRoutesInDestByRTE(NewRTE);
  3436. } else
  3437. NewRTE->rte_flags &= ~RTE_IF_VALID;
  3438. NewRTE->rte_admintype = AType;
  3439. NewRTE->rte_proto = Proto;
  3440. NewRTE->rte_valid = Now;
  3441. NewRTE->rte_mtuchange = Now;
  3442. NewRTE->rte_context = Context;
  3443. // Check if this is a new route or an old one
  3444. if (OldFlags & RTE_NEW) {
  3445. // Reset few fields in new route
  3446. NewRTE->rte_todg = NULL;
  3447. NewRTE->rte_fromdg = NULL;
  3448. NewRTE->rte_rces = 0;
  3449. RtlZeroMemory(NewRTE->rte_arpcontext, sizeof(RCE_CONTEXT_SIZE));
  3450. IPSInfo.ipsi_numroutes++;
  3451. if (NewRTE->rte_mask == DEFAULT_MASK) {
  3452. // A default route.
  3453. DefGWConfigured++;
  3454. DefGWActive++;
  3455. UpdateDeadGWState();
  3456. }
  3457. } else {
  3458. // If the RTE is for a default gateway and the old flags indicate
  3459. // he wasn't valid then we're essentially creating a new active
  3460. // default gateway. So bump up the active default gateway count.
  3461. if (NewRTE->rte_mask == DEFAULT_MASK) {
  3462. if (!(OldFlags & RTE_VALID)) {
  3463. DefGWActive++;
  3464. UpdateDeadGWState();
  3465. // Reset few fields in this route
  3466. NewRTE->rte_todg = NULL;
  3467. NewRTE->rte_fromdg = NULL;
  3468. NewRTE->rte_rces = 0;
  3469. }
  3470. }
  3471. }
  3472. // If a route-notification structure was supplied, fill it in.
  3473. if (RNO) {
  3474. RNO->irno_dest = NewRTE->rte_dest;
  3475. RNO->irno_mask = NewRTE->rte_mask;
  3476. RNO->irno_nexthop = GetNextHopForRTE(NewRTE);
  3477. RNO->irno_proto = NewRTE->rte_proto;
  3478. RNO->irno_ifindex = OutIF->if_index;
  3479. RNO->irno_metric = NewRTE->rte_metric;
  3480. if (OldFlags & RTE_NEW) {
  3481. RNO->irno_flags = IRNO_FLAG_ADD;
  3482. }
  3483. }
  3484. return IP_SUCCESS;
  3485. }
  3486. //* AddRoute - Add a route to the routing table.
  3487. //
  3488. // This is just a shell for the real add route routine. All we do is take
  3489. // the route table lock, and call the LockedAddRoute routine to deal with
  3490. // the request. This is done this way because there are certain routines that
  3491. // need to be able to atomically examine and add routes.
  3492. //
  3493. // Entry: Destination - Destination address for which route is being
  3494. // added.
  3495. // Mask - Mask for destination.
  3496. // FirstHop - First hop for address. Could be IPADDR_LOCAL.
  3497. // OutIF - Pointer to outgoing I/F.
  3498. // MTU - Maximum MTU for this route.
  3499. // Metric - Metric for this route.
  3500. // Proto - Protocol type to store in route.
  3501. // AType - Administrative type of route.
  3502. // Context - Context for this route.
  3503. //
  3504. // Returns: Status of attempt to add route.
  3505. //
  3506. IP_STATUS
  3507. AddRoute(IPAddr Destination, IPMask Mask, IPAddr FirstHop,
  3508. Interface * OutIF, uint MTU, uint Metric, uint Proto, uint AType,
  3509. ROUTE_CONTEXT Context, uint Flags)
  3510. {
  3511. CTELockHandle TableHandle;
  3512. IP_STATUS Status;
  3513. BOOLEAN SkipExNotifyQ = FALSE;
  3514. IPRouteNotifyOutput RNO = {0};
  3515. if ((Flags & RT_EXCLUDE_LOCAL) && Proto == IRE_PROTO_LOCAL) {
  3516. return IP_BAD_REQ;
  3517. }
  3518. CTEGetLock(&RouteTableLock.Lock, &TableHandle);
  3519. if (Flags & RT_NO_NOTIFY) {
  3520. SkipExNotifyQ = TRUE;
  3521. }
  3522. Status = LockedAddRoute(Destination, Mask, FirstHop, OutIF, MTU, Metric,
  3523. Proto, AType, Context,
  3524. (BOOLEAN)((Flags & RT_REFCOUNT) ? TRUE : FALSE),
  3525. &RNO);
  3526. if (Status == IP_SUCCESS) {
  3527. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  3528. #if FFP_SUPPORT
  3529. FFPFlushRequired = TRUE;
  3530. #endif
  3531. // Under certain conditions, LockedAddRoute returns IP_SUCCESS
  3532. // even though no route was added. We catch such cases by examining
  3533. // the interface index on output which, for true additions, should
  3534. // always be non-zero.
  3535. if (RNO.irno_ifindex) {
  3536. if (!SkipExNotifyQ) {
  3537. RtChangeNotifyEx(&RNO);
  3538. }
  3539. RtChangeNotify(&RNO);
  3540. }
  3541. } else {
  3542. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  3543. }
  3544. return Status;
  3545. }
  3546. //* RtChangeNotify - Supply a route-change for notification to any clients
  3547. //
  3548. // This routine is a shell around the address-/route-change notification
  3549. // handler. It unpacks information about the changed route, and passes it
  3550. // to the common handler specifying the route-change notification queue
  3551. // as the source for pending client-requests.
  3552. //
  3553. // Entry: RNO - describes the route-notification event
  3554. //
  3555. // Returns: nothing.
  3556. //
  3557. void
  3558. RtChangeNotify(IPRouteNotifyOutput *RNO)
  3559. {
  3560. ChangeNotify((IPNotifyOutput *)RNO, &RtChangeNotifyQueue,
  3561. &RouteTableLock.Lock);
  3562. }
  3563. //* RtChangeNotifyEx - Supply a route-change for notification to any clients
  3564. //
  3565. // This routine is a shell around the address-/route-change notification
  3566. // handler. It unpacks information about the changed route, and passes it
  3567. // to the common handler specifying the extended route-change notification
  3568. // queue as the source for pending client-requests.
  3569. //
  3570. // Entry: RNO - describes the route-notification event
  3571. //
  3572. // Returns: nothing.
  3573. //
  3574. void
  3575. RtChangeNotifyEx(IPRouteNotifyOutput *RNO)
  3576. {
  3577. ChangeNotify((IPNotifyOutput *)RNO, &RtChangeNotifyQueueEx,
  3578. &RouteTableLock.Lock);
  3579. }
  3580. //* ChangeNotifyAsync - Supply a change for notification
  3581. //
  3582. // This routine is a handler for a deferred change-notification. It unpacks
  3583. // information about the change, and passes it to the common handler.
  3584. //
  3585. // Entry: Event - CTEEvent for the deferred call
  3586. // Context - context containing information about the change
  3587. //
  3588. // Returns: nothing.
  3589. //
  3590. void
  3591. ChangeNotifyAsync(CTEEvent *Event, PVOID Context)
  3592. {
  3593. ChangeNotifyEvent *CNE = (ChangeNotifyEvent *)Context;
  3594. ChangeNotify(&CNE->cne_info, CNE->cne_queue, CNE->cne_lock);
  3595. CTEFreeMem(Context);
  3596. }
  3597. //* ChangeNotifyClientInQueue - See if a client is in a notification queue
  3598. //
  3599. // This is a utility routine called by ChangeNotify to determine
  3600. // if a given client, identified by a file object, has a request
  3601. // in a given notification queue.
  3602. //
  3603. // Entry: FileObject - identifies the client
  3604. // NotifyQueue - contains a list of requests to be searched
  3605. //
  3606. // Returns: TRUE if the client is present, FALSE otherwise.
  3607. //
  3608. BOOLEAN
  3609. ChangeNotifyClientInQueue(PFILE_OBJECT FileObject, PLIST_ENTRY NotifyQueue)
  3610. {
  3611. PLIST_ENTRY ListEntry;
  3612. PIRP Irp;
  3613. PIO_STACK_LOCATION IrpSp;
  3614. for (ListEntry = NotifyQueue->Flink; ListEntry != NotifyQueue;
  3615. ListEntry = ListEntry->Flink) {
  3616. Irp = CONTAINING_RECORD(ListEntry, IRP, Tail.Overlay.ListEntry);
  3617. IrpSp = IoGetCurrentIrpStackLocation(Irp);
  3618. if (FileObject == IrpSp->FileObject) {
  3619. return TRUE;
  3620. }
  3621. }
  3622. return FALSE;
  3623. }
  3624. //* ChangeNotify - Notify about a route change
  3625. //
  3626. // This routine is the common handler for change notifications.
  3627. // It takes a description of a change, and searches the specified queue
  3628. // for a pending client-request that corresponds to the changed item.
  3629. //
  3630. // Entry: NotifyOutput - contains information about the change event
  3631. // NotifyQueue - supplies the queue in which to search for clients
  3632. // Lock - supplies the lock protecting 'NotifyQueue'.
  3633. //
  3634. // Returns: nothing.
  3635. //
  3636. void
  3637. ChangeNotify(IPNotifyOutput* NotifyOutput, PLIST_ENTRY NotifyQueue, PVOID Lock)
  3638. {
  3639. IPAddr Add = NotifyOutput->ino_addr;
  3640. IPMask Mask = NotifyOutput->ino_mask;
  3641. PIRP Irp;
  3642. CTELockHandle LockHandle;
  3643. PLIST_ENTRY ListEntry;
  3644. uint i;
  3645. PIPNotifyData NotifyData;
  3646. LIST_ENTRY LocalNotifyQueue;
  3647. PIO_STACK_LOCATION IrpSp;
  3648. BOOLEAN synchronizeWithCancelRoutine = FALSE;
  3649. // See if we're being invoked it dispatch IRQL and, if so,
  3650. // defer the notification to a worker thread.
  3651. //
  3652. // N.B. We do this *without* touching 'Lock' which might already
  3653. // be held by the caller.
  3654. if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
  3655. ChangeNotifyEvent *CNE;
  3656. CNE = CTEAllocMemNBoot(sizeof(ChangeNotifyEvent), 'xiCT');
  3657. if (CNE) {
  3658. CNE->cne_info = *NotifyOutput;
  3659. CNE->cne_queue = NotifyQueue;
  3660. CNE->cne_lock = Lock;
  3661. CTEInitEvent(&CNE->cne_event, ChangeNotifyAsync);
  3662. CTEScheduleDelayedEvent(&CNE->cne_event, CNE);
  3663. }
  3664. return;
  3665. }
  3666. // Examine the list of pending change-notification requeusts
  3667. // to see if any of them match the parameters of the current event.
  3668. InitializeListHead(&LocalNotifyQueue);
  3669. CTEGetLock(Lock, &LockHandle);
  3670. for (ListEntry = NotifyQueue->Flink; ListEntry != NotifyQueue; ) {
  3671. Irp = CONTAINING_RECORD(ListEntry, IRP, Tail.Overlay.ListEntry);
  3672. IrpSp = IoGetCurrentIrpStackLocation(Irp);
  3673. // Determine whether an input buffer was supplied and, if so,
  3674. // pick it up to see if the event matches the notification request.
  3675. if (IrpSp->Parameters.DeviceIoControl.InputBufferLength >=
  3676. sizeof(IPNotifyData)) {
  3677. NotifyData = Irp->AssociatedIrp.SystemBuffer;
  3678. } else {
  3679. NotifyData = NULL;
  3680. }
  3681. // Now determine whether we should consider this IRP at all.
  3682. // We'll normally complete all matching IRPs when an event occurs,
  3683. // but certain clients want only one matching IRP to be completed,
  3684. // so they can maintain a backlog of IRPs to make sure that they don't
  3685. // miss any events. Such clients set 'Synchronization' as the version
  3686. // in their requests.
  3687. if (NotifyData &&
  3688. NotifyData->Version == IPNotifySynchronization &&
  3689. ChangeNotifyClientInQueue(IrpSp->FileObject, &LocalNotifyQueue)) {
  3690. ListEntry = ListEntry->Flink;
  3691. continue;
  3692. }
  3693. // If no data was passed or it contains NULL address or an Address that
  3694. // matches the address that was added or deleted, complete the irp
  3695. if ((NotifyData == NULL) ||
  3696. (NotifyData->Add == 0) ||
  3697. ((NotifyData->Add & Mask) == (Add & Mask))) {
  3698. //
  3699. // We are going to remove the LE, so first save the Flink
  3700. //
  3701. ListEntry = ListEntry->Flink;
  3702. RemoveEntryList(&Irp->Tail.Overlay.ListEntry);
  3703. if (IoSetCancelRoutine(Irp, NULL) == NULL) {
  3704. synchronizeWithCancelRoutine = TRUE;
  3705. }
  3706. #if !MILLEN
  3707. if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength >=
  3708. sizeof(IPNotifyOutput)) {
  3709. RtlCopyMemory(Irp->AssociatedIrp.SystemBuffer, NotifyOutput,
  3710. sizeof(IPNotifyOutput));
  3711. Irp->IoStatus.Information = sizeof(IPNotifyOutput);
  3712. } else {
  3713. Irp->IoStatus.Information = 0;
  3714. }
  3715. #else // !MILLEN
  3716. // For Millennium, this is only called for RtChange queues now.
  3717. //
  3718. ASSERT(NotifyQueue == &RtChangeNotifyQueue);
  3719. if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength >=
  3720. sizeof(IP_RTCHANGE_NOTIFY)) {
  3721. PIP_RTCHANGE_NOTIFY pReply = Irp->AssociatedIrp.SystemBuffer;
  3722. pReply->Addr = Add;
  3723. pReply->Mask = Mask;
  3724. Irp->IoStatus.Information = sizeof(IP_RTCHANGE_NOTIFY);
  3725. } else {
  3726. Irp->IoStatus.Information = 0;
  3727. }
  3728. #endif // MILLEN
  3729. InsertTailList(&LocalNotifyQueue, &Irp->Tail.Overlay.ListEntry);
  3730. } else {
  3731. ListEntry = ListEntry->Flink;
  3732. }
  3733. }
  3734. CTEFreeLock(Lock, LockHandle);
  3735. if (!IsListEmpty(&LocalNotifyQueue)) {
  3736. if (synchronizeWithCancelRoutine) {
  3737. IoAcquireCancelSpinLock(&LockHandle);
  3738. IoReleaseCancelSpinLock(LockHandle);
  3739. }
  3740. do {
  3741. ListEntry = RemoveHeadList(&LocalNotifyQueue);
  3742. Irp = CONTAINING_RECORD(ListEntry, IRP, Tail.Overlay.ListEntry);
  3743. Irp->IoStatus.Status = STATUS_SUCCESS;
  3744. IoCompleteRequest(Irp, IO_NETWORK_INCREMENT);
  3745. } while (!IsListEmpty(&LocalNotifyQueue));
  3746. }
  3747. }
  3748. //* RtChangeNotifyCancel - cancels a route-change notification request.
  3749. //
  3750. // This routine is a wrapper around the common request-cancelation handler
  3751. // for change-notification requests.
  3752. //
  3753. // Returns: nothing.
  3754. //
  3755. void
  3756. RtChangeNotifyCancel(PDEVICE_OBJECT DeviceObject, PIRP Irp)
  3757. {
  3758. CancelNotify(Irp, &RtChangeNotifyQueue, &RouteTableLock.Lock);
  3759. }
  3760. //* RtChangeNotifyCancelEx - cancels a route-change notification request.
  3761. //
  3762. // This routine is a wrapper around the common request-cancelation handler
  3763. // for change-notification requests.
  3764. //
  3765. // Returns: nothing.
  3766. //
  3767. void
  3768. RtChangeNotifyCancelEx(PDEVICE_OBJECT DeviceObject, PIRP Irp)
  3769. {
  3770. CancelNotify(Irp, &RtChangeNotifyQueueEx, &RouteTableLock.Lock);
  3771. }
  3772. //* CancelNotify - cancels a change-notification request.
  3773. //
  3774. // This routine is the common handler for cancelation of change-notification
  3775. // requests. It searches for the given request in the qiven queue and,
  3776. // if found, completes it immediately with a cancelation status.
  3777. //
  3778. // It is invoked with the I/O cancel spin-lock held by the caller,
  3779. // and frees the cancel spin-lock before returning.
  3780. //
  3781. // Entry: Irp - the I/O request packet for the request
  3782. // NotifyQueue - change-notification queue containing the request
  3783. // Lock - lock protecting 'NotifyQueue'.
  3784. //
  3785. // Returns: nothing.
  3786. //
  3787. void
  3788. CancelNotify(PIRP Irp, PLIST_ENTRY NotifyQueue, PVOID Lock)
  3789. {
  3790. CTELockHandle LockHandle;
  3791. PLIST_ENTRY ListEntry;
  3792. BOOLEAN Found = FALSE;
  3793. CTEGetLock(Lock, &LockHandle);
  3794. for (ListEntry = NotifyQueue->Flink; ListEntry != NotifyQueue;
  3795. ListEntry = ListEntry->Flink) {
  3796. if (CONTAINING_RECORD(ListEntry, IRP, Tail.Overlay.ListEntry) == Irp) {
  3797. RemoveEntryList(&Irp->Tail.Overlay.ListEntry);
  3798. Found = TRUE;
  3799. break;
  3800. }
  3801. }
  3802. CTEFreeLock(Lock, LockHandle);
  3803. IoReleaseCancelSpinLock(Irp->CancelIrql);
  3804. if (Found) {
  3805. Irp->IoStatus.Information = 0;
  3806. Irp->IoStatus.Status = STATUS_CANCELLED;
  3807. IoCompleteRequest(Irp, IO_NETWORK_INCREMENT);
  3808. }
  3809. }
  3810. //* DeleteRoute - Delete a route from the routing table.
  3811. //
  3812. // Called by upper layer or management code to delete a route from the routing
  3813. // table. If we can't find the route we return an error. If we do find it, we
  3814. // remove it, and invalidate any RCEs associated with it. These RCEs will be
  3815. // reassigned the next time they're used. A route is uniquely identified by
  3816. // a (Destination, Mask, FirstHop, Interface) tuple.
  3817. //
  3818. // Entry: Destination - Destination address for which route is being
  3819. // deleted.
  3820. // Mask - Mask for destination.
  3821. // FirstHop - First hop on way to Destination.
  3822. // -1 means route is local.
  3823. // OutIF - Outgoing interface for route.
  3824. // Flags - selects various semantics for deletion.
  3825. //
  3826. // Returns: Status of attempt to delete route.
  3827. //
  3828. IP_STATUS
  3829. DeleteRoute(IPAddr Destination, IPMask Mask, IPAddr FirstHop,
  3830. Interface * OutIF, uint Flags)
  3831. {
  3832. RouteTableEntry *RTE; // RTE being deleted.
  3833. RouteTableEntry *PrevRTE; // Pointer to RTE in front of one
  3834. // being deleted.
  3835. CTELockHandle TableLock; // Lock handle for table.
  3836. UINT retval;
  3837. RouteTableEntry *pOldBestRTE;
  3838. RouteTableEntry *pNewBestRTE;
  3839. BOOLEAN DeleteDone = FALSE;
  3840. IPRouteNotifyOutput RNO = {0};
  3841. uint MatchFlags = MATCH_FULL;
  3842. // Look up the route by calling FindSpecificRTE. If we can't find it,
  3843. // fail the call.
  3844. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  3845. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  3846. "DeleteRoute: D = %08x, M = %08x, NH = %08x, IF = %08x\n",
  3847. Destination, Mask, FirstHop, OutIF));
  3848. if (Flags & RT_EXCLUDE_LOCAL) {
  3849. MatchFlags |= MATCH_EXCLUDE_LOCAL;
  3850. }
  3851. if (Flags & RT_REFCOUNT) {
  3852. RouteTableEntry *TempRTE;
  3853. RTE = FindSpecificRTE(Destination, Mask, FirstHop, OutIF, &TempRTE,
  3854. FALSE);
  3855. if (RTE) {
  3856. ASSERT(RTE->rte_refcnt > 0);
  3857. RTE->rte_refcnt--;
  3858. if (!RTE->rte_refcnt) {
  3859. retval = DelRoute(Destination, Mask, FirstHop, OutIF,
  3860. MatchFlags, &RTE, &pOldBestRTE, &pNewBestRTE);
  3861. } else {
  3862. retval = IP_SUCCESS;
  3863. }
  3864. } else {
  3865. retval = IP_BAD_ROUTE;
  3866. }
  3867. } else {
  3868. retval = DelRoute(Destination, Mask, FirstHop, OutIF, MatchFlags,
  3869. &RTE, &pOldBestRTE, &pNewBestRTE);
  3870. }
  3871. if (retval == IP_SUCCESS) {
  3872. if (!((Flags & RT_REFCOUNT) && RTE->rte_refcnt)) {
  3873. RNO.irno_dest = RTE->rte_dest;
  3874. RNO.irno_mask = RTE->rte_mask;
  3875. RNO.irno_nexthop = GetNextHopForRTE(RTE);
  3876. RNO.irno_proto = RTE->rte_proto;
  3877. RNO.irno_ifindex = OutIF->if_index;
  3878. RNO.irno_metric = RTE->rte_metric;
  3879. RNO.irno_flags = IRNO_FLAG_DELETE;
  3880. DeleteDone = TRUE;
  3881. CleanupP2MP_RTE(RTE);
  3882. CleanupRTE(RTE);
  3883. }
  3884. }
  3885. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  3886. #if FFP_SUPPORT
  3887. FFPFlushRequired = TRUE;
  3888. #endif
  3889. if (DeleteDone) {
  3890. if (!(Flags & RT_NO_NOTIFY)) {
  3891. RtChangeNotifyEx(&RNO);
  3892. }
  3893. RtChangeNotify(&RNO);
  3894. }
  3895. return retval;
  3896. }
  3897. //* DeleteRouteWithNoLock - utility routine called by DeleteDest
  3898. //
  3899. // Called to remove a single route for a given destination.
  3900. // It's assumed that this routine is called with the routing table lock held,
  3901. // and that it doesn't release the route-table-lock as part of its operation.
  3902. //
  3903. // Entry: IRE - describes the entry to be deleted
  3904. // DeletedRTE - contains a pointer to the deleted entry on output
  3905. // Flags - selects various semantics for deletion.
  3906. //
  3907. // Returns: IP_SUCCESS if the entry to be deleted was found
  3908. //
  3909. IP_STATUS
  3910. DeleteRouteWithNoLock(IPRouteEntry * IRE, RouteTableEntry **DeletedRTE,
  3911. uint Flags)
  3912. {
  3913. NetTableEntry *OutNTE, *LocalNTE, *TempNTE;
  3914. IPAddr FirstHop, Dest, NextHop;
  3915. uint MTU;
  3916. Interface *OutIF;
  3917. uint Status;
  3918. uint i;
  3919. RouteTableEntry *RTE, *RTE1, *RTE2;
  3920. IPRouteNotifyOutput RNO = {0};
  3921. uint MatchFlags = MATCH_FULL;
  3922. *DeletedRTE = NULL;
  3923. OutNTE = NULL;
  3924. LocalNTE = NULL;
  3925. Dest = IRE->ire_dest;
  3926. NextHop = IRE->ire_nexthop;
  3927. // Make sure that the nexthop is sensible. We don't allow nexthops
  3928. // to be broadcast or invalid or loopback addresses.
  3929. if (IP_LOOPBACK(NextHop) || CLASSD_ADDR(NextHop) || CLASSE_ADDR(NextHop))
  3930. return IP_BAD_REQ;
  3931. // Also make sure that the destination we're routing to is sensible.
  3932. // Don't allow routes to be added to Class D or E or loopback
  3933. // addresses.
  3934. if (IP_LOOPBACK(Dest) || CLASSD_ADDR(Dest) || CLASSE_ADDR(Dest))
  3935. return IP_BAD_REQ;
  3936. if (IRE->ire_index == LoopIndex)
  3937. return IP_BAD_REQ;
  3938. if (IRE->ire_index != INVALID_IF_INDEX) {
  3939. // First thing to do is to find the outgoing NTE for specified
  3940. // interface, and also make sure that it matches the destination
  3941. // if the destination is one of my addresses.
  3942. for (i = 0; i < NET_TABLE_SIZE; i++) {
  3943. NetTableEntry *NetTableList = NewNetTableList[i];
  3944. for (TempNTE = NetTableList; TempNTE != NULL;
  3945. TempNTE = TempNTE->nte_next) {
  3946. if ((OutNTE == NULL) && (TempNTE->nte_flags & NTE_VALID) && (IRE->ire_index == TempNTE->nte_if->if_index))
  3947. OutNTE = TempNTE;
  3948. if (!IP_ADDR_EQUAL(NextHop, NULL_IP_ADDR) &&
  3949. IP_ADDR_EQUAL(NextHop, TempNTE->nte_addr) &&
  3950. (TempNTE->nte_flags & NTE_VALID))
  3951. LocalNTE = TempNTE;
  3952. // Don't let a route be set through a broadcast address.
  3953. if (IsBCastOnNTE(NextHop, TempNTE) != DEST_LOCAL)
  3954. return STATUS_INVALID_PARAMETER;
  3955. // Don't let a route to a broadcast address be added or deleted.
  3956. if (IsBCastOnNTE(Dest, TempNTE) != DEST_LOCAL)
  3957. return IP_BAD_REQ;
  3958. }
  3959. }
  3960. // At this point OutNTE points to the outgoing NTE, and LocalNTE
  3961. // points to the NTE for the local address, if this is a direct route.
  3962. // Make sure they point to the same interface, and that the type is
  3963. // reasonable.
  3964. if (OutNTE == NULL)
  3965. return IP_BAD_REQ;
  3966. if (LocalNTE != NULL) {
  3967. // He's routing straight out a local interface. The interface for
  3968. // the local address must match the interface passed in, and the
  3969. // type must be DIRECT (if we're adding) or INVALID (if we're
  3970. // deleting).
  3971. if (LocalNTE->nte_if->if_index != IRE->ire_index)
  3972. return IP_BAD_REQ;
  3973. if (IRE->ire_type != IRE_TYPE_DIRECT &&
  3974. IRE->ire_type != IRE_TYPE_INVALID)
  3975. return IP_BAD_REQ;
  3976. OutNTE = LocalNTE;
  3977. }
  3978. // Figure out what the first hop should be. If he's routing straight
  3979. // through a local interface, or the next hop is equal to the
  3980. // destination, then the first hop is IPADDR_LOCAL. Otherwise it's the
  3981. // address of the gateway.
  3982. if ((LocalNTE != NULL) || IP_ADDR_EQUAL(NextHop, NULL_IP_ADDR))
  3983. FirstHop = IPADDR_LOCAL;
  3984. else if (IP_ADDR_EQUAL(Dest, NextHop))
  3985. FirstHop = IPADDR_LOCAL;
  3986. else
  3987. FirstHop = NextHop;
  3988. MTU = OutNTE->nte_mss;
  3989. OutIF = OutNTE->nte_if;
  3990. if (IP_ADDR_EQUAL(NextHop, NULL_IP_ADDR)) {
  3991. if (!(OutIF->if_flags & IF_FLAGS_P2P)) {
  3992. return IP_BAD_REQ;
  3993. }
  3994. }
  3995. } else {
  3996. OutIF = (Interface *) & DummyInterface;
  3997. MTU = DummyInterface.ri_if.if_mtu - sizeof(IPHeader);
  3998. if (IP_ADDR_EQUAL(Dest, NextHop))
  3999. FirstHop = IPADDR_LOCAL;
  4000. else
  4001. FirstHop = NextHop;
  4002. }
  4003. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Calling DelRoute On :\n"));
  4004. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"\tDest = %p\n", Dest));
  4005. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4006. "\tMask = %p\n", IRE->ire_mask));
  4007. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"\tIntf = %p\n", OutIF));
  4008. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"\tNhop = %p\n\n", FirstHop));
  4009. if (Flags & RT_EXCLUDE_LOCAL) {
  4010. MatchFlags |= MATCH_EXCLUDE_LOCAL;
  4011. }
  4012. Status = DelRoute(Dest, IRE->ire_mask, FirstHop, OutIF, MatchFlags,
  4013. &RTE, &RTE1, &RTE2);
  4014. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Status = %08x\n", Status));
  4015. if (Status == IP_SUCCESS) {
  4016. // Queue a route-change notification for the destination-removal.
  4017. //
  4018. // N.B. We are being called with the route-table-lock held;
  4019. // this means we're at DISPATCH_LEVEL, and so the call below
  4020. // to RtChangeNotify will schedule a deferred notification.
  4021. // It definitely *must* not attempt to recursively acquire
  4022. // the route-table-lock, since that would instantly deadlock.
  4023. RNO.irno_dest = RTE->rte_dest;
  4024. RNO.irno_mask = RTE->rte_mask;
  4025. RNO.irno_nexthop = GetNextHopForRTE(RTE);
  4026. RNO.irno_proto = RTE->rte_proto;
  4027. RNO.irno_ifindex = OutIF->if_index;
  4028. RNO.irno_metric = RTE->rte_metric;
  4029. RNO.irno_flags = IRNO_FLAG_DELETE;
  4030. RtChangeNotify(&RNO);
  4031. CleanupP2MP_RTE(RTE);
  4032. CleanupRTE(RTE);
  4033. *DeletedRTE = RTE;
  4034. return IP_SUCCESS;
  4035. }
  4036. return IP_BAD_REQ;
  4037. }
  4038. //* DeleteDest - delete all routes to a destination
  4039. //
  4040. // Called to remove all routes to a given destination. This results
  4041. // in the entry for the destination itself being removed.
  4042. //
  4043. // Entry: Dest - identifies the destination to be removed
  4044. // Mask - supplies the mask for the destination
  4045. //
  4046. // Returns: IP_SUCCESS if the destination was found
  4047. //
  4048. IP_STATUS
  4049. DeleteDest(IPAddr Dest, IPMask Mask)
  4050. {
  4051. CTELockHandle TableLock;
  4052. RouteTableEntry *RTE, *NextRTE, *DeletedRTE;
  4053. IP_STATUS retval;
  4054. IPRouteEntry IRE;
  4055. NetTableEntry *SrcNTE;
  4056. BOOLEAN DeleteDone = FALSE;
  4057. CTEGetLock(&RouteTableLock.Lock, &TableLock);
  4058. do {
  4059. // Begin by locating the first entry for the destination in question.
  4060. // Once we find that, we'll use it to begin a loop in which all the
  4061. // entries for the destination will be deleted.
  4062. retval = SearchRouteInSTrie(RouteTable->sTrie, Dest, Mask, 0, NULL,
  4063. MATCH_NONE, &RTE);
  4064. if (retval != IP_SUCCESS) {
  4065. break;
  4066. }
  4067. // Iteratively remove all routes on the destination.
  4068. // Initialize the fields that are common to all the destination's
  4069. // routes, and then iterate over the routes removing each one.
  4070. IRE.ire_type = IRE_TYPE_INVALID;
  4071. IRE.ire_dest = Dest;
  4072. IRE.ire_mask = Mask;
  4073. do {
  4074. // Set the fields which are specific to the current entry
  4075. // for the destination (the interface index and nexthop),
  4076. // and pick up the entry *after* this entry (since we're about
  4077. // to delete this entry) so we can continue our enumeration
  4078. // once the current entry is removed.
  4079. IRE.ire_index = RTE->rte_if->if_index;
  4080. IRE.ire_nexthop = GetNextHopForRTE(RTE);
  4081. NextRTE = RTE->rte_next;
  4082. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4083. "Deleting RTE @ %p:\n", RTE));
  4084. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4085. "Next in List = %p:\n", NextRTE));
  4086. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4087. "Using an IRE @ %p\n", IRE));
  4088. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4089. "\tDest = %08x\n", IRE.ire_dest));
  4090. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4091. "\tMask = %08x\n", IRE.ire_mask));
  4092. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4093. "\tIntf = %08x\n", IRE.ire_index));
  4094. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4095. "\tNhop = %08x\n\n", IRE.ire_nexthop));
  4096. // Delete the current entry. The deletion routine
  4097. // takes care of notification, if any.
  4098. retval = DeleteRouteWithNoLock(&IRE, &DeletedRTE, RT_EXCLUDE_LOCAL);
  4099. if (retval == IP_SUCCESS) {
  4100. DeleteDone = TRUE;
  4101. }
  4102. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4103. "Status = %08x, RTE = %p, DeletedRTE = %p\n",
  4104. retval, RTE, DeletedRTE));
  4105. // Attempt to continue the enumeration by picking up
  4106. // the next entry.
  4107. if ((retval != IP_SUCCESS) || (RTE == DeletedRTE)) {
  4108. // Either we are not allowed to delete this route
  4109. // Or we deleted what we were expecting to delete
  4110. RTE = NextRTE;
  4111. } else {
  4112. // We deleted an RTE thats further down the list
  4113. // NextRTE might be pointing to this deleted RTE
  4114. // Try to delete again and skip over RTE if cant
  4115. }
  4116. } while (RTE);
  4117. retval = IP_SUCCESS;
  4118. } while (FALSE);
  4119. CTEFreeLock(&RouteTableLock.Lock, TableLock);
  4120. if (DeleteDone) {
  4121. #if FFP_SUPPORT
  4122. FFPFlushRequired = TRUE;
  4123. #endif
  4124. }
  4125. return retval;
  4126. }
  4127. //* Redirect - Process a redirect request.
  4128. //
  4129. // This is the redirect handler . We treat all redirects as host redirects as
  4130. // per the host requirements RFC. We make a few sanity checks on the new first
  4131. // hop address, and then we look up the current route. If it's not through the
  4132. // source of the redirect, just return.
  4133. // If the current route to the destination is a host route, update the first
  4134. // hop and return.
  4135. // If the route is not a host route, remove any RCE for this route from the
  4136. // RTE, create a host route and place the RCE (if any) on the new RTE.
  4137. //
  4138. // Entry: NTE - Pointer to NetTableEntry for net on which Redirect
  4139. // arrived.
  4140. // RDSrc - IPAddress of source of redirect.
  4141. // Target - IPAddress being redirected.
  4142. // Src - Src IP address of DG that triggered RD.
  4143. // FirstHop - New first hop for Target.
  4144. //
  4145. // Returns: Nothing.
  4146. //
  4147. void
  4148. Redirect(NetTableEntry * NTE, IPAddr RDSrc, IPAddr Target, IPAddr Src,
  4149. IPAddr FirstHop)
  4150. {
  4151. uint MTU;
  4152. RouteTableEntry *RTE;
  4153. CTELockHandle Handle;
  4154. IP_STATUS Status;
  4155. IPRouteNotifyOutput RNO = {0};
  4156. if (IP_ADDR_EQUAL(FirstHop, NULL_IP_ADDR) ||
  4157. IP_LOOPBACK(FirstHop) ||
  4158. IP_ADDR_EQUAL(FirstHop, RDSrc) ||
  4159. !(NTE->nte_flags & NTE_VALID)) {
  4160. // Invalid FirstHop
  4161. return;
  4162. }
  4163. if (GetAddrType(FirstHop) == DEST_LOCAL) {
  4164. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4165. "Redirect: Local firsthop %x\n", FirstHop));
  4166. return;
  4167. }
  4168. // If the redirect is received on a loopback interface, drop it.
  4169. // This can happen in case of NAT, where it sends a packet to an addr in
  4170. // its local pool.
  4171. // These addresses are local but not bound to any interface and IP doesn't
  4172. // know about them
  4173. if (NTE == LoopNTE)
  4174. return;
  4175. ASSERT((NTE->nte_if->if_promiscuousmode) ||
  4176. ((!NTE->nte_if->if_promiscuousmode) &&
  4177. IP_ADDR_EQUAL(NTE->nte_addr, Src)));
  4178. // First make sure that this came from the gateway we're currently using to
  4179. // get to Target, and then lookup up the route to the new first hop. The new
  4180. // firsthop must be directly reachable, and on the same subnetwork or
  4181. // physical interface on which we received the redirect.
  4182. CTEGetLock(&RouteTableLock.Lock, &Handle);
  4183. // Make sure the source of the redirect is the current first hop gateway.
  4184. RTE = LookupRTE(Target, Src, HOST_ROUTE_PRI, FALSE);
  4185. if (RTE == NULL || IP_ADDR_EQUAL(RTE->rte_addr, IPADDR_LOCAL) ||
  4186. !IP_ADDR_EQUAL(RTE->rte_addr, RDSrc)) {
  4187. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4188. return; // A bad redirect.
  4189. }
  4190. ASSERT(RTE->rte_flags & RTE_IF_VALID);
  4191. // If the current first hop gateway is a default gateway, see if we have
  4192. // another default gateway at FirstHop that is down. If so, mark him as
  4193. // up and invalidate the RCEs on this guy.
  4194. if (RTE->rte_mask == DEFAULT_MASK && ValidateDefaultGWs(FirstHop) != 0) {
  4195. // Have a default gateway that's been newly activated. Invalidate RCEs
  4196. // on the route, and we're done.
  4197. InvalidateRCEChain(RTE);
  4198. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4199. return;
  4200. }
  4201. // We really need to add a host route through FirstHop. Make sure he's
  4202. // a valid first hop.
  4203. RTE = LookupRTE(FirstHop, Src, HOST_ROUTE_PRI, FALSE);
  4204. if (RTE == NULL) {
  4205. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4206. return; // Can't get there from here.
  4207. }
  4208. ASSERT(RTE->rte_flags & RTE_IF_VALID);
  4209. // Check to make sure the new first hop is directly reachable, and is on the
  4210. // same subnet or physical interface we received the redirect on.
  4211. if (!IP_ADDR_EQUAL(RTE->rte_addr, IPADDR_LOCAL) || // Not directly reachable
  4212. // or wrong subnet.
  4213. ((NTE->nte_addr & NTE->nte_mask) != (FirstHop & NTE->nte_mask))) {
  4214. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4215. return;
  4216. }
  4217. if (RTE->rte_link)
  4218. MTU = RTE->rte_link->link_mtu;
  4219. else
  4220. MTU = RTE->rte_mtu;
  4221. // Now add a host route. AddRoute will do the correct things with shifting
  4222. // RCEs around. We know that FirstHop is on the same subnet as NTE (from
  4223. // the check above), so it's valid to add the route to FirstHop as out
  4224. // going through NTE.
  4225. Status = LockedAddRoute(Target, HOST_MASK,
  4226. IP_ADDR_EQUAL(FirstHop, Target)
  4227. ? IPADDR_LOCAL : FirstHop,
  4228. NTE->nte_if, MTU, 1, IRE_PROTO_ICMP, ATYPE_OVERRIDE,
  4229. RTE->rte_context, FALSE, &RNO);
  4230. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4231. if (Status == IP_SUCCESS && RNO.irno_ifindex) {
  4232. RtChangeNotifyEx(&RNO);
  4233. RtChangeNotify(&RNO);
  4234. }
  4235. //
  4236. // Bug: #67333: delete the old route thru' RDSrc, now that we have a new one.
  4237. //
  4238. // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4239. // "Re-direct: deleting old route thru: %lx, to Target: %lx\n",
  4240. // RDSrc, Target));
  4241. DeleteRoute(Target, HOST_MASK, RDSrc, NTE->nte_if, 0);
  4242. }
  4243. //* GetRaisedMTU - Get the next largest MTU in table.
  4244. //
  4245. // A utility function to search the MTU table for a larger value.
  4246. //
  4247. // Input: PrevMTU - MTU we're currently using. We want the next largest one.
  4248. //
  4249. // Returns: New MTU size.
  4250. //
  4251. uint
  4252. GetRaisedMTU(uint PrevMTU)
  4253. {
  4254. uint i;
  4255. for (i = (sizeof(MTUTable) / sizeof(uint)) - 1; i != 0; i--) {
  4256. if (MTUTable[i] > PrevMTU)
  4257. break;
  4258. }
  4259. return MTUTable[i];
  4260. }
  4261. //* GuessNewMTU - Guess a new MTU, giving a DG size too big.
  4262. //
  4263. // A utility function to search the MTU table. As input we take in an MTU
  4264. // size we believe to be too large, and search the table looking for the
  4265. // next smallest one.
  4266. //
  4267. // Input: TooBig - Size that's too big.
  4268. //
  4269. // Returns: New MTU size.
  4270. //
  4271. uint
  4272. GuessNewMTU(uint TooBig)
  4273. {
  4274. uint i;
  4275. for (i = 0; i < ((sizeof(MTUTable) / sizeof(uint)) - 1); i++)
  4276. if (MTUTable[i] < TooBig)
  4277. break;
  4278. return MTUTable[i];
  4279. }
  4280. //* RouteFragNeeded - Handle being told we need to fragment.
  4281. //
  4282. // Called when we receive some external indication that we need to fragment
  4283. // along a particular path. If we're doing MTU discovery we'll try to
  4284. // update the route, if we can. We'll also notify the upper layers about
  4285. // the new MTU.
  4286. //
  4287. // Input: IPH - Pointer to IP Header of datagram needing
  4288. // fragmentation.
  4289. // NewMTU - New MTU to be used (may be 0).
  4290. //
  4291. // Returns: Nothing.
  4292. //
  4293. void
  4294. RouteFragNeeded(IPHeader UNALIGNED * IPH, ushort NewMTU)
  4295. {
  4296. uint OldMTU;
  4297. CTELockHandle Handle;
  4298. RouteTableEntry *RTE;
  4299. ushort HeaderLength;
  4300. ushort mtu;
  4301. IP_STATUS Status;
  4302. IPRouteNotifyOutput RNO = {0};
  4303. // If we're not doing PMTU discovery, don't do anything.
  4304. if (!PMTUDiscovery) {
  4305. return;
  4306. }
  4307. // We're doing PMTU discovery. Before doing any work, make sure this is
  4308. // an acceptable message.
  4309. if (GetAddrType(IPH->iph_dest) != DEST_REMOTE) {
  4310. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  4311. "RouteFragNeeded: non-remote dest %x\n", IPH->iph_dest));
  4312. return;
  4313. }
  4314. // Correct the given new MTU for the IP header size, which we don't save
  4315. // as we track MTUs.
  4316. if (NewMTU != 0) {
  4317. // Make sure the new MTU we got is at least the minimum valid size.
  4318. NewMTU = MAX(NewMTU, MIN_VALID_MTU);
  4319. NewMTU -= sizeof(IPHeader);
  4320. }
  4321. HeaderLength = (IPH->iph_verlen & (uchar) ~ IP_VER_FLAG) << 2;
  4322. // Get the current routing information.
  4323. CTEGetLock(&RouteTableLock.Lock, &Handle);
  4324. // Find an RTE for the destination.
  4325. RTE = LookupRTE(IPH->iph_dest, IPH->iph_src, HOST_ROUTE_PRI, FALSE);
  4326. // If we couldn't find one, give up now.
  4327. if (RTE == NULL) {
  4328. // No RTE. Just bail out now.
  4329. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4330. return;
  4331. }
  4332. if (RTE->rte_link)
  4333. mtu = (ushort) RTE->rte_link->link_mtu;
  4334. else
  4335. mtu = (ushort) RTE->rte_mtu;
  4336. // If the existing MTU is less than the new
  4337. // MTU, give up now.
  4338. if ((OldMTU = mtu) < NewMTU) {
  4339. // No RTE, or an invalid new MTU. Just bail out now.
  4340. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4341. return;
  4342. }
  4343. // If the new MTU is zero, figure out what the new MTU should be.
  4344. if (NewMTU == 0) {
  4345. ushort DGLength;
  4346. // The new MTU is zero. We'll make a best guess what the new
  4347. // MTU should be. We have the RTE for this route already.
  4348. // Get the length of the datagram that triggered this. Since we'll
  4349. // be comparing it against MTU values that we track without the
  4350. // IP header size included, subtract off that amount.
  4351. DGLength = (ushort) net_short(IPH->iph_length) - sizeof(IPHeader);
  4352. // We may need to correct this as per RFC 1191 for dealing with
  4353. // old style routers.
  4354. if (DGLength >= OldMTU) {
  4355. // The length of the datagram sent is not less than our
  4356. // current MTU estimate, so we need to back it down (assuming
  4357. // that the sending route has incorrectly added in the header
  4358. // length).
  4359. DGLength -= HeaderLength;
  4360. }
  4361. // If it's still larger than our current MTU, use the current
  4362. // MTU. This could happen if the upper layer sends a burst of
  4363. // packets which generate a sequence of ICMP discard messages. The
  4364. // first one we receive will cause us to lower our MTU. We then
  4365. // want to discard subsequent messages to avoid lowering it
  4366. // too much. This could conceivably be a problem if our
  4367. // first adjustment still results in an MTU that's too big,
  4368. // but we should converge adequately fast anyway, and it's
  4369. // better than accidentally underestimating the MTU.
  4370. if (DGLength > OldMTU)
  4371. NewMTU = (ushort) OldMTU;
  4372. else
  4373. // Move down the table to the next lowest MTU.
  4374. NewMTU = (ushort) GuessNewMTU(DGLength);
  4375. }
  4376. // We have the new MTU. Now add it to the table as a host route.
  4377. Status = IP_GENERAL_FAILURE;
  4378. if (NewMTU != OldMTU) {
  4379. // Use ICMP protocol type only when adding a new host route;
  4380. // otherwise, an existing static entry might get overwritten and,
  4381. // later on, timed out as though it were an ICMP route.
  4382. if (IP_ADDR_EQUAL(RTE->rte_dest,IPH->iph_dest)) {
  4383. Status = LockedAddRoute(IPH->iph_dest, HOST_MASK, RTE->rte_addr,
  4384. RTE->rte_if, NewMTU, RTE->rte_metric,
  4385. RTE->rte_proto, ATYPE_OVERRIDE,
  4386. RTE->rte_context, FALSE, &RNO);
  4387. } else {
  4388. Status = LockedAddRoute(IPH->iph_dest, HOST_MASK, RTE->rte_addr,
  4389. RTE->rte_if, NewMTU, RTE->rte_metric,
  4390. IRE_PROTO_ICMP, ATYPE_OVERRIDE,
  4391. RTE->rte_context, FALSE, &RNO);
  4392. }
  4393. }
  4394. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4395. // We've added the route. Now notify the upper layers of the change.
  4396. ULMTUNotify(IPH->iph_dest, IPH->iph_src, IPH->iph_protocol,
  4397. (void *)((uchar *) IPH + HeaderLength), NewMTU);
  4398. if (Status == IP_SUCCESS && RNO.irno_ifindex) {
  4399. RtChangeNotifyEx(&RNO);
  4400. RtChangeNotify(&RNO);
  4401. }
  4402. }
  4403. //** IPRouteTimeout - IP routeing timeout handler.
  4404. //
  4405. // The IP routeing timeout routine, called once a minute. We look at all
  4406. // host routes, and if we raise the MTU on them we do so.
  4407. //
  4408. // Entry: Timer - Timer being fired.
  4409. // Context - Pointer to NTE being time out.
  4410. //
  4411. // Returns: Nothing.
  4412. //
  4413. void
  4414. IPRouteTimeout(CTEEvent * Timer, void *Context)
  4415. {
  4416. uint Now = CTESystemUpTime() / 1000L;
  4417. CTELockHandle Handle;
  4418. uint i;
  4419. RouteTableEntry *RTE, *PrevRTE;
  4420. uint RaiseMTU, Delta;
  4421. Interface *IF;
  4422. IPAddr Dest;
  4423. uint NewMTU;
  4424. NetTableEntry *NTE;
  4425. RouteTableEntry *pOldBestRTE, *pNewBestRTE;
  4426. UINT IsDataLeft, IsValid;
  4427. UCHAR IteratorContext[CONTEXT_SIZE];
  4428. uint mtu;
  4429. RtChangeList *CurrentRtChangeList = NULL;
  4430. DampCheck();
  4431. if ((CTEInterlockedIncrementLong(&RouteTimerTicks) * IP_ROUTE_TIMEOUT) == IP_RTABL_TIMEOUT) {
  4432. RouteTimerTicks = 0;
  4433. CTEGetLock(&RouteTableLock.Lock, &Handle);
  4434. // First we set up an iterator over all routes
  4435. RtlZeroMemory(IteratorContext, CONTEXT_SIZE);
  4436. // Do we have any routes at all in the table ?
  4437. IsDataLeft = RTValidateContext(IteratorContext, &IsValid);
  4438. PrevRTE = NULL;
  4439. while (IsDataLeft) {
  4440. // Advance context by getting the next route
  4441. IsDataLeft = GetNextRoute(IteratorContext, &RTE);
  4442. // Do we have to delete the previous route ?
  4443. if (PrevRTE != NULL) {
  4444. IPRouteNotifyOutput RNO = {0};
  4445. RtChangeList *NewRtChange;
  4446. // Retrieve information about the route for change-notification
  4447. // before proceeding with deletion.
  4448. RNO.irno_dest = PrevRTE->rte_dest;
  4449. RNO.irno_mask = PrevRTE->rte_mask;
  4450. RNO.irno_nexthop = GetNextHopForRTE(PrevRTE);
  4451. RNO.irno_proto = PrevRTE->rte_proto;
  4452. RNO.irno_ifindex = PrevRTE->rte_if->if_index;
  4453. RNO.irno_metric = PrevRTE->rte_metric;
  4454. RNO.irno_flags = IRNO_FLAG_DELETE;
  4455. DelRoute(PrevRTE->rte_dest, PrevRTE->rte_mask,
  4456. PrevRTE->rte_addr, PrevRTE->rte_if, MATCH_FULL,
  4457. &PrevRTE, &pOldBestRTE, &pNewBestRTE);
  4458. CleanupP2MP_RTE(PrevRTE);
  4459. CleanupRTE(PrevRTE);
  4460. //... so we don't delete same route again
  4461. PrevRTE = NULL;
  4462. // Allocate, initialize and queue a change-notification entry
  4463. // for the deleted route.
  4464. NewRtChange = CTEAllocMemNBoot(sizeof(RtChangeList), 'XICT');
  4465. if (NewRtChange != NULL) {
  4466. NewRtChange->rt_next = CurrentRtChangeList;
  4467. NewRtChange->rt_info = RNO;
  4468. CurrentRtChangeList = NewRtChange;
  4469. }
  4470. }
  4471. // Make sure this route is a valid host route
  4472. if (!(RTE->rte_flags & RTE_VALID))
  4473. continue;
  4474. if (RTE->rte_mask != HOST_MASK)
  4475. continue;
  4476. // We have valid host route here
  4477. if (PMTUDiscovery) {
  4478. // Check to see if we can raise the MTU on this guy.
  4479. Delta = Now - RTE->rte_mtuchange;
  4480. if (RTE->rte_flags & RTE_INCREASE)
  4481. RaiseMTU = (Delta >= MTU_INCREASE_TIME ? 1 : 0);
  4482. else
  4483. RaiseMTU = (Delta >= MTU_DECREASE_TIME ? 1 : 0);
  4484. if (RaiseMTU) {
  4485. // We need to raise this MTU. Set his change time to
  4486. // Now, so we don't do this again, and figure out
  4487. // what the new MTU should be.
  4488. RTE->rte_mtuchange = Now;
  4489. IF = RTE->rte_if;
  4490. if (RTE->rte_mtu < IF->if_mtu) {
  4491. uint RaisedMTU;
  4492. RTE->rte_flags |= RTE_INCREASE;
  4493. // This is a candidate for change. Figure out
  4494. // what it should be.
  4495. RaisedMTU = GetRaisedMTU(RTE->rte_mtu);
  4496. NewMTU = MIN(RaisedMTU,
  4497. IF->if_mtu);
  4498. RTE->rte_mtu = NewMTU;
  4499. Dest = RTE->rte_dest;
  4500. // We have the new MTU. Free the lock, and walk
  4501. // down the NTEs on the I/F. For each NTE,
  4502. // call up to the upper layer and tell him what
  4503. // his new MTU is.
  4504. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4505. NTE = IF->if_nte;
  4506. while (NTE != NULL) {
  4507. if (NTE->nte_flags & NTE_VALID) {
  4508. ULMTUNotify(Dest, NTE->nte_addr, 0, NULL,
  4509. MIN(NewMTU, NTE->nte_mss));
  4510. }
  4511. NTE = NTE->nte_ifnext;
  4512. }
  4513. // We've notified everyone. Get the lock again,
  4514. // and validate context in case something changed
  4515. // after we freed the lock. In case it's invalid,
  4516. // start from first. We've updated the mtuchange
  4517. // time of this RTE, so we won't hit him again.
  4518. CTEGetLock(&RouteTableLock.Lock, &Handle);
  4519. RTValidateContext(IteratorContext, &IsValid);
  4520. if (!IsValid) {
  4521. RtlZeroMemory(IteratorContext, CONTEXT_SIZE);
  4522. IsDataLeft = RTValidateContext(IteratorContext, &IsValid);
  4523. continue;
  4524. }
  4525. // We still have a valid iterator context here
  4526. } else {
  4527. RTE->rte_flags &= ~RTE_INCREASE;
  4528. }
  4529. }
  4530. }
  4531. // If this route came in via ICMP, and we have no RCEs on it,
  4532. // and it's at least 10 minutes old, delete it.
  4533. if (RTE->rte_proto == IRE_PROTO_ICMP &&
  4534. RTE->rte_rcelist == NULL &&
  4535. (Now - RTE->rte_valid) > MAX_ICMP_ROUTE_VALID) {
  4536. // He needs to be deleted. Call DelRoute to do this.
  4537. // But after you have updated the context to next RTE
  4538. // Route for deletion in next iteration
  4539. PrevRTE = RTE;
  4540. continue;
  4541. }
  4542. }
  4543. // Did we have to delete the previous route ?
  4544. if (PrevRTE != NULL) {
  4545. IPRouteNotifyOutput RNO = {0};
  4546. RtChangeList *NewRtChange;
  4547. // Retrieve information about the route for change-notification
  4548. // before proceeding with deletion.
  4549. RNO.irno_dest = PrevRTE->rte_dest;
  4550. RNO.irno_mask = PrevRTE->rte_mask;
  4551. RNO.irno_nexthop = GetNextHopForRTE(PrevRTE);
  4552. RNO.irno_proto = PrevRTE->rte_proto;
  4553. RNO.irno_ifindex = PrevRTE->rte_if->if_index;
  4554. RNO.irno_metric = PrevRTE->rte_metric;
  4555. RNO.irno_flags = IRNO_FLAG_DELETE;
  4556. // Delete the route and perform cleanup.
  4557. DelRoute(PrevRTE->rte_dest, PrevRTE->rte_mask, PrevRTE->rte_addr,
  4558. PrevRTE->rte_if, MATCH_FULL, &PrevRTE, &pOldBestRTE,
  4559. &pNewBestRTE);
  4560. CleanupP2MP_RTE(PrevRTE);
  4561. CleanupRTE(PrevRTE);
  4562. // Allocate, initialize and queue a change-notification entry
  4563. // for the deleted route.
  4564. NewRtChange = CTEAllocMemNBoot(sizeof(RtChangeList), 'DiCT');
  4565. if (NewRtChange != NULL) {
  4566. NewRtChange->rt_next = CurrentRtChangeList;
  4567. NewRtChange->rt_info = RNO;
  4568. CurrentRtChangeList = NewRtChange;
  4569. }
  4570. }
  4571. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4572. }
  4573. #if FFP_SUPPORT
  4574. if (FFPFlushRequired) {
  4575. FFPFlushRequired = FALSE;
  4576. IPFlushFFPCaches();
  4577. }
  4578. #endif
  4579. if ((CTEInterlockedIncrementLong(&FlushIFTimerTicks) * IP_ROUTE_TIMEOUT) == FLUSH_IFLIST_TIMEOUT) {
  4580. Interface *TmpIF;
  4581. RouteCacheEntry *RCE, *PrevRCE;
  4582. FlushIFTimerTicks = 0;
  4583. CTEGetLock(&RouteTableLock.Lock, &Handle);
  4584. // check whether FreeIFList is non empty
  4585. if (FrontFreeList) {
  4586. ASSERT(*(int *)&TotalFreeInterfaces > 0);
  4587. // free the first interface in the list
  4588. TmpIF = FrontFreeList;
  4589. FrontFreeList = FrontFreeList->if_next;
  4590. CTEFreeMem(TmpIF);
  4591. TotalFreeInterfaces--;
  4592. // check whether the list became empty
  4593. if (FrontFreeList == NULL) {
  4594. RearFreeList = NULL;
  4595. ASSERT(TotalFreeInterfaces == 0);
  4596. }
  4597. }
  4598. // use the same timer to scan the RCEFreeList
  4599. PrevRCE = STRUCT_OF(RouteCacheEntry, &RCEFreeList, rce_next);
  4600. RCE = RCEFreeList;
  4601. while (RCE) {
  4602. if (RCE->rce_usecnt == 0) {
  4603. RouteCacheEntry *nextRCE;
  4604. // time to free this RCE
  4605. // remove it from the list
  4606. PrevRCE->rce_next = RCE->rce_next;
  4607. if (RCE->rce_flags & RCE_REFERENCED) {
  4608. // IF is ref'd so it better be in the IFList
  4609. LockedDerefIF((Interface *) RCE->rce_rte);
  4610. }
  4611. nextRCE = RCE->rce_next;
  4612. CTEFreeMem(RCE);
  4613. RCE = nextRCE;
  4614. } else {
  4615. PrevRCE = RCE;
  4616. RCE = RCE->rce_next;
  4617. }
  4618. }
  4619. CTEFreeLock(&RouteTableLock.Lock, Handle);
  4620. }
  4621. // Call RtChangeNotify for each of the entries in the change-notification
  4622. // list that we've built up so far. In the process, free each entry.
  4623. if (CurrentRtChangeList) {
  4624. RtChangeList *TmpRtChangeList;
  4625. do {
  4626. TmpRtChangeList = CurrentRtChangeList->rt_next;
  4627. RtChangeNotify(&CurrentRtChangeList->rt_info);
  4628. CTEFreeMem(CurrentRtChangeList);
  4629. CurrentRtChangeList = TmpRtChangeList;
  4630. } while(CurrentRtChangeList);
  4631. }
  4632. // If the driver is unloading, dont restart the timer
  4633. if (fRouteTimerStopping) {
  4634. CTESignal(&TcpipUnloadBlock, NDIS_STATUS_SUCCESS);
  4635. } else {
  4636. CTEStartTimer(&IPRouteTimer, IP_ROUTE_TIMEOUT, IPRouteTimeout, NULL);
  4637. }
  4638. }
  4639. //* FreeFWPacket - Free a fowarding packet to its pool.
  4640. //
  4641. // Input: Packet - Packet to be freed.
  4642. //
  4643. // Returns: nothing.
  4644. //
  4645. void
  4646. FreeFWPacket(PNDIS_PACKET Packet)
  4647. {
  4648. FWContext *FWC = (FWContext *)Packet->ProtocolReserved;
  4649. ASSERT(FWC->fc_pc.pc_common.pc_IpsecCtx == NULL);
  4650. // Return any buffers to their respective pools.
  4651. //
  4652. if (FWC->fc_buffhead) {
  4653. PNDIS_BUFFER Head, Mdl;
  4654. Head = FWC->fc_buffhead;
  4655. do {
  4656. Mdl = Head;
  4657. Head = Head->Next;
  4658. MdpFree(Mdl);
  4659. } while (Head);
  4660. FWC->fc_buffhead = NULL;
  4661. }
  4662. if (FWC->fc_options) {
  4663. CTEFreeMem(FWC->fc_options);
  4664. FWC->fc_options = NULL;
  4665. FWC->fc_optlength = 0;
  4666. FWC->fc_pc.pc_common.pc_flags &= ~PACKET_FLAG_OPTIONS;
  4667. }
  4668. if (FWC->fc_iflink) {
  4669. DerefLink(FWC->fc_iflink);
  4670. FWC->fc_iflink = NULL;
  4671. }
  4672. if (FWC->fc_if) {
  4673. DerefIF(FWC->fc_if);
  4674. FWC->fc_if = NULL;
  4675. }
  4676. NdisReinitializePacket(Packet);
  4677. #if MCAST_BUG_TRACKING
  4678. FWC->fc_pc.pc_common.pc_owner = 0;
  4679. #endif
  4680. FwPacketFree(Packet);
  4681. }
  4682. //* FWSendComplete - Complete the transmission of a forwarded packet.
  4683. //
  4684. // This is called when the send of a forwarded packet is done. We'll free the
  4685. // resources and get the next send going, if there is one. If there isn't,
  4686. // we'll decrement the pending count.
  4687. //
  4688. // Input: Packet - Packet being completed.
  4689. // Buffer - Pointer to buffer chain being completed.
  4690. //
  4691. // Returns: Nothing.
  4692. //
  4693. void
  4694. FWSendComplete(void *SendContext, PNDIS_BUFFER Buffer, IP_STATUS SendStatus)
  4695. {
  4696. PNDIS_PACKET Packet = (PNDIS_PACKET) SendContext;
  4697. FWContext *FWC = (FWContext *) Packet->ProtocolReserved;
  4698. RouteSendQ *RSQ;
  4699. CTELockHandle Handle;
  4700. FWQ *NewFWQ;
  4701. PNDIS_PACKET NewPacket;
  4702. #if MCAST_BUG_TRACKING
  4703. FWC->fc_MacHdrSize = SendStatus;
  4704. #endif
  4705. if (Buffer && FWC->fc_bufown) {
  4706. //Undo the offset manipulation
  4707. //which was done in super fast path
  4708. int MacHeaderSize = FWC->fc_MacHdrSize;
  4709. PNDIS_PACKET RtnPacket = FWC->fc_bufown;
  4710. NdisAdjustBuffer(
  4711. Buffer,
  4712. (PCHAR) NdisBufferVirtualAddress(Buffer) - MacHeaderSize,
  4713. NdisBufferLength(Buffer) + MacHeaderSize);
  4714. Packet->Private.Head = NULL;
  4715. Packet->Private.Tail = NULL;
  4716. NdisReturnPackets(&RtnPacket, 1);
  4717. FWC->fc_bufown = NULL;
  4718. #if MCAST_BUG_TRACKING
  4719. FWC->fc_sos = __LINE__;
  4720. #endif
  4721. FreeFWPacket(Packet);
  4722. return;
  4723. }
  4724. if (!IS_BCAST_DEST(FWC->fc_dtype))
  4725. RSQ = &((RouteInterface *) FWC->fc_if)->ri_q;
  4726. else
  4727. RSQ = BCastRSQ;
  4728. if (IS_MCAST_DEST(FWC->fc_dtype)) {
  4729. RSQ = NULL;
  4730. }
  4731. #if MCAST_BUG_TRACKING
  4732. FWC->fc_sos = __LINE__;
  4733. #endif
  4734. FreeFWPacket(Packet);
  4735. if (RSQ == NULL) {
  4736. return;
  4737. }
  4738. CTEGetLock(&RSQ->rsq_lock, &Handle);
  4739. ASSERT(RSQ->rsq_pending <= RSQ->rsq_maxpending);
  4740. RSQ->rsq_pending--;
  4741. ASSERT(*(int *)&RSQ->rsq_pending >= 0);
  4742. if (RSQ->rsq_qlength != 0) { // Have more to send.
  4743. ASSERT(IPSecHandlerPtr == NULL);
  4744. // Make sure we're not already running through this. If we are, quit.
  4745. if (!RSQ->rsq_running) {
  4746. // We could schedule this off for an event, but under NT that
  4747. // could me a context switch for every completing packet in the
  4748. // normal case. For now, just do it in a loop guarded with
  4749. // rsq_running.
  4750. RSQ->rsq_running = TRUE;
  4751. // Loop while we haven't hit our send limit and we still have
  4752. // stuff to send.
  4753. while (RSQ->rsq_pending < RSQ->rsq_maxpending &&
  4754. RSQ->rsq_qlength != 0) {
  4755. ASSERT(RSQ->rsq_qh.fq_next != &RSQ->rsq_qh);
  4756. // Pull one off the queue, and update qlength.
  4757. NewFWQ = RSQ->rsq_qh.fq_next;
  4758. RSQ->rsq_qh.fq_next = NewFWQ->fq_next;
  4759. NewFWQ->fq_next->fq_prev = NewFWQ->fq_prev;
  4760. RSQ->rsq_qlength--;
  4761. // Update pending before we send.
  4762. RSQ->rsq_pending++;
  4763. CTEFreeLock(&RSQ->rsq_lock, Handle);
  4764. NewPacket = PACKET_FROM_FWQ(NewFWQ);
  4765. TransmitFWPacket(NewPacket,
  4766. ((FWContext *) NewPacket->ProtocolReserved)->fc_datalength);
  4767. CTEGetLock(&RSQ->rsq_lock, &Handle);
  4768. }
  4769. RSQ->rsq_running = FALSE;
  4770. }
  4771. }
  4772. CTEFreeLock(&RSQ->rsq_lock, Handle);
  4773. }
  4774. //* TransmitFWPacket - Transmit a forwarded packet on a link.
  4775. //
  4776. // Called when we know we can send a packet. We fix up the header, and send it.
  4777. //
  4778. // Input: Packet - Packet to be sent.
  4779. // DataLength - Length of data.
  4780. //
  4781. // Returns: Nothing.
  4782. //
  4783. void
  4784. TransmitFWPacket(PNDIS_PACKET Packet, uint DataLength)
  4785. {
  4786. FWContext *FC = (FWContext *) Packet->ProtocolReserved;
  4787. PNDIS_BUFFER HBuffer, Buffer;
  4788. IP_STATUS Status;
  4789. PVOID VirtualAddress;
  4790. UINT BufLen;
  4791. ULONG ipsecByteCount = 0;
  4792. ULONG ipsecMTU;
  4793. ULONG ipsecFlags;
  4794. IPHeader *IPH;
  4795. ULONG len;
  4796. IPAddr SrcAddr;
  4797. PNDIS_BUFFER OptBuffer;
  4798. PNDIS_BUFFER newBuf = NULL;
  4799. IPHeader *pSaveIPH;
  4800. UCHAR saveIPH[MAX_IP_HDR_SIZE + ICMP_HEADER_SIZE];
  4801. ULONG hdrLen;
  4802. void *ArpCtxt = NULL;
  4803. //
  4804. // Fix up the packet. Remove the existing buffer chain, and put our
  4805. // header on the front.
  4806. //
  4807. Buffer = Packet->Private.Head;
  4808. HBuffer = FC->fc_hndisbuff;
  4809. Packet->Private.Head = HBuffer;
  4810. Packet->Private.Tail = HBuffer;
  4811. NDIS_BUFFER_LINKAGE(HBuffer) = (PNDIS_BUFFER) NULL;
  4812. Packet->Private.TotalLength = sizeof(IPHeader);
  4813. Packet->Private.Count = 1;
  4814. TcpipQueryBuffer(HBuffer, &VirtualAddress, &BufLen, NormalPagePriority);
  4815. if (VirtualAddress == NULL) {
  4816. #if MCAST_BUG_TRACKING
  4817. FC->fc_mtu = __LINE__;
  4818. #endif
  4819. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  4820. IPSInfo.ipsi_outdiscards++;
  4821. return;
  4822. }
  4823. Packet->Private.PhysicalCount =
  4824. ADDRESS_AND_SIZE_TO_SPAN_PAGES(VirtualAddress,
  4825. sizeof(IPHeader));
  4826. TcpipQueryBuffer(HBuffer, (PVOID *) &IPH, &len, NormalPagePriority);
  4827. if (IPH == NULL) {
  4828. #if MCAST_BUG_TRACKING
  4829. FC->fc_mtu = __LINE__;
  4830. #endif
  4831. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  4832. IPSInfo.ipsi_outdiscards++;
  4833. return;
  4834. }
  4835. if (IPSecHandlerPtr) {
  4836. //
  4837. // See if IPSEC is enabled, see if it needs to do anything with this
  4838. // packet - we need to construct the full IP header in the first MDL
  4839. // before we call out to IPSEC.
  4840. //
  4841. IPSEC_ACTION Action;
  4842. ulong csum;
  4843. PUCHAR pTpt;
  4844. ULONG tptLen;
  4845. pSaveIPH = (IPHeader *) saveIPH;
  4846. *pSaveIPH = *IPH;
  4847. csum = xsum(IPH, sizeof(IPHeader));
  4848. //
  4849. // Link the header buffer to the options buffer before we indicate
  4850. // to IPSEC
  4851. //
  4852. if (FC->fc_options) {
  4853. //
  4854. // Allocate the MDL for options too
  4855. //
  4856. NdisAllocateBuffer(&Status,
  4857. &OptBuffer,
  4858. BufferPool,
  4859. FC->fc_options,
  4860. (uint) FC->fc_optlength);
  4861. if (Status != NDIS_STATUS_SUCCESS) {
  4862. //
  4863. // Couldn't get the needed option buffer.
  4864. //
  4865. #if MCAST_BUG_TRACKING
  4866. FC->fc_mtu = __LINE__;
  4867. #endif
  4868. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  4869. IPSInfo.ipsi_outdiscards++;
  4870. return;
  4871. }
  4872. NDIS_BUFFER_LINKAGE(HBuffer) = OptBuffer;
  4873. NDIS_BUFFER_LINKAGE(OptBuffer) = Buffer;
  4874. //
  4875. // update the xsum in the IP header
  4876. //
  4877. FC->fc_pc.pc_common.pc_flags |= PACKET_FLAG_OPTIONS;
  4878. NdisChainBufferAtBack(Packet, OptBuffer);
  4879. csum += xsum(FC->fc_options, (uint) FC->fc_optlength);
  4880. csum = (csum >> 16) + (csum & 0xffff);
  4881. csum += (csum >> 16);
  4882. } else {
  4883. NDIS_BUFFER_LINKAGE(HBuffer) = Buffer;
  4884. }
  4885. //
  4886. // Prepare ourselves for sending an ICMP dont frag in case
  4887. // IPSEC bloats beyond the MTU on this interface.
  4888. //
  4889. // SendICMPErr expects the next transport header in the same
  4890. // contiguous buffer as the IPHeader, with or without options.
  4891. // We need to ensure that this is satisfied if in fact we need to
  4892. // fragment on account of IPSEC. So, setup the buffer right here.
  4893. //
  4894. //
  4895. // If this is a zero-payload packet (i.e. just a header), then Buffer
  4896. // is NULL and there is nothing for IPSEC to bloat. We only have to
  4897. // deal with the don't fragment flag if there is a Buffer.
  4898. //
  4899. if (Buffer && (pSaveIPH->iph_offset & IP_DF_FLAG)) {
  4900. TcpipQueryBuffer(Buffer, &pTpt, &tptLen, NormalPagePriority);
  4901. if (pTpt == NULL) {
  4902. #if MCAST_BUG_TRACKING
  4903. FC->fc_mtu = __LINE__;
  4904. #endif
  4905. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  4906. IPSInfo.ipsi_outdiscards++;
  4907. return;
  4908. }
  4909. RtlCopyMemory(((PUCHAR) (pSaveIPH + 1)) + FC->fc_optlength,
  4910. pTpt,
  4911. ICMP_HEADER_SIZE);
  4912. }
  4913. IPH->iph_xsum = ~(ushort) csum;
  4914. SrcAddr = FC->fc_if->if_nte->nte_addr;
  4915. ipsecMTU = FC->fc_mtu;
  4916. if ((DataLength + (uint) FC->fc_optlength) < FC->fc_mtu) {
  4917. ipsecByteCount = FC->fc_mtu - (DataLength + (uint) FC->fc_optlength);
  4918. }
  4919. ipsecFlags = IPSEC_FLAG_FORWARD;
  4920. Action = (*IPSecHandlerPtr) ((PUCHAR) IPH,
  4921. (PVOID) HBuffer,
  4922. FC->fc_if,
  4923. Packet,
  4924. &ipsecByteCount,
  4925. &ipsecMTU,
  4926. (PVOID) & newBuf,
  4927. &ipsecFlags,
  4928. FC->fc_dtype);
  4929. if (Action != eFORWARD) {
  4930. #if MCAST_BUG_TRACKING
  4931. FC->fc_mtu = __LINE__;
  4932. #endif
  4933. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  4934. IPSInfo.ipsi_outdiscards++;
  4935. //
  4936. // We can get MTU redeuced also when forwarding because in the nested
  4937. // tunneling configuration, the tunnel that starts from this machine
  4938. // can get a ICMP PMTU packet. We can't reduce the MTU on the interface
  4939. // but we can send back to the sender (which can be a router with yet
  4940. // another tunnel for this packet) a PMTU packet asking him to reduce his
  4941. // MTU even further. If the sender is an end-station, this PMTU info
  4942. // will eventually propogate back to TCP stack. If it is a router, the
  4943. // same logic used here will be applied. The MTU info will thus be
  4944. // relayed all the way back to the original sender (TCP stack).
  4945. // Of course the more common case is that a packet with the added IPSec
  4946. // header exceeds the link MTU. No matter what is the case, we send the
  4947. // new MTU information back to the sender.
  4948. //
  4949. if (ipsecMTU) {
  4950. SendICMPIPSecErr(SrcAddr,
  4951. pSaveIPH,
  4952. ICMP_DEST_UNREACH,
  4953. FRAG_NEEDED,
  4954. net_long((ulong) (ipsecMTU + sizeof(IPHeader))));
  4955. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"TransmitFWPacket: Sent ICMP frag_needed to %lx, from src: %lx\n", pSaveIPH->iph_src, SrcAddr));
  4956. }
  4957. return;
  4958. } else {
  4959. //
  4960. // Use the new buffer chain - IPSEC will restore the old one
  4961. // on send complete
  4962. //
  4963. if (newBuf) {
  4964. NdisReinitializePacket(Packet);
  4965. NdisChainBufferAtBack(Packet, newBuf);
  4966. }
  4967. DataLength += ipsecByteCount;
  4968. }
  4969. }
  4970. //
  4971. // Figure out how to send it. If it's not a broadcast we'll either
  4972. // send it or have it fragmented. If it is a broadcast we'll let our
  4973. // send broadcast routine handle it.
  4974. //
  4975. if (FC->fc_dtype != DEST_BCAST) {
  4976. if ((DataLength + (uint) FC->fc_optlength) <= FC->fc_mtu) {
  4977. if (FC->fc_iflink) {
  4978. ASSERT(FC->fc_if->if_flags & IF_FLAGS_P2MP);
  4979. ArpCtxt = FC->fc_iflink->link_arpctxt;
  4980. }
  4981. //
  4982. // In case of synchronous completion though
  4983. // FreeIPPacket is called, which will not
  4984. // free the FW packet.
  4985. //
  4986. Status = SendIPPacket(FC->fc_if,
  4987. FC->fc_nexthop,
  4988. Packet,
  4989. Buffer,
  4990. FC->fc_hbuff,
  4991. FC->fc_options,
  4992. (uint) FC->fc_optlength,
  4993. (BOOLEAN) (IPSecHandlerPtr != NULL),
  4994. ArpCtxt,
  4995. FALSE);
  4996. } else {
  4997. //
  4998. // Need to fragment this.
  4999. //
  5000. BufferReference *BR = CTEAllocMemN(sizeof(BufferReference), 'GiCT');
  5001. if (BR == (BufferReference *) NULL) {
  5002. //
  5003. // Couldn't get a BufferReference
  5004. //
  5005. #if MCAST_BUG_TRACKING
  5006. FC->fc_mtu = __LINE__;
  5007. #endif
  5008. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  5009. return;
  5010. }
  5011. BR->br_buffer = Buffer;
  5012. BR->br_refcount = 0;
  5013. CTEInitLock(&BR->br_lock);
  5014. FC->fc_pc.pc_br = BR;
  5015. BR->br_userbuffer = 0;
  5016. if (IPSecHandlerPtr) {
  5017. Buffer = NDIS_BUFFER_LINKAGE(HBuffer);
  5018. //
  5019. // This is to ensure that options are freed appropriately.
  5020. // In the fragment code, the first fragment inherits the
  5021. // options of the entire packet; but these packets have
  5022. // no IPSEC context, hence cannot be freed appropriately.
  5023. // So, we allocate temporary options here and use these
  5024. // to represent the real options. These are freed when the
  5025. // first fragment is freed and the real options are freed here.
  5026. //
  5027. if (FC->fc_options) {
  5028. PUCHAR tmpOptions;
  5029. if (newBuf) {
  5030. //
  5031. // if a new buffer chain was returned above by IPSEC,
  5032. // then it is most prob. a tunnel => options were
  5033. // copied, hence get rid of ours.
  5034. //
  5035. NdisFreeBuffer(OptBuffer);
  5036. CTEFreeMem(FC->fc_options);
  5037. FC->fc_options = NULL;
  5038. FC->fc_optlength = 0;
  5039. } else {
  5040. Buffer = NDIS_BUFFER_LINKAGE(OptBuffer);
  5041. NdisFreeBuffer(OptBuffer);
  5042. }
  5043. FC->fc_pc.pc_common.pc_flags &= ~PACKET_FLAG_OPTIONS;
  5044. }
  5045. NDIS_BUFFER_LINKAGE(HBuffer) = NULL;
  5046. NdisReinitializePacket(Packet);
  5047. NdisChainBufferAtBack(Packet, HBuffer);
  5048. IPH->iph_xsum = 0;
  5049. //
  5050. // If the DF flag is set, make sure the packet doesn't need
  5051. // fragmentation. If this is the case, send an ICMP error
  5052. // now while we still have the original IP header. The ICMP
  5053. // message includes the MTU so the source host can perform
  5054. // Path MTU discovery.
  5055. //
  5056. // IPSEC headers might have caused this to happen.
  5057. // Send an ICMP to the source so he can adjust his MTU.
  5058. //
  5059. if (pSaveIPH->iph_offset & IP_DF_FLAG) {
  5060. IPSInfo.ipsi_fragfails++;
  5061. SendICMPIPSecErr(SrcAddr,
  5062. pSaveIPH,
  5063. ICMP_DEST_UNREACH,
  5064. FRAG_NEEDED,
  5065. net_long((ulong) (FC->fc_mtu - ipsecByteCount + sizeof(IPHeader))));
  5066. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"TransmitFWPacket: Sent ICMP frag_needed to %lx, from src: %lx\n", pSaveIPH->iph_src, SrcAddr));
  5067. // FreeIPpacket will do header fix up if
  5068. // original header chain was modified by ipsec/firewall/hdrincl
  5069. Status = IP_PACKET_TOO_BIG;
  5070. FreeIPPacket(Packet, TRUE, Status);
  5071. // Don't want to fall through and complete packet after
  5072. // we have freed it.
  5073. return;
  5074. } else {
  5075. //
  5076. // DF bit is not set, ok to fragment
  5077. //
  5078. if (FC->fc_iflink) {
  5079. ASSERT(FC->fc_if->if_flags & IF_FLAGS_P2MP);
  5080. ArpCtxt = FC->fc_iflink->link_arpctxt;
  5081. }
  5082. Status = IPFragment(FC->fc_if,
  5083. FC->fc_mtu - ipsecByteCount,
  5084. FC->fc_nexthop,
  5085. Packet,
  5086. FC->fc_hbuff,
  5087. Buffer,
  5088. DataLength,
  5089. FC->fc_options,
  5090. (uint) FC->fc_optlength,
  5091. (int *)NULL,
  5092. FALSE,
  5093. ArpCtxt);
  5094. //
  5095. // Fragmentation needed with the DF flag set should have
  5096. // been handled in IPForward. We don't have the original
  5097. // header any longer, so silently drop the packet.
  5098. //
  5099. ASSERT(Status != IP_PACKET_TOO_BIG);
  5100. }
  5101. } else {
  5102. //
  5103. // No IPSec handler. No need to check for DF bit here
  5104. // because unlike in the IPSec case, we are not messing
  5105. // with the MTUs so the DF check done in IPForwardPkt is
  5106. // valid
  5107. //
  5108. if (FC->fc_iflink) {
  5109. ASSERT(FC->fc_if->if_flags & IF_FLAGS_P2MP);
  5110. ArpCtxt = FC->fc_iflink->link_arpctxt;
  5111. }
  5112. Status = IPFragment(FC->fc_if,
  5113. FC->fc_mtu - ipsecByteCount,
  5114. FC->fc_nexthop,
  5115. Packet,
  5116. FC->fc_hbuff,
  5117. Buffer,
  5118. DataLength,
  5119. FC->fc_options,
  5120. (uint) FC->fc_optlength,
  5121. (int *)NULL,
  5122. FALSE,
  5123. ArpCtxt);
  5124. //
  5125. // Fragmentation needed with the DF flag set should have been
  5126. // handled in IPForward. We don't have the original header
  5127. // any longer, so silently drop the packet.
  5128. //
  5129. ASSERT(Status != IP_PACKET_TOO_BIG);
  5130. }
  5131. }
  5132. } else {
  5133. //
  5134. // Dest type is bcast
  5135. //
  5136. Status = SendIPBCast(FC->fc_srcnte,
  5137. FC->fc_nexthop,
  5138. Packet,
  5139. FC->fc_hbuff,
  5140. Buffer,
  5141. DataLength,
  5142. FC->fc_options,
  5143. (uint) FC->fc_optlength,
  5144. FC->fc_sos,
  5145. &FC->fc_index);
  5146. }
  5147. if (Status != IP_PENDING) {
  5148. #if MCAST_BUG_TRACKING
  5149. FC->fc_mtu = __LINE__;
  5150. #endif
  5151. FWSendComplete(Packet, Buffer, IP_SUCCESS);
  5152. }
  5153. }
  5154. //* SendFWPacket - Send a packet that needs to be forwarded.
  5155. //
  5156. // This routine is invoked when we actually get around to sending a packet.
  5157. // We look and see if we can give another queued send to the outgoing link,
  5158. // and if so we send on that link. Otherwise we put it on the outgoing queue
  5159. // and remove it later.
  5160. //
  5161. // Input: SrcNTE - Source NTE of packet.
  5162. // Packet - Packet to be send, containg all needed context info.
  5163. // Status - Status of transfer data.
  5164. // DataLength - Length in bytes of data to be send.
  5165. //
  5166. // Returns: Nothing.
  5167. //
  5168. void
  5169. SendFWPacket(PNDIS_PACKET Packet, NDIS_STATUS Status, uint DataLength)
  5170. {
  5171. FWContext *FC = (FWContext *) Packet->ProtocolReserved;
  5172. Interface *IF = FC->fc_if;
  5173. RouteSendQ *RSQ;
  5174. CTELockHandle Handle;
  5175. if (Status == NDIS_STATUS_SUCCESS) {
  5176. // Figure out which logical queue it belongs on, and if we don't already
  5177. // have too many things going there, send it. If we can't send it now we'll
  5178. // queue it for later.
  5179. if (IS_BCAST_DEST(FC->fc_dtype))
  5180. RSQ = BCastRSQ;
  5181. else
  5182. RSQ = &((RouteInterface *) IF)->ri_q;
  5183. CTEGetLock(&RSQ->rsq_lock, &Handle);
  5184. if ((RSQ->rsq_pending < RSQ->rsq_maxpending) && (RSQ->rsq_qlength == 0)) {
  5185. // We can send on this interface.
  5186. RSQ->rsq_pending++;
  5187. CTEFreeLock(&RSQ->rsq_lock, Handle);
  5188. TransmitFWPacket(Packet, DataLength);
  5189. } else { // Need to queue this packet for later.
  5190. if (IPSecHandlerPtr) {
  5191. ASSERT(RSQ->rsq_qlength == 0);
  5192. CTEFreeLock(&RSQ->rsq_lock, Handle);
  5193. IPSInfo.ipsi_outdiscards++;
  5194. #if MCAST_BUG_TRACKING
  5195. FC->fc_mtu = __LINE__;
  5196. #endif
  5197. FreeFWPacket(Packet);
  5198. } else {
  5199. FC->fc_datalength = DataLength;
  5200. FC->fc_q.fq_next = &RSQ->rsq_qh;
  5201. FC->fc_q.fq_prev = RSQ->rsq_qh.fq_prev;
  5202. RSQ->rsq_qh.fq_prev->fq_next = &FC->fc_q;
  5203. RSQ->rsq_qh.fq_prev = &FC->fc_q;
  5204. RSQ->rsq_qlength++;
  5205. CTEFreeLock(&RSQ->rsq_lock, Handle);
  5206. }
  5207. }
  5208. } else {
  5209. IPSInfo.ipsi_outdiscards++;
  5210. #if MCAST_BUG_TRACKING
  5211. FC->fc_mtu = __LINE__;
  5212. #endif
  5213. FreeFWPacket(Packet);
  5214. }
  5215. }
  5216. //* GetFWBufferChain - Get a buffer chain from our buffer pools
  5217. // sufficiently long enough to be able to copy DataLength bytes into it.
  5218. //
  5219. // Input: DataLength - Length in bytes that the buffer chain must be able
  5220. // to describe.
  5221. // Packet - Forwarding packet to link the buffer chain into.
  5222. // TailPointer - Returned pointer to the tail of the buffer chain.
  5223. //
  5224. // Returns: Pointer to the head of the buffer chain on success, NULL
  5225. // on failure.
  5226. //
  5227. PNDIS_BUFFER
  5228. GetFWBufferChain(uint DataLength, PNDIS_PACKET Packet,
  5229. PNDIS_BUFFER *TailPointer)
  5230. {
  5231. KIRQL OldIrql;
  5232. PNDIS_BUFFER Head, Tail, Mdl;
  5233. HANDLE PoolHandle;
  5234. PVOID Buffer;
  5235. uint Remaining, Length;
  5236. // Raise to dispatch level to make multiple calls to MdpAllocate
  5237. // more efficient. This is no less efficient in the single call case
  5238. // either.
  5239. //
  5240. #if !MILLEN
  5241. OldIrql = KeRaiseIrqlToDpcLevel();
  5242. #endif
  5243. // Loop allocating buffers until we have enough to describe DataLength.
  5244. //
  5245. Head = NULL;
  5246. for (Remaining = DataLength; Remaining != 0; Remaining -= Length) {
  5247. // Figure out which buffer pool to use based on the length
  5248. // of data remaining. Use "large" buffers unless the remaining
  5249. // data will fit in a "small" buffer.
  5250. //
  5251. if (Remaining >= BUFSIZE_LARGE_POOL) {
  5252. PoolHandle = IpForwardLargePool;
  5253. Length = BUFSIZE_LARGE_POOL;
  5254. } else if (Remaining > BUFSIZE_SMALL_POOL) {
  5255. PoolHandle = IpForwardLargePool;
  5256. Length = Remaining;
  5257. } else {
  5258. PoolHandle = IpForwardSmallPool;
  5259. Length = Remaining;
  5260. }
  5261. // Allocate a buffer from the chosen pool and link it at the tail.
  5262. //
  5263. Mdl = MdpAllocateAtDpcLevel(PoolHandle, &Buffer);
  5264. if (Mdl) {
  5265. // Expect MdpAllocate to initialize Mdl->Next.
  5266. //
  5267. ASSERT(!Mdl->Next);
  5268. NdisAdjustBufferLength(Mdl, Length);
  5269. if (!Head) {
  5270. Head = Mdl;
  5271. } else {
  5272. Tail->Next = Mdl;
  5273. }
  5274. Tail = Mdl;
  5275. } else {
  5276. // Free what we allocated so far and quit the loop.
  5277. //
  5278. while (Head) {
  5279. Mdl = Head;
  5280. Head = Head->Next;
  5281. MdpFree(Mdl);
  5282. }
  5283. // Need to leave the loop with Head == NULL in the error
  5284. // case for the remaining logic to work correctly.
  5285. //
  5286. ASSERT(!Head);
  5287. break;
  5288. }
  5289. }
  5290. #if !MILLEN
  5291. KeLowerIrql(OldIrql);
  5292. #endif
  5293. // If we've succeeded, put the buffer chain in the packet and
  5294. // adjust our forwarding context.
  5295. //
  5296. if (Head) {
  5297. FWContext *FWC = (FWContext *)Packet->ProtocolReserved;
  5298. ASSERT(Tail);
  5299. NdisChainBufferAtFront(Packet, Head);
  5300. FWC->fc_buffhead = Head;
  5301. FWC->fc_bufftail = Tail;
  5302. *TailPointer = Tail;
  5303. }
  5304. return Head;
  5305. }
  5306. //* AllocateCopyBuffers - Get a buffer chain from our buffer pools
  5307. // sufficiently long enough to be able to copy DataLength bytes into it.
  5308. //
  5309. // Input: Packet - Forwarding packet to link the buffer chain into.
  5310. // DataLength - Length in bytes that the buffer chain must be able
  5311. // to describe.
  5312. // Head - Returned pointer to the head of the buffer chain.
  5313. // CountBuffers - Returned count of buffers in the chain.
  5314. //
  5315. // Returns: NDIS_STATUS_SUCCESS or NDIS_STATUS_RESOURCES
  5316. //
  5317. NDIS_STATUS
  5318. AllocateCopyBuffers(PNDIS_PACKET Packet, uint DataLength, PNDIS_BUFFER *Head,
  5319. uint *CountBuffers)
  5320. {
  5321. PNDIS_BUFFER Tail, Mdl;
  5322. uint Count = 0;
  5323. *Head = GetFWBufferChain(DataLength, Packet, &Tail);
  5324. if (*Head) {
  5325. for (Count = 1, Mdl = *Head; Mdl != Tail; Mdl = Mdl->Next, Count++);
  5326. *CountBuffers = Count;
  5327. return NDIS_STATUS_SUCCESS;
  5328. }
  5329. return NDIS_STATUS_RESOURCES;
  5330. }
  5331. //* GetFWBuffer - Get a list of buffers for forwarding.
  5332. //
  5333. // This routine gets a list of buffers for forwarding, and puts the data into
  5334. // it. This may involve calling TransferData, or we may be able to copy
  5335. // directly into them ourselves.
  5336. //
  5337. // Input: SrcNTE - Pointer to NTE on which packet was received.
  5338. // Packet - Packet being forwarded, used for TD.
  5339. // Data - Pointer to data buffer being forwarded.
  5340. // DataLength - Length in bytes of Data.
  5341. // BufferLength - Length in bytes available in buffer pointer to
  5342. // by Data.
  5343. // Offset - Offset into original data from which to transfer.
  5344. // LContext1, LContext2 - Context values for the link layer.
  5345. //
  5346. // Returns: NDIS_STATUS of attempt to get buffer.
  5347. //
  5348. NDIS_STATUS
  5349. GetFWBuffer(NetTableEntry * SrcNTE, PNDIS_PACKET Packet, uchar * Data,
  5350. uint DataLength, uint BufferLength, uint Offset,
  5351. NDIS_HANDLE LContext1, uint LContext2)
  5352. {
  5353. CTELockHandle Handle;
  5354. uint BufNeeded, i;
  5355. PNDIS_BUFFER FirstBuffer, CurrentBuffer;
  5356. void *DestPtr;
  5357. Interface *SrcIF;
  5358. FWContext *FWC;
  5359. uint LastBufSize;
  5360. uint FirewallMode = 0;
  5361. FirstBuffer = GetFWBufferChain(DataLength, Packet, &CurrentBuffer);
  5362. if (!FirstBuffer) {
  5363. return NDIS_STATUS_RESOURCES;
  5364. }
  5365. #if DBG
  5366. {
  5367. uint TotalBufferSize;
  5368. PNDIS_BUFFER TempBuffer;
  5369. // Sanity check the buffer chain and packet.
  5370. TempBuffer = FirstBuffer;
  5371. TotalBufferSize = 0;
  5372. while (TempBuffer != NULL) {
  5373. TotalBufferSize += NdisBufferLength(TempBuffer);
  5374. TempBuffer = NDIS_BUFFER_LINKAGE(TempBuffer);
  5375. }
  5376. ASSERT(TotalBufferSize == DataLength);
  5377. NdisQueryPacket(Packet, NULL, NULL, NULL, &TotalBufferSize);
  5378. ASSERT(TotalBufferSize == DataLength);
  5379. }
  5380. #endif
  5381. // First buffer points to the list of buffers we have. If we can copy the
  5382. // data here, do so, otherwise invoke the link's transfer data routine.
  5383. // if ((DataLength <= BufferLength) && (SrcNTE->nte_flags & NTE_COPY))
  5384. // change because of firewall
  5385. FirewallMode = ProcessFirewallQ();
  5386. // If DataLength is more than Lookahead size, we may need to
  5387. // call transfer data handler. If IpSec is enabled, make sure that this
  5388. // instance is not from loopback interface.
  5389. if (((DataLength <= BufferLength) && (SrcNTE->nte_flags & NTE_COPY)) ||
  5390. (FirewallMode) || (SrcNTE->nte_if->if_promiscuousmode) ||
  5391. ((SrcNTE != LoopNTE) && IPSecHandlerPtr && ForwardFilterEnabled)) {
  5392. while (DataLength) {
  5393. uint CopyLength;
  5394. TcpipQueryBuffer(FirstBuffer, &DestPtr, &CopyLength, NormalPagePriority);
  5395. if (DestPtr == NULL) {
  5396. return NDIS_STATUS_RESOURCES;
  5397. }
  5398. RtlCopyMemory(DestPtr, Data, CopyLength);
  5399. Data += CopyLength;
  5400. DataLength -= CopyLength;
  5401. FirstBuffer = NDIS_BUFFER_LINKAGE(FirstBuffer);
  5402. }
  5403. return NDIS_STATUS_SUCCESS;
  5404. }
  5405. // We need to call transfer data for this.
  5406. SrcIF = SrcNTE->nte_if;
  5407. return (*(SrcIF->if_transfer)) (SrcIF->if_lcontext, LContext1, LContext2,
  5408. Offset, DataLength, Packet, &DataLength);
  5409. }
  5410. //* GetFWPacket - Get a packet for forwarding.
  5411. //
  5412. // Called when we need to get a packet to forward a datagram.
  5413. //
  5414. // Input: ReturnedPacket - Pointer to where to return a packet.
  5415. //
  5416. // Returns: Pointer to IP header buffer.
  5417. //
  5418. IPHeader *
  5419. GetFWPacket(PNDIS_PACKET *ReturnedPacket)
  5420. {
  5421. PNDIS_PACKET Packet;
  5422. Packet = FwPacketAllocate(0, 0, 0);
  5423. if (Packet) {
  5424. FWContext *FWC = (FWContext *)Packet->ProtocolReserved;
  5425. PNDIS_PACKET_EXTENSION PktExt =
  5426. NDIS_PACKET_EXTENSION_FROM_PACKET(Packet);
  5427. #if MCAST_BUG_TRACKING
  5428. if (FWC->fc_pc.pc_common.pc_owner == PACKET_OWNER_IP) {
  5429. DbgPrint("Packet %x",Packet);
  5430. DbgBreakPoint();
  5431. }
  5432. FWC->fc_pc.pc_common.pc_owner = PACKET_OWNER_IP;
  5433. #else
  5434. ASSERT(FWC->fc_pc.pc_common.pc_owner == PACKET_OWNER_IP);
  5435. #endif
  5436. ASSERT(FWC->fc_hndisbuff);
  5437. ASSERT(FWC->fc_hbuff);
  5438. ASSERT(FWC->fc_pc.pc_pi == RtPI);
  5439. ASSERT(FWC->fc_pc.pc_context == Packet);
  5440. FWC->fc_pc.pc_common.pc_flags |= PACKET_FLAG_IPHDR;
  5441. FWC->fc_pc.pc_common.pc_IpsecCtx = NULL;
  5442. FWC->fc_pc.pc_br = NULL;
  5443. FWC->fc_pc.pc_ipsec_flags = 0;
  5444. PktExt = NDIS_PACKET_EXTENSION_FROM_PACKET(Packet);
  5445. PktExt->NdisPacketInfo[TcpIpChecksumPacketInfo] = NULL;
  5446. PktExt->NdisPacketInfo[IpSecPacketInfo] = NULL;
  5447. PktExt->NdisPacketInfo[TcpLargeSendPacketInfo] = NULL;
  5448. // Make sure that fwpackets cancel ids are initialized.
  5449. #if !MILLEN
  5450. NDIS_SET_PACKET_CANCEL_ID(Packet, NULL);
  5451. #endif
  5452. *ReturnedPacket = Packet;
  5453. return FWC->fc_hbuff;
  5454. }
  5455. return NULL;
  5456. }
  5457. //* IPForward / Forward a packet.
  5458. //
  5459. // The routine called when we need to forward a packet. We check if we're
  5460. // supposed to act as a gateway, and if we are and the incoming packet is a
  5461. // bcast we check and see if we're supposed to forward broadcasts. Assuming
  5462. // we're supposed to forward it, we will process any options. If we find some,
  5463. // we do some validation to make sure everything is good. After that, we look
  5464. // up the next hop. If we can't find one, we'll issue an error. Then we get
  5465. // a packet and buffers, and send it.
  5466. //
  5467. // Input: SrcNTE - NTE for net on which we received this.
  5468. // Header - Pointer to received IPheader.
  5469. // HeaderLength - Length of header.
  5470. // Data - Pointer to data to be forwarded.
  5471. // BufferLength - Length in bytes available in the buffer.
  5472. // LContext1 - lower-layer context supplied upon reception
  5473. // LContext2 - lower-layer context supplied upon reception
  5474. // DestType - Type of destination.
  5475. // MacHeadersize - Media header size
  5476. // pNdisBuffer - Pointer to NDIS_BUFFER describing the frame
  5477. // pClientCnt - Ndis return variable indicating
  5478. // if miniport buffer is pended
  5479. // LinkCtxt - contains per-link context for link-receptions
  5480. //
  5481. // Returns: Nothing.
  5482. //
  5483. void
  5484. IPForwardPkt(NetTableEntry *SrcNTE, IPHeader UNALIGNED *Header,
  5485. uint HeaderLength, void *Data, uint BufferLength,
  5486. NDIS_HANDLE LContext1, uint LContext2, uchar DestType,
  5487. uint MacHeaderSize, PNDIS_BUFFER pNdisBuffer, uint *pClientCnt,
  5488. LinkEntry *LinkCtxt)
  5489. {
  5490. uchar *Options;
  5491. uchar OptLength;
  5492. OptIndex Index;
  5493. IPAddr DestAddr; // IP address we're routing towards.
  5494. uchar SendOnSource = DisableSendOnSource;
  5495. IPAddr NextHop; // Next hop IP address.
  5496. PNDIS_PACKET Packet;
  5497. FWContext *FWC;
  5498. IPHeader *NewHeader; // New header.
  5499. NDIS_STATUS Status;
  5500. uint DataLength;
  5501. CTELockHandle TableHandle;
  5502. uchar ErrIndex;
  5503. IPAddr OutAddr; // Address of interface we're send out on.
  5504. Interface *IF; // Interface we're sending out on.
  5505. uint MTU;
  5506. BOOLEAN HoldPkt = TRUE;
  5507. RouteCacheEntry *FwdRce;
  5508. uint FirewallMode = 0;
  5509. void *ArpCtxt = NULL;
  5510. LinkEntry *Link = NULL;
  5511. DEBUGMSG(DBG_TRACE && DBG_FWD,
  5512. (DTEXT("IPForwardPkt(%x, %x, %d, %x, %d,...)\n"),
  5513. SrcNTE, Header, HeaderLength, Data, BufferLength));
  5514. if (ForwardPackets) {
  5515. DestAddr = Header->iph_dest;
  5516. // If it's a broadcast, see if we can forward it. We won't forward it if broadcast
  5517. // forwarding is turned off, or the destination if the local (all one's) broadcast,
  5518. // or it's a multicast (Class D address). We'll pass through subnet broadcasts in
  5519. // case there's a source route. This would be odd - maybe we should disable this?
  5520. if (IS_BCAST_DEST(DestType)) {
  5521. #if IPMCAST
  5522. if (((DestType == DEST_REM_MCAST) ||
  5523. (DestType == DEST_MCAST)) &&
  5524. (g_dwMcastState == MCAST_STARTED)) {
  5525. BOOLEAN Filter;
  5526. //
  5527. // Dont forward local groups
  5528. //
  5529. if (((Header->iph_dest & 0x00FFFFFF) == 0x000000E0) ||
  5530. (Header->iph_ttl <= 1) ||
  5531. !(SrcNTE->nte_if->if_mcastflags & IPMCAST_IF_ENABLED)) {
  5532. return;
  5533. }
  5534. if (pNdisBuffer) {
  5535. Filter = IPMForwardAfterRcvPkt(SrcNTE, Header, HeaderLength,
  5536. Data, BufferLength,
  5537. LContext1, LContext2,
  5538. DestType, MacHeaderSize,
  5539. pNdisBuffer, pClientCnt,
  5540. LinkCtxt);
  5541. } else {
  5542. Filter = IPMForwardAfterRcv(SrcNTE, Header, HeaderLength,
  5543. Data, BufferLength, LContext1,
  5544. LContext2, DestType, LinkCtxt);
  5545. }
  5546. if (Filter && ForwardFilterEnabled) {
  5547. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength);
  5548. }
  5549. return;
  5550. }
  5551. #endif
  5552. if (!ForwardBCast) {
  5553. if (DestType > DEST_REMOTE)
  5554. IPSInfo.ipsi_inaddrerrors++;
  5555. if (ForwardFilterEnabled) {
  5556. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength);
  5557. }
  5558. return;
  5559. }
  5560. if ((DestAddr == IP_LOCAL_BCST) ||
  5561. (DestAddr == IP_ZERO_BCST) ||
  5562. (DestType == DEST_SN_BCAST) ||
  5563. CLASSD_ADDR(DestAddr)) {
  5564. if (ForwardFilterEnabled) {
  5565. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength);
  5566. }
  5567. return;
  5568. }
  5569. // broad cast
  5570. HoldPkt = FALSE;
  5571. } else {
  5572. FirewallMode = ProcessFirewallQ();
  5573. if ((DestType == DEST_REMOTE) && (!FirewallMode)) {
  5574. NetTableEntry* OrigNTE = SrcNTE;
  5575. SrcNTE = BestNTEForIF(Header->iph_src, SrcNTE->nte_if);
  5576. if (SrcNTE == NULL) {
  5577. // Something bad happened.
  5578. if (ForwardFilterEnabled) {
  5579. NotifyFilterOfDiscard(OrigNTE, Header, Data,
  5580. BufferLength);
  5581. }
  5582. return;
  5583. }
  5584. }
  5585. }
  5586. // If the TTL would expire, send a message.
  5587. if (Header->iph_ttl <= 1) {
  5588. IPSInfo.ipsi_inhdrerrors++;
  5589. if (!ForwardFilterEnabled ||
  5590. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength)) {
  5591. SendICMPErr(SrcNTE->nte_addr, Header, ICMP_TIME_EXCEED,
  5592. TTL_IN_TRANSIT, 0);
  5593. }
  5594. return;
  5595. }
  5596. DataLength = net_short(Header->iph_length) - HeaderLength;
  5597. Index.oi_srtype = NO_SR; // So we know we don't have a source route.
  5598. Index.oi_srindex = MAX_OPT_SIZE;
  5599. Index.oi_rrindex = MAX_OPT_SIZE;
  5600. Index.oi_tsindex = MAX_OPT_SIZE;
  5601. // Now check for options, and process any we find.
  5602. if (HeaderLength != sizeof(IPHeader)) {
  5603. IPOptInfo OptInfo;
  5604. RtlZeroMemory(&OptInfo, sizeof(OptInfo));
  5605. // Options and possible SR . No buffer ownership opt
  5606. HoldPkt = FALSE;
  5607. OptInfo.ioi_options = (uchar *) (Header + 1);
  5608. OptInfo.ioi_optlength = (uchar) (HeaderLength - sizeof(IPHeader));
  5609. // Validate options, and set up indices.
  5610. if ((ErrIndex = ParseRcvdOptions(&OptInfo, &Index)) < MAX_OPT_SIZE) {
  5611. IPSInfo.ipsi_inhdrerrors++;
  5612. if (!ForwardFilterEnabled ||
  5613. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength)) {
  5614. SendICMPErr(SrcNTE->nte_addr, Header, ICMP_PARAM_PROBLEM,
  5615. PTR_VALID, ((uint)ErrIndex + sizeof(IPHeader)));
  5616. }
  5617. return;
  5618. }
  5619. // If source routing option was set, and source routing is disabled,
  5620. // then drop the packet.
  5621. if ((OptInfo.ioi_flags & IP_FLAG_SSRR) && DisableIPSourceRouting) {
  5622. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Pkt dropped - Source routing disabled\n"));
  5623. if (ForwardFilterEnabled) {
  5624. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength);
  5625. }
  5626. return;
  5627. }
  5628. Options = CTEAllocMemN(OptInfo.ioi_optlength, 'IiCT');
  5629. if (!Options) {
  5630. IPSInfo.ipsi_outdiscards++;
  5631. return; // Couldn't get an
  5632. } // option buffer, return;
  5633. // Now copy into our buffer.
  5634. RtlCopyMemory(Options, OptInfo.ioi_options, OptLength = OptInfo.ioi_optlength);
  5635. // See if we have a source routing option, and if so we may need to process it. If
  5636. // we have one, and the destination in the header is us, we need to update the
  5637. // route and the header.
  5638. if (Index.oi_srindex != MAX_OPT_SIZE) {
  5639. if (DestType >= DEST_REMOTE) { // Not for us.
  5640. if (Index.oi_srtype == IP_OPT_SSRR) {
  5641. // This packet is strict source routed, but we're not
  5642. // the destination! We can't continue from here -
  5643. // perhaps we should send an ICMP, but I'm not sure
  5644. // which one it would be.
  5645. CTEFreeMem(Options);
  5646. IPSInfo.ipsi_inaddrerrors++;
  5647. if (ForwardFilterEnabled) {
  5648. NotifyFilterOfDiscard(SrcNTE, Header, Data,
  5649. BufferLength);
  5650. }
  5651. return;
  5652. }
  5653. Index.oi_srindex = MAX_OPT_SIZE; // Don't need to update this.
  5654. } else { // This came here, we need to update the destination address.
  5655. uchar *SROpt = Options + Index.oi_srindex;
  5656. uchar Pointer;
  5657. Pointer = SROpt[IP_OPT_PTR] - 1; // Index starts from one.
  5658. // Get the next hop address, and see if it's a broadcast.
  5659. DestAddr = *(IPAddr UNALIGNED *) & SROpt[Pointer];
  5660. DestType = GetAddrType(DestAddr); // Find address type.
  5661. if ((DestType == DEST_INVALID) ||
  5662. (DestType == DEST_BCAST) ||
  5663. (DestType == DEST_SN_BCAST)) {
  5664. if (!ForwardFilterEnabled ||
  5665. NotifyFilterOfDiscard(SrcNTE, Header, Data,
  5666. BufferLength)) {
  5667. SendICMPErr(SrcNTE->nte_addr, Header,
  5668. ICMP_DEST_UNREACH, SR_FAILED, 0);
  5669. }
  5670. IPSInfo.ipsi_inhdrerrors++;
  5671. CTEFreeMem(Options);
  5672. return;
  5673. }
  5674. // If we came through here, any sort of broadcast needs
  5675. // to be sent out the way it came, so update that flag.
  5676. SendOnSource = EnableSendOnSource;
  5677. }
  5678. }
  5679. } else { // No options.
  5680. Options = (uchar *) NULL;
  5681. OptLength = 0;
  5682. }
  5683. IPSInfo.ipsi_forwdatagrams++;
  5684. // We've processed the options. Now look up the next hop. If we can't
  5685. // find one, send back an error.
  5686. IF = LookupForwardingNextHop(DestAddr, Header->iph_src, &NextHop, &MTU,
  5687. Header->iph_protocol, (uchar *) Data,
  5688. BufferLength, &FwdRce, &Link,
  5689. Header->iph_src);
  5690. if (IF == NULL) {
  5691. // Couldn't find an outgoing route.
  5692. IPSInfo.ipsi_outnoroutes++;
  5693. if (!ForwardFilterEnabled ||
  5694. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength)) {
  5695. SendICMPErr(SrcNTE->nte_addr, Header, ICMP_DEST_UNREACH,
  5696. HOST_UNREACH, 0);
  5697. }
  5698. if (Options)
  5699. CTEFreeMem(Options);
  5700. return;
  5701. } else {
  5702. if (IF->if_flags & IF_FLAGS_P2MP) {
  5703. ASSERT(Link);
  5704. if (Link) {
  5705. ArpCtxt = Link->link_arpctxt;
  5706. }
  5707. }
  5708. }
  5709. //
  5710. // If the DF flag is set, make sure the packet doesn't need
  5711. // fragmentation. If this is the case, send an ICMP error
  5712. // now while we still have the original IP header. The ICMP
  5713. // message includes the MTU so the source host can perform
  5714. // Path MTU discovery.
  5715. //
  5716. if ((Header->iph_offset & IP_DF_FLAG) &&
  5717. ((DataLength + (uint) OptLength) > MTU)) {
  5718. ASSERT((MTU + sizeof(IPHeader)) >= 68);
  5719. ASSERT((MTU + sizeof(IPHeader)) <= 0xFFFF);
  5720. IPSInfo.ipsi_fragfails++;
  5721. if (!ForwardFilterEnabled ||
  5722. NotifyFilterOfDiscard(SrcNTE, Header, Data, BufferLength)) {
  5723. SendICMPErr(SrcNTE->nte_addr, Header, ICMP_DEST_UNREACH,
  5724. FRAG_NEEDED,
  5725. net_long((ulong)(MTU + sizeof(IPHeader))));
  5726. }
  5727. if (Options)
  5728. CTEFreeMem(Options);
  5729. if (Link) {
  5730. DerefLink(Link);
  5731. }
  5732. DerefIF(IF);
  5733. return;
  5734. }
  5735. if (DataLength > MTU) {
  5736. HoldPkt = FALSE;
  5737. }
  5738. // If there is no ipsec policy, it is safe to
  5739. // reuse the indicated mdl chain.
  5740. if (IPSecStatus) {
  5741. HoldPkt = FALSE;
  5742. }
  5743. // See if we need to filter this packet. If we do, call the filter routine
  5744. // to see if it's OK to forward it.
  5745. if (ForwardFilterEnabled) {
  5746. Interface *InIF = SrcNTE->nte_if;
  5747. uint InIFIndex;
  5748. IPAddr InLinkNextHop;
  5749. IPAddr OutLinkNextHop;
  5750. FORWARD_ACTION Action;
  5751. uint FirewallMode = 0;
  5752. FirewallMode = ProcessFirewallQ();
  5753. if (FirewallMode) {
  5754. InIFIndex = INVALID_IF_INDEX;
  5755. InLinkNextHop = NULL_IP_ADDR;
  5756. } else {
  5757. InIFIndex = InIF->if_index;
  5758. if ((InIF->if_flags & IF_FLAGS_P2MP) && LinkCtxt) {
  5759. InLinkNextHop = LinkCtxt->link_NextHop;
  5760. } else {
  5761. InLinkNextHop = NULL_IP_ADDR;
  5762. }
  5763. }
  5764. if ((IF->if_flags & IF_FLAGS_P2MP) && Link) {
  5765. OutLinkNextHop = Link->link_NextHop;
  5766. } else {
  5767. OutLinkNextHop = NULL_IP_ADDR;
  5768. }
  5769. CTEInterlockedIncrementLong(&ForwardFilterRefCount);
  5770. Action = (*ForwardFilterPtr) (Header, Data, BufferLength,
  5771. InIFIndex, IF->if_index,
  5772. InLinkNextHop, OutLinkNextHop);
  5773. DerefFilterPtr();
  5774. if (Action != FORWARD) {
  5775. IPSInfo.ipsi_outdiscards++;
  5776. if (Options)
  5777. CTEFreeMem(Options);
  5778. if (Link) {
  5779. DerefLink(Link);
  5780. }
  5781. DerefIF(IF);
  5782. #if FFP_SUPPORT
  5783. // Seed a -ve FFP entry; Packet henceforth dropped in NIC Driver
  5784. TCPTRACE(("Filter dropped a packet, Seeding -ve cache entry\n"));
  5785. IPSetInFFPCaches(Header, Data, BufferLength, FFP_DISCARD_PACKET);
  5786. #endif
  5787. return;
  5788. }
  5789. }
  5790. // If we have a strict source route and the next hop is not the one
  5791. // specified, send back an error.
  5792. if (Index.oi_srtype == IP_OPT_SSRR) {
  5793. if (DestAddr != NextHop) {
  5794. IPSInfo.ipsi_outnoroutes++;
  5795. SendICMPErr(SrcNTE->nte_addr, Header, ICMP_DEST_UNREACH,
  5796. SR_FAILED, 0);
  5797. CTEFreeMem(Options);
  5798. if (Link) {
  5799. DerefLink(Link);
  5800. }
  5801. DerefIF(IF);
  5802. return;
  5803. }
  5804. }
  5805. // Update the options, if we can and we need to.
  5806. if ((DestType != DEST_BCAST) && Options != NULL) {
  5807. NetTableEntry *OutNTE;
  5808. // Need to find a valid source address for the outgoing interface.
  5809. CTEGetLock(&RouteTableLock.Lock, &TableHandle);
  5810. OutNTE = BestNTEForIF(DestAddr, IF);
  5811. if (OutNTE == NULL) {
  5812. // No NTE for this IF. Something's wrong, just bail out.
  5813. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  5814. CTEFreeMem(Options);
  5815. if (Link) {
  5816. DerefLink(Link);
  5817. }
  5818. DerefIF(IF);
  5819. return;
  5820. } else {
  5821. OutAddr = OutNTE->nte_addr;
  5822. CTEFreeLock(&RouteTableLock.Lock, TableHandle);
  5823. }
  5824. ErrIndex = UpdateOptions(Options, &Index,
  5825. (IP_LOOPBACK(OutAddr) ? DestAddr : OutAddr));
  5826. if (ErrIndex != MAX_OPT_SIZE) {
  5827. IPSInfo.ipsi_inhdrerrors++;
  5828. SendICMPErr(OutAddr, Header, ICMP_PARAM_PROBLEM, PTR_VALID,
  5829. ((ulong) ErrIndex + sizeof(IPHeader)));
  5830. CTEFreeMem(Options);
  5831. if (Link) {
  5832. DerefLink(Link);
  5833. }
  5834. DerefIF(IF);
  5835. return;
  5836. }
  5837. }
  5838. // Send a redirect, if we need to. We'll send a redirect if the packet
  5839. // is going out on the interface it came in on and the next hop address
  5840. // is on the same subnet as the NTE we received it on, and if there
  5841. // are no source route options. We also need to make sure that the
  5842. // source of the datagram is on the I/F we received it on, so we don't
  5843. // send a redirect to another gateway.
  5844. // SendICMPErr will check and not send a redirect if this is a broadcast.
  5845. if ((SrcNTE->nte_if == IF) &&
  5846. IP_ADDR_EQUAL(SrcNTE->nte_addr & SrcNTE->nte_mask,
  5847. NextHop & SrcNTE->nte_mask) &&
  5848. IP_ADDR_EQUAL(SrcNTE->nte_addr & SrcNTE->nte_mask,
  5849. Header->iph_src & SrcNTE->nte_mask)) {
  5850. if (Index.oi_srindex == MAX_OPT_SIZE) {
  5851. #ifdef REDIRECT_DEBUG
  5852. #define PR_IP_ADDR(x) \
  5853. ((x)&0x000000ff),(((x)&0x0000ff00)>>8),(((x)&0x00ff0000)>>16),(((x)&0xff000000)>>24)
  5854. DbgPrint("IP: Sending Redirect. IF = %x SRC_NTE = %x SrcNteIF = %x\n",
  5855. IF, SrcNTE, SrcNTE->nte_if);
  5856. DbgPrint("IP: SrcNteAddr = %d.%d.%d.%d Mask = %d.%d.%d.%d\n",
  5857. PR_IP_ADDR(SrcNTE->nte_addr), PR_IP_ADDR(SrcNTE->nte_mask));
  5858. DbgPrint("IP: NextHop = %d.%d.%d.%d Header Src = %d.%d.%d.%d, Dst = %d.%d.%d.%d\n",
  5859. PR_IP_ADDR(NextHop),
  5860. PR_IP_ADDR(Header->iph_src),
  5861. PR_IP_ADDR(Header->iph_dest));
  5862. #endif
  5863. SendICMPErr(SrcNTE->nte_addr, Header, ICMP_REDIRECT,
  5864. REDIRECT_HOST, NextHop);
  5865. }
  5866. }
  5867. // We have the next hop. Now get a forwarding packet.
  5868. if ((NewHeader = GetFWPacket(&Packet)) != NULL) {
  5869. Packet->Private.Flags |= NDIS_PROTOCOL_ID_TCP_IP;
  5870. // Save the packet forwarding context info.
  5871. FWC = (FWContext *) Packet->ProtocolReserved;
  5872. FWC->fc_options = Options;
  5873. FWC->fc_optlength = OptLength;
  5874. FWC->fc_if = IF;
  5875. FWC->fc_mtu = MTU;
  5876. FWC->fc_srcnte = SrcNTE;
  5877. FWC->fc_nexthop = NextHop;
  5878. FWC->fc_sos = SendOnSource;
  5879. FWC->fc_dtype = DestType;
  5880. FWC->fc_index = Index;
  5881. FWC->fc_iflink = Link;
  5882. if (pNdisBuffer && HoldPkt &&
  5883. (NDIS_GET_PACKET_STATUS((PNDIS_PACKET) LContext1) != NDIS_STATUS_RESOURCES)) {
  5884. uint xsum;
  5885. DEBUGMSG(DBG_INFO && DBG_FWD,
  5886. (DTEXT("IPForwardPkt: bufown %x\n"), pNdisBuffer));
  5887. // Buffer transfer possible!
  5888. //ASSERT(LContext2 <= 8);
  5889. MacHeaderSize += LContext2;
  5890. // remember the original Packet and mac hdr size
  5891. FWC->fc_bufown = LContext1;
  5892. FWC->fc_MacHdrSize = MacHeaderSize;
  5893. //Munge ttl and xsum fields
  5894. Header->iph_ttl = Header->iph_ttl - 1;
  5895. xsum = Header->iph_xsum + 1;
  5896. //add carry
  5897. Header->iph_xsum = (ushort)(xsum + (xsum >> 16));
  5898. // Adjust incoming mdl pointer and counts
  5899. NdisAdjustBuffer(
  5900. pNdisBuffer,
  5901. (PCHAR) NdisBufferVirtualAddress(pNdisBuffer) + MacHeaderSize,
  5902. NdisBufferLength(pNdisBuffer) - MacHeaderSize);
  5903. //Now link this mdl to the packet
  5904. Packet->Private.Head = pNdisBuffer;
  5905. Packet->Private.Tail = pNdisBuffer;
  5906. Packet->Private.TotalLength = DataLength + HeaderLength;
  5907. Packet->Private.Count = 1;
  5908. // We never loopback the packet
  5909. // except if we are in promiscuous mode
  5910. if (!IF->if_promiscuousmode) {
  5911. NdisSetPacketFlags(Packet, NDIS_FLAGS_DONT_LOOPBACK);
  5912. }
  5913. Status = (*(IF->if_xmit)) (IF->if_lcontext, &Packet, 1,
  5914. NextHop, FwdRce, ArpCtxt);
  5915. DbgNumPktFwd++;
  5916. if (Status != NDIS_STATUS_PENDING) {
  5917. NdisAdjustBuffer(
  5918. pNdisBuffer,
  5919. (PCHAR) NdisBufferVirtualAddress(pNdisBuffer) - MacHeaderSize,
  5920. NdisBufferLength(pNdisBuffer) + MacHeaderSize);
  5921. Packet->Private.Head = NULL;
  5922. Packet->Private.Tail = NULL;
  5923. FWC->fc_bufown = NULL;
  5924. #if MCAST_BUG_TRACKING
  5925. FWC->fc_mtu = __LINE__;
  5926. #endif
  5927. FreeFWPacket(Packet);
  5928. *pClientCnt = 0;
  5929. } else {
  5930. //Okay, the xmit is pending indicate this to ndis.
  5931. *pClientCnt = 1;
  5932. }
  5933. return;
  5934. } else {
  5935. FWC->fc_bufown = NULL;
  5936. }
  5937. // Fill in the header in the forwarding context
  5938. NewHeader->iph_verlen = Header->iph_verlen;
  5939. NewHeader->iph_tos = Header->iph_tos;
  5940. NewHeader->iph_length = Header->iph_length;
  5941. NewHeader->iph_id = Header->iph_id;
  5942. NewHeader->iph_offset = Header->iph_offset;
  5943. NewHeader->iph_protocol = Header->iph_protocol;
  5944. NewHeader->iph_src = Header->iph_src;
  5945. NewHeader->iph_dest = DestAddr;
  5946. NewHeader->iph_ttl = Header->iph_ttl - 1;
  5947. NewHeader->iph_xsum = 0;
  5948. // Now that we have a packet, go ahead and transfer data the
  5949. // data in if we need to.
  5950. if (DataLength == 0) {
  5951. Status = NDIS_STATUS_SUCCESS;
  5952. } else {
  5953. Status = GetFWBuffer(SrcNTE, Packet, Data, DataLength,
  5954. BufferLength, HeaderLength, LContext1,
  5955. LContext2);
  5956. }
  5957. // If the status is pending, don't do anything now. Otherwise,
  5958. // if the status is success send the packet.
  5959. if (Status != NDIS_STATUS_PENDING)
  5960. if (Status == NDIS_STATUS_SUCCESS) {
  5961. if (!IF->if_promiscuousmode) {
  5962. NdisSetPacketFlags(Packet, NDIS_FLAGS_DONT_LOOPBACK);
  5963. }
  5964. SendFWPacket(Packet, Status, DataLength);
  5965. } else {
  5966. // Some sort of failure. Free the packet.
  5967. IPSInfo.ipsi_outdiscards++;
  5968. #if MCAST_BUG_TRACKING
  5969. FWC->fc_mtu = __LINE__;
  5970. #endif
  5971. FreeFWPacket(Packet);
  5972. }
  5973. } else { // Couldn't get a packet, so drop this.
  5974. DEBUGMSG(DBG_ERROR && DBG_FWD,
  5975. (DTEXT("IPForwardPkt: failed to get a forwarding packet!\n")));
  5976. IPSInfo.ipsi_outdiscards++;
  5977. if (Options)
  5978. CTEFreeMem(Options);
  5979. if (Link) {
  5980. DerefLink(Link);
  5981. }
  5982. DerefIF(IF);
  5983. }
  5984. } else { // Forward called, but forwarding turned off.
  5985. DEBUGMSG(DBG_WARN && DBG_FWD,
  5986. (DTEXT("IPForwardPkt: Forwarding called but is actually OFF.\n")));
  5987. if (DestType != DEST_BCAST && DestType != DEST_SN_BCAST) {
  5988. // No need to go through here for strictly broadcast packets,
  5989. // although we want to bump the counters for remote bcast stuff.
  5990. IPSInfo.ipsi_inaddrerrors++;
  5991. if (!IS_BCAST_DEST(DestType)) {
  5992. if (DestType == DEST_LOCAL) // Called when local, must be SR.
  5993. SendICMPErr(SrcNTE->nte_addr, Header,
  5994. ICMP_DEST_UNREACH, SR_FAILED, 0);
  5995. }
  5996. }
  5997. }
  5998. }
  5999. //* AddNTERoutes - Add the routes for an NTE.
  6000. //
  6001. // Called during initalization or during DHCP address assignment to add
  6002. // routes. We add routes for the address of the NTE, including routes
  6003. // to the subnet and the address itself.
  6004. //
  6005. // Input: NTE - NTE for which to add routes.
  6006. //
  6007. // Returns: TRUE if they were all added, FALSE if not.
  6008. //
  6009. uint
  6010. AddNTERoutes(NetTableEntry * NTE)
  6011. {
  6012. IPMask Mask, SNMask;
  6013. Interface *IF;
  6014. CTELockHandle Handle;
  6015. IPAddr AllSNBCast;
  6016. IP_STATUS Status;
  6017. IPRouteNotifyOutput RNO = {0};
  6018. // First, add the route to the address itself. This is a route through
  6019. // the loopback interface.
  6020. IF_IPDBG(IP_DEBUG_ADDRESS)
  6021. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  6022. " AddNTE: Adding host route for %x\n", NTE->nte_addr));
  6023. IF = NTE->nte_if;
  6024. if (AddRoute(NTE->nte_addr, HOST_MASK, IPADDR_LOCAL, LoopNTE->nte_if,
  6025. LOOPBACK_MSS, IF->if_metric, IRE_PROTO_LOCAL, ATYPE_OVERRIDE,
  6026. 0, 0) != IP_SUCCESS)
  6027. return FALSE;
  6028. Mask = IPNetMask(NTE->nte_addr);
  6029. // Now add the route for the all-subnet's broadcast, if one doesn't already
  6030. // exist. There is special case code to handle this in SendIPBCast, so the
  6031. // exact interface we add this on doesn't really matter.
  6032. CTEGetLock(&RouteTableLock.Lock, &Handle);
  6033. AllSNBCast = (NTE->nte_addr & Mask) | (IF->if_bcast & ~Mask);
  6034. IF_IPDBG(IP_DEBUG_ADDRESS)
  6035. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  6036. " AddNTE: SNBCast address %x\n", AllSNBCast));
  6037. Status = LockedAddRoute(AllSNBCast, HOST_MASK, IPADDR_LOCAL, IF,
  6038. NTE->nte_mss, IF->if_metric, IRE_PROTO_LOCAL,
  6039. ATYPE_PERM, 0, FALSE, &RNO);
  6040. CTEFreeLock(&RouteTableLock.Lock, Handle);
  6041. if (Status != IP_SUCCESS) {
  6042. return FALSE;
  6043. } else if (RNO.irno_ifindex) {
  6044. RtChangeNotifyEx(&RNO);
  6045. RtChangeNotify(&RNO);
  6046. }
  6047. // If we're doing IGMP, add the route to the multicast address.
  6048. if (IGMPLevel != 0) {
  6049. IF_IPDBG(IP_DEBUG_ADDRESS)
  6050. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  6051. " AddNTE: Adding classD address\n"));
  6052. if (AddRoute(MCAST_DEST, CLASSD_MASK, IPADDR_LOCAL, NTE->nte_if,
  6053. NTE->nte_mss, IF->if_metric, IRE_PROTO_LOCAL, ATYPE_PERM,
  6054. 0, 0) != IP_SUCCESS)
  6055. return FALSE;
  6056. }
  6057. if (NTE->nte_mask != HOST_MASK) {
  6058. // And finally the route to the subnet.
  6059. SNMask = NTE->nte_mask;
  6060. IF_IPDBG(IP_DEBUG_ADDRESS)
  6061. KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,
  6062. " AddNTE: Adding subnet route %x\n",
  6063. NTE->nte_addr & SNMask));
  6064. if (AddRoute(NTE->nte_addr & SNMask, SNMask, IPADDR_LOCAL, NTE->nte_if,
  6065. NTE->nte_mss, IF->if_metric, IRE_PROTO_LOCAL, ATYPE_PERM,
  6066. 0, 0) != IP_SUCCESS)
  6067. return FALSE;
  6068. }
  6069. return TRUE;
  6070. }
  6071. //* DelNTERoutes - Add the routes for an NTE.
  6072. //
  6073. // Called when we receive media disconnect indication.
  6074. // routes.
  6075. //
  6076. // Input: NTE - NTE for which to delete routes.
  6077. //
  6078. // Returns: TRUE if they were all deleted, FALSE if not.
  6079. //
  6080. uint
  6081. DelNTERoutes(NetTableEntry * NTE)
  6082. {
  6083. IPMask Mask, SNMask;
  6084. Interface *IF;
  6085. CTELockHandle Handle;
  6086. IPAddr AllSNBCast;
  6087. uint retVal;
  6088. retVal = TRUE;
  6089. // First, delete the route to the address itself. This is a route through
  6090. // the loopback interface.
  6091. if (DeleteRoute(NTE->nte_addr, HOST_MASK, IPADDR_LOCAL, LoopNTE->nte_if, 0) != IP_SUCCESS)
  6092. retVal = FALSE;
  6093. // If we're doing IGMP, add the route to the multicast address.
  6094. if (IGMPLevel != 0) {
  6095. if (!(NTE->nte_flags & NTE_IF_DELETING) &&
  6096. (NTE->nte_if->if_ntecount == 0)) { // this is the last NTE on this if
  6097. if (DeleteRoute(MCAST_DEST, CLASSD_MASK, IPADDR_LOCAL, NTE->nte_if, 0) != IP_SUCCESS)
  6098. retVal = FALSE;
  6099. }
  6100. }
  6101. if (NTE->nte_mask != HOST_MASK) {
  6102. // And finally the route to the subnet.
  6103. // if there are no other NTEs on IF for the same subnet route
  6104. NetTableEntry *tmpNTE = NTE->nte_if->if_nte;
  6105. while (tmpNTE) {
  6106. if ((tmpNTE != NTE) && (tmpNTE->nte_flags & NTE_VALID) && ((tmpNTE->nte_addr & tmpNTE->nte_mask) == (NTE->nte_addr & NTE->nte_mask))) {
  6107. break;
  6108. }
  6109. tmpNTE = tmpNTE->nte_ifnext;
  6110. }
  6111. if (!tmpNTE) {
  6112. SNMask = NTE->nte_mask;
  6113. if (DeleteRoute(NTE->nte_addr & SNMask, SNMask, IPADDR_LOCAL, NTE->nte_if, 0) != IP_SUCCESS)
  6114. retVal = FALSE;
  6115. }
  6116. }
  6117. if (!(NTE->nte_flags & NTE_IF_DELETING)) {
  6118. Interface *IF = NTE->nte_if;
  6119. NetTableEntry *tmpNTE = IF->if_nte;
  6120. IPMask Mask;
  6121. IPAddr AllSNBCast;
  6122. Mask = IPNetMask(NTE->nte_addr);
  6123. AllSNBCast = (NTE->nte_addr & Mask) | (IF->if_bcast & ~Mask);
  6124. while (tmpNTE) {
  6125. IPMask tmpMask;
  6126. IPAddr tmpAllSNBCast;
  6127. tmpMask = IPNetMask(tmpNTE->nte_addr);
  6128. tmpAllSNBCast = (tmpNTE->nte_addr & tmpMask) | (IF->if_bcast & ~tmpMask);
  6129. if ((tmpNTE != NTE) && (tmpNTE->nte_flags & NTE_VALID) && IP_ADDR_EQUAL(AllSNBCast, tmpAllSNBCast)) {
  6130. break;
  6131. }
  6132. tmpNTE = tmpNTE->nte_ifnext;
  6133. }
  6134. if (!tmpNTE) {
  6135. // Delete the route for the all-subnet's broadcast.
  6136. if (DeleteRoute(AllSNBCast, HOST_MASK, IPADDR_LOCAL, IF, 0) != IP_SUCCESS)
  6137. retVal = FALSE;
  6138. }
  6139. }
  6140. return retVal;
  6141. }
  6142. //* DelIFRoutes - Delete the routes for an interface.
  6143. //
  6144. // Called when we receive media disconnect indication.
  6145. // routes.
  6146. //
  6147. // Input: IF - IF for which to delete routes.
  6148. //
  6149. // Returns: TRUE if they were all deleted, FALSE if not.
  6150. //
  6151. uint
  6152. DelIFRoutes(Interface * IF)
  6153. {
  6154. NetTableEntry *NTE;
  6155. uint i;
  6156. for (i = 0; i < NET_TABLE_SIZE; i++) {
  6157. NetTableEntry *NetTableList = NewNetTableList[i];
  6158. for (NTE = NetTableList; NTE != NULL; NTE = NTE->nte_next) {
  6159. if ((NTE->nte_flags & NTE_VALID) && NTE->nte_if == IF) {
  6160. // This guy is on the interface, and needs to be deleted.
  6161. if (!DelNTERoutes(NTE)) {
  6162. return FALSE;
  6163. }
  6164. }
  6165. }
  6166. }
  6167. return TRUE;
  6168. }
  6169. //* AddIFRoutes - Add the routes for an interface.
  6170. //
  6171. // Called when we receive media disconnect indication.
  6172. // routes.
  6173. //
  6174. // Input: IF - IF for which to Add routes.
  6175. //
  6176. // Returns: TRUE if they were all Added, FALSE if not.
  6177. //
  6178. uint
  6179. AddIFRoutes(Interface * IF)
  6180. {
  6181. NetTableEntry *NTE;
  6182. uint i;
  6183. for (i = 0; i < NET_TABLE_SIZE; i++) {
  6184. NetTableEntry *NetTableList = NewNetTableList[i];
  6185. for (NTE = NetTableList; NTE != NULL; NTE = NTE->nte_next) {
  6186. if ((NTE->nte_flags & NTE_VALID) && NTE->nte_if == IF) {
  6187. // This guy is on the interface, and needs to be added.
  6188. if (!AddNTERoutes(NTE)) {
  6189. return FALSE;
  6190. }
  6191. }
  6192. }
  6193. }
  6194. return TRUE;
  6195. }
  6196. #pragma BEGIN_INIT
  6197. uint BCastMinMTU = 0xffff;
  6198. //* InitNTERouting - do per NTE route initialization.
  6199. //
  6200. // Called when we need to initialize per-NTE routing. For the specified NTE,
  6201. // call AddNTERoutes to add a route for a net bcast, subnet bcast, and local
  6202. // attached subnet. The net bcast entry is sort of a filler - net and
  6203. // global bcasts are always handled specially. For this reason we specify
  6204. // the FirstInterface when adding the route. Subnet bcasts are assumed to
  6205. // only go out on one interface, so the actual interface to be used is
  6206. // specifed. If two interfaces are on the same subnet the last interface is
  6207. // the one that will be used.
  6208. //
  6209. // Input: NTE - NTE for which routing is to be initialized.
  6210. // NumGWs - Number of default gateways to add.
  6211. // GWList - List of default gateways.
  6212. // GWMetricList - the metric for each gateway.
  6213. //
  6214. // Returns: TRUE if we succeed, FALSE if we don't.
  6215. //
  6216. uint
  6217. InitNTERouting(NetTableEntry * NTE, uint NumGWs, IPAddr * GWList,
  6218. uint * GWMetricList)
  6219. {
  6220. uint i;
  6221. Interface *IF;
  6222. if (NTE != LoopNTE) {
  6223. BCastMinMTU = MIN(BCastMinMTU, NTE->nte_mss);
  6224. IF = NTE->nte_if;
  6225. AddRoute(IF->if_bcast, HOST_MASK, IPADDR_LOCAL, IF,
  6226. BCastMinMTU, 1, IRE_PROTO_LOCAL, ATYPE_OVERRIDE,
  6227. 0, 0); // Route for local
  6228. // bcast.
  6229. if (NTE->nte_flags & NTE_VALID) {
  6230. if (!AddNTERoutes(NTE))
  6231. return FALSE;
  6232. // Now add the default routes that are present on this net. We
  6233. // don't check for errors here, but we should probably
  6234. // log an error.
  6235. for (i = 0; i < NumGWs; i++) {
  6236. IPAddr GWAddr;
  6237. GWAddr = net_long(GWList[i]);
  6238. if (IP_ADDR_EQUAL(GWAddr, NTE->nte_addr)) {
  6239. GWAddr = IPADDR_LOCAL;
  6240. }
  6241. AddRoute(NULL_IP_ADDR, DEFAULT_MASK,
  6242. GWAddr, NTE->nte_if, NTE->nte_mss,
  6243. GWMetricList[i] ? GWMetricList[i] : IF->if_metric,
  6244. IRE_PROTO_NETMGMT, ATYPE_OVERRIDE, 0, 0);
  6245. }
  6246. }
  6247. }
  6248. return TRUE;
  6249. }
  6250. //* EnableRouter - enables forwarding.
  6251. //
  6252. // This routine configures this node to enable packet-forwarding.
  6253. // It must be called with the route table lock held.
  6254. //
  6255. // Entry:
  6256. //
  6257. // Returns: nothing.
  6258. //
  6259. void
  6260. EnableRouter()
  6261. {
  6262. RouterConfigured = TRUE;
  6263. ForwardBCast = FALSE;
  6264. ForwardPackets = TRUE;
  6265. }
  6266. //* DisableRouter - disables forwarding.
  6267. //
  6268. // This routine configures this node to disable packet-forwarding.
  6269. // It must be called with the route table lock held.
  6270. //
  6271. // Entry:
  6272. //
  6273. // Returns: nothing.
  6274. //
  6275. void
  6276. DisableRouter()
  6277. {
  6278. RouterConfigured = FALSE;
  6279. ForwardBCast = FALSE;
  6280. ForwardPackets = FALSE;
  6281. }
  6282. //* IPEnableRouterWithRefCount - acquires or releases a reference to forwarding
  6283. //
  6284. // This routine increments or decrements the reference-count on forwarding
  6285. // functionality. When the first reference is acquired, forwarding is enabled.
  6286. // When the last reference is released, forwarding is disabled.
  6287. // It must be called with the route table lock held.
  6288. //
  6289. // Entry: Enable - indicates whether to acquire or release a reference
  6290. //
  6291. // Return: the number of remaining references.
  6292. //
  6293. int
  6294. IPEnableRouterWithRefCount(LOGICAL Enable)
  6295. {
  6296. if (Enable) {
  6297. if (++IPEnableRouterRefCount == 1 && !RouterConfigured) {
  6298. EnableRouter();
  6299. }
  6300. } else {
  6301. if (--IPEnableRouterRefCount == 0 && RouterConfigured) {
  6302. DisableRouter();
  6303. }
  6304. }
  6305. return IPEnableRouterRefCount;
  6306. }
  6307. //* InitRouting - Initialize our routing table.
  6308. //
  6309. // Called during initialization to initialize the routing table.
  6310. //
  6311. // Entry: Nothing.
  6312. //
  6313. // Returns: True if we succeeded, False if we didn't.
  6314. //
  6315. int
  6316. InitRouting(IPConfigInfo * ci)
  6317. {
  6318. int i;
  6319. UINT initStatus;
  6320. ULONG initFlags;
  6321. CTEInitLock(&RouteTableLock.Lock);
  6322. CTEInitBlockStruc(&ForwardFilterBlock);
  6323. DefGWConfigured = 0;
  6324. DefGWActive = 0;
  6325. RtlZeroMemory(&DummyInterface, sizeof(DummyInterface));
  6326. DummyInterface.ri_if.if_xmit = DummyXmit;
  6327. DummyInterface.ri_if.if_transfer = DummyXfer;
  6328. DummyInterface.ri_if.if_close = DummyClose;
  6329. DummyInterface.ri_if.if_invalidate = DummyInvalidate;
  6330. DummyInterface.ri_if.if_qinfo = DummyQInfo;
  6331. DummyInterface.ri_if.if_setinfo = DummySetInfo;
  6332. DummyInterface.ri_if.if_getelist = DummyGetEList;
  6333. DummyInterface.ri_if.if_addaddr = DummyAddAddr;
  6334. DummyInterface.ri_if.if_deladdr = DummyDelAddr;
  6335. DummyInterface.ri_if.if_dondisreq = DummyDoNdisReq;
  6336. DummyInterface.ri_if.if_bcast = IP_LOCAL_BCST;
  6337. DummyInterface.ri_if.if_speed = 10000000;
  6338. DummyInterface.ri_if.if_mtu = 1500;
  6339. DummyInterface.ri_if.if_index = INVALID_IF_INDEX;
  6340. LOCKED_REFERENCE_IF(&DummyInterface.ri_if);
  6341. DummyInterface.ri_if.if_pnpcontext = 0;
  6342. initFlags = ci->ici_fastroutelookup ? TFLAG_FAST_TRIE_ENABLED : 0;
  6343. if ((initStatus = InitRouteTable(initFlags,
  6344. ci->ici_fastlookuplevels,
  6345. ci->ici_maxfastlookupmemory,
  6346. ci->ici_maxnormlookupmemory))
  6347. != STATUS_SUCCESS) {
  6348. TCPTRACE(("Init Route Table Failed: %08x\n", initStatus));
  6349. return FALSE;
  6350. }
  6351. // We've created at least one net. We need to add routing table entries for
  6352. // the global broadcast address, as well as for subnet and net broadcasts,
  6353. // and routing entries for the local subnet. We alse need to add a loopback
  6354. // route for the loopback net. Below, we'll add a host route for ourselves
  6355. // through the loopback net.
  6356. AddRoute(LOOPBACK_ADDR & CLASSA_MASK, CLASSA_MASK, IPADDR_LOCAL,
  6357. LoopNTE->nte_if, LOOPBACK_MSS, 1, IRE_PROTO_LOCAL, ATYPE_PERM,
  6358. 0, 0);
  6359. // Route for loopback.
  6360. if ((uchar) ci->ici_gateway) {
  6361. EnableRouter();
  6362. }
  6363. CTEInitTimer(&IPRouteTimer);
  6364. RouteTimerTicks = 0;
  6365. #if FFP_SUPPORT
  6366. FFPFlushRequired = FALSE;
  6367. #endif
  6368. FlushIFTimerTicks = 0;
  6369. CTEStartTimer(&IPRouteTimer, IP_ROUTE_TIMEOUT, IPRouteTimeout, NULL);
  6370. return TRUE;
  6371. }
  6372. PVOID
  6373. NTAPI
  6374. FwPacketAllocate (
  6375. IN POOL_TYPE PoolType,
  6376. IN SIZE_T NumberOfBytes,
  6377. IN ULONG Tag
  6378. )
  6379. {
  6380. NDIS_STATUS Status;
  6381. PNDIS_PACKET Packet;
  6382. // Get a packet from our forwarding packet pool.
  6383. //
  6384. NdisAllocatePacket(&Status, &Packet, IpForwardPacketPool);
  6385. if (Status == NDIS_STATUS_SUCCESS) {
  6386. PNDIS_BUFFER Buffer;
  6387. IPHeader *Header;
  6388. // Get an IP header buffer from our IP header pool.
  6389. //
  6390. Buffer = MdpAllocate(IpHeaderPool, &Header);
  6391. if (Buffer) {
  6392. FWContext *FWC = (FWContext *)Packet->ProtocolReserved;
  6393. // Intialize the fowarding context area of the packet.
  6394. //
  6395. RtlZeroMemory(FWC, sizeof(FWContext));
  6396. FWC->fc_hndisbuff = Buffer;
  6397. FWC->fc_hbuff = Header;
  6398. FWC->fc_pc.pc_common.pc_flags = PACKET_FLAG_FW | PACKET_FLAG_IPHDR;
  6399. #if MCAST_BUG_TRACKING
  6400. FWC->fc_pc.pc_common.pc_owner = 0;
  6401. #else
  6402. FWC->fc_pc.pc_common.pc_owner = PACKET_OWNER_IP;
  6403. #endif
  6404. FWC->fc_pc.pc_pi = RtPI;
  6405. FWC->fc_pc.pc_context = Packet;
  6406. return Packet;
  6407. }
  6408. NdisFreePacket(Packet);
  6409. }
  6410. return NULL;
  6411. }
  6412. VOID
  6413. NTAPI
  6414. FwPacketFree (
  6415. IN PVOID Buffer
  6416. )
  6417. {
  6418. PNDIS_PACKET Packet = (PNDIS_PACKET)Buffer;
  6419. FWContext *FWC = (FWContext *)Packet->ProtocolReserved;
  6420. // Return any IP header to its pool.
  6421. //
  6422. if (FWC->fc_hndisbuff) {
  6423. MdpFree(FWC->fc_hndisbuff);
  6424. }
  6425. NdisFreePacket(Packet);
  6426. }
  6427. //* InitForwardingPools - Initialize the packet and buffer pools used
  6428. // for forwarding operations.
  6429. //
  6430. // Returns: TRUE if the operations succeeded.
  6431. //
  6432. BOOLEAN InitForwardingPools()
  6433. {
  6434. NDIS_STATUS Status;
  6435. // Create our "large" forwarding buffer pool.
  6436. //
  6437. IpForwardLargePool = MdpCreatePool(BUFSIZE_LARGE_POOL, 'lfCT');
  6438. if (!IpForwardLargePool) {
  6439. return FALSE;
  6440. }
  6441. // Create our "small" forwarding buffer pool.
  6442. //
  6443. IpForwardSmallPool = MdpCreatePool(BUFSIZE_SMALL_POOL, 'sfCT');
  6444. if (!IpForwardSmallPool) {
  6445. MdpDestroyPool(IpForwardLargePool);
  6446. IpForwardLargePool = NULL;
  6447. return FALSE;
  6448. }
  6449. // Create our forwarding packet pool.
  6450. //
  6451. NdisAllocatePacketPoolEx(&Status, &IpForwardPacketPool,
  6452. PACKET_POOL_SIZE, 0, sizeof(FWContext));
  6453. if (Status != NDIS_STATUS_SUCCESS) {
  6454. MdpDestroyPool(IpForwardSmallPool);
  6455. IpForwardSmallPool = NULL;
  6456. MdpDestroyPool(IpForwardLargePool);
  6457. IpForwardLargePool = NULL;
  6458. return FALSE;
  6459. }
  6460. NdisSetPacketPoolProtocolId(IpForwardPacketPool, NDIS_PROTOCOL_ID_TCP_IP);
  6461. return TRUE;
  6462. }
  6463. //* InitGateway - Initialize our gateway functionality.
  6464. //
  6465. // Called during init. time to initialize our gateway functionality. If we're
  6466. // not connfigured as a router, we do nothing. If we are, we allocate the
  6467. // resources we need and do other router initialization.
  6468. //
  6469. // Input: ci - Config info.
  6470. //
  6471. // Returns: TRUE if we succeed, FALSE if don't.
  6472. //
  6473. uint
  6474. InitGateway(IPConfigInfo * ci)
  6475. {
  6476. uint FWBufSize, FWPackets;
  6477. uint FWBufCount;
  6478. NDIS_STATUS Status;
  6479. NDIS_HANDLE BufferPool, FWBufferPool, PacketPool;
  6480. IPHeader *HeaderPtr = NULL;
  6481. uchar *FWBuffer = NULL;
  6482. PNDIS_BUFFER Buffer;
  6483. PNDIS_PACKET Packet;
  6484. RouteInterface *RtIF;
  6485. NetTableEntry *NTE;
  6486. uint i;
  6487. // If we're going to be a router, allocate and initialize the resources we
  6488. // need for that.
  6489. BCastRSQ = NULL;
  6490. if (1) {
  6491. RtPI = CTEAllocMemNBoot(sizeof(ProtInfo), 'JiCT');
  6492. if (RtPI == (ProtInfo *) NULL)
  6493. goto failure;
  6494. RtPI->pi_xmitdone = FWSendComplete;
  6495. for (i = 0; i < NET_TABLE_SIZE; i++) {
  6496. NetTableEntry *NetTableList = NewNetTableList[i];
  6497. for (NTE = NetTableList; NTE != NULL; NTE = NTE->nte_next) {
  6498. RtIF = (RouteInterface *) NTE->nte_if;
  6499. RtIF->ri_q.rsq_qh.fq_next = &RtIF->ri_q.rsq_qh;
  6500. RtIF->ri_q.rsq_qh.fq_prev = &RtIF->ri_q.rsq_qh;
  6501. RtIF->ri_q.rsq_running = FALSE;
  6502. RtIF->ri_q.rsq_pending = 0;
  6503. RtIF->ri_q.rsq_qlength = 0;
  6504. CTEInitLock(&RtIF->ri_q.rsq_lock);
  6505. }
  6506. }
  6507. BCastRSQ = CTEAllocMemNBoot(sizeof(RouteSendQ), 'KiCT');
  6508. if (BCastRSQ == (RouteSendQ *) NULL)
  6509. goto failure;
  6510. BCastRSQ->rsq_qh.fq_next = &BCastRSQ->rsq_qh;
  6511. BCastRSQ->rsq_qh.fq_prev = &BCastRSQ->rsq_qh;
  6512. BCastRSQ->rsq_pending = 0;
  6513. BCastRSQ->rsq_maxpending = DEFAULT_MAX_PENDING;
  6514. BCastRSQ->rsq_qlength = 0;
  6515. BCastRSQ->rsq_running = FALSE;
  6516. CTEInitLock(&BCastRSQ->rsq_lock);
  6517. RtIF = (RouteInterface *) &LoopInterface;
  6518. RtIF->ri_q.rsq_maxpending = DEFAULT_MAX_PENDING;
  6519. if (!InitForwardingPools()) {
  6520. goto failure;
  6521. }
  6522. }
  6523. return TRUE;
  6524. failure:
  6525. if (RtPI != NULL)
  6526. CTEFreeMem(RtPI);
  6527. if (BCastRSQ != NULL)
  6528. CTEFreeMem(BCastRSQ);
  6529. if (HeaderPtr != NULL)
  6530. CTEFreeMem(HeaderPtr);
  6531. if (FWBuffer != NULL)
  6532. CTEFreeMem(FWBuffer);
  6533. ForwardBCast = FALSE;
  6534. ForwardPackets = FALSE;
  6535. RouterConfigured = FALSE;
  6536. IPEnableRouterRefCount = (ci->ici_gateway ? 1 : 0);
  6537. return FALSE;
  6538. }
  6539. NTSTATUS
  6540. GetIFAndLink(void *Rce, UINT * IFIndex, IPAddr * NextHop)
  6541. {
  6542. RouteTableEntry *RTE = NULL;
  6543. RouteCacheEntry *RCE = (RouteCacheEntry *) Rce;
  6544. Interface *IF;
  6545. KIRQL rtlIrql;
  6546. CTEGetLock(&RouteTableLock.Lock, &rtlIrql);
  6547. if (RCE && (RCE->rce_flags & RCE_VALID) &&
  6548. !(RCE->rce_flags & RCE_LINK_DELETED))
  6549. RTE = RCE->rce_rte;
  6550. if (RTE) {
  6551. if ((IF = IF_FROM_RTE(RTE)) == NULL) {
  6552. CTEFreeLock(&RouteTableLock.Lock, rtlIrql);
  6553. return IP_GENERAL_FAILURE;
  6554. }
  6555. *IFIndex = IF->if_index;
  6556. if (RTE->rte_link) {
  6557. ASSERT(IF->if_flags & IF_FLAGS_P2MP);
  6558. *NextHop = RTE->rte_link->link_NextHop;
  6559. } else
  6560. *NextHop = NULL_IP_ADDR;
  6561. CTEFreeLock(&RouteTableLock.Lock, rtlIrql);
  6562. return IP_SUCCESS;
  6563. }
  6564. CTEFreeLock(&RouteTableLock.Lock, rtlIrql);
  6565. return IP_GENERAL_FAILURE;
  6566. }
  6567. #pragma END_INIT