udp.c 50 KB

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