ip4.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607
  1. /*++
  2. Copyright (c) 2013 Minoca Corp. All Rights Reserved
  3. Module Name:
  4. ip4.c
  5. Abstract:
  6. This module implements support for the Internet Protocol version 4 (IPv4).
  7. Author:
  8. Evan Green 4-Apr-2013
  9. Environment:
  10. Kernel
  11. --*/
  12. //
  13. // ------------------------------------------------------------------- Includes
  14. //
  15. //
  16. // Network layer drivers are supposed to be able to stand on their own (i.e. be
  17. // able to be implemented outside the core net library). For the builtin ones,
  18. // avoid including netcore.h, but still redefine those functions that would
  19. // otherwise generate imports.
  20. //
  21. #define NET_API __DLLEXPORT
  22. #include <minoca/kernel/driver.h>
  23. #include <minoca/net/netdrv.h>
  24. #include <minoca/net/ip4.h>
  25. //
  26. // ---------------------------------------------------------------- Definitions
  27. //
  28. //
  29. // Define the maximum size of an IPv4 address string, including the null
  30. // terminator. The longest string would look something like
  31. // "255.255.255.255:65535"
  32. //
  33. #define IP4_MAX_ADDRESS_STRING 22
  34. //
  35. // Define the timeout for a set if IPv4 fragments, in microseconds.
  36. //
  37. #define IP4_FRAGMENT_TIMEOUT (15 * MICROSECONDS_PER_SECOND)
  38. //
  39. // Define the byte alignment for IPv4 fragment lengths.
  40. //
  41. #define IP4_FRAGMENT_ALIGNMENT 8
  42. //
  43. // Define the maximum number of fragments that can be stored at any one time.
  44. //
  45. #define IP4_MAX_FRAGMENT_COUNT 1000
  46. //
  47. // --------------------------------------------------------------------- Macros
  48. //
  49. //
  50. // Define macros to convert between fragment bytes and fragment offset units.
  51. //
  52. #define IP4_CONVERT_OFFSET_TO_BYTES(_Offset) (_Offset << 3)
  53. #define IP4_CONVERT_BYTES_TO_OFFSET(_Bytes) (_Bytes >> 3)
  54. //
  55. // ------------------------------------------------------ Data Type Definitions
  56. //
  57. /*++
  58. Structure Description:
  59. This structure defines an IPv4 fragmented packet node which represents one
  60. IPv4 packet that is in the process of being reassembled from its various
  61. fragments.
  62. Members:
  63. Node - Stores the Red-Black tree node information for this IPv4 packet.
  64. FargmentListHead - Stores the head of the list of fragments being
  65. reassembled into a packet.
  66. Timeout - Stores the time, in time ticks, at which the the attempt to
  67. reassemble this packet will be abandoned.
  68. LocalAddress - Stores the local IPv4 address for the packet.
  69. RemoteAddress - Stores the remote IPv4 address for the packet.
  70. Protocol - Stores the IPv4 protocol for which this packet is destined.
  71. Identification - Stores the IPv4 unique identification for the packet.
  72. --*/
  73. typedef struct _IP4_FRAGMENTED_PACKET_NODE {
  74. RED_BLACK_TREE_NODE Node;
  75. LIST_ENTRY FragmentListHead;
  76. ULONGLONG Timeout;
  77. ULONG LocalAddress;
  78. ULONG RemoteAddress;
  79. USHORT Protocol;
  80. USHORT Identification;
  81. } IP4_FRAGMENTED_PACKET_NODE, *PIP4_FRAGMENTED_PACKET_NODE;
  82. /*++
  83. Structure Description:
  84. This structure defines a fragment entry for an IPv4 packet. This entry
  85. may contain data from one or more fragments that have already been
  86. processed.
  87. Members:
  88. ListEntry - Stores pointer to the next and previous fragments in the list.
  89. Length - Stores the length, in bytes, of this fragment.
  90. Offset - Stores the offset, in 8 byte blocks, from the beginning of the
  91. packet.
  92. LastFragment - Stores a boolean indicating whether or not this fragment
  93. contains the last chunk of data for the packet.
  94. --*/
  95. typedef struct _IP4_FRAGMENT_ENTRY {
  96. LIST_ENTRY ListEntry;
  97. ULONG Length;
  98. USHORT Offset;
  99. BOOL LastFragment;
  100. } IP4_FRAGMENT_ENTRY, *PIP4_FRAGMENT_ENTRY;
  101. //
  102. // ----------------------------------------------- Internal Function Prototypes
  103. //
  104. KSTATUS
  105. NetpIp4InitializeLink (
  106. PNET_LINK Link
  107. );
  108. VOID
  109. NetpIp4DestroyLink (
  110. PNET_LINK Link
  111. );
  112. KSTATUS
  113. NetpIp4InitializeSocket (
  114. PNET_PROTOCOL_ENTRY ProtocolEntry,
  115. PNET_NETWORK_ENTRY NetworkEntry,
  116. ULONG NetworkProtocol,
  117. PNET_SOCKET NewSocket
  118. );
  119. KSTATUS
  120. NetpIp4BindToAddress (
  121. PNET_SOCKET Socket,
  122. PNET_LINK Link,
  123. PNETWORK_ADDRESS Address
  124. );
  125. KSTATUS
  126. NetpIp4Listen (
  127. PNET_SOCKET Socket
  128. );
  129. KSTATUS
  130. NetpIp4Connect (
  131. PNET_SOCKET Socket,
  132. PNETWORK_ADDRESS Address
  133. );
  134. KSTATUS
  135. NetpIp4Disconnect (
  136. PNET_SOCKET Socket
  137. );
  138. KSTATUS
  139. NetpIp4Close (
  140. PNET_SOCKET Socket
  141. );
  142. KSTATUS
  143. NetpIp4Send (
  144. PNET_SOCKET Socket,
  145. PNETWORK_ADDRESS Destination,
  146. PNET_SOCKET_LINK_OVERRIDE LinkOverride,
  147. PNET_PACKET_LIST PacketList
  148. );
  149. VOID
  150. NetpIp4ProcessReceivedData (
  151. PNET_LINK Link,
  152. PNET_PACKET_BUFFER Packet
  153. );
  154. ULONG
  155. NetpIp4PrintAddress (
  156. PNETWORK_ADDRESS Address,
  157. PSTR Buffer,
  158. ULONG BufferLength
  159. );
  160. KSTATUS
  161. NetpIp4GetSetInformation (
  162. PNET_SOCKET Socket,
  163. SOCKET_INFORMATION_TYPE InformationType,
  164. UINTN SocketOption,
  165. PVOID Data,
  166. PUINTN DataSize,
  167. BOOL Set
  168. );
  169. USHORT
  170. NetpIp4ChecksumData (
  171. PVOID Data,
  172. ULONG Length
  173. );
  174. KSTATUS
  175. NetpIp4TranslateNetworkAddress (
  176. PNETWORK_ADDRESS NetworkAddress,
  177. PNET_LINK Link,
  178. PNET_LINK_ADDRESS_ENTRY LinkAddress,
  179. PNETWORK_ADDRESS PhysicalAddress
  180. );
  181. PNET_PACKET_BUFFER
  182. NetpIp4ProcessPacketFragment (
  183. PNET_LINK Link,
  184. PNET_PACKET_BUFFER PacketFragment
  185. );
  186. COMPARISON_RESULT
  187. NetpIp4CompareFragmentedPacketEntries (
  188. PRED_BLACK_TREE Tree,
  189. PRED_BLACK_TREE_NODE FirstNode,
  190. PRED_BLACK_TREE_NODE SecondNode
  191. );
  192. VOID
  193. NetpIp4RemoveFragmentedPackets (
  194. PNET_SOCKET Socket
  195. );
  196. PIP4_FRAGMENTED_PACKET_NODE
  197. NetpIp4CreateFragmentedPacketNode (
  198. PIP4_HEADER Header
  199. );
  200. VOID
  201. NetpIp4DestroyFragmentedPacketNode (
  202. PIP4_FRAGMENTED_PACKET_NODE PacketNode
  203. );
  204. //
  205. // -------------------------------------------------------------------- Globals
  206. //
  207. BOOL NetIp4DebugPrintPackets = FALSE;
  208. //
  209. // Store values used to manage fragmented IPv4 packets.
  210. //
  211. ULONG NetIp4FragmentCount;
  212. PQUEUED_LOCK NetIp4FragmentedPacketLock;
  213. RED_BLACK_TREE NetIp4FragmentedPacketTree;
  214. //
  215. // ------------------------------------------------------------------ Functions
  216. //
  217. VOID
  218. NetpIp4Initialize (
  219. VOID
  220. )
  221. /*++
  222. Routine Description:
  223. This routine initializes support for IPv4 packets.
  224. Arguments:
  225. None.
  226. Return Value:
  227. None.
  228. --*/
  229. {
  230. NET_NETWORK_ENTRY NetworkEntry;
  231. KSTATUS Status;
  232. //
  233. // Initialize the IPv4 fragmented packet tree.
  234. //
  235. RtlRedBlackTreeInitialize(&NetIp4FragmentedPacketTree,
  236. 0,
  237. NetpIp4CompareFragmentedPacketEntries);
  238. NetIp4FragmentCount = 0;
  239. NetIp4FragmentedPacketLock = KeCreateQueuedLock();
  240. if (NetIp4FragmentedPacketLock == NULL) {
  241. ASSERT(FALSE);
  242. goto Ip4InitializeEnd;
  243. }
  244. //
  245. // Register the IPv4 handlers with the core networking library.
  246. //
  247. NetworkEntry.Domain = NetDomainIp4;
  248. NetworkEntry.ParentProtocolNumber = IP4_PROTOCOL_NUMBER;
  249. NetworkEntry.Interface.InitializeLink = NetpIp4InitializeLink;
  250. NetworkEntry.Interface.DestroyLink = NetpIp4DestroyLink;
  251. NetworkEntry.Interface.InitializeSocket = NetpIp4InitializeSocket;
  252. NetworkEntry.Interface.BindToAddress = NetpIp4BindToAddress;
  253. NetworkEntry.Interface.Listen = NetpIp4Listen;
  254. NetworkEntry.Interface.Connect = NetpIp4Connect;
  255. NetworkEntry.Interface.Disconnect = NetpIp4Disconnect;
  256. NetworkEntry.Interface.Close = NetpIp4Close;
  257. NetworkEntry.Interface.Send = NetpIp4Send;
  258. NetworkEntry.Interface.ProcessReceivedData = NetpIp4ProcessReceivedData;
  259. NetworkEntry.Interface.PrintAddress = NetpIp4PrintAddress;
  260. NetworkEntry.Interface.GetSetInformation = NetpIp4GetSetInformation;
  261. Status = NetRegisterNetworkLayer(&NetworkEntry, NULL);
  262. if (!KSUCCESS(Status)) {
  263. ASSERT(FALSE);
  264. }
  265. Ip4InitializeEnd:
  266. return;
  267. }
  268. KSTATUS
  269. NetpIp4InitializeLink (
  270. PNET_LINK Link
  271. )
  272. /*++
  273. Routine Description:
  274. This routine initializes any pieces of information needed by the network
  275. layer for a new link.
  276. Arguments:
  277. Link - Supplies a pointer to the new link.
  278. Return Value:
  279. Status code.
  280. --*/
  281. {
  282. PNET_LINK_ADDRESS_ENTRY AddressEntry;
  283. IP4_ADDRESS InitialAddress;
  284. KSTATUS Status;
  285. //
  286. // A dummy address with only the network filled in is required, otherwise
  287. // this link entry cannot be bound to in order to establish the real
  288. // address.
  289. //
  290. RtlZeroMemory((PNETWORK_ADDRESS)&InitialAddress, sizeof(NETWORK_ADDRESS));
  291. InitialAddress.Domain = NetDomainIp4;
  292. InitialAddress.Address = 0;
  293. Status = NetCreateLinkAddressEntry(Link,
  294. (PNETWORK_ADDRESS)&InitialAddress,
  295. NULL,
  296. NULL,
  297. FALSE,
  298. &AddressEntry);
  299. if (!KSUCCESS(Status)) {
  300. goto Ip4InitializeLinkEnd;
  301. }
  302. Ip4InitializeLinkEnd:
  303. if (!KSUCCESS(Status)) {
  304. if (AddressEntry != NULL) {
  305. NetDestroyLinkAddressEntry(Link, AddressEntry);
  306. }
  307. }
  308. return Status;
  309. }
  310. VOID
  311. NetpIp4DestroyLink (
  312. PNET_LINK Link
  313. )
  314. /*++
  315. Routine Description:
  316. This routine allows the network layer to tear down any state before a link
  317. is destroyed.
  318. Arguments:
  319. Link - Supplies a pointer to the dying link.
  320. Return Value:
  321. None.
  322. --*/
  323. {
  324. return;
  325. }
  326. KSTATUS
  327. NetpIp4InitializeSocket (
  328. PNET_PROTOCOL_ENTRY ProtocolEntry,
  329. PNET_NETWORK_ENTRY NetworkEntry,
  330. ULONG NetworkProtocol,
  331. PNET_SOCKET NewSocket
  332. )
  333. /*++
  334. Routine Description:
  335. This routine initializes any pieces of information needed by the network
  336. layer for the socket. The core networking library will fill in the common
  337. header when this routine returns.
  338. Arguments:
  339. ProtocolEntry - Supplies a pointer to the protocol information.
  340. NetworkEntry - Supplies a pointer to the network information.
  341. NetworkProtocol - Supplies the raw protocol value for this socket used on
  342. the network. This value is network specific.
  343. NewSocket - Supplies a pointer to the new socket. The network layer should
  344. at the very least add any needed header size.
  345. Return Value:
  346. Status code.
  347. --*/
  348. {
  349. ULONG MaxPacketSize;
  350. //
  351. // If this is coming from the raw protocol and the network protocol is the
  352. // raw, wildcard protocol, then this socket automatically gets the headers
  353. // included flag.
  354. //
  355. if ((ProtocolEntry->Type == NetSocketRaw) &&
  356. (NetworkProtocol == SOCKET_INTERNET_PROTOCOL_RAW)) {
  357. RtlAtomicOr32(&(NewSocket->Flags),
  358. NET_SOCKET_FLAG_NETWORK_HEADER_INCLUDED);
  359. }
  360. //
  361. // Determine if the maximum IPv4 packet size plus all existing headers and
  362. // footers is less than the current maximum packet size. If so, truncate
  363. // the maximum packet size. Note that the IPv4 maximum packet size includes
  364. // the size of the header.
  365. //
  366. MaxPacketSize = NewSocket->PacketSizeInformation.HeaderSize +
  367. IP4_MAX_PACKET_SIZE +
  368. NewSocket->PacketSizeInformation.FooterSize;
  369. if (NewSocket->PacketSizeInformation.MaxPacketSize > MaxPacketSize) {
  370. NewSocket->PacketSizeInformation.MaxPacketSize = MaxPacketSize;
  371. }
  372. //
  373. // Add the IPv4 header size for higher layers to perform the same
  374. // truncation procedure. Skip this for raw sockets using the raw protocol;
  375. // the must always supply an IPv4 header, so it doesn't make sense to add
  376. // it to the header size. It comes in the data packet.
  377. //
  378. if ((ProtocolEntry->Type != NetSocketRaw) ||
  379. (NetworkProtocol != SOCKET_INTERNET_PROTOCOL_RAW)) {
  380. NewSocket->PacketSizeInformation.HeaderSize += sizeof(IP4_HEADER);
  381. }
  382. return STATUS_SUCCESS;
  383. }
  384. KSTATUS
  385. NetpIp4BindToAddress (
  386. PNET_SOCKET Socket,
  387. PNET_LINK Link,
  388. PNETWORK_ADDRESS Address
  389. )
  390. /*++
  391. Routine Description:
  392. This routine binds the given socket to the specified network address.
  393. Arguments:
  394. Socket - Supplies a pointer to the socket to bind.
  395. Link - Supplies an optional pointer to a link to bind to.
  396. Address - Supplies a pointer to the address to bind the socket to.
  397. Return Value:
  398. Status code.
  399. --*/
  400. {
  401. BOOL AnyAddress;
  402. NET_SOCKET_BINDING_TYPE BindingType;
  403. PIP4_ADDRESS Ip4Address;
  404. NET_LINK_LOCAL_ADDRESS LocalInformation;
  405. ULONG Port;
  406. KSTATUS Status;
  407. Ip4Address = (PIP4_ADDRESS)Address;
  408. LocalInformation.Link = NULL;
  409. //
  410. // If a specific link is given, try to find the given address in that link.
  411. //
  412. if (Link != NULL) {
  413. if (Ip4Address->Address == 0) {
  414. BindingType = SocketUnbound;
  415. AnyAddress = TRUE;
  416. } else {
  417. BindingType = SocketLocallyBound;
  418. AnyAddress = FALSE;
  419. }
  420. Port = Address->Port;
  421. Address->Port = 0;
  422. Status = NetFindLinkForLocalAddress(Address,
  423. AnyAddress,
  424. Link,
  425. &LocalInformation);
  426. Address->Port = Port;
  427. if (!KSUCCESS(Status)) {
  428. goto Ip4BindToAddressEnd;
  429. }
  430. LocalInformation.LocalAddress.Port = Port;
  431. //
  432. // No specific link was passed.
  433. //
  434. } else {
  435. //
  436. // If the address is not the "unbound" address, then look for the link
  437. // that owns this address.
  438. //
  439. if (Ip4Address->Address != 0) {
  440. BindingType = SocketLocallyBound;
  441. Port = Address->Port;
  442. Address->Port = 0;
  443. Status = NetFindLinkForLocalAddress(Address,
  444. FALSE,
  445. NULL,
  446. &LocalInformation);
  447. Address->Port = Port;
  448. if (!KSUCCESS(Status)) {
  449. goto Ip4BindToAddressEnd;
  450. }
  451. LocalInformation.LocalAddress.Port = Port;
  452. //
  453. // No link nor address was passed, this is a generic bind to a port on
  454. // any address.
  455. //
  456. } else {
  457. BindingType = SocketUnbound;
  458. LocalInformation.Link = NULL;
  459. LocalInformation.LinkAddress = NULL;
  460. RtlCopyMemory(&(LocalInformation.LocalAddress),
  461. Address,
  462. sizeof(NETWORK_ADDRESS));
  463. }
  464. }
  465. //
  466. // Bind the socket to the local address. The socket remains inactive,
  467. // unable to receive packets.
  468. //
  469. Status = NetBindSocket(Socket, BindingType, &LocalInformation, NULL, 0);
  470. if (!KSUCCESS(Status)) {
  471. goto Ip4BindToAddressEnd;
  472. }
  473. Status = STATUS_SUCCESS;
  474. Ip4BindToAddressEnd:
  475. if (LocalInformation.Link != NULL) {
  476. NetLinkReleaseReference(LocalInformation.Link);
  477. }
  478. return Status;
  479. }
  480. KSTATUS
  481. NetpIp4Listen (
  482. PNET_SOCKET Socket
  483. )
  484. /*++
  485. Routine Description:
  486. This routine adds a bound socket to the list of listening sockets,
  487. officially allowing clients to attempt to connect to it.
  488. Arguments:
  489. Socket - Supplies a pointer to the socket to mark as listning.
  490. Return Value:
  491. Status code.
  492. --*/
  493. {
  494. NETWORK_ADDRESS LocalAddress;
  495. KSTATUS Status;
  496. RtlZeroMemory(&(Socket->RemoteAddress), sizeof(NETWORK_ADDRESS));
  497. if (Socket->BindingType == SocketBindingInvalid) {
  498. RtlZeroMemory(&LocalAddress, sizeof(NETWORK_ADDRESS));
  499. LocalAddress.Domain = NetDomainIp4;
  500. Status = NetpIp4BindToAddress(Socket, NULL, &LocalAddress);
  501. if (!KSUCCESS(Status)) {
  502. goto Ip4ListenEnd;
  503. }
  504. }
  505. Status = NetActivateSocket(Socket);
  506. if (!KSUCCESS(Status)) {
  507. goto Ip4ListenEnd;
  508. }
  509. Ip4ListenEnd:
  510. return Status;
  511. }
  512. KSTATUS
  513. NetpIp4Connect (
  514. PNET_SOCKET Socket,
  515. PNETWORK_ADDRESS Address
  516. )
  517. /*++
  518. Routine Description:
  519. This routine connects the given socket to a specific remote address. It
  520. will implicitly bind the socket if it is not yet locally bound.
  521. Arguments:
  522. Socket - Supplies a pointer to the socket to use for the connection.
  523. Address - Supplies a pointer to the remote address to bind this socket to.
  524. Return Value:
  525. Status code.
  526. --*/
  527. {
  528. ULONG Flags;
  529. KSTATUS Status;
  530. //
  531. // Fully bind the socket and activate it. It's ready to receive.
  532. //
  533. Flags = NET_SOCKET_BINDING_FLAG_ACTIVATE;
  534. Status = NetBindSocket(Socket, SocketFullyBound, NULL, Address, Flags);
  535. if (!KSUCCESS(Status)) {
  536. goto Ip4ConnectEnd;
  537. }
  538. Status = STATUS_SUCCESS;
  539. Ip4ConnectEnd:
  540. return Status;
  541. }
  542. KSTATUS
  543. NetpIp4Disconnect (
  544. PNET_SOCKET Socket
  545. )
  546. /*++
  547. Routine Description:
  548. This routine will disconnect the given socket from its remote address.
  549. Arguments:
  550. Socket - Supplies a pointer to the socket to disconnect.
  551. Return Value:
  552. Status code.
  553. --*/
  554. {
  555. KSTATUS Status;
  556. //
  557. // Roll the fully bound socket back to the locally bound state.
  558. //
  559. Status = NetDisconnectSocket(Socket);
  560. if (!KSUCCESS(Status)) {
  561. goto Ip4DisconnectEnd;
  562. }
  563. Status = STATUS_SUCCESS;
  564. Ip4DisconnectEnd:
  565. return Status;
  566. }
  567. KSTATUS
  568. NetpIp4Close (
  569. PNET_SOCKET Socket
  570. )
  571. /*++
  572. Routine Description:
  573. This routine closes a socket connection.
  574. Arguments:
  575. Socket - Supplies a pointer to the socket to shut down.
  576. Return Value:
  577. Status code.
  578. --*/
  579. {
  580. //
  581. // Deactivate the socket. This will most likely release a reference. There
  582. // should be at least one more sitting around.
  583. //
  584. ASSERT(Socket->KernelSocket.ReferenceCount > 1);
  585. NetDeactivateSocket(Socket);
  586. //
  587. // Now that the socket is deactiviated, destroy any pending fragments.
  588. //
  589. if (Socket->LocalAddress.Domain == NetDomainIp4) {
  590. KeAcquireQueuedLock(NetIp4FragmentedPacketLock);
  591. NetpIp4RemoveFragmentedPackets(Socket);
  592. KeReleaseQueuedLock(NetIp4FragmentedPacketLock);
  593. }
  594. return STATUS_SUCCESS;
  595. }
  596. KSTATUS
  597. NetpIp4Send (
  598. PNET_SOCKET Socket,
  599. PNETWORK_ADDRESS Destination,
  600. PNET_SOCKET_LINK_OVERRIDE LinkOverride,
  601. PNET_PACKET_LIST PacketList
  602. )
  603. /*++
  604. Routine Description:
  605. This routine sends data through the network.
  606. Arguments:
  607. Socket - Supplies a pointer to the socket to send the data to.
  608. Destination - Supplies a pointer to the network address to send to.
  609. LinkOverride - Supplies an optional pointer to a structure that contains
  610. all the necessary information to send data out a link on behalf
  611. of the given socket.
  612. PacketList - Supplies a pointer to a list of network packets to send. Data
  613. in these packets may be modified by this routine, but must not be used
  614. once this routine returns.
  615. Return Value:
  616. Status code. It is assumed that either all packets are submitted (if
  617. success is returned) or none of the packets were submitted (if a failing
  618. status is returned).
  619. --*/
  620. {
  621. ULONG BytesCompleted;
  622. ULONG BytesRemaining;
  623. USHORT Checksum;
  624. PLIST_ENTRY CurrentEntry;
  625. ULONG FooterSize;
  626. PNET_PACKET_BUFFER Fragment;
  627. ULONG FragmentLength;
  628. USHORT FragmentOffset;
  629. PIP4_HEADER Header;
  630. ULONG HeaderSize;
  631. PNET_LINK Link;
  632. PNET_LINK_ADDRESS_ENTRY LinkAddress;
  633. PIP4_ADDRESS LocalAddress;
  634. ULONG MaxFragmentLength;
  635. ULONG MaxPacketSize;
  636. PNET_PACKET_BUFFER Packet;
  637. PVOID PacketBuffer;
  638. PNETWORK_ADDRESS PhysicalNetworkAddress;
  639. NETWORK_ADDRESS PhysicalNetworkAddressBuffer;
  640. PIP4_ADDRESS RemoteAddress;
  641. PNET_DATA_LINK_SEND Send;
  642. PNETWORK_ADDRESS Source;
  643. KSTATUS Status;
  644. ULONG TotalLength;
  645. ASSERT((Socket->KernelSocket.Type == NetSocketRaw) ||
  646. (Socket->KernelSocket.Protocol ==
  647. Socket->Protocol->ParentProtocolNumber));
  648. //
  649. // If an override was supplied, prefer that link and link address.
  650. //
  651. if (LinkOverride != NULL) {
  652. Link = LinkOverride->LinkInformation.Link;
  653. LinkAddress = LinkOverride->LinkInformation.LinkAddress;
  654. MaxPacketSize = LinkOverride->PacketSizeInformation.MaxPacketSize;
  655. Source = &(LinkOverride->LinkInformation.LocalAddress);
  656. //
  657. // Otherwise use the socket's information.
  658. //
  659. } else {
  660. Link = Socket->Link;
  661. LinkAddress = Socket->LinkAddress;
  662. MaxPacketSize = Socket->PacketSizeInformation.MaxPacketSize;
  663. Source = &(Socket->LocalAddress);
  664. }
  665. LocalAddress = (PIP4_ADDRESS)Source;
  666. RemoteAddress = (PIP4_ADDRESS)Destination;
  667. //
  668. // There better be a link and link address.
  669. //
  670. ASSERT((Link != NULL) && (LinkAddress != NULL));
  671. //
  672. // Sending to the broadcast address must be specifically requested through
  673. // socket options.
  674. //
  675. if ((RemoteAddress->Address == IP4_BROADCAST_ADDRESS) &&
  676. ((Socket->Flags & NET_SOCKET_FLAG_BROADCAST_ENABLED) == 0)) {
  677. Status = STATUS_ACCESS_DENIED;
  678. goto Ip4SendEnd;
  679. }
  680. //
  681. // Figure out the physical network address for the given IP destination
  682. // address. This answer is the same for every packet. Use the cached
  683. // version in the network socket if it's there and the destination matches
  684. // the remote address in the net socket.
  685. //
  686. PhysicalNetworkAddress = &(Socket->RemotePhysicalAddress);
  687. if ((Destination != &(Socket->RemoteAddress)) ||
  688. (PhysicalNetworkAddress->Domain == NetDomainInvalid)) {
  689. if (Destination != &(Socket->RemoteAddress)) {
  690. PhysicalNetworkAddress = &PhysicalNetworkAddressBuffer;
  691. }
  692. Status = NetpIp4TranslateNetworkAddress(Destination,
  693. Link,
  694. LinkAddress,
  695. PhysicalNetworkAddress);
  696. if (!KSUCCESS(Status)) {
  697. goto Ip4SendEnd;
  698. }
  699. ASSERT(PhysicalNetworkAddress->Domain != NetDomainInvalid);
  700. }
  701. //
  702. // Add the IP4 and Ethernet headers to each packet.
  703. //
  704. CurrentEntry = PacketList->Head.Next;
  705. while (CurrentEntry != &(PacketList->Head)) {
  706. Packet = LIST_VALUE(CurrentEntry, NET_PACKET_BUFFER, ListEntry);
  707. CurrentEntry = CurrentEntry->Next;
  708. //
  709. // If the socket is supposed to include the IP header in its
  710. // packets, but this packet is too large, then fail without sending any
  711. // packets.
  712. //
  713. if ((Packet->DataSize > MaxPacketSize) &&
  714. ((Socket->Flags & NET_SOCKET_FLAG_NETWORK_HEADER_INCLUDED) != 0)) {
  715. Status = STATUS_MESSAGE_TOO_LONG;
  716. goto Ip4SendEnd;
  717. //
  718. // If the current packet's total data size (including all headers and
  719. // footers) is larger than the socket's/link's maximum size, then the
  720. // IP layer needs to break it into multiple fragments.
  721. //
  722. } else if (Packet->DataSize > MaxPacketSize) {
  723. //
  724. // Determine the size of the remaining headers and footers that
  725. // will be added to each fragment. These can be determined from the
  726. // current packet's data offset, total size and footer offset.
  727. //
  728. HeaderSize = Packet->DataOffset;
  729. FooterSize = Packet->DataSize - Packet->FooterOffset;
  730. //
  731. // Determine the maximum size of each fragment based on the headers
  732. // and footers required.
  733. //
  734. MaxFragmentLength = MaxPacketSize - HeaderSize - FooterSize;
  735. MaxFragmentLength = ALIGN_RANGE_DOWN(MaxFragmentLength,
  736. IP4_FRAGMENT_ALIGNMENT);
  737. //
  738. // Iterate over the current packet, breaking it up into multiple
  739. // fragments.
  740. //
  741. PacketBuffer = Packet->Buffer + Packet->DataOffset;
  742. BytesCompleted = 0;
  743. BytesRemaining = Packet->FooterOffset - Packet->DataOffset;
  744. while (BytesRemaining != 0) {
  745. FragmentLength = MaxFragmentLength;
  746. if (FragmentLength > BytesRemaining) {
  747. FragmentLength = BytesRemaining;
  748. }
  749. Status = NetAllocateBuffer(HeaderSize,
  750. FragmentLength,
  751. FooterSize,
  752. Link,
  753. 0,
  754. &Fragment);
  755. if (!KSUCCESS(Status)) {
  756. goto Ip4SendEnd;
  757. }
  758. //
  759. // Copy the data from the packet to the fragment.
  760. //
  761. RtlCopyMemory(Fragment->Buffer + Fragment->DataOffset,
  762. PacketBuffer,
  763. FragmentLength);
  764. //
  765. // Get a pointer to the header, which is right before the data.
  766. //
  767. ASSERT(Fragment->DataOffset > sizeof(IP4_HEADER));
  768. Fragment->DataOffset -= sizeof(IP4_HEADER);
  769. Header = (PIP4_HEADER)(Fragment->Buffer + Fragment->DataOffset);
  770. //
  771. // Fill out that IPv4 header.
  772. //
  773. Header->VersionAndHeaderLength =
  774. IP4_VERSION | (UCHAR)(sizeof(IP4_HEADER) / sizeof(ULONG));
  775. Header->Type = 0;
  776. TotalLength = Fragment->FooterOffset - Fragment->DataOffset;
  777. Header->TotalLength = CPU_TO_NETWORK16(TotalLength);
  778. Header->Identification =
  779. CPU_TO_NETWORK16(Socket->SendPacketCount);
  780. ASSERT(IS_ALIGNED(BytesCompleted, IP4_FRAGMENT_ALIGNMENT) != 0);
  781. FragmentOffset = IP4_CONVERT_BYTES_TO_OFFSET(BytesCompleted);
  782. FragmentOffset &= IP4_FRAGMENT_OFFSET_MASK;
  783. FragmentOffset <<= IP4_FRAGMENT_OFFSET_SHIFT;
  784. if (FragmentLength != BytesRemaining) {
  785. FragmentOffset |= (IP4_FLAG_MORE_FRAGMENTS <<
  786. IP4_FRAGMENT_FLAGS_SHIFT);
  787. }
  788. Header->FragmentOffset = CPU_TO_NETWORK16(FragmentOffset);
  789. Header->TimeToLive = IP4_INITIAL_TIME_TO_LIVE;
  790. ASSERT(Socket->KernelSocket.Protocol !=
  791. SOCKET_INTERNET_PROTOCOL_RAW);
  792. Header->Protocol = Socket->KernelSocket.Protocol;
  793. Header->SourceAddress = LocalAddress->Address;
  794. Header->DestinationAddress = RemoteAddress->Address;
  795. Header->HeaderChecksum = 0;
  796. if ((Link->Properties.ChecksumFlags &
  797. NET_LINK_CHECKSUM_FLAG_TRANSMIT_IP_OFFLOAD) == 0) {
  798. Checksum = NetpIp4ChecksumData((PSHORT)Header,
  799. sizeof(IP4_HEADER));
  800. Header->HeaderChecksum = CPU_TO_NETWORK16(Checksum);
  801. } else {
  802. Fragment->Flags |= NET_PACKET_FLAG_IP_CHECKSUM_OFFLOAD;
  803. }
  804. //
  805. // Add the fragment to the list of packets.
  806. //
  807. NET_INSERT_PACKET_BEFORE(Fragment, Packet, PacketList);
  808. PacketBuffer += FragmentLength;
  809. BytesCompleted += FragmentLength;
  810. BytesRemaining -= FragmentLength;
  811. }
  812. //
  813. // Remove the original packet. It just got fragmented. And move on
  814. // to the next packet ID.
  815. //
  816. Socket->SendPacketCount += 1;
  817. NET_REMOVE_PACKET_FROM_LIST(Packet, PacketList);
  818. NetFreeBuffer(Packet);
  819. continue;
  820. }
  821. //
  822. // Add the IP4 network header unless it is already included.
  823. //
  824. if ((Socket->Flags & NET_SOCKET_FLAG_NETWORK_HEADER_INCLUDED) == 0) {
  825. //
  826. // Get a pointer to the header, which is right before the data.
  827. //
  828. ASSERT(Packet->DataOffset > sizeof(IP4_HEADER));
  829. Packet->DataOffset -= sizeof(IP4_HEADER);
  830. Header = (PIP4_HEADER)(Packet->Buffer + Packet->DataOffset);
  831. //
  832. // Fill out that IPv4 header.
  833. //
  834. Header->VersionAndHeaderLength = IP4_VERSION |
  835. (UCHAR)(sizeof(IP4_HEADER) /
  836. sizeof(ULONG));
  837. Header->Type = 0;
  838. TotalLength = Packet->FooterOffset - Packet->DataOffset;
  839. Header->TotalLength = CPU_TO_NETWORK16(TotalLength);
  840. Header->Identification = CPU_TO_NETWORK16(Socket->SendPacketCount);
  841. Socket->SendPacketCount += 1;
  842. Header->FragmentOffset = 0;
  843. Header->TimeToLive = IP4_INITIAL_TIME_TO_LIVE;
  844. ASSERT(Socket->KernelSocket.Protocol !=
  845. SOCKET_INTERNET_PROTOCOL_RAW);
  846. Header->Protocol = Socket->KernelSocket.Protocol;
  847. Header->SourceAddress = LocalAddress->Address;
  848. Header->DestinationAddress = RemoteAddress->Address;
  849. Header->HeaderChecksum = 0;
  850. if ((Link->Properties.ChecksumFlags &
  851. NET_LINK_CHECKSUM_FLAG_TRANSMIT_IP_OFFLOAD) == 0) {
  852. Checksum = NetpIp4ChecksumData((PVOID)Header,
  853. sizeof(IP4_HEADER));
  854. Header->HeaderChecksum = Checksum;
  855. } else {
  856. Packet->Flags |= NET_PACKET_FLAG_IP_CHECKSUM_OFFLOAD;
  857. }
  858. //
  859. // Otherwise the packet may need to be shifted. Unless this is a raw
  860. // socket using the "raw" protocol, the packet was created thinking
  861. // that the IPv4 header needed to be included by the network layer. The
  862. // flags now indicate that the IPv4 header is included by the caller.
  863. // The packet needs to be properly aligned for the hardware, so it
  864. // needs to be shifted by the IPv4 header size.
  865. //
  866. } else {
  867. ASSERT(Socket->KernelSocket.Type == NetSocketRaw);
  868. //
  869. // This can be skipped if the socket is signed up to use the "raw"
  870. // protocol. The IPv4 header size isn't added to such sockets upon
  871. // initialization.
  872. //
  873. if (Socket->KernelSocket.Protocol != SOCKET_INTERNET_PROTOCOL_RAW) {
  874. ASSERT(Packet->DataOffset > sizeof(IP4_HEADER));
  875. Header = (PIP4_HEADER)(Packet->Buffer +
  876. Packet->DataOffset -
  877. sizeof(IP4_HEADER));
  878. TotalLength = Packet->DataSize - Packet->DataOffset;
  879. RtlCopyMemory(Header,
  880. Packet->Buffer + Packet->DataOffset,
  881. TotalLength);
  882. Packet->DataOffset -= sizeof(IP4_HEADER);
  883. Packet->FooterOffset -= sizeof(IP4_HEADER);
  884. Packet->DataSize -= sizeof(IP4_HEADER);
  885. }
  886. }
  887. }
  888. //
  889. // The packets are all ready to go, send them down the link.
  890. //
  891. Send = Link->DataLinkEntry->Interface.Send;
  892. Status = Send(Link->DataLinkContext,
  893. PacketList,
  894. &(LinkAddress->PhysicalAddress),
  895. PhysicalNetworkAddress,
  896. Socket->Network->ParentProtocolNumber);
  897. if (!KSUCCESS(Status)) {
  898. goto Ip4SendEnd;
  899. }
  900. Status = STATUS_SUCCESS;
  901. Ip4SendEnd:
  902. if (NetIp4DebugPrintPackets != FALSE) {
  903. RtlDebugPrint("Net: IP4 Packet send from ");
  904. NetDebugPrintAddress(Source);
  905. RtlDebugPrint(" to ");
  906. NetDebugPrintAddress(Destination);
  907. RtlDebugPrint(" : %x.\n", Status);
  908. }
  909. return Status;
  910. }
  911. VOID
  912. NetpIp4ProcessReceivedData (
  913. PNET_LINK Link,
  914. PNET_PACKET_BUFFER Packet
  915. )
  916. /*++
  917. Routine Description:
  918. This routine is called to process a received packet.
  919. Arguments:
  920. Link - Supplies a pointer to the link that received the packet.
  921. Packet - Supplies a pointer to a structure describing the incoming packet.
  922. This structure may be used as a scratch space while this routine
  923. executes and the packet travels up the stack, but will not be accessed
  924. after this routine returns.
  925. Return Value:
  926. None. When the function returns, the memory associated with the packet may
  927. be reclaimed and reused.
  928. --*/
  929. {
  930. USHORT ComputedChecksum;
  931. IP4_ADDRESS DestinationAddress;
  932. USHORT FragmentFlags;
  933. USHORT FragmentOffset;
  934. PIP4_HEADER Header;
  935. ULONG HeaderSize;
  936. PNET_PROTOCOL_ENTRY ProtocolEntry;
  937. PNET_PACKET_BUFFER ReassembledPacket;
  938. IP4_ADDRESS SourceAddress;
  939. USHORT TotalLength;
  940. ReassembledPacket = NULL;
  941. Header = (PIP4_HEADER)(Packet->Buffer + Packet->DataOffset);
  942. //
  943. // Check the protocol version and header length.
  944. //
  945. if ((Header->VersionAndHeaderLength & IP4_VERSION_MASK) != IP4_VERSION) {
  946. RtlDebugPrint("Invalid IPv4 version. Byte: 0x%02x.\n",
  947. Header->VersionAndHeaderLength);
  948. goto Ip4ProcessReceivedDataEnd;
  949. }
  950. HeaderSize = (Header->VersionAndHeaderLength & IP4_HEADER_LENGTH_MASK) *
  951. sizeof(ULONG);
  952. if (HeaderSize < sizeof(IP4_HEADER)) {
  953. RtlDebugPrint("Invalid IPv4 header length. Byte: 0x%02x.\n",
  954. Header->VersionAndHeaderLength);
  955. goto Ip4ProcessReceivedDataEnd;
  956. }
  957. //
  958. // Validate the total length field.
  959. //
  960. TotalLength = NETWORK_TO_CPU16(Header->TotalLength);
  961. if (TotalLength > (Packet->FooterOffset - Packet->DataOffset)) {
  962. RtlDebugPrint("Invalid IPv4 total length %d is bigger than packet "
  963. "data, which is only %d bytes large.\n",
  964. TotalLength,
  965. (Packet->FooterOffset - Packet->DataOffset));
  966. goto Ip4ProcessReceivedDataEnd;
  967. }
  968. //
  969. // Validate the header checksum, which with the checksum field should work
  970. // out to zero. Skip this if the checksum was offloaded and valid.
  971. //
  972. if (((Packet->Flags & NET_PACKET_FLAG_IP_CHECKSUM_OFFLOAD) == 0) ||
  973. ((Packet->Flags & NET_PACKET_FLAG_IP_CHECKSUM_FAILED) != 0)) {
  974. ComputedChecksum = NetpIp4ChecksumData((PVOID)Header, HeaderSize);
  975. if (ComputedChecksum != 0) {
  976. RtlDebugPrint("Invalid IPv4 header checksum. Computed checksum: "
  977. "0x%04x, should have been zero.\n",
  978. ComputedChecksum);
  979. goto Ip4ProcessReceivedDataEnd;
  980. }
  981. }
  982. //
  983. // Initialize the network address.
  984. //
  985. RtlZeroMemory(&SourceAddress, sizeof(NETWORK_ADDRESS));
  986. RtlZeroMemory(&DestinationAddress, sizeof(NETWORK_ADDRESS));
  987. SourceAddress.Domain = NetDomainIp4;
  988. SourceAddress.Address = Header->SourceAddress;
  989. DestinationAddress.Domain = NetDomainIp4;
  990. DestinationAddress.Address = Header->DestinationAddress;
  991. //
  992. // Update the packet's size. Raw sockets should get everything at the IPv4
  993. // layer. So, lop any footers beyond the IPv4 packet. IPv4 has no footer
  994. // itself.
  995. //
  996. Packet->FooterOffset = Packet->DataOffset + TotalLength;
  997. //
  998. // If this is part of a fragmented datagram, add it to the mix with hopes
  999. // of completing the reassembly of the protocol layer packet.
  1000. //
  1001. FragmentOffset = NETWORK_TO_CPU16(Header->FragmentOffset);
  1002. FragmentFlags = (FragmentOffset >> IP4_FRAGMENT_FLAGS_SHIFT) &
  1003. IP4_FRAGMENT_FLAGS_MASK;
  1004. FragmentOffset = (FragmentOffset >> IP4_FRAGMENT_OFFSET_SHIFT) &
  1005. IP4_FRAGMENT_OFFSET_MASK;
  1006. if (((FragmentFlags & IP4_FLAG_MORE_FRAGMENTS) != 0) ||
  1007. (FragmentOffset != 0)) {
  1008. if (NetIp4DebugPrintPackets != FALSE) {
  1009. RtlDebugPrint("IP4: Fragment for protocol %d:\n%20s: ",
  1010. Header->Protocol,
  1011. "LocalAddress");
  1012. NetDebugPrintAddress((PNETWORK_ADDRESS)&DestinationAddress);
  1013. RtlDebugPrint("\n%20s: ", "RemoteAddress");
  1014. NetDebugPrintAddress((PNETWORK_ADDRESS)&SourceAddress);
  1015. RtlDebugPrint("\n%20s: 0x%x\n"
  1016. "%20s: 0x%x\n"
  1017. "%20s: 0x%x\n",
  1018. "ID",
  1019. NETWORK_TO_CPU16(Header->Identification),
  1020. "Offset",
  1021. FragmentOffset,
  1022. "Flags",
  1023. FragmentFlags);
  1024. }
  1025. //
  1026. // If the "do not fragment" flag is also set, skip this fragment.
  1027. //
  1028. if ((FragmentFlags & IP4_FLAG_DO_NOT_FRAGMENT) != 0) {
  1029. goto Ip4ProcessReceivedDataEnd;
  1030. }
  1031. ReassembledPacket = NetpIp4ProcessPacketFragment(Link, Packet);
  1032. if (ReassembledPacket == NULL) {
  1033. goto Ip4ProcessReceivedDataEnd;
  1034. }
  1035. Packet = ReassembledPacket;
  1036. //
  1037. // Update the header information. There is no reason to validate it. It
  1038. // just got created from a trusted source.
  1039. //
  1040. Header = (PIP4_HEADER)(Packet->Buffer + Packet->DataOffset);
  1041. HeaderSize = (Header->VersionAndHeaderLength & IP4_HEADER_LENGTH_MASK) *
  1042. sizeof(ULONG);
  1043. TotalLength = NETWORK_TO_CPU16(Header->TotalLength);
  1044. //
  1045. // Otherwise notify the debugger of a complete packet's arrival.
  1046. //
  1047. } else if (NetIp4DebugPrintPackets != FALSE) {
  1048. RtlDebugPrint("Net: IP4 Packet received from ");
  1049. NetDebugPrintAddress((PNETWORK_ADDRESS)&SourceAddress);
  1050. RtlDebugPrint(" to ");
  1051. NetDebugPrintAddress((PNETWORK_ADDRESS)&DestinationAddress);
  1052. RtlDebugPrint("\n");
  1053. }
  1054. //
  1055. // Give raw sockets a chance to look at the packet.
  1056. //
  1057. NetRawSocketsProcessReceivedData(Link,
  1058. Packet,
  1059. (PNETWORK_ADDRESS)&SourceAddress,
  1060. (PNETWORK_ADDRESS)&DestinationAddress,
  1061. Header->Protocol);
  1062. //
  1063. // Find the local protocol entry for the protocol specified in the header
  1064. // and process the packet.
  1065. //
  1066. ProtocolEntry = NetGetProtocolEntry(Header->Protocol);
  1067. if (ProtocolEntry == NULL) {
  1068. RtlDebugPrint("No protocol found for IPv4 packet protocol number "
  1069. "0x%02x.\n",
  1070. Header->Protocol);
  1071. goto Ip4ProcessReceivedDataEnd;
  1072. }
  1073. //
  1074. // Update the packet's data offset so that it starts at the protocol layer.
  1075. //
  1076. Packet->DataOffset += HeaderSize;
  1077. ProtocolEntry->Interface.ProcessReceivedData(
  1078. Link,
  1079. Packet,
  1080. (PNETWORK_ADDRESS)&SourceAddress,
  1081. (PNETWORK_ADDRESS)&DestinationAddress,
  1082. ProtocolEntry);
  1083. Ip4ProcessReceivedDataEnd:
  1084. if (ReassembledPacket != NULL) {
  1085. NetFreeBuffer(ReassembledPacket);
  1086. }
  1087. return;
  1088. }
  1089. ULONG
  1090. NetpIp4PrintAddress (
  1091. PNETWORK_ADDRESS Address,
  1092. PSTR Buffer,
  1093. ULONG BufferLength
  1094. )
  1095. /*++
  1096. Routine Description:
  1097. This routine is called to convert a network address into a string, or
  1098. determine the length of the buffer needed to convert an address into a
  1099. string.
  1100. Arguments:
  1101. Address - Supplies an optional pointer to a network address to convert to
  1102. a string.
  1103. Buffer - Supplies an optional pointer where the string representation of
  1104. the address will be returned.
  1105. BufferLength - Supplies the length of the supplied buffer, in bytes.
  1106. Return Value:
  1107. Returns the maximum length of any address if no network address is
  1108. supplied.
  1109. Returns the actual length of the network address string if a network address
  1110. was supplied, including the null terminator.
  1111. --*/
  1112. {
  1113. UCHAR Components[4];
  1114. PIP4_ADDRESS Ip4Address;
  1115. ULONG Length;
  1116. if (Address == NULL) {
  1117. return IP4_MAX_ADDRESS_STRING;
  1118. }
  1119. ASSERT(Address->Domain == NetDomainIp4);
  1120. Ip4Address = (PIP4_ADDRESS)Address;
  1121. Components[0] = (UCHAR)(Ip4Address->Address);
  1122. Components[1] = (UCHAR)(Ip4Address->Address >> 8);
  1123. Components[2] = (UCHAR)(Ip4Address->Address >> 16);
  1124. Components[3] = (UCHAR)(Ip4Address->Address >> 24);
  1125. //
  1126. // If the buffer is present, print that bad boy out.
  1127. //
  1128. if (Ip4Address->Port != 0) {
  1129. Length = RtlPrintToString(Buffer,
  1130. BufferLength,
  1131. CharacterEncodingDefault,
  1132. "%d.%d.%d.%d:%d",
  1133. Components[0],
  1134. Components[1],
  1135. Components[2],
  1136. Components[3],
  1137. Ip4Address->Port);
  1138. } else {
  1139. Length = RtlPrintToString(Buffer,
  1140. BufferLength,
  1141. CharacterEncodingDefault,
  1142. "%d.%d.%d.%d",
  1143. Components[0],
  1144. Components[1],
  1145. Components[2],
  1146. Components[3]);
  1147. }
  1148. return Length;
  1149. }
  1150. KSTATUS
  1151. NetpIp4GetSetInformation (
  1152. PNET_SOCKET Socket,
  1153. SOCKET_INFORMATION_TYPE InformationType,
  1154. UINTN Option,
  1155. PVOID Data,
  1156. PUINTN DataSize,
  1157. BOOL Set
  1158. )
  1159. /*++
  1160. Routine Description:
  1161. This routine gets or sets properties of the given socket.
  1162. Arguments:
  1163. Socket - Supplies a pointer to the socket to get or set information for.
  1164. InformationType - Supplies the socket information type category to which
  1165. specified option belongs.
  1166. Option - Supplies the option to get or set, which is specific to the
  1167. information type. The type of this value is generally
  1168. SOCKET_<information_type>_OPTION.
  1169. Data - Supplies a pointer to the data buffer where the data is either
  1170. returned for a get operation or given for a set operation.
  1171. DataSize - Supplies a pointer that on input constains the size of the data
  1172. buffer. On output, this contains the required size of the data buffer.
  1173. Set - Supplies a boolean indicating if this is a get operation (FALSE) or
  1174. a set operation (TRUE).
  1175. Return Value:
  1176. STATUS_SUCCESS on success.
  1177. STATUS_INVALID_PARAMETER if the information type is incorrect.
  1178. STATUS_BUFFER_TOO_SMALL if the data buffer is too small to receive the
  1179. requested option.
  1180. STATUS_NOT_SUPPORTED_BY_PROTOCOL if the socket option is not supported by
  1181. the socket.
  1182. --*/
  1183. {
  1184. ULONG BooleanOption;
  1185. ULONG Flags;
  1186. SOCKET_IP4_OPTION Ip4Option;
  1187. UINTN RequiredSize;
  1188. PVOID Source;
  1189. KSTATUS Status;
  1190. if (InformationType != SocketInformationIp4) {
  1191. Status = STATUS_INVALID_PARAMETER;
  1192. goto Ip4GetSetInformationEnd;
  1193. }
  1194. RequiredSize = 0;
  1195. Source = NULL;
  1196. Status = STATUS_SUCCESS;
  1197. Ip4Option = (SOCKET_IP4_OPTION)Option;
  1198. switch (Ip4Option) {
  1199. case SocketIp4OptionHeaderIncluded:
  1200. RequiredSize = sizeof(ULONG);
  1201. if (Set != FALSE) {
  1202. //
  1203. // Setting the header included option is only allowed on raw
  1204. // sockets that are not operating on the "raw" network protocol.
  1205. //
  1206. if ((Socket->KernelSocket.Type != NetSocketRaw) ||
  1207. (Socket->KernelSocket.Protocol ==
  1208. SOCKET_INTERNET_PROTOCOL_RAW)) {
  1209. Status = STATUS_NOT_SUPPORTED_BY_PROTOCOL;
  1210. break;
  1211. }
  1212. if (*DataSize < RequiredSize) {
  1213. *DataSize = RequiredSize;
  1214. Status = STATUS_BUFFER_TOO_SMALL;
  1215. break;
  1216. }
  1217. BooleanOption = *((PULONG)Data);
  1218. if (BooleanOption != FALSE) {
  1219. RtlAtomicOr32(&(Socket->Flags),
  1220. NET_SOCKET_FLAG_NETWORK_HEADER_INCLUDED);
  1221. } else {
  1222. RtlAtomicAnd32(&(Socket->Flags),
  1223. ~NET_SOCKET_FLAG_NETWORK_HEADER_INCLUDED);
  1224. }
  1225. } else {
  1226. Source = &BooleanOption;
  1227. BooleanOption = FALSE;
  1228. Flags = Socket->Flags;
  1229. if ((Flags & NET_SOCKET_FLAG_NETWORK_HEADER_INCLUDED) != 0) {
  1230. BooleanOption = TRUE;
  1231. }
  1232. }
  1233. break;
  1234. default:
  1235. Status = STATUS_NOT_SUPPORTED_BY_PROTOCOL;
  1236. break;
  1237. }
  1238. if (!KSUCCESS(Status)) {
  1239. goto Ip4GetSetInformationEnd;
  1240. }
  1241. //
  1242. // Truncate all copies for get requests down to the required size and
  1243. // always return the required size on set requests.
  1244. //
  1245. if (*DataSize > RequiredSize) {
  1246. *DataSize = RequiredSize;
  1247. }
  1248. //
  1249. // For get requests, copy the gathered information to the supplied data
  1250. // buffer.
  1251. //
  1252. if (Set == FALSE) {
  1253. ASSERT(Source != NULL);
  1254. RtlCopyMemory(Data, Source, *DataSize);
  1255. //
  1256. // If the copy truncated the data, report that the given buffer was too
  1257. // small. The caller can choose to ignore this if the truncated data is
  1258. // enough.
  1259. //
  1260. if (*DataSize < RequiredSize) {
  1261. *DataSize = RequiredSize;
  1262. Status = STATUS_BUFFER_TOO_SMALL;
  1263. goto Ip4GetSetInformationEnd;
  1264. }
  1265. }
  1266. Ip4GetSetInformationEnd:
  1267. return Status;
  1268. }
  1269. //
  1270. // --------------------------------------------------------- Internal Functions
  1271. //
  1272. USHORT
  1273. NetpIp4ChecksumData (
  1274. PVOID Data,
  1275. ULONG Length
  1276. )
  1277. /*++
  1278. Routine Description:
  1279. This routine checksums a section of data for use in an IP datagram
  1280. checksum and returns it in network byte order.
  1281. Arguments:
  1282. Data - Supplies a pointer to the data to checksum.
  1283. Length - Supplies the number of bytes to checksum. This must be an even
  1284. number.
  1285. Return Value:
  1286. Returns the checksum of the data.
  1287. --*/
  1288. {
  1289. PUCHAR BytePointer;
  1290. PULONG LongPointer;
  1291. ULONG NextValue;
  1292. USHORT ShortOne;
  1293. PUSHORT ShortPointer;
  1294. USHORT ShortTwo;
  1295. ULONG Sum;
  1296. ASSERT((Length & 0x1) == 0);
  1297. Sum = 0;
  1298. LongPointer = (PULONG)Data;
  1299. while (Length >= sizeof(ULONG)) {
  1300. NextValue = *LongPointer;
  1301. LongPointer += 1;
  1302. Sum += NextValue;
  1303. if (Sum < NextValue) {
  1304. Sum += 1;
  1305. }
  1306. Length -= sizeof(ULONG);
  1307. }
  1308. BytePointer = (PUCHAR)LongPointer;
  1309. if (Length == sizeof(USHORT)) {
  1310. ShortPointer = (PUSHORT)BytePointer;
  1311. NextValue = (USHORT)*ShortPointer;
  1312. Sum += NextValue;
  1313. if (Sum < NextValue) {
  1314. Sum += 1;
  1315. }
  1316. }
  1317. //
  1318. // Fold the 32-bit value down to 16-bits.
  1319. //
  1320. ShortOne = (USHORT)Sum;
  1321. ShortTwo = (USHORT)(Sum >> 16);
  1322. ShortTwo += ShortOne;
  1323. if (ShortTwo < ShortOne) {
  1324. ShortTwo += 1;
  1325. }
  1326. return (USHORT)~ShortTwo;
  1327. }
  1328. KSTATUS
  1329. NetpIp4TranslateNetworkAddress (
  1330. PNETWORK_ADDRESS NetworkAddress,
  1331. PNET_LINK Link,
  1332. PNET_LINK_ADDRESS_ENTRY LinkAddress,
  1333. PNETWORK_ADDRESS PhysicalAddress
  1334. )
  1335. /*++
  1336. Routine Description:
  1337. This routine translates a network level address to a physical address.
  1338. Arguments:
  1339. NetworkAddress - Supplies a pointer to the network address to translate.
  1340. Link - Supplies a pointer to the link to use.
  1341. LinkAddress - Supplies a pointer to the link address entry to use for this
  1342. request.
  1343. PhysicalAddress - Supplies a pointer where the corresponding physical
  1344. address for this network address will be returned.
  1345. Return Value:
  1346. Status code.
  1347. --*/
  1348. {
  1349. ULONG BitsDifferentInSubnet;
  1350. NETWORK_ADDRESS DefaultGateway;
  1351. PIP4_ADDRESS Ip4Address;
  1352. PIP4_ADDRESS LocalIpAddress;
  1353. BOOL LockHeld;
  1354. KSTATUS Status;
  1355. PIP4_ADDRESS SubnetMask;
  1356. ASSERT(KeGetRunLevel() == RunLevelLow);
  1357. Ip4Address = (PIP4_ADDRESS)NetworkAddress;
  1358. //
  1359. // This function is very simple: it perform some filtering on known
  1360. // addresses, and if none of those match passes it on to the link layer.
  1361. // Start by checking against 0.0.0.0, an invalid address.
  1362. //
  1363. if (Ip4Address->Address == 0) {
  1364. return STATUS_INVALID_ADDRESS;
  1365. }
  1366. //
  1367. // Check against the broadcast address, which automatically translates to
  1368. // the broadcast link address.
  1369. //
  1370. if (Ip4Address->Address == IP4_BROADCAST_ADDRESS) {
  1371. Link->DataLinkEntry->Interface.GetBroadcastAddress(PhysicalAddress);
  1372. return STATUS_SUCCESS;
  1373. }
  1374. //
  1375. // Make sure the link address is still configured when using it.
  1376. //
  1377. KeAcquireQueuedLock(Link->QueuedLock);
  1378. LockHeld = TRUE;
  1379. if (LinkAddress->Configured == FALSE) {
  1380. Status = STATUS_NO_NETWORK_CONNECTION;
  1381. goto Ip4TranslateNetworkAddressEnd;
  1382. }
  1383. //
  1384. // Check to see if the destination address is in the subnet. If it is,
  1385. // then pass it down directly to get translated. Otherwise, pass down the
  1386. // gateway address.
  1387. //
  1388. LocalIpAddress = (PIP4_ADDRESS)&(LinkAddress->Address);
  1389. SubnetMask = (PIP4_ADDRESS)&(LinkAddress->Subnet);
  1390. //
  1391. // This calculates if any bits are different within the subnet mask. If
  1392. // they are, then the destination is outside of the subnet and should go to
  1393. // the default gateway.
  1394. //
  1395. BitsDifferentInSubnet = ((Ip4Address->Address ^ LocalIpAddress->Address) &
  1396. SubnetMask->Address);
  1397. if (BitsDifferentInSubnet != 0) {
  1398. RtlCopyMemory(&DefaultGateway,
  1399. &(LinkAddress->DefaultGateway),
  1400. sizeof(NETWORK_ADDRESS));
  1401. NetworkAddress = &DefaultGateway;
  1402. }
  1403. KeReleaseQueuedLock(Link->QueuedLock);
  1404. LockHeld = FALSE;
  1405. //
  1406. // Well, it looks like a run-of-the-mill IP address, so pass it on to get
  1407. // translated.
  1408. //
  1409. Status = NetTranslateNetworkAddress(NetworkAddress,
  1410. Link,
  1411. LinkAddress,
  1412. PhysicalAddress);
  1413. Ip4TranslateNetworkAddressEnd:
  1414. if (LockHeld != FALSE) {
  1415. KeReleaseQueuedLock(Link->QueuedLock);
  1416. }
  1417. return Status;
  1418. }
  1419. PNET_PACKET_BUFFER
  1420. NetpIp4ProcessPacketFragment (
  1421. PNET_LINK Link,
  1422. PNET_PACKET_BUFFER PacketFragment
  1423. )
  1424. /*++
  1425. Routine Description:
  1426. This routine processes a fragment of an IPv4 packet. The fragment will get
  1427. added to the list of received fragments. If it is the missing piece and
  1428. completes the original packet, then the reassembled packet will be returned.
  1429. Arguments:
  1430. Link - Supplies a pointer to the owning network link.
  1431. PacketFragment - Supplies a pointer to the IPv4 fragment. This packet
  1432. includes the IPv4 header.
  1433. Return Value:
  1434. Returns a pointer to a reassembled packet if the given fragment completed
  1435. the packet. Returns NULL if the fragment was not enough to form a completed
  1436. packet.
  1437. --*/
  1438. {
  1439. ULONG AllocationSize;
  1440. USHORT Checksum;
  1441. PNET_PACKET_BUFFER CompletedPacket;
  1442. PLIST_ENTRY CurrentEntry;
  1443. PVOID DestinationBuffer;
  1444. PRED_BLACK_TREE_NODE FoundNode;
  1445. USHORT FragmentEnd;
  1446. PIP4_FRAGMENT_ENTRY FragmentEntry;
  1447. USHORT FragmentFlags;
  1448. ULONG FragmentLength;
  1449. USHORT FragmentOffset;
  1450. PIP4_HEADER Header;
  1451. ULONG HeaderSize;
  1452. BOOL JoinNext;
  1453. BOOL JoinPrevious;
  1454. BOOL LastFragment;
  1455. PIP4_FRAGMENT_ENTRY NewFragment;
  1456. PIP4_HEADER NewHeader;
  1457. PIP4_FRAGMENT_ENTRY NextEntry;
  1458. PIP4_FRAGMENTED_PACKET_NODE PacketNode;
  1459. PIP4_FRAGMENT_ENTRY PreviousEntry;
  1460. IP4_FRAGMENTED_PACKET_NODE SearchNode;
  1461. PVOID SourceBuffer;
  1462. USHORT StartingOffset;
  1463. KSTATUS Status;
  1464. ULONG TotalLength;
  1465. CompletedPacket = NULL;
  1466. Header = (PIP4_HEADER)(PacketFragment->Buffer + PacketFragment->DataOffset);
  1467. KeAcquireQueuedLock(NetIp4FragmentedPacketLock);
  1468. //
  1469. // Run through the tree and remove any entries that have expired.
  1470. //
  1471. NetpIp4RemoveFragmentedPackets(NULL);
  1472. //
  1473. // If there are too many packets, then exit.
  1474. //
  1475. if (NetIp4FragmentCount > IP4_MAX_FRAGMENT_COUNT) {
  1476. goto Ip4ProcessPacketFragmentEnd;
  1477. }
  1478. //
  1479. // Now that the tree has been purged of old entries, attempt to find an
  1480. // existing entry for this fragment.
  1481. //
  1482. SearchNode.LocalAddress = Header->DestinationAddress;
  1483. SearchNode.RemoteAddress = Header->SourceAddress;
  1484. SearchNode.Protocol = Header->Protocol;
  1485. SearchNode.Identification = NETWORK_TO_CPU16(Header->Identification);
  1486. FoundNode = RtlRedBlackTreeSearch(&NetIp4FragmentedPacketTree,
  1487. &(SearchNode.Node));
  1488. //
  1489. // If an entry is found the new fragment will be inserted in the existing
  1490. // packt's list of fragments.
  1491. //
  1492. if (FoundNode != NULL) {
  1493. PacketNode = RED_BLACK_TREE_VALUE(FoundNode,
  1494. IP4_FRAGMENTED_PACKET_NODE,
  1495. Node);
  1496. //
  1497. // Otherwise a new fragmented packet needs to be created before the
  1498. // fragment can be inserted.
  1499. //
  1500. } else {
  1501. PacketNode = NetpIp4CreateFragmentedPacketNode(Header);
  1502. if (PacketNode == NULL) {
  1503. goto Ip4ProcessPacketFragmentEnd;
  1504. }
  1505. }
  1506. //
  1507. // Determine the fragment's flags and offset.
  1508. //
  1509. FragmentOffset = NETWORK_TO_CPU16(Header->FragmentOffset);
  1510. FragmentFlags = (FragmentOffset >> IP4_FRAGMENT_FLAGS_SHIFT) &
  1511. IP4_FRAGMENT_FLAGS_MASK;
  1512. FragmentOffset = (FragmentOffset >> IP4_FRAGMENT_OFFSET_SHIFT) &
  1513. IP4_FRAGMENT_OFFSET_MASK;
  1514. ASSERT(((FragmentFlags & IP4_FLAG_MORE_FRAGMENTS) != 0) ||
  1515. ((FragmentOffset & IP4_FRAGMENT_OFFSET_MASK) != 0));
  1516. //
  1517. // Find this fragment's place in the list. It goes before the first entry
  1518. // with a larger offset.
  1519. //
  1520. NextEntry = NULL;
  1521. PreviousEntry = NULL;
  1522. CurrentEntry = PacketNode->FragmentListHead.Next;
  1523. while (CurrentEntry != &(PacketNode->FragmentListHead)) {
  1524. FragmentEntry = LIST_VALUE(CurrentEntry, IP4_FRAGMENT_ENTRY, ListEntry);
  1525. CurrentEntry = CurrentEntry->Next;
  1526. if (FragmentEntry->Offset <= FragmentOffset) {
  1527. PreviousEntry = FragmentEntry;
  1528. continue;
  1529. }
  1530. NextEntry = FragmentEntry;
  1531. break;
  1532. }
  1533. JoinNext = FALSE;
  1534. JoinPrevious = FALSE;
  1535. LastFragment = FALSE;
  1536. NewFragment = NULL;
  1537. StartingOffset = FragmentOffset;
  1538. HeaderSize = (Header->VersionAndHeaderLength & IP4_HEADER_LENGTH_MASK) *
  1539. sizeof(ULONG);
  1540. //
  1541. // Calculate the length of the fragment, not including the IPv4 header.
  1542. // That doesn't need to be saved for a packet fragment. A valid header will
  1543. // be rebuilt once all the fragments are received.
  1544. //
  1545. FragmentLength = PacketFragment->FooterOffset -
  1546. PacketFragment->DataOffset;
  1547. ASSERT(FragmentLength == NETWORK_TO_CPU16(Header->TotalLength));
  1548. FragmentLength -= HeaderSize;
  1549. TotalLength = FragmentLength;
  1550. //
  1551. // If a previous fragment exists, combine it with the new fragment if they
  1552. // are adjacent. Ignore overlapping fragments.
  1553. //
  1554. if (PreviousEntry != NULL) {
  1555. ASSERT(IS_ALIGNED(PreviousEntry->Length, IP4_FRAGMENT_ALIGNMENT));
  1556. FragmentEnd = PreviousEntry->Offset +
  1557. IP4_CONVERT_BYTES_TO_OFFSET(PreviousEntry->Length);
  1558. if (FragmentEnd == FragmentOffset) {
  1559. TotalLength += PreviousEntry->Length;
  1560. ASSERT(PreviousEntry->LastFragment == FALSE);
  1561. StartingOffset = PreviousEntry->Offset;
  1562. JoinPrevious = TRUE;
  1563. } else if (FragmentEnd > FragmentOffset) {
  1564. if (NetIp4DebugPrintPackets != FALSE) {
  1565. RtlDebugPrint("IP4: Ignoring overlapping fragment at offset "
  1566. "0x%x.\n",
  1567. FragmentOffset);
  1568. }
  1569. goto Ip4ProcessPacketFragmentEnd;
  1570. }
  1571. }
  1572. //
  1573. // If a next fragment exists, combine it with the new fragment if they are
  1574. // adjacent. Ignore overlapping fragments.
  1575. //
  1576. if (NextEntry != NULL) {
  1577. ASSERT(IS_ALIGNED(TotalLength, IP4_FRAGMENT_ALIGNMENT));
  1578. FragmentEnd = StartingOffset + IP4_CONVERT_BYTES_TO_OFFSET(TotalLength);
  1579. if (FragmentEnd == NextEntry->Offset) {
  1580. TotalLength += NextEntry->Length;
  1581. LastFragment = NextEntry->LastFragment;
  1582. JoinNext = TRUE;
  1583. } else if (FragmentEnd > NextEntry->Offset) {
  1584. if (NetIp4DebugPrintPackets != FALSE) {
  1585. RtlDebugPrint("IP4: Ignoring overlapping fragment at offset "
  1586. "0x%x.\n",
  1587. FragmentOffset);
  1588. }
  1589. goto Ip4ProcessPacketFragmentEnd;
  1590. }
  1591. }
  1592. //
  1593. // Record if the new fragment is the last fragment.
  1594. //
  1595. if ((FragmentFlags & IP4_FLAG_MORE_FRAGMENTS) == 0) {
  1596. LastFragment = TRUE;
  1597. }
  1598. //
  1599. // If the total length is now greater than the maximum packet size, exit.
  1600. // Something suspicious is up with these fragments.
  1601. //
  1602. if (TotalLength > IP4_MAX_PACKET_SIZE) {
  1603. NetpIp4DestroyFragmentedPacketNode(PacketNode);
  1604. goto Ip4ProcessPacketFragmentEnd;
  1605. }
  1606. //
  1607. // After the coalescing, if the last fragment is included and the starting
  1608. // offset is zero, then the packet is complete.
  1609. //
  1610. FragmentEntry = NULL;
  1611. if ((LastFragment != FALSE) && (StartingOffset == 0)) {
  1612. Status = NetAllocateBuffer(sizeof(IP4_HEADER),
  1613. TotalLength,
  1614. 0,
  1615. Link,
  1616. 0,
  1617. &CompletedPacket);
  1618. if (!KSUCCESS(Status)) {
  1619. ASSERT(CompletedPacket == NULL);
  1620. goto Ip4ProcessPacketFragmentEnd;
  1621. }
  1622. DestinationBuffer = CompletedPacket->Buffer +
  1623. CompletedPacket->DataOffset;
  1624. //
  1625. // Otherwise allocate a new fragment to contain the new fragment and any
  1626. // adjacent fragments.
  1627. //
  1628. } else {
  1629. AllocationSize = sizeof(IP4_FRAGMENT_ENTRY) + TotalLength;
  1630. NewFragment = MmAllocatePagedPool(AllocationSize, IP4_ALLOCATION_TAG);
  1631. if (NewFragment == NULL) {
  1632. goto Ip4ProcessPacketFragmentEnd;
  1633. }
  1634. NewFragment->LastFragment = LastFragment;
  1635. NewFragment->Length = TotalLength;
  1636. NewFragment->Offset = StartingOffset;
  1637. DestinationBuffer = (PVOID)(NewFragment + 1);
  1638. NetIp4FragmentCount += 1;
  1639. }
  1640. //
  1641. // Copy the data into the destination buffer.
  1642. //
  1643. if (JoinPrevious != FALSE) {
  1644. SourceBuffer = (PVOID)(PreviousEntry + 1);
  1645. RtlCopyMemory(DestinationBuffer, SourceBuffer, PreviousEntry->Length);
  1646. DestinationBuffer += PreviousEntry->Length;
  1647. }
  1648. SourceBuffer = PacketFragment->Buffer +
  1649. PacketFragment->DataOffset +
  1650. HeaderSize;
  1651. RtlCopyMemory(DestinationBuffer, SourceBuffer, FragmentLength);
  1652. DestinationBuffer += FragmentLength;
  1653. if (JoinNext != FALSE) {
  1654. SourceBuffer = (PVOID)(NextEntry + 1);
  1655. RtlCopyMemory(DestinationBuffer, SourceBuffer, NextEntry->Length);
  1656. }
  1657. //
  1658. // If the packet was completed, finish up by destroying the packet node and
  1659. // adding an IP4 header.
  1660. //
  1661. if (CompletedPacket != NULL) {
  1662. NetpIp4DestroyFragmentedPacketNode(PacketNode);
  1663. //
  1664. // Fill out the IPv4 header. Raw sockets get an accurate IPv4 header
  1665. // once all the fragments arrive.
  1666. //
  1667. CompletedPacket->DataOffset -= sizeof(IP4_HEADER);
  1668. NewHeader = CompletedPacket->Buffer + CompletedPacket->DataOffset;
  1669. NewHeader->VersionAndHeaderLength = IP4_VERSION |
  1670. (UCHAR)(sizeof(IP4_HEADER) /
  1671. sizeof(ULONG));
  1672. NewHeader->Type = 0;
  1673. TotalLength = CompletedPacket->FooterOffset -
  1674. CompletedPacket->DataOffset;
  1675. NewHeader->TotalLength = CPU_TO_NETWORK16(TotalLength);
  1676. NewHeader->Identification = Header->Identification;
  1677. NewHeader->FragmentOffset = 0;
  1678. NewHeader->TimeToLive = IP4_INITIAL_TIME_TO_LIVE;
  1679. NewHeader->Protocol = Header->Protocol;
  1680. NewHeader->SourceAddress = Header->SourceAddress;
  1681. NewHeader->DestinationAddress = Header->DestinationAddress;
  1682. NewHeader->HeaderChecksum = 0;
  1683. Checksum = NetpIp4ChecksumData((PSHORT)Header, sizeof(IP4_HEADER));
  1684. NewHeader->HeaderChecksum = Checksum;
  1685. //
  1686. // Otherwise insert the new fragment into the appropriate position.
  1687. //
  1688. } else {
  1689. ASSERT(NewFragment != NULL);
  1690. //
  1691. // If a previous entry exists then the entry gets inserted after that
  1692. // entry.
  1693. //
  1694. if (PreviousEntry != NULL) {
  1695. INSERT_AFTER(&(NewFragment->ListEntry),
  1696. &(PreviousEntry->ListEntry));
  1697. //
  1698. // Otherwise the new fragment is first in the list.
  1699. //
  1700. } else {
  1701. ASSERT(((NextEntry != NULL) &&
  1702. (NextEntry->ListEntry.Previous ==
  1703. &(PacketNode->FragmentListHead))) ||
  1704. (LIST_EMPTY(&(PacketNode->FragmentListHead)) != FALSE));
  1705. INSERT_AFTER(&(NewFragment->ListEntry),
  1706. &(PacketNode->FragmentListHead));
  1707. }
  1708. //
  1709. // Remove any entries that were coalesced.
  1710. //
  1711. if (JoinPrevious != FALSE) {
  1712. LIST_REMOVE(&(PreviousEntry->ListEntry));
  1713. MmFreePagedPool(PreviousEntry);
  1714. NetIp4FragmentCount -= 1;
  1715. }
  1716. if (JoinNext != FALSE) {
  1717. LIST_REMOVE(&(NextEntry->ListEntry));
  1718. MmFreePagedPool(NextEntry);
  1719. NetIp4FragmentCount -= 1;
  1720. }
  1721. }
  1722. Ip4ProcessPacketFragmentEnd:
  1723. KeReleaseQueuedLock(NetIp4FragmentedPacketLock);
  1724. return CompletedPacket;
  1725. }
  1726. COMPARISON_RESULT
  1727. NetpIp4CompareFragmentedPacketEntries (
  1728. PRED_BLACK_TREE Tree,
  1729. PRED_BLACK_TREE_NODE FirstNode,
  1730. PRED_BLACK_TREE_NODE SecondNode
  1731. )
  1732. /*++
  1733. Routine Description:
  1734. This routine compares two Red-Black tree nodes, in this case two IPv4
  1735. fragmented packet nodes.
  1736. Arguments:
  1737. Tree - Supplies a pointer to the Red-Black tree that owns both nodes.
  1738. FirstNode - Supplies a pointer to the left side of the comparison.
  1739. SecondNode - Supplies a pointer to the second side of the comparison.
  1740. Return Value:
  1741. Same if the two nodes have the same value.
  1742. Ascending if the first node is less than the second node.
  1743. Descending if the second node is less than the first node.
  1744. --*/
  1745. {
  1746. PIP4_FRAGMENTED_PACKET_NODE FirstPacket;
  1747. PIP4_FRAGMENTED_PACKET_NODE SecondPacket;
  1748. FirstPacket = RED_BLACK_TREE_VALUE(FirstNode,
  1749. IP4_FRAGMENTED_PACKET_NODE,
  1750. Node);
  1751. SecondPacket = RED_BLACK_TREE_VALUE(SecondNode,
  1752. IP4_FRAGMENTED_PACKET_NODE,
  1753. Node);
  1754. if (FirstPacket->Protocol != SecondPacket->Protocol) {
  1755. if (FirstPacket->Protocol < SecondPacket->Protocol) {
  1756. return ComparisonResultAscending;
  1757. } else {
  1758. return ComparisonResultDescending;
  1759. }
  1760. }
  1761. if (FirstPacket->RemoteAddress != SecondPacket->RemoteAddress) {
  1762. if (FirstPacket->RemoteAddress < SecondPacket->RemoteAddress) {
  1763. return ComparisonResultAscending;
  1764. } else {
  1765. return ComparisonResultDescending;
  1766. }
  1767. }
  1768. if (FirstPacket->LocalAddress != SecondPacket->LocalAddress) {
  1769. if (FirstPacket->LocalAddress < SecondPacket->LocalAddress) {
  1770. return ComparisonResultAscending;
  1771. } else {
  1772. return ComparisonResultDescending;
  1773. }
  1774. }
  1775. if (FirstPacket->Identification != SecondPacket->Identification) {
  1776. if (FirstPacket->Identification < SecondPacket->Identification) {
  1777. return ComparisonResultAscending;
  1778. } else {
  1779. return ComparisonResultDescending;
  1780. }
  1781. }
  1782. return ComparisonResultSame;
  1783. }
  1784. VOID
  1785. NetpIp4RemoveFragmentedPackets (
  1786. PNET_SOCKET Socket
  1787. )
  1788. /*++
  1789. Routine Description:
  1790. This routine removes fragmented packets from the tree of fragmented
  1791. packets. If a socket is supplied, then it removes all of the packets for
  1792. that socket. Otherwise it removes all of the expired packets, for all
  1793. sockets.
  1794. Arguments:
  1795. Socket - Supplies an optional pointer to a network socket.
  1796. Return Value:
  1797. None.
  1798. --*/
  1799. {
  1800. ULONGLONG CurrentTime;
  1801. PIP4_ADDRESS LocalAddress;
  1802. PIP4_FRAGMENTED_PACKET_NODE PacketNode;
  1803. PIP4_ADDRESS RemoteAddress;
  1804. PRED_BLACK_TREE_NODE TreeNode;
  1805. ASSERT(KeIsQueuedLockHeld(NetIp4FragmentedPacketLock) != FALSE);
  1806. //
  1807. // If a socket was supplied, remove all pending fragments for the local
  1808. // address, remote address, and protocol tuple.
  1809. //
  1810. if (Socket != NULL) {
  1811. ASSERT(Socket->LocalAddress.Domain == NetDomainIp4);
  1812. ASSERT((Socket->RemoteAddress.Domain == NetDomainIp4) ||
  1813. (Socket->RemoteAddress.Domain == NetDomainInvalid));
  1814. LocalAddress = (PIP4_ADDRESS)&(Socket->LocalAddress);
  1815. RemoteAddress = (PIP4_ADDRESS)&(Socket->RemoteAddress);
  1816. //
  1817. // Otherwise collect the current time as only the expired packets will be
  1818. // removed.
  1819. //
  1820. } else {
  1821. CurrentTime = HlQueryTimeCounter();
  1822. }
  1823. //
  1824. // Iterate over the tree and remove the appropriate packets.
  1825. //
  1826. TreeNode = RtlRedBlackTreeGetNextNode(&NetIp4FragmentedPacketTree,
  1827. FALSE,
  1828. NULL);
  1829. while (TreeNode != NULL) {
  1830. PacketNode = RED_BLACK_TREE_VALUE(TreeNode,
  1831. IP4_FRAGMENTED_PACKET_NODE,
  1832. Node);
  1833. TreeNode = RtlRedBlackTreeGetNextNode(&NetIp4FragmentedPacketTree,
  1834. FALSE,
  1835. TreeNode);
  1836. if (Socket != NULL) {
  1837. if ((PacketNode->LocalAddress != LocalAddress->Address) ||
  1838. (PacketNode->RemoteAddress != RemoteAddress->Address) ||
  1839. (PacketNode->Protocol !=
  1840. Socket->Protocol->ParentProtocolNumber)) {
  1841. continue;
  1842. }
  1843. } else {
  1844. if (PacketNode->Timeout > CurrentTime) {
  1845. continue;
  1846. }
  1847. }
  1848. //
  1849. // This packet needs to be destroyed.
  1850. //
  1851. NetpIp4DestroyFragmentedPacketNode(PacketNode);
  1852. }
  1853. return;
  1854. }
  1855. PIP4_FRAGMENTED_PACKET_NODE
  1856. NetpIp4CreateFragmentedPacketNode (
  1857. PIP4_HEADER Header
  1858. )
  1859. /*++
  1860. Routine Description:
  1861. This routine allocates a new fragmented packet node and inserts it into the
  1862. tree.
  1863. Arguments:
  1864. Header - Supplies a pointer to the header of the fragmented IPv4 packet.
  1865. Return Value:
  1866. Returns a pointer to the newly created fragmented packet node on success or
  1867. NULL on failure.
  1868. --*/
  1869. {
  1870. PIP4_FRAGMENTED_PACKET_NODE NewNode;
  1871. KSTATUS Status;
  1872. ULONGLONG Timeout;
  1873. //
  1874. // Allocate the new fragmented packet node and insert it into the tree.
  1875. //
  1876. NewNode = MmAllocatePagedPool(sizeof(IP4_FRAGMENTED_PACKET_NODE),
  1877. IP4_ALLOCATION_TAG);
  1878. if (NewNode == NULL) {
  1879. Status = STATUS_INSUFFICIENT_RESOURCES;
  1880. goto Ip4CreateFragmentedPacketNodeEnd;
  1881. }
  1882. RtlZeroMemory(NewNode, sizeof(IP4_FRAGMENTED_PACKET_NODE));
  1883. INITIALIZE_LIST_HEAD(&(NewNode->FragmentListHead));
  1884. NewNode->LocalAddress = Header->DestinationAddress;
  1885. NewNode->RemoteAddress = Header->SourceAddress;
  1886. NewNode->Protocol = Header->Protocol;
  1887. NewNode->Identification = NETWORK_TO_CPU16(Header->Identification);
  1888. Timeout = HlQueryTimeCounter() +
  1889. KeConvertMicrosecondsToTimeTicks(IP4_FRAGMENT_TIMEOUT);
  1890. NewNode->Timeout = Timeout;
  1891. RtlRedBlackTreeInsert(&NetIp4FragmentedPacketTree, &(NewNode->Node));
  1892. Status = STATUS_SUCCESS;
  1893. Ip4CreateFragmentedPacketNodeEnd:
  1894. if (!KSUCCESS(Status)) {
  1895. if (NewNode != NULL) {
  1896. NetpIp4DestroyFragmentedPacketNode(NewNode);
  1897. NewNode = NULL;
  1898. }
  1899. }
  1900. return NewNode;
  1901. }
  1902. VOID
  1903. NetpIp4DestroyFragmentedPacketNode (
  1904. PIP4_FRAGMENTED_PACKET_NODE PacketNode
  1905. )
  1906. /*++
  1907. Routine Description:
  1908. This routine destroys the given fragmented packet node, removing it from
  1909. the tree and destroying any fragments associated with it.
  1910. Arguments:
  1911. PacketNode - Supplies a pointer to the fragmented packet node to destroy.
  1912. Return Value:
  1913. None.
  1914. --*/
  1915. {
  1916. PIP4_FRAGMENT_ENTRY FragmentEntry;
  1917. if (PacketNode->Node.Parent != NULL) {
  1918. RtlRedBlackTreeRemove(&NetIp4FragmentedPacketTree, &(PacketNode->Node));
  1919. }
  1920. while (LIST_EMPTY(&(PacketNode->FragmentListHead)) == FALSE) {
  1921. FragmentEntry = LIST_VALUE(PacketNode->FragmentListHead.Next,
  1922. IP4_FRAGMENT_ENTRY,
  1923. ListEntry);
  1924. LIST_REMOVE(&(FragmentEntry->ListEntry));
  1925. MmFreePagedPool(FragmentEntry);
  1926. NetIp4FragmentCount -= 1;
  1927. }
  1928. MmFreePagedPool(PacketNode);
  1929. return;
  1930. }