udp.c 51 KB

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