udp.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. /*++
  2. Copyright (c) 2013 Minoca Corp.
  3. This file is licensed under the terms of the GNU General Public License
  4. version 3. Alternative licensing terms are available. Contact
  5. info@minocacorp.com for details. See the LICENSE file at the root of this
  6. project for complete licensing information.
  7. Module Name:
  8. udp.c
  9. Abstract:
  10. This module implements the User Datagram Protocol (UDP).
  11. Author:
  12. Evan Green 5-Apr-2013
  13. Environment:
  14. Kernel
  15. --*/
  16. //
  17. // ------------------------------------------------------------------- Includes
  18. //
  19. //
  20. // Protocol drivers are supposed to be able to stand on their own (ie be able to
  21. // be implemented outside the core net library). For the builtin ones, avoid
  22. // including netcore.h, but still redefine those functions that would otherwise
  23. // generate imports.
  24. //
  25. #define NET_API __DLLEXPORT
  26. #include <minoca/kernel/driver.h>
  27. #include <minoca/net/netdrv.h>
  28. //
  29. // ---------------------------------------------------------------- Definitions
  30. //
  31. //
  32. // Define the allocation tag used by the UDP socket protocol.
  33. //
  34. #define UDP_PROTOCOL_ALLOCATION_TAG 0x21706455 // '!pdU'
  35. //
  36. // Define the maximum supported packet size of the UDP protocol, including the
  37. // UDP headers.
  38. //
  39. #define UDP_MAX_PACKET_SIZE 0xFFFF
  40. //
  41. // Define the default size of UDP's receive data buffer, in bytes.
  42. //
  43. #define UDP_DEFAULT_RECEIVE_BUFFER_SIZE (256 * _1KB)
  44. //
  45. // Define the minimum receive buffer size.
  46. //
  47. #define UDP_MIN_RECEIVE_BUFFER_SIZE _2KB
  48. //
  49. // Define the default minimum number of bytes necessary for the UDP socket to
  50. // become readable.
  51. //
  52. #define UDP_DEFAULT_RECEIVE_MINIMUM 1
  53. //
  54. // Define the minmum number of bytes necessary for UDP sockets to become
  55. // writable. There is no minimum and bytes are immediately sent on the wire.
  56. //
  57. #define UDP_SEND_MINIMUM 1
  58. //
  59. // ------------------------------------------------------ Data Type Definitions
  60. //
  61. /*++
  62. Structure Description:
  63. This structure defines a UDP data socket.
  64. Members:
  65. NetSocket - Stores the common core networking parameters.
  66. ReceivedPacketList - Stores the list of packets ready to be read by the
  67. user.
  68. ReceiveLock - Stores the lock that protects the received packets list,
  69. dropped packet count, and various receive buffer parameters. This lock
  70. must always be acquired at low level.
  71. ReceiveBufferTotalSize - Stores the total size of the receive buffer, in
  72. bytes. Packets that are received but will not fit in the buffer are
  73. discarded.
  74. ReceiveBufferFreeSize - Stores the receive buffer's free space, in bytes.
  75. Packets that are received but do not fit in the free space are
  76. discarded.
  77. ReceiveTimeout - Stores the maximum amount of time, in milliseconds, that
  78. the socket will wait when receiving data.
  79. ReceiveMinimum - Stores the minimum amount of bytes that must be available
  80. before the socket is made readable. This is ignored.
  81. DroppedPacketCount - Stores the number of packets that have been dropped
  82. because the receive queue was full.
  83. ShutdownTypes - Stores the mask of shutdowns that have occurred on this
  84. socket.
  85. MaxPacketSize - Stores the maximum size of UDP datagrams.
  86. --*/
  87. typedef struct _UDP_SOCKET {
  88. NET_SOCKET NetSocket;
  89. LIST_ENTRY ReceivedPacketList;
  90. PQUEUED_LOCK ReceiveLock;
  91. ULONG ReceiveBufferTotalSize;
  92. ULONG ReceiveBufferFreeSize;
  93. ULONG ReceiveTimeout;
  94. ULONG ReceiveMinimum;
  95. ULONG DroppedPacketCount;
  96. ULONG ShutdownTypes;
  97. USHORT MaxPacketSize;
  98. } UDP_SOCKET, *PUDP_SOCKET;
  99. /*++
  100. Structure Description:
  101. This structure defines a UDP protocol header, which is pretty darn simple.
  102. Members:
  103. SourcePort - Stores the optional source port number (use 0 if not supplied).
  104. DestinationPort - Stores the destination port number.
  105. Length - Stores the length of the header and data.
  106. Checksum - Stores the optional checksum. Set to 0 if not supplied. The
  107. checksum is the one's complement of the one's complement sum of the
  108. entire header plus data, padded with zeros if needed to be a multiple of
  109. two octets. A pseudo IP header is used for the calculation.
  110. --*/
  111. typedef struct _UDP_HEADER {
  112. USHORT SourcePort;
  113. USHORT DestinationPort;
  114. USHORT Length;
  115. USHORT Checksum;
  116. } PACKED UDP_HEADER, *PUDP_HEADER;
  117. /*++
  118. Structure Description:
  119. This structure defines a UDP received message.
  120. Members:
  121. ListEntry - Stores pointers to the next and previous packets.
  122. Address - Stores the network address where this data came from.
  123. DataBuffer - Stores a pointer to the buffer containing the actual data.
  124. Size - Stores the number of bytes in the data buffer.
  125. --*/
  126. typedef struct _UDP_RECEIVED_PACKET {
  127. LIST_ENTRY ListEntry;
  128. NETWORK_ADDRESS Address;
  129. PVOID DataBuffer;
  130. ULONG Size;
  131. } UDP_RECEIVED_PACKET, *PUDP_RECEIVED_PACKET;
  132. /*++
  133. Structure Description:
  134. This structure defines a UDP socket option.
  135. Members:
  136. InformationType - Stores the information type for the socket option.
  137. Option - Stores the type-specific option identifier.
  138. Size - Stores the size of the option value, in bytes.
  139. SetAllowed - Stores a boolean indicating whether or not the option is
  140. allowed to be set.
  141. --*/
  142. typedef struct _UDP_SOCKET_OPTION {
  143. SOCKET_INFORMATION_TYPE InformationType;
  144. UINTN Option;
  145. UINTN Size;
  146. BOOL SetAllowed;
  147. } UDP_SOCKET_OPTION, *PUDP_SOCKET_OPTION;
  148. //
  149. // ----------------------------------------------- Internal Function Prototypes
  150. //
  151. KSTATUS
  152. NetpUdpCreateSocket (
  153. PNET_PROTOCOL_ENTRY ProtocolEntry,
  154. PNET_NETWORK_ENTRY NetworkEntry,
  155. ULONG NetworkProtocol,
  156. PNET_SOCKET *NewSocket
  157. );
  158. VOID
  159. NetpUdpDestroySocket (
  160. PNET_SOCKET Socket
  161. );
  162. KSTATUS
  163. NetpUdpBindToAddress (
  164. PNET_SOCKET Socket,
  165. PNET_LINK Link,
  166. PNETWORK_ADDRESS Address
  167. );
  168. KSTATUS
  169. NetpUdpListen (
  170. PNET_SOCKET Socket
  171. );
  172. KSTATUS
  173. NetpUdpAccept (
  174. PNET_SOCKET Socket,
  175. PIO_HANDLE *NewConnectionSocket,
  176. PNETWORK_ADDRESS RemoteAddress
  177. );
  178. KSTATUS
  179. NetpUdpConnect (
  180. PNET_SOCKET Socket,
  181. PNETWORK_ADDRESS Address
  182. );
  183. KSTATUS
  184. NetpUdpClose (
  185. PNET_SOCKET Socket
  186. );
  187. KSTATUS
  188. NetpUdpShutdown (
  189. PNET_SOCKET Socket,
  190. ULONG ShutdownType
  191. );
  192. KSTATUS
  193. NetpUdpSend (
  194. BOOL FromKernelMode,
  195. PNET_SOCKET Socket,
  196. PSOCKET_IO_PARAMETERS Parameters,
  197. PIO_BUFFER IoBuffer
  198. );
  199. VOID
  200. NetpUdpProcessReceivedData (
  201. PNET_LINK Link,
  202. PNET_PACKET_BUFFER Packet,
  203. PNETWORK_ADDRESS SourceAddress,
  204. PNETWORK_ADDRESS DestinationAddress,
  205. PNET_PROTOCOL_ENTRY ProtocolEntry
  206. );
  207. KSTATUS
  208. NetpUdpProcessReceivedSocketData (
  209. PNET_LINK Link,
  210. PNET_SOCKET Socket,
  211. PNET_PACKET_BUFFER Packet,
  212. PNETWORK_ADDRESS SourceAddress,
  213. PNETWORK_ADDRESS DestinationAddress
  214. );
  215. KSTATUS
  216. NetpUdpReceive (
  217. BOOL FromKernelMode,
  218. PNET_SOCKET Socket,
  219. PSOCKET_IO_PARAMETERS Parameters,
  220. PIO_BUFFER IoBuffer
  221. );
  222. KSTATUS
  223. NetpUdpGetSetInformation (
  224. PNET_SOCKET Socket,
  225. SOCKET_INFORMATION_TYPE InformationType,
  226. UINTN SocketOption,
  227. PVOID Data,
  228. PUINTN DataSize,
  229. BOOL Set
  230. );
  231. KSTATUS
  232. NetpUdpUserControl (
  233. PNET_SOCKET Socket,
  234. ULONG CodeNumber,
  235. BOOL FromKernelMode,
  236. PVOID ContextBuffer,
  237. UINTN ContextBufferSize
  238. );
  239. //
  240. // -------------------------------------------------------------------- Globals
  241. //
  242. NET_PROTOCOL_ENTRY NetUdpProtocol = {
  243. {NULL, NULL},
  244. NetSocketDatagram,
  245. SOCKET_INTERNET_PROTOCOL_UDP,
  246. NULL,
  247. NULL,
  248. {{0}, {0}, {0}},
  249. {
  250. NetpUdpCreateSocket,
  251. NetpUdpDestroySocket,
  252. NetpUdpBindToAddress,
  253. NetpUdpListen,
  254. NetpUdpAccept,
  255. NetpUdpConnect,
  256. NetpUdpClose,
  257. NetpUdpShutdown,
  258. NetpUdpSend,
  259. NetpUdpProcessReceivedData,
  260. NetpUdpProcessReceivedSocketData,
  261. NetpUdpReceive,
  262. NetpUdpGetSetInformation,
  263. NetpUdpUserControl
  264. }
  265. };
  266. UDP_SOCKET_OPTION NetUdpSocketOptions[] = {
  267. {
  268. SocketInformationBasic,
  269. SocketBasicOptionSendBufferSize,
  270. sizeof(ULONG),
  271. TRUE
  272. },
  273. {
  274. SocketInformationBasic,
  275. SocketBasicOptionSendMinimum,
  276. sizeof(ULONG),
  277. FALSE
  278. },
  279. {
  280. SocketInformationBasic,
  281. SocketBasicOptionReceiveBufferSize,
  282. sizeof(ULONG),
  283. TRUE
  284. },
  285. {
  286. SocketInformationBasic,
  287. SocketBasicOptionReceiveMinimum,
  288. sizeof(ULONG),
  289. TRUE
  290. },
  291. {
  292. SocketInformationBasic,
  293. SocketBasicOptionReceiveTimeout,
  294. sizeof(SOCKET_TIME),
  295. TRUE
  296. },
  297. };
  298. //
  299. // ------------------------------------------------------------------ Functions
  300. //
  301. VOID
  302. NetpUdpInitialize (
  303. VOID
  304. )
  305. /*++
  306. Routine Description:
  307. This routine initializes support for UDP sockets.
  308. Arguments:
  309. None.
  310. Return Value:
  311. None.
  312. --*/
  313. {
  314. KSTATUS Status;
  315. //
  316. // Register the UDP socket handlers with the core networking library.
  317. //
  318. Status = NetRegisterProtocol(&NetUdpProtocol, NULL);
  319. if (!KSUCCESS(Status)) {
  320. ASSERT(FALSE);
  321. }
  322. return;
  323. }
  324. KSTATUS
  325. NetpUdpCreateSocket (
  326. PNET_PROTOCOL_ENTRY ProtocolEntry,
  327. PNET_NETWORK_ENTRY NetworkEntry,
  328. ULONG NetworkProtocol,
  329. PNET_SOCKET *NewSocket
  330. )
  331. /*++
  332. Routine Description:
  333. This routine allocates resources associated with a new socket. The protocol
  334. driver is responsible for allocating the structure (with additional length
  335. for any of its context). The core networking library will fill in the
  336. common header when this routine returns.
  337. Arguments:
  338. ProtocolEntry - Supplies a pointer to the protocol information.
  339. NetworkEntry - Supplies a pointer to the network information.
  340. NetworkProtocol - Supplies the raw protocol value for this socket used on
  341. the network. This value is network specific.
  342. NewSocket - Supplies a pointer where a pointer to a newly allocated
  343. socket structure will be returned. The caller is responsible for
  344. allocating the socket (and potentially a larger structure for its own
  345. context). The core network library will fill in the standard socket
  346. structure after this routine returns.
  347. Return Value:
  348. Status code.
  349. --*/
  350. {
  351. ULONG MaxPacketSize;
  352. PNET_SOCKET NetSocket;
  353. PNET_PACKET_SIZE_INFORMATION PacketSizeInformation;
  354. KSTATUS Status;
  355. PUDP_SOCKET UdpSocket;
  356. ASSERT(ProtocolEntry->Type == NetSocketDatagram);
  357. ASSERT((ProtocolEntry->ParentProtocolNumber ==
  358. SOCKET_INTERNET_PROTOCOL_UDP) &&
  359. (NetworkProtocol == ProtocolEntry->ParentProtocolNumber));
  360. NetSocket = NULL;
  361. UdpSocket = MmAllocatePagedPool(sizeof(UDP_SOCKET),
  362. UDP_PROTOCOL_ALLOCATION_TAG);
  363. if (UdpSocket == NULL) {
  364. Status = STATUS_INSUFFICIENT_RESOURCES;
  365. goto UdpCreateSocketEnd;
  366. }
  367. RtlZeroMemory(UdpSocket, sizeof(UDP_SOCKET));
  368. NetSocket = &(UdpSocket->NetSocket);
  369. NetSocket->KernelSocket.Protocol = NetworkProtocol;
  370. NetSocket->KernelSocket.ReferenceCount = 1;
  371. INITIALIZE_LIST_HEAD(&(UdpSocket->ReceivedPacketList));
  372. UdpSocket->ReceiveTimeout = WAIT_TIME_INDEFINITE;
  373. UdpSocket->ReceiveBufferTotalSize = UDP_DEFAULT_RECEIVE_BUFFER_SIZE;
  374. UdpSocket->ReceiveBufferFreeSize = UdpSocket->ReceiveBufferTotalSize;
  375. UdpSocket->ReceiveMinimum = UDP_DEFAULT_RECEIVE_MINIMUM;
  376. UdpSocket->MaxPacketSize = UDP_MAX_PACKET_SIZE;
  377. UdpSocket->ReceiveLock = KeCreateQueuedLock();
  378. if (UdpSocket->ReceiveLock == NULL) {
  379. Status = STATUS_INSUFFICIENT_RESOURCES;
  380. goto UdpCreateSocketEnd;
  381. }
  382. //
  383. // Give the lower layers a chance to initialize. Start the maximum packet
  384. // size at the largest possible value.
  385. //
  386. PacketSizeInformation = &(NetSocket->PacketSizeInformation);
  387. PacketSizeInformation->MaxPacketSize = MAX_ULONG;
  388. Status = NetworkEntry->Interface.InitializeSocket(ProtocolEntry,
  389. NetworkEntry,
  390. NetworkProtocol,
  391. NetSocket);
  392. if (!KSUCCESS(Status)) {
  393. goto UdpCreateSocketEnd;
  394. }
  395. //
  396. // If the max packet size is greater than what is allowed for a UDP packet
  397. // plus all the previous headers and footers, then truncate the max packet
  398. // size. Note that the UDP max packet size includes the UDP header.
  399. //
  400. MaxPacketSize = PacketSizeInformation->HeaderSize +
  401. UDP_MAX_PACKET_SIZE +
  402. PacketSizeInformation->FooterSize;
  403. if (PacketSizeInformation->MaxPacketSize > MaxPacketSize) {
  404. PacketSizeInformation->MaxPacketSize = MaxPacketSize;
  405. }
  406. //
  407. // Add the UDP header size to the protocol header size.
  408. //
  409. PacketSizeInformation->HeaderSize += sizeof(UDP_HEADER);
  410. Status = STATUS_SUCCESS;
  411. UdpCreateSocketEnd:
  412. if (!KSUCCESS(Status)) {
  413. if (UdpSocket != NULL) {
  414. if (UdpSocket->ReceiveLock != NULL) {
  415. KeDestroyQueuedLock(UdpSocket->ReceiveLock);
  416. }
  417. MmFreePagedPool(UdpSocket);
  418. UdpSocket = NULL;
  419. NetSocket = NULL;
  420. }
  421. }
  422. *NewSocket = NetSocket;
  423. return Status;
  424. }
  425. VOID
  426. NetpUdpDestroySocket (
  427. PNET_SOCKET Socket
  428. )
  429. /*++
  430. Routine Description:
  431. This routine destroys resources associated with an open socket, officially
  432. marking the end of the kernel and core networking library's knowledge of
  433. this structure.
  434. Arguments:
  435. Socket - Supplies a pointer to the socket to destroy. The core networking
  436. library will have already destroyed any resources inside the common
  437. header, the protocol should not reach through any pointers inside the
  438. socket header except the protocol and network entries.
  439. Return Value:
  440. None. This routine is responsible for freeing the memory associated with
  441. the socket structure itself.
  442. --*/
  443. {
  444. PUDP_RECEIVED_PACKET Packet;
  445. PUDP_SOCKET UdpSocket;
  446. UdpSocket = (PUDP_SOCKET)Socket;
  447. //
  448. // Loop through and free any leftover packets.
  449. //
  450. KeAcquireQueuedLock(UdpSocket->ReceiveLock);
  451. while (!LIST_EMPTY(&(UdpSocket->ReceivedPacketList))) {
  452. Packet = LIST_VALUE(UdpSocket->ReceivedPacketList.Next,
  453. UDP_RECEIVED_PACKET,
  454. ListEntry);
  455. LIST_REMOVE(&(Packet->ListEntry));
  456. UdpSocket->ReceiveBufferFreeSize += Packet->Size;
  457. MmFreePagedPool(Packet);
  458. }
  459. ASSERT(UdpSocket->ReceiveBufferFreeSize ==
  460. UdpSocket->ReceiveBufferTotalSize);
  461. KeReleaseQueuedLock(UdpSocket->ReceiveLock);
  462. KeDestroyQueuedLock(UdpSocket->ReceiveLock);
  463. MmFreePagedPool(UdpSocket);
  464. return;
  465. }
  466. KSTATUS
  467. NetpUdpBindToAddress (
  468. PNET_SOCKET Socket,
  469. PNET_LINK Link,
  470. PNETWORK_ADDRESS Address
  471. )
  472. /*++
  473. Routine Description:
  474. This routine binds the given socket to the specified network address.
  475. Usually this is a no-op for the protocol, it's simply responsible for
  476. passing the request down to the network layer.
  477. Arguments:
  478. Socket - Supplies a pointer to the socket to bind.
  479. Link - Supplies an optional pointer to a link to bind to.
  480. Address - Supplies a pointer to the address to bind the socket to.
  481. Return Value:
  482. Status code.
  483. --*/
  484. {
  485. KSTATUS Status;
  486. if (Socket->LocalAddress.Domain != NetDomainInvalid) {
  487. Status = STATUS_INVALID_PARAMETER;
  488. goto UdpBindToAddressEnd;
  489. }
  490. //
  491. // Currently only IPv4 addresses are supported.
  492. //
  493. if (Address->Domain != NetDomainIp4) {
  494. Status = STATUS_NOT_SUPPORTED;
  495. goto UdpBindToAddressEnd;
  496. }
  497. //
  498. // Pass the request down to the network layer.
  499. //
  500. Status = Socket->Network->Interface.BindToAddress(Socket, Link, Address);
  501. if (!KSUCCESS(Status)) {
  502. goto UdpBindToAddressEnd;
  503. }
  504. //
  505. // Begin listening immediately, as there is no explicit listen step for UDP.
  506. //
  507. Status = Socket->Network->Interface.Listen(Socket);
  508. if (!KSUCCESS(Status)) {
  509. goto UdpBindToAddressEnd;
  510. }
  511. IoSetIoObjectState(Socket->KernelSocket.IoState, POLL_EVENT_OUT, TRUE);
  512. UdpBindToAddressEnd:
  513. return Status;
  514. }
  515. KSTATUS
  516. NetpUdpListen (
  517. PNET_SOCKET Socket
  518. )
  519. /*++
  520. Routine Description:
  521. This routine adds a bound socket to the list of listening sockets,
  522. officially allowing clients to attempt to connect to it.
  523. Arguments:
  524. Socket - Supplies a pointer to the socket to mark as listning.
  525. Return Value:
  526. Status code.
  527. --*/
  528. {
  529. return STATUS_NOT_SUPPORTED;
  530. }
  531. KSTATUS
  532. NetpUdpAccept (
  533. PNET_SOCKET Socket,
  534. PIO_HANDLE *NewConnectionSocket,
  535. PNETWORK_ADDRESS RemoteAddress
  536. )
  537. /*++
  538. Routine Description:
  539. This routine accepts an incoming connection on a listening connection-based
  540. socket.
  541. Arguments:
  542. Socket - Supplies a pointer to the socket to accept a connection from.
  543. NewConnectionSocket - Supplies a pointer where a new socket will be
  544. returned that represents the accepted connection with the remote
  545. host.
  546. RemoteAddress - Supplies a pointer where the address of the connected
  547. remote host will be returned.
  548. Return Value:
  549. Status code.
  550. --*/
  551. {
  552. return STATUS_NOT_SUPPORTED;
  553. }
  554. KSTATUS
  555. NetpUdpConnect (
  556. PNET_SOCKET Socket,
  557. PNETWORK_ADDRESS Address
  558. )
  559. /*++
  560. Routine Description:
  561. This routine attempts to make an outgoing connection to a server.
  562. Arguments:
  563. Socket - Supplies a pointer to the socket to use for the connection.
  564. Address - Supplies a pointer to the address to connect to.
  565. Return Value:
  566. Status code.
  567. --*/
  568. {
  569. KSTATUS Status;
  570. //
  571. // Pass the request down to the network layer.
  572. //
  573. Status = Socket->Network->Interface.Connect(Socket, Address);
  574. if (!KSUCCESS(Status)) {
  575. goto UdpConnectEnd;
  576. }
  577. IoSetIoObjectState(Socket->KernelSocket.IoState, POLL_EVENT_OUT, TRUE);
  578. UdpConnectEnd:
  579. return Status;
  580. }
  581. KSTATUS
  582. NetpUdpClose (
  583. PNET_SOCKET Socket
  584. )
  585. /*++
  586. Routine Description:
  587. This routine closes a socket connection.
  588. Arguments:
  589. Socket - Supplies a pointer to the socket to shut down.
  590. Return Value:
  591. Status code.
  592. --*/
  593. {
  594. KSTATUS Status;
  595. //
  596. // Close it at the lower level and then release the reference taken on
  597. // create if the close was successful.
  598. //
  599. Status = Socket->Network->Interface.Close(Socket);
  600. if (!KSUCCESS(Status)) {
  601. goto UdpCloseEnd;
  602. }
  603. IoSocketReleaseReference(&(Socket->KernelSocket));
  604. UdpCloseEnd:
  605. return Status;
  606. }
  607. KSTATUS
  608. NetpUdpShutdown (
  609. PNET_SOCKET Socket,
  610. ULONG ShutdownType
  611. )
  612. /*++
  613. Routine Description:
  614. This routine shuts down communication with a given socket.
  615. Arguments:
  616. Socket - Supplies a pointer to the socket.
  617. ShutdownType - Supplies the shutdown type to perform. See the
  618. SOCKET_SHUTDOWN_* definitions.
  619. Return Value:
  620. Status code.
  621. --*/
  622. {
  623. PUDP_SOCKET UdpSocket;
  624. //
  625. // Shutdown is not supported unless the socket is connected.
  626. //
  627. if (Socket->RemoteAddress.Domain == NetDomainInvalid) {
  628. return STATUS_NOT_CONNECTED;
  629. }
  630. UdpSocket = (PUDP_SOCKET)Socket;
  631. RtlAtomicOr32(&(UdpSocket->ShutdownTypes), ShutdownType);
  632. //
  633. // Signal the read event if the read end was shut down.
  634. //
  635. if ((ShutdownType & SOCKET_SHUTDOWN_READ) != 0) {
  636. KeAcquireQueuedLock(UdpSocket->ReceiveLock);
  637. IoSetIoObjectState(Socket->KernelSocket.IoState, POLL_EVENT_IN, TRUE);
  638. KeReleaseQueuedLock(UdpSocket->ReceiveLock);
  639. }
  640. if ((ShutdownType & SOCKET_SHUTDOWN_WRITE) != 0) {
  641. IoSetIoObjectState(Socket->KernelSocket.IoState, POLL_EVENT_OUT, TRUE);
  642. }
  643. return STATUS_SUCCESS;
  644. }
  645. KSTATUS
  646. NetpUdpSend (
  647. BOOL FromKernelMode,
  648. PNET_SOCKET Socket,
  649. PSOCKET_IO_PARAMETERS Parameters,
  650. PIO_BUFFER IoBuffer
  651. )
  652. /*++
  653. Routine Description:
  654. This routine sends the given data buffer through the network using a
  655. specific protocol.
  656. Arguments:
  657. FromKernelMode - Supplies a boolean indicating whether the request is
  658. coming from kernel mode (TRUE) or user mode (FALSE).
  659. Socket - Supplies a pointer to the socket to send the data to.
  660. Parameters - Supplies a pointer to the socket I/O parameters. This will
  661. always be a kernel mode pointer.
  662. IoBuffer - Supplies a pointer to the I/O buffer containing the data to
  663. send.
  664. Return Value:
  665. Status code.
  666. --*/
  667. {
  668. UINTN BytesComplete;
  669. PNETWORK_ADDRESS Destination;
  670. NETWORK_ADDRESS DestinationLocal;
  671. ULONG Flags;
  672. ULONG FooterSize;
  673. ULONG HeaderSize;
  674. PNET_LINK Link;
  675. NET_LINK_LOCAL_ADDRESS LinkInformation;
  676. PNET_SOCKET_LINK_OVERRIDE LinkOverride;
  677. NET_SOCKET_LINK_OVERRIDE LinkOverrideBuffer;
  678. NETWORK_ADDRESS LocalAddress;
  679. USHORT NetworkLocalPort;
  680. USHORT NetworkRemotePort;
  681. PNET_PACKET_BUFFER Packet;
  682. NET_PACKET_LIST PacketList;
  683. UINTN Size;
  684. USHORT SourcePort;
  685. KSTATUS Status;
  686. PUDP_HEADER UdpHeader;
  687. PUDP_SOCKET UdpSocket;
  688. ASSERT(Socket->PacketSizeInformation.MaxPacketSize > sizeof(UDP_HEADER));
  689. BytesComplete = 0;
  690. Link = NULL;
  691. LinkInformation.Link = NULL;
  692. LinkOverride = NULL;
  693. NET_INITIALIZE_PACKET_LIST(&PacketList);
  694. Size = Parameters->Size;
  695. UdpSocket = (PUDP_SOCKET)Socket;
  696. Flags = Parameters->SocketIoFlags;
  697. Parameters->SocketIoFlags = 0;
  698. Destination = Parameters->NetworkAddress;
  699. if ((Destination != NULL) && (FromKernelMode == FALSE)) {
  700. Status = MmCopyFromUserMode(&DestinationLocal,
  701. Destination,
  702. sizeof(NETWORK_ADDRESS));
  703. Destination = &DestinationLocal;
  704. if (!KSUCCESS(Status)) {
  705. goto UdpSendEnd;
  706. }
  707. }
  708. if ((Destination == NULL) ||
  709. (Destination->Domain == NetDomainInvalid)) {
  710. if (Socket->RemoteAddress.Port == 0) {
  711. Status = STATUS_NOT_CONFIGURED;
  712. goto UdpSendEnd;
  713. }
  714. Destination = &(Socket->RemoteAddress);
  715. }
  716. //
  717. // Fail if the socket has already been closed for writing.
  718. //
  719. if ((UdpSocket->ShutdownTypes & SOCKET_SHUTDOWN_WRITE) != 0) {
  720. if ((Flags & SOCKET_IO_NO_SIGNAL) != 0) {
  721. Status = STATUS_BROKEN_PIPE_SILENT;
  722. } else {
  723. Status = STATUS_BROKEN_PIPE;
  724. }
  725. goto UdpSendEnd;
  726. }
  727. //
  728. // Fail if the socket's link went down.
  729. //
  730. if ((Socket->KernelSocket.IoState->Events & POLL_EVENT_DISCONNECTED) != 0) {
  731. Status = STATUS_NO_NETWORK_CONNECTION;
  732. goto UdpSendEnd;
  733. }
  734. //
  735. // Fail if there's ancillary data.
  736. //
  737. if (Parameters->ControlDataSize != 0) {
  738. Status = STATUS_NOT_SUPPORTED;
  739. goto UdpSendEnd;
  740. }
  741. //
  742. // If the size, including the header, is greater than the UDP socket's
  743. // maximum packet size, fail.
  744. //
  745. if ((Size + sizeof(UDP_HEADER)) > UdpSocket->MaxPacketSize) {
  746. Status = STATUS_MESSAGE_TOO_LONG;
  747. goto UdpSendEnd;
  748. }
  749. //
  750. // If the socket is not yet bound, then at least try to bind it to a local
  751. // port. This bind attempt may race with another bind attempt, but leave it
  752. // to the socket owner to synchronize bind and send.
  753. //
  754. if (Socket->BindingType == SocketBindingInvalid) {
  755. RtlZeroMemory(&LocalAddress, sizeof(NETWORK_ADDRESS));
  756. LocalAddress.Domain = Socket->Network->Domain;
  757. Status = NetpUdpBindToAddress(Socket, NULL, &LocalAddress);
  758. if (!KSUCCESS(Status)) {
  759. goto UdpSendEnd;
  760. }
  761. }
  762. //
  763. // The socket needs to at least be bound to a local port.
  764. //
  765. ASSERT(Socket->LocalAddress.Port != 0);
  766. //
  767. // If the socket has no link, then try to find a link that can service the
  768. // destination address.
  769. //
  770. if (Socket->Link == NULL) {
  771. Status = NetFindLinkForRemoteAddress(Destination, &LinkInformation);
  772. if (KSUCCESS(Status)) {
  773. //
  774. // The link override should use the socket's port.
  775. //
  776. LinkInformation.LocalAddress.Port = Socket->LocalAddress.Port;
  777. //
  778. // Synchronously get the correct header, footer, and max packet
  779. // sizes.
  780. //
  781. Status = NetInitializeSocketLinkOverride(Socket,
  782. &LinkInformation,
  783. &LinkOverrideBuffer);
  784. if (KSUCCESS(Status)) {
  785. LinkOverride = &LinkOverrideBuffer;
  786. }
  787. }
  788. if (!KSUCCESS(Status) && (Status != STATUS_CONNECTION_EXISTS)) {
  789. goto UdpSendEnd;
  790. }
  791. }
  792. //
  793. // Set the necessary local variables based on whether the socket's link or
  794. // an override link will be used to send the data.
  795. //
  796. if (LinkOverride != NULL) {
  797. ASSERT(LinkOverride == &LinkOverrideBuffer);
  798. Link = LinkOverrideBuffer.LinkInformation.Link;
  799. HeaderSize = LinkOverrideBuffer.PacketSizeInformation.HeaderSize;
  800. FooterSize = LinkOverrideBuffer.PacketSizeInformation.FooterSize;
  801. SourcePort = LinkOverrideBuffer.LinkInformation.LocalAddress.Port;
  802. } else {
  803. ASSERT(Socket->Link != NULL);
  804. Link = Socket->Link;
  805. HeaderSize = Socket->PacketSizeInformation.HeaderSize;
  806. FooterSize = Socket->PacketSizeInformation.FooterSize;
  807. SourcePort = Socket->LocalAddress.Port;
  808. }
  809. NetworkLocalPort = CPU_TO_NETWORK16(SourcePort);
  810. NetworkRemotePort = CPU_TO_NETWORK16(Destination->Port);
  811. //
  812. // Allocate a buffer for the packet.
  813. //
  814. Status = NetAllocateBuffer(HeaderSize,
  815. Size,
  816. FooterSize,
  817. Link,
  818. 0,
  819. &Packet);
  820. if (!KSUCCESS(Status)) {
  821. goto UdpSendEnd;
  822. }
  823. NET_ADD_PACKET_TO_LIST(Packet, &PacketList);
  824. //
  825. // Copy the packet data.
  826. //
  827. Status = MmCopyIoBufferData(IoBuffer,
  828. Packet->Buffer + Packet->DataOffset,
  829. BytesComplete,
  830. Size - BytesComplete,
  831. FALSE);
  832. if (!KSUCCESS(Status)) {
  833. goto UdpSendEnd;
  834. }
  835. //
  836. // Add the UDP header.
  837. //
  838. ASSERT(Packet->DataOffset >= sizeof(UDP_HEADER));
  839. Packet->DataOffset -= sizeof(UDP_HEADER);
  840. UdpHeader = (PUDP_HEADER)(Packet->Buffer + Packet->DataOffset);
  841. UdpHeader->SourcePort = NetworkLocalPort;
  842. UdpHeader->DestinationPort = NetworkRemotePort;
  843. UdpHeader->Length = CPU_TO_NETWORK16(Size + sizeof(UDP_HEADER));
  844. UdpHeader->Checksum = 0;
  845. if ((Link->Properties.ChecksumFlags &
  846. NET_LINK_CHECKSUM_FLAG_TRANSMIT_UDP_OFFLOAD) != 0) {
  847. Packet->Flags |= NET_PACKET_FLAG_UDP_CHECKSUM_OFFLOAD;
  848. }
  849. //
  850. // Send the datagram down to the network layer, which may have to send it
  851. // in fragments.
  852. //
  853. Status = Socket->Network->Interface.Send(Socket,
  854. Destination,
  855. LinkOverride,
  856. &PacketList);
  857. if (!KSUCCESS(Status)) {
  858. goto UdpSendEnd;
  859. }
  860. Packet = NULL;
  861. BytesComplete = Size;
  862. UdpSendEnd:
  863. Parameters->BytesCompleted = BytesComplete;
  864. if (!KSUCCESS(Status)) {
  865. NetDestroyBufferList(&PacketList);
  866. }
  867. if (LinkInformation.Link != NULL) {
  868. NetLinkReleaseReference(LinkInformation.Link);
  869. }
  870. if (LinkOverride == &LinkOverrideBuffer) {
  871. ASSERT(LinkOverrideBuffer.LinkInformation.Link != NULL);
  872. NetLinkReleaseReference(LinkOverrideBuffer.LinkInformation.Link);
  873. }
  874. return Status;
  875. }
  876. VOID
  877. NetpUdpProcessReceivedData (
  878. PNET_LINK Link,
  879. PNET_PACKET_BUFFER Packet,
  880. PNETWORK_ADDRESS SourceAddress,
  881. PNETWORK_ADDRESS DestinationAddress,
  882. PNET_PROTOCOL_ENTRY ProtocolEntry
  883. )
  884. /*++
  885. Routine Description:
  886. This routine is called to process a received packet.
  887. Arguments:
  888. Link - Supplies a pointer to the link that received the packet.
  889. Packet - Supplies a pointer to a structure describing the incoming packet.
  890. This structure may be used as a scratch space while this routine
  891. executes and the packet travels up the stack, but will not be accessed
  892. after this routine returns.
  893. SourceAddress - Supplies a pointer to the source (remote) address that the
  894. packet originated from. This memory will not be referenced once the
  895. function returns, it can be stack allocated.
  896. DestinationAddress - Supplies a pointer to the destination (local) address
  897. that the packet is heading to. This memory will not be referenced once
  898. the function returns, it can be stack allocated.
  899. ProtocolEntry - Supplies a pointer to this protocol's protocol entry.
  900. Return Value:
  901. None. When the function returns, the memory associated with the packet may
  902. be reclaimed and reused.
  903. --*/
  904. {
  905. PUDP_HEADER Header;
  906. USHORT Length;
  907. PNET_SOCKET Socket;
  908. ASSERT(KeGetRunLevel() == RunLevelLow);
  909. Header = (PUDP_HEADER)(Packet->Buffer + Packet->DataOffset);
  910. Length = NETWORK_TO_CPU16(Header->Length);
  911. if (Length > (Packet->FooterOffset - Packet->DataOffset)) {
  912. RtlDebugPrint("Invalid UDP length %d is bigger than packet data, "
  913. "which is only %d bytes large.\n",
  914. Length,
  915. (Packet->FooterOffset - Packet->DataOffset));
  916. return;
  917. }
  918. SourceAddress->Port = NETWORK_TO_CPU16(Header->SourcePort);
  919. DestinationAddress->Port = NETWORK_TO_CPU16(Header->DestinationPort);
  920. //
  921. // Find a socket willing to take this packet.
  922. //
  923. Socket = NetFindSocket(ProtocolEntry, DestinationAddress, SourceAddress);
  924. if (Socket == NULL) {
  925. return;
  926. }
  927. //
  928. // Pass the packet onto the socket for copying and safe keeping until the
  929. // data is read.
  930. //
  931. NetpUdpProcessReceivedSocketData(Link,
  932. Socket,
  933. Packet,
  934. SourceAddress,
  935. DestinationAddress);
  936. //
  937. // Release the reference on the socket added by the find socket call.
  938. //
  939. IoSocketReleaseReference(&(Socket->KernelSocket));
  940. return;
  941. }
  942. KSTATUS
  943. NetpUdpProcessReceivedSocketData (
  944. PNET_LINK Link,
  945. PNET_SOCKET Socket,
  946. PNET_PACKET_BUFFER Packet,
  947. PNETWORK_ADDRESS SourceAddress,
  948. PNETWORK_ADDRESS DestinationAddress
  949. )
  950. /*++
  951. Routine Description:
  952. This routine is called for a particular socket to process a received packet
  953. that was sent to it.
  954. Arguments:
  955. Link - Supplies a pointer to the network link that received the packet.
  956. Socket - Supplies a pointer to the socket that received the packet.
  957. Packet - Supplies a pointer to a structure describing the incoming packet.
  958. Use of this structure depends on its flags. If it is a multicast
  959. packet, then it cannot be modified by this routine. Otherwise it can
  960. be used as scratch space and modified.
  961. SourceAddress - Supplies a pointer to the source (remote) address that the
  962. packet originated from. This memory will not be referenced once the
  963. function returns, it can be stack allocated.
  964. DestinationAddress - Supplies a pointer to the destination (local) address
  965. that the packet is heading to. This memory will not be referenced once
  966. the function returns, it can be stack allocated.
  967. Return Value:
  968. Status code.
  969. --*/
  970. {
  971. ULONG AllocationSize;
  972. PUDP_HEADER Header;
  973. USHORT Length;
  974. USHORT PayloadLength;
  975. KSTATUS Status;
  976. PUDP_RECEIVED_PACKET UdpPacket;
  977. PUDP_SOCKET UdpSocket;
  978. ASSERT(KeGetRunLevel() == RunLevelLow);
  979. UdpSocket = (PUDP_SOCKET)Socket;
  980. Header = (PUDP_HEADER)(Packet->Buffer + Packet->DataOffset);
  981. Length = NETWORK_TO_CPU16(Header->Length);
  982. if (Length > (Packet->FooterOffset - Packet->DataOffset)) {
  983. RtlDebugPrint("Invalid UDP length %d is bigger than packet data, "
  984. "which is only %d bytes large.\n",
  985. Length,
  986. (Packet->FooterOffset - Packet->DataOffset));
  987. Status = STATUS_BUFFER_TOO_SMALL;
  988. goto ProcessReceivedSocketDataEnd;
  989. }
  990. //
  991. // Since the socket has already been matched, the source and destination
  992. // addresses better be completely filled in.
  993. //
  994. ASSERT(SourceAddress->Port == NETWORK_TO_CPU16(Header->SourcePort));
  995. ASSERT(DestinationAddress->Port ==
  996. NETWORK_TO_CPU16(Header->DestinationPort));
  997. //
  998. // Create a received packet entry for this data.
  999. //
  1000. PayloadLength = Length - sizeof(UDP_HEADER);
  1001. AllocationSize = sizeof(UDP_RECEIVED_PACKET) + PayloadLength;
  1002. UdpPacket = MmAllocatePagedPool(AllocationSize,
  1003. UDP_PROTOCOL_ALLOCATION_TAG);
  1004. if (UdpPacket == NULL) {
  1005. Status = STATUS_INSUFFICIENT_RESOURCES;
  1006. goto ProcessReceivedSocketDataEnd;
  1007. }
  1008. RtlCopyMemory(&(UdpPacket->Address),
  1009. SourceAddress,
  1010. sizeof(NETWORK_ADDRESS));
  1011. UdpPacket->DataBuffer = (PVOID)(UdpPacket + 1);
  1012. UdpPacket->Size = PayloadLength;
  1013. //
  1014. // Copy the packet contents into the receive packet buffer.
  1015. //
  1016. RtlCopyMemory(UdpPacket->DataBuffer, Header + 1, PayloadLength);
  1017. //
  1018. // Work to insert the packet on the list of received packets.
  1019. //
  1020. KeAcquireQueuedLock(UdpSocket->ReceiveLock);
  1021. if (UdpPacket->Size <= UdpSocket->ReceiveBufferFreeSize) {
  1022. INSERT_BEFORE(&(UdpPacket->ListEntry),
  1023. &(UdpSocket->ReceivedPacketList));
  1024. UdpSocket->ReceiveBufferFreeSize -= UdpPacket->Size;
  1025. ASSERT(UdpSocket->ReceiveBufferFreeSize <
  1026. UdpSocket->ReceiveBufferTotalSize);
  1027. //
  1028. // One packet is always enough to notify a waiting receiver.
  1029. //
  1030. IoSetIoObjectState(Socket->KernelSocket.IoState, POLL_EVENT_IN, TRUE);
  1031. UdpPacket = NULL;
  1032. } else {
  1033. UdpSocket->DroppedPacketCount += 1;
  1034. }
  1035. KeReleaseQueuedLock(UdpSocket->ReceiveLock);
  1036. //
  1037. // If the packet wasn't nulled out, that's an indication it wasn't added to
  1038. // the list, so free it up.
  1039. //
  1040. if (UdpPacket != NULL) {
  1041. MmFreePagedPool(UdpPacket);
  1042. }
  1043. Status = STATUS_SUCCESS;
  1044. ProcessReceivedSocketDataEnd:
  1045. return Status;
  1046. }
  1047. KSTATUS
  1048. NetpUdpReceive (
  1049. BOOL FromKernelMode,
  1050. PNET_SOCKET Socket,
  1051. PSOCKET_IO_PARAMETERS Parameters,
  1052. PIO_BUFFER IoBuffer
  1053. )
  1054. /*++
  1055. Routine Description:
  1056. This routine is called by the user to receive data from the socket on a
  1057. particular protocol.
  1058. Arguments:
  1059. FromKernelMode - Supplies a boolean indicating whether the request is
  1060. coming from kernel mode (TRUE) or user mode (FALSE).
  1061. Socket - Supplies a pointer to the socket to receive data from.
  1062. Parameters - Supplies a pointer to the socket I/O parameters.
  1063. IoBuffer - Supplies a pointer to the I/O buffer where the received data
  1064. will be returned.
  1065. Return Value:
  1066. STATUS_SUCCESS if any bytes were read.
  1067. STATUS_TIMEOUT if the request timed out.
  1068. STATUS_BUFFER_TOO_SMALL if the incoming datagram was too large for the
  1069. buffer. The remainder of the datagram is discarded in this case.
  1070. Other error codes on other failures.
  1071. --*/
  1072. {
  1073. UINTN BytesComplete;
  1074. ULONG CopySize;
  1075. ULONGLONG CurrentTime;
  1076. ULONGLONG EndTime;
  1077. ULONG Flags;
  1078. BOOL LockHeld;
  1079. PUDP_RECEIVED_PACKET Packet;
  1080. PLIST_ENTRY PacketEntry;
  1081. ULONG ReturnedEvents;
  1082. ULONG ReturnSize;
  1083. UINTN Size;
  1084. KSTATUS Status;
  1085. ULONGLONG TimeCounterFrequency;
  1086. ULONG Timeout;
  1087. PUDP_SOCKET UdpSocket;
  1088. ULONG WaitTime;
  1089. ASSERT(KeGetRunLevel() == RunLevelLow);
  1090. BytesComplete = 0;
  1091. EndTime = 0;
  1092. LockHeld = FALSE;
  1093. Flags = Parameters->SocketIoFlags;
  1094. Parameters->SocketIoFlags = 0;
  1095. if ((Flags & SOCKET_IO_OUT_OF_BAND) != 0) {
  1096. Status = STATUS_NOT_SUPPORTED;
  1097. goto UdpReceiveEnd;
  1098. }
  1099. //
  1100. // Fail if there's ancillary data.
  1101. //
  1102. if (Parameters->ControlDataSize != 0) {
  1103. Status = STATUS_NOT_SUPPORTED;
  1104. goto UdpReceiveEnd;
  1105. }
  1106. Packet = NULL;
  1107. Size = Parameters->Size;
  1108. TimeCounterFrequency = 0;
  1109. Timeout = Parameters->TimeoutInMilliseconds;
  1110. UdpSocket = (PUDP_SOCKET)Socket;
  1111. //
  1112. // Set a timeout timer to give up on. The socket stores the maximum timeout.
  1113. //
  1114. if (Timeout > UdpSocket->ReceiveTimeout) {
  1115. Timeout = UdpSocket->ReceiveTimeout;
  1116. }
  1117. if ((Timeout != 0) && (Timeout != WAIT_TIME_INDEFINITE)) {
  1118. EndTime = KeGetRecentTimeCounter();
  1119. EndTime += KeConvertMicrosecondsToTimeTicks(
  1120. Timeout * MICROSECONDS_PER_MILLISECOND);
  1121. TimeCounterFrequency = HlQueryTimeCounterFrequency();
  1122. }
  1123. //
  1124. // Loop trying to get some data. This loop exits once one packet is read.
  1125. //
  1126. while (TRUE) {
  1127. //
  1128. // Wait for a packet to become available. Start by computing the wait
  1129. // time.
  1130. //
  1131. if (Timeout == 0) {
  1132. WaitTime = 0;
  1133. } else if (Timeout != WAIT_TIME_INDEFINITE) {
  1134. CurrentTime = KeGetRecentTimeCounter();
  1135. WaitTime = (EndTime - CurrentTime) * MILLISECONDS_PER_SECOND /
  1136. TimeCounterFrequency;
  1137. } else {
  1138. WaitTime = WAIT_TIME_INDEFINITE;
  1139. }
  1140. //
  1141. // Wait for something to maybe become available. If the wait fails due
  1142. // to a timeout, interruption, or something else, then fail out.
  1143. // Otherwise when the read event is signalled, there is at least one
  1144. // packet to receive.
  1145. //
  1146. Status = IoWaitForIoObjectState(Socket->KernelSocket.IoState,
  1147. POLL_EVENT_IN,
  1148. TRUE,
  1149. WaitTime,
  1150. &ReturnedEvents);
  1151. if (!KSUCCESS(Status)) {
  1152. goto UdpReceiveEnd;
  1153. }
  1154. if ((ReturnedEvents & POLL_ERROR_EVENTS) != 0) {
  1155. if ((ReturnedEvents & POLL_EVENT_DISCONNECTED) != 0) {
  1156. Status = STATUS_NO_NETWORK_CONNECTION;
  1157. } else {
  1158. Status = NET_SOCKET_GET_LAST_ERROR(Socket);
  1159. if (KSUCCESS(Status)) {
  1160. Status = STATUS_DEVICE_IO_ERROR;
  1161. }
  1162. }
  1163. goto UdpReceiveEnd;
  1164. }
  1165. KeAcquireQueuedLock(UdpSocket->ReceiveLock);
  1166. LockHeld = TRUE;
  1167. //
  1168. // Fail with EOF if the socket has already been closed for reading.
  1169. //
  1170. if ((UdpSocket->ShutdownTypes & SOCKET_SHUTDOWN_READ) != 0) {
  1171. Status = STATUS_END_OF_FILE;
  1172. goto UdpReceiveEnd;
  1173. }
  1174. //
  1175. // If another thread beat this one to the punch, try again.
  1176. //
  1177. if (LIST_EMPTY(&(UdpSocket->ReceivedPacketList)) != FALSE) {
  1178. KeReleaseQueuedLock(UdpSocket->ReceiveLock);
  1179. LockHeld = FALSE;
  1180. continue;
  1181. }
  1182. //
  1183. // This should be the first packet being read.
  1184. //
  1185. ASSERT(BytesComplete == 0);
  1186. PacketEntry = UdpSocket->ReceivedPacketList.Next;
  1187. Packet = LIST_VALUE(PacketEntry, UDP_RECEIVED_PACKET, ListEntry);
  1188. ReturnSize = Packet->Size;
  1189. CopySize = ReturnSize;
  1190. if (CopySize > Size) {
  1191. Parameters->SocketIoFlags |= SOCKET_IO_DATA_TRUNCATED;
  1192. CopySize = Size;
  1193. //
  1194. // The real packet size is only returned to the user on truncation
  1195. // if the truncated flag was supplied to this routine. Default to
  1196. // returning the truncated size.
  1197. //
  1198. if ((Flags & SOCKET_IO_DATA_TRUNCATED) == 0) {
  1199. ReturnSize = CopySize;
  1200. }
  1201. }
  1202. Status = MmCopyIoBufferData(IoBuffer,
  1203. Packet->DataBuffer,
  1204. 0,
  1205. CopySize,
  1206. TRUE);
  1207. if (!KSUCCESS(Status)) {
  1208. goto UdpReceiveEnd;
  1209. }
  1210. //
  1211. // Copy the packet address out to the caller if requested.
  1212. //
  1213. if (Parameters->NetworkAddress != NULL) {
  1214. if (FromKernelMode != FALSE) {
  1215. RtlCopyMemory(Parameters->NetworkAddress,
  1216. &(Packet->Address),
  1217. sizeof(NETWORK_ADDRESS));
  1218. } else {
  1219. Status = MmCopyToUserMode(Parameters->NetworkAddress,
  1220. &(Packet->Address),
  1221. sizeof(NETWORK_ADDRESS));
  1222. if (!KSUCCESS(Status)) {
  1223. goto UdpReceiveEnd;
  1224. }
  1225. }
  1226. }
  1227. BytesComplete = ReturnSize;
  1228. //
  1229. // Remove the packet if not peeking.
  1230. //
  1231. if ((Flags & SOCKET_IO_PEEK) == 0) {
  1232. LIST_REMOVE(&(Packet->ListEntry));
  1233. UdpSocket->ReceiveBufferFreeSize += Packet->Size;
  1234. //
  1235. // The total receive buffer size may have been decreased. Don't
  1236. // increment the free size above the total.
  1237. //
  1238. if (UdpSocket->ReceiveBufferFreeSize >
  1239. UdpSocket->ReceiveBufferTotalSize) {
  1240. UdpSocket->ReceiveBufferFreeSize =
  1241. UdpSocket->ReceiveBufferTotalSize;
  1242. }
  1243. MmFreePagedPool(Packet);
  1244. //
  1245. // Unsignal the IN event if there are no more packets.
  1246. //
  1247. if (LIST_EMPTY(&(UdpSocket->ReceivedPacketList)) != FALSE) {
  1248. IoSetIoObjectState(Socket->KernelSocket.IoState,
  1249. POLL_EVENT_IN,
  1250. FALSE);
  1251. }
  1252. }
  1253. //
  1254. // Wait-all does not apply to UDP sockets. Break out.
  1255. //
  1256. Status = STATUS_SUCCESS;
  1257. break;
  1258. }
  1259. UdpReceiveEnd:
  1260. if (LockHeld != FALSE) {
  1261. KeReleaseQueuedLock(UdpSocket->ReceiveLock);
  1262. }
  1263. Parameters->BytesCompleted = BytesComplete;
  1264. return Status;
  1265. }
  1266. KSTATUS
  1267. NetpUdpGetSetInformation (
  1268. PNET_SOCKET Socket,
  1269. SOCKET_INFORMATION_TYPE InformationType,
  1270. UINTN Option,
  1271. PVOID Data,
  1272. PUINTN DataSize,
  1273. BOOL Set
  1274. )
  1275. /*++
  1276. Routine Description:
  1277. This routine gets or sets properties of the given socket.
  1278. Arguments:
  1279. Socket - Supplies a pointer to the socket to get or set information for.
  1280. InformationType - Supplies the socket information type category to which
  1281. specified option belongs.
  1282. Option - Supplies the option to get or set, which is specific to the
  1283. information type. The type of this value is generally
  1284. SOCKET_<information_type>_OPTION.
  1285. Data - Supplies a pointer to the data buffer where the data is either
  1286. returned for a get operation or given for a set operation.
  1287. DataSize - Supplies a pointer that on input constains the size of the data
  1288. buffer. On output, this contains the required size of the data buffer.
  1289. Set - Supplies a boolean indicating if this is a get operation (FALSE) or
  1290. a set operation (TRUE).
  1291. Return Value:
  1292. STATUS_SUCCESS on success.
  1293. STATUS_INVALID_PARAMETER if the information type is incorrect.
  1294. STATUS_BUFFER_TOO_SMALL if the data buffer is too small to receive the
  1295. requested option.
  1296. STATUS_NOT_SUPPORTED_BY_PROTOCOL if the socket option is not supported by
  1297. the socket.
  1298. STATUS_NOT_HANDLED if the protocol does not override the default behavior
  1299. for a basic socket option.
  1300. --*/
  1301. {
  1302. ULONG Count;
  1303. ULONG Index;
  1304. LONGLONG Milliseconds;
  1305. PNET_PACKET_SIZE_INFORMATION SizeInformation;
  1306. ULONG SizeOption;
  1307. PSOCKET_TIME SocketTime;
  1308. SOCKET_TIME SocketTimeBuffer;
  1309. PVOID Source;
  1310. KSTATUS Status;
  1311. PUDP_SOCKET_OPTION UdpOption;
  1312. PUDP_SOCKET UdpSocket;
  1313. UdpSocket = (PUDP_SOCKET)Socket;
  1314. if ((InformationType != SocketInformationBasic) &&
  1315. (InformationType != SocketInformationUdp)) {
  1316. Status = STATUS_NOT_SUPPORTED;
  1317. goto UdpGetSetInformationEnd;
  1318. }
  1319. //
  1320. // Search to see if the socket option is supported by UDP.
  1321. //
  1322. Count = sizeof(NetUdpSocketOptions) / sizeof(NetUdpSocketOptions[0]);
  1323. for (Index = 0; Index < Count; Index += 1) {
  1324. UdpOption = &(NetUdpSocketOptions[Index]);
  1325. if ((UdpOption->InformationType == InformationType) &&
  1326. (UdpOption->Option == Option)) {
  1327. break;
  1328. }
  1329. }
  1330. if (Index == Count) {
  1331. if (InformationType == SocketInformationBasic) {
  1332. Status = STATUS_NOT_HANDLED;
  1333. } else {
  1334. Status = STATUS_NOT_SUPPORTED_BY_PROTOCOL;
  1335. }
  1336. goto UdpGetSetInformationEnd;
  1337. }
  1338. //
  1339. // Handle failure cases common to all options.
  1340. //
  1341. if (Set != FALSE) {
  1342. if (UdpOption->SetAllowed == FALSE) {
  1343. Status = STATUS_NOT_SUPPORTED_BY_PROTOCOL;
  1344. goto UdpGetSetInformationEnd;
  1345. }
  1346. if (*DataSize < UdpOption->Size) {
  1347. *DataSize = UdpOption->Size;
  1348. Status = STATUS_BUFFER_TOO_SMALL;
  1349. goto UdpGetSetInformationEnd;
  1350. }
  1351. }
  1352. //
  1353. // There are currently no UDP options.
  1354. //
  1355. ASSERT(InformationType != SocketInformationUdp);
  1356. //
  1357. // Parse the basic socket option, getting the information from the UDP
  1358. // socket or setting the new state in the UDP socket.
  1359. //
  1360. Source = NULL;
  1361. Status = STATUS_SUCCESS;
  1362. switch ((SOCKET_BASIC_OPTION)Option) {
  1363. case SocketBasicOptionSendBufferSize:
  1364. if (Set != FALSE) {
  1365. SizeOption = *((PULONG)Data);
  1366. ASSERT(UDP_MAX_PACKET_SIZE <= SOCKET_OPTION_MAX_ULONG);
  1367. SizeInformation = &(Socket->PacketSizeInformation);
  1368. if (SizeOption > UDP_MAX_PACKET_SIZE) {
  1369. SizeOption = UDP_MAX_PACKET_SIZE;
  1370. } else if (SizeOption < SizeInformation->MaxPacketSize) {
  1371. SizeOption = SizeInformation->MaxPacketSize;
  1372. }
  1373. UdpSocket->MaxPacketSize = SizeOption;
  1374. } else {
  1375. SizeOption = UdpSocket->MaxPacketSize;
  1376. Source = &SizeOption;
  1377. }
  1378. break;
  1379. case SocketBasicOptionSendMinimum:
  1380. ASSERT(Set == FALSE);
  1381. SizeOption = UDP_SEND_MINIMUM;
  1382. Source = &SizeOption;
  1383. break;
  1384. case SocketBasicOptionReceiveBufferSize:
  1385. if (Set != FALSE) {
  1386. SizeOption = *((PULONG)Data);
  1387. if (SizeOption > SOCKET_OPTION_MAX_ULONG) {
  1388. SizeOption = SOCKET_OPTION_MAX_ULONG;
  1389. }
  1390. if (SizeOption < UDP_MIN_RECEIVE_BUFFER_SIZE) {
  1391. SizeOption = UDP_MIN_RECEIVE_BUFFER_SIZE;
  1392. }
  1393. //
  1394. // Set the receive buffer size and truncate the available free
  1395. // space if necessary. Do not remove any packets that have already
  1396. // been received. This is not meant to be a truncate call.
  1397. //
  1398. KeAcquireQueuedLock(UdpSocket->ReceiveLock);
  1399. UdpSocket->ReceiveBufferTotalSize = SizeOption;
  1400. if (UdpSocket->ReceiveBufferFreeSize > SizeOption) {
  1401. UdpSocket->ReceiveBufferFreeSize = SizeOption;
  1402. }
  1403. KeReleaseQueuedLock(UdpSocket->ReceiveLock);
  1404. } else {
  1405. SizeOption = UdpSocket->ReceiveBufferTotalSize;
  1406. Source = &SizeOption;
  1407. }
  1408. break;
  1409. case SocketBasicOptionReceiveMinimum:
  1410. if (Set != FALSE) {
  1411. SizeOption = *((PULONG)Data);
  1412. if (SizeOption > SOCKET_OPTION_MAX_ULONG) {
  1413. SizeOption = SOCKET_OPTION_MAX_ULONG;
  1414. }
  1415. UdpSocket->ReceiveMinimum = SizeOption;
  1416. } else {
  1417. Source = &SizeOption;
  1418. SizeOption = UdpSocket->ReceiveMinimum;
  1419. }
  1420. break;
  1421. case SocketBasicOptionReceiveTimeout:
  1422. if (Set != FALSE) {
  1423. SocketTime = (PSOCKET_TIME)Data;
  1424. if (SocketTime->Seconds < 0) {
  1425. Status = STATUS_DOMAIN_ERROR;
  1426. break;
  1427. }
  1428. Milliseconds = SocketTime->Seconds * MILLISECONDS_PER_SECOND;
  1429. if (Milliseconds < SocketTime->Seconds) {
  1430. Status = STATUS_DOMAIN_ERROR;
  1431. break;
  1432. }
  1433. Milliseconds += SocketTime->Microseconds /
  1434. MICROSECONDS_PER_MILLISECOND;
  1435. if ((Milliseconds < 0) || (Milliseconds > MAX_LONG)) {
  1436. Status = STATUS_DOMAIN_ERROR;
  1437. break;
  1438. }
  1439. UdpSocket->ReceiveTimeout = (ULONG)(LONG)Milliseconds;
  1440. } else {
  1441. Source = &SocketTimeBuffer;
  1442. if (UdpSocket->ReceiveTimeout == WAIT_TIME_INDEFINITE) {
  1443. SocketTimeBuffer.Seconds = 0;
  1444. SocketTimeBuffer.Microseconds = 0;
  1445. } else {
  1446. SocketTimeBuffer.Seconds = UdpSocket->ReceiveTimeout /
  1447. MILLISECONDS_PER_SECOND;
  1448. SocketTimeBuffer.Microseconds = (UdpSocket->ReceiveTimeout %
  1449. MILLISECONDS_PER_SECOND) *
  1450. MICROSECONDS_PER_MILLISECOND;
  1451. }
  1452. }
  1453. break;
  1454. default:
  1455. ASSERT(FALSE);
  1456. Status = STATUS_NOT_HANDLED;
  1457. break;
  1458. }
  1459. if (!KSUCCESS(Status)) {
  1460. goto UdpGetSetInformationEnd;
  1461. }
  1462. //
  1463. // Truncate all copies for get requests down to the required size and only
  1464. // return the required size on set requests.
  1465. //
  1466. if (*DataSize > UdpOption->Size) {
  1467. *DataSize = UdpOption->Size;
  1468. }
  1469. //
  1470. // For get requests, copy the gathered information to the supplied data
  1471. // buffer.
  1472. //
  1473. if (Set == FALSE) {
  1474. ASSERT(Source != NULL);
  1475. RtlCopyMemory(Data, Source, *DataSize);
  1476. //
  1477. // If the copy truncated the data, report that the given buffer was too
  1478. // small. The caller can choose to ignore this if the truncated data is
  1479. // enough.
  1480. //
  1481. if (*DataSize < UdpOption->Size) {
  1482. *DataSize = UdpOption->Size;
  1483. Status = STATUS_BUFFER_TOO_SMALL;
  1484. goto UdpGetSetInformationEnd;
  1485. }
  1486. }
  1487. UdpGetSetInformationEnd:
  1488. return Status;
  1489. }
  1490. KSTATUS
  1491. NetpUdpUserControl (
  1492. PNET_SOCKET Socket,
  1493. ULONG CodeNumber,
  1494. BOOL FromKernelMode,
  1495. PVOID ContextBuffer,
  1496. UINTN ContextBufferSize
  1497. )
  1498. /*++
  1499. Routine Description:
  1500. This routine handles user control requests destined for a socket.
  1501. Arguments:
  1502. Socket - Supplies a pointer to the socket.
  1503. CodeNumber - Supplies the minor code of the request.
  1504. FromKernelMode - Supplies a boolean indicating whether or not this request
  1505. (and the buffer associated with it) originates from user mode (FALSE)
  1506. or kernel mode (TRUE).
  1507. ContextBuffer - Supplies a pointer to the context buffer allocated by the
  1508. caller for the request.
  1509. ContextBufferSize - Supplies the size of the supplied context buffer.
  1510. Return Value:
  1511. Status code.
  1512. --*/
  1513. {
  1514. return STATUS_NOT_SUPPORTED;
  1515. }
  1516. //
  1517. // --------------------------------------------------------- Internal Functions
  1518. //