Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1760 lines
45 KiB

  1. /*++
  2. Copyright (c) 1998, Microsoft Corporation
  3. Module Name:
  4. socket.c
  5. Abstract:
  6. This module contains code for socket-management.
  7. The routines provided generally follow the same asynchronous model
  8. using a completion routine that is invoked in the context of
  9. a callback thread.
  10. Author:
  11. Abolade Gbadegesin (aboladeg) 2-Mar-1998
  12. Revision History:
  13. Abolade Gbadegesin (aboladeg) 23-May-1999
  14. Added support for stream sockets.
  15. Jonathan Burstein (jonburs) 12-April-2001
  16. Added support for raw datagram sockets.
  17. --*/
  18. #include "precomp.h"
  19. #pragma hdrstop
  20. #include <ws2tcpip.h>
  21. #include <mstcpip.h>
  22. #include <mswsock.h>
  23. #if DBG
  24. ULONG NhpReadCount = 0;
  25. #endif
  26. ULONG UnusedBytesTransferred;
  27. typedef struct _NH_CLOSE_BUFFER {
  28. HANDLE Event OPTIONAL;
  29. HANDLE WaitHandle OPTIONAL;
  30. PNH_COMPLETION_ROUTINE CloseNotificationRoutine;
  31. } NH_CLOSE_BUFFER, *PNH_CLOSE_BUFFER;
  32. typedef struct _NH_CONNECT_BUFFER {
  33. HANDLE Event;
  34. HANDLE WaitHandle;
  35. PNH_COMPLETION_ROUTINE CloseNotificationRoutine OPTIONAL;
  36. BOOLEAN CloseNotificationReceived;
  37. } NH_CONNECT_BUFFER, *PNH_CONNECT_BUFFER;
  38. //
  39. // FORWARD DECLARATIONS
  40. //
  41. VOID NTAPI
  42. NhpCloseNotificationCallbackRoutine(
  43. PVOID Context,
  44. BOOLEAN WaitCompleted
  45. );
  46. VOID NTAPI
  47. NhpConnectOrCloseCallbackRoutine(
  48. PVOID Context,
  49. BOOLEAN WaitCompleted
  50. );
  51. VOID WINAPI
  52. NhpIoCompletionRoutine(
  53. ULONG ErrorCode,
  54. ULONG BytesTransferred,
  55. LPOVERLAPPED Overlapped
  56. );
  57. VOID APIENTRY
  58. NhpIoWorkerRoutine(
  59. PVOID Context
  60. );
  61. ULONG
  62. NhAcceptStreamSocket(
  63. PCOMPONENT_REFERENCE Component,
  64. SOCKET ListeningSocket,
  65. SOCKET AcceptedSocket OPTIONAL,
  66. PNH_BUFFER Bufferp,
  67. PNH_COMPLETION_ROUTINE AcceptCompletionRoutine,
  68. PVOID Context,
  69. PVOID Context2
  70. )
  71. /*++
  72. Routine Description:
  73. This routine is invoked to accept an incoming connection-request
  74. on a listening stream socket using 'AcceptEx'. The I/O system invokes
  75. the provided 'CompletionRoutine' upon completion of the read.
  76. It is the completion-routine's responsibility to use 'setsockopt' to
  77. set the SO_UPDATE_ACCEPT_CONTEXT option on the accepted socket before
  78. the accepted socket can be used with Winsock2 routines.
  79. A reference is made to the given component, if any, if the request is
  80. submitted successfully. This guarantees the component will not be unloaded
  81. before the completion routine runs.
  82. Arguments:
  83. Component - the component to be referenced for the completion routine
  84. ListeningSocket - the endpoint that is listening for connection-requests
  85. AcceptedSocket - the endpoint to be assigned a connection-request,
  86. or INVALID_SOCKET to create a new endpoint
  87. Bufferp - the buffer to be used for asynchronous completion
  88. or NULL to acquire a new buffer
  89. AcceptCompletionRoutine - the routine to be invoked upon completion
  90. Context - the context to be associated with the accept-request;
  91. this can be obtained from 'Bufferp->Context' upon completion.
  92. Context2 - secondary context
  93. Return Value:
  94. ULONG - Win32/Winsock2 status code.
  95. A success code is a guarantee that the accept-completion routine
  96. will be invoked.
  97. Conversely, a failure code is a guarantee that the routine will not
  98. be invoked.
  99. --*/
  100. {
  101. ULONG Error;
  102. PNH_BUFFER LocalBufferp = NULL;
  103. SOCKET LocalSocket = INVALID_SOCKET;
  104. if (Component) {
  105. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  106. }
  107. if (!Bufferp) {
  108. Bufferp = LocalBufferp = NhAcquireBuffer();
  109. if (!Bufferp) {
  110. NhTrace(TRACE_FLAG_SOCKET, "error allocating buffer for accept");
  111. if (Component) { DEREFERENCE_COMPONENT(Component); }
  112. return ERROR_NOT_ENOUGH_MEMORY;
  113. }
  114. }
  115. if (AcceptedSocket == INVALID_SOCKET) {
  116. Error = NhCreateStreamSocket(INADDR_NONE, 0, &LocalSocket);
  117. if (Error) {
  118. NhTrace(
  119. TRACE_FLAG_SOCKET, "error %d creating socket for accept", Error
  120. );
  121. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  122. if (Component) { DEREFERENCE_COMPONENT(Component); }
  123. return ERROR_NOT_ENOUGH_MEMORY;
  124. }
  125. AcceptedSocket = LocalSocket;
  126. }
  127. ZeroMemory(&Bufferp->Overlapped, sizeof(Bufferp->Overlapped));
  128. Bufferp->Socket = AcceptedSocket;
  129. Bufferp->CompletionRoutine = AcceptCompletionRoutine;
  130. Bufferp->Context = Context;
  131. Bufferp->Context2 = Context2;
  132. if (AcceptEx(
  133. ListeningSocket,
  134. AcceptedSocket,
  135. Bufferp->Buffer,
  136. 0,
  137. sizeof(SOCKADDR_IN) + 16,
  138. sizeof(SOCKADDR_IN) + 16,
  139. &UnusedBytesTransferred,
  140. &Bufferp->Overlapped
  141. )) {
  142. Error = NO_ERROR;
  143. } else {
  144. if ((Error = WSAGetLastError()) == ERROR_IO_PENDING) {
  145. Error = NO_ERROR;
  146. } else if (Error) {
  147. if (LocalSocket != INVALID_SOCKET) {
  148. NhDeleteStreamSocket(LocalSocket);
  149. }
  150. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  151. if (Component) { DEREFERENCE_COMPONENT(Component); }
  152. NhTrace(
  153. TRACE_FLAG_SOCKET, "error %d returned by 'AcceptEx'", Error
  154. );
  155. }
  156. }
  157. return Error;
  158. } // NhAcceptStreamSocket
  159. ULONG
  160. NhConnectStreamSocket(
  161. PCOMPONENT_REFERENCE Component,
  162. SOCKET ConnectingSocket,
  163. ULONG Address,
  164. USHORT Port,
  165. PNH_BUFFER Bufferp OPTIONAL,
  166. PNH_COMPLETION_ROUTINE ConnectCompletionRoutine,
  167. PNH_COMPLETION_ROUTINE CloseNotificationRoutine OPTIONAL,
  168. PVOID Context,
  169. PVOID Context2
  170. )
  171. /*++
  172. Routine Description:
  173. This routine is invoked to establish a connection using a stream socket.
  174. A reference is made to the given component, if any, if the request is
  175. submitted successfully. This guarantees the component will not be unloaded
  176. before the completion routine runs.
  177. Since Windows Sockets does not deliver connect-notifications to
  178. I/O completion ports, we need to make some special arrangements in order
  179. to notify the caller's completion routine the way we do for send-requests
  180. and receive-requests. Specifically, we create an event-handle and
  181. request connect-notification on it by calling 'WSAEventSelect'.
  182. We then register a wait on the event-handle, specifying a private
  183. completion routine. (See 'NhpConnectOrCloseCallbackRoutine'.)
  184. When this completion routine runs, it extracts the status code of the
  185. connection-attempt using 'WSAEnumNetworkEvents'. It then passes the status
  186. along with the usual parameters to the caller's completion routine.
  187. The caller may optionally receive notification when the remote endpoint
  188. closes the socket after a successful connection. We use the same
  189. 'WSAEventSelect' mechanism to detect that condition and invoke the
  190. caller's notification routine.
  191. N.B. The buffer supplied to this routine may not be released by either
  192. the connect-completion routine or the close-notification routine.
  193. (See 'NhpConnectOrCloseCallbackRoutine' for more information.)
  194. Arguments:
  195. Component - the component to be referenced for the completion routine
  196. Socket - the socket with which to establish a connection
  197. Address - the IP address of the remote endpoint
  198. Port - the port number of the remote endpoint
  199. Bufferp - optionally supplies the buffer to be used to hold context
  200. during the connection-attempt
  201. ConnectCompletionRoutine - a routine to be invoked upon completion
  202. of the connect-attempt
  203. CloseNotificationRoutine - optionally specifies a routine to be invoked
  204. upon notification of the resulting socket's closure by the remote
  205. endpoint
  206. Context - passed to the 'ConnectCompletionRoutine' and
  207. 'CloseNotificationRoutine'
  208. Context2 - secondary context
  209. Return Value:
  210. ULONG - Win32/Winsock2 status code
  211. A success code is a guarantee that both the connect-completion routine
  212. and the close-notification routine, if any, will be invoked.
  213. Conversely, a failure code is a guarantee that the neither routine will
  214. be invoked.
  215. --*/
  216. {
  217. PNH_CONNECT_BUFFER Contextp;
  218. ULONG Error;
  219. PNH_BUFFER LocalBufferp = NULL;
  220. if (Component) {
  221. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  222. }
  223. if (!Bufferp) {
  224. Bufferp = LocalBufferp = NhAcquireBuffer();
  225. if (!Bufferp) {
  226. NhTrace(
  227. TRACE_FLAG_SOCKET,
  228. "NhConnectStreamSocket: error allocating buffer for connect"
  229. );
  230. if (Component) { DEREFERENCE_COMPONENT(Component); }
  231. return ERROR_NOT_ENOUGH_MEMORY;
  232. }
  233. }
  234. Bufferp->Socket = ConnectingSocket;
  235. Bufferp->ReceiveFlags = 0;
  236. Bufferp->CompletionRoutine = ConnectCompletionRoutine;
  237. Bufferp->Context = Context;
  238. Bufferp->Context2 = Context2;
  239. Bufferp->ConnectAddress.sin_family = AF_INET;
  240. Bufferp->ConnectAddress.sin_addr.s_addr = Address;
  241. Bufferp->ConnectAddress.sin_port = Port;
  242. Contextp = (PNH_CONNECT_BUFFER)Bufferp->Buffer;
  243. Contextp->CloseNotificationReceived = FALSE;
  244. Contextp->CloseNotificationRoutine = CloseNotificationRoutine;
  245. Contextp->WaitHandle = NULL;
  246. Contextp->Event = CreateEvent(NULL, FALSE, FALSE, NULL);
  247. if (!Contextp->Event ||
  248. !RegisterWaitForSingleObject(
  249. &Contextp->WaitHandle,
  250. Contextp->Event,
  251. NhpConnectOrCloseCallbackRoutine,
  252. Bufferp,
  253. INFINITE,
  254. WT_EXECUTEINIOTHREAD
  255. )) {
  256. Error = GetLastError();
  257. } else {
  258. ULONG EventsSelected = FD_CONNECT;
  259. if (CloseNotificationRoutine) { EventsSelected |= FD_CLOSE; }
  260. Error =
  261. WSAEventSelect(
  262. ConnectingSocket, Contextp->Event, EventsSelected
  263. );
  264. if (Error == SOCKET_ERROR) {
  265. Error = WSAGetLastError();
  266. } else {
  267. Error =
  268. WSAConnect(
  269. ConnectingSocket,
  270. (PSOCKADDR)&Bufferp->ConnectAddress,
  271. sizeof(Bufferp->ConnectAddress),
  272. NULL,
  273. NULL,
  274. NULL,
  275. NULL
  276. );
  277. }
  278. }
  279. if (Error == SOCKET_ERROR &&
  280. (Error = WSAGetLastError()) == WSAEWOULDBLOCK) {
  281. Error = NO_ERROR;
  282. } else if (Error) {
  283. if (Contextp->WaitHandle) { UnregisterWait(Contextp->WaitHandle); }
  284. if (Contextp->Event) { CloseHandle(Contextp->Event); }
  285. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  286. if (Component) { DEREFERENCE_COMPONENT(Component); }
  287. }
  288. return Error;
  289. } // NhConnectStreamSocket
  290. ULONG
  291. NhCreateDatagramSocket(
  292. ULONG Address,
  293. USHORT Port,
  294. OUT SOCKET* Socketp
  295. )
  296. /*++
  297. Routine Description:
  298. This routine is called to initialize a datagram socket.
  299. Arguments:
  300. Address - the IP address to which the socket should be bound (network-order)
  301. Port - the UDP port to which the socket should be bound (network-order)
  302. Socketp - receives the created socket
  303. Return Value:
  304. ULONG - Win32/Winsock2 error code
  305. --*/
  306. {
  307. ULONG Error;
  308. ULONG Option;
  309. ULONG OutputBufferLength;
  310. SOCKET Socket;
  311. SOCKADDR_IN SocketAddress;
  312. do {
  313. //
  314. // Create a new socket
  315. //
  316. Socket =
  317. WSASocket(
  318. AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED
  319. );
  320. if (Socket == INVALID_SOCKET) {
  321. Error = WSAGetLastError();
  322. NhTrace(
  323. TRACE_FLAG_SOCKET,
  324. "NhCreateDatagramSocket: error %d creating socket", Error
  325. );
  326. break;
  327. }
  328. //
  329. // Associate the socket with our I/O completion port
  330. //
  331. BindIoCompletionCallback((HANDLE)Socket, NhpIoCompletionRoutine, 0);
  332. //
  333. // Attempt to enable endpoint-reuse on the socket
  334. //
  335. Option = 1;
  336. Error =
  337. setsockopt(
  338. Socket,
  339. SOL_SOCKET,
  340. SO_REUSEADDR,
  341. (PCHAR)&Option,
  342. sizeof(Option)
  343. );
  344. //
  345. // Attempt to enable broadcasting on the socket
  346. //
  347. Option = 1;
  348. Error =
  349. setsockopt(
  350. Socket,
  351. SOL_SOCKET,
  352. SO_BROADCAST,
  353. (PCHAR)&Option,
  354. sizeof(Option)
  355. );
  356. //
  357. // Limit broadcasts to the outgoing network
  358. // (the default is to send broadcasts on all interfaces).
  359. //
  360. Option = 1;
  361. WSAIoctl(
  362. Socket,
  363. SIO_LIMIT_BROADCASTS,
  364. &Option,
  365. sizeof(Option),
  366. NULL,
  367. 0,
  368. &OutputBufferLength,
  369. NULL,
  370. NULL
  371. );
  372. //
  373. // Bind the socket
  374. //
  375. SocketAddress.sin_family = AF_INET;
  376. SocketAddress.sin_port = Port;
  377. SocketAddress.sin_addr.s_addr = Address;
  378. Error = bind(Socket, (PSOCKADDR)&SocketAddress, sizeof(SocketAddress));
  379. if (Error == SOCKET_ERROR) {
  380. Error = WSAGetLastError();
  381. NhTrace(
  382. TRACE_FLAG_SOCKET,
  383. "NhCreateDatagramSocket: error %d binding socket", Error
  384. );
  385. break;
  386. }
  387. //
  388. // Save the socket and return
  389. //
  390. *Socketp = Socket;
  391. return NO_ERROR;
  392. } while (FALSE);
  393. if (Socket != INVALID_SOCKET) { closesocket(Socket); }
  394. return Error;
  395. } // NhCreateDatagramSocket
  396. ULONG
  397. NhCreateRawDatagramSocket(
  398. OUT SOCKET* Socketp
  399. )
  400. /*++
  401. Routine Description:
  402. This routine is called to initialize a raw, header-include
  403. datagram socket.
  404. Arguments:
  405. Socketp - receives the created socket
  406. Return Value:
  407. ULONG - Win32/Winsock2 error code
  408. --*/
  409. {
  410. ULONG Error;
  411. ULONG Option;
  412. ULONG OutputBufferLength;
  413. SOCKET Socket;
  414. SOCKADDR_IN SocketAddress;
  415. do {
  416. //
  417. // Create a new socket
  418. //
  419. Socket =
  420. WSASocket(
  421. AF_INET, SOCK_RAW, IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED
  422. );
  423. if (Socket == INVALID_SOCKET) {
  424. Error = WSAGetLastError();
  425. NhTrace(
  426. TRACE_FLAG_SOCKET,
  427. "NhCreateRawDatagramSocket: error %d creating socket", Error
  428. );
  429. break;
  430. }
  431. //
  432. // Associate the socket with our I/O completion port
  433. //
  434. BindIoCompletionCallback((HANDLE)Socket, NhpIoCompletionRoutine, 0);
  435. //
  436. // Turn on header-include mode
  437. //
  438. Option = 1;
  439. Error =
  440. setsockopt(
  441. Socket,
  442. IPPROTO_IP,
  443. IP_HDRINCL,
  444. (PCHAR)&Option,
  445. sizeof(Option)
  446. );
  447. if (SOCKET_ERROR == Error) {
  448. Error = WSAGetLastError();
  449. NhTrace(
  450. TRACE_FLAG_SOCKET,
  451. "NhCreateRawDatagramSocket: error %d setting IP_HDRINCL", Error
  452. );
  453. break;
  454. }
  455. //
  456. // Limit broadcasts to the outgoing network
  457. // (the default is to send broadcasts on all interfaces).
  458. //
  459. Option = 1;
  460. WSAIoctl(
  461. Socket,
  462. SIO_LIMIT_BROADCASTS,
  463. &Option,
  464. sizeof(Option),
  465. NULL,
  466. 0,
  467. &OutputBufferLength,
  468. NULL,
  469. NULL
  470. );
  471. //
  472. // Save the socket and return
  473. //
  474. *Socketp = Socket;
  475. return NO_ERROR;
  476. } while (FALSE);
  477. if (Socket != INVALID_SOCKET) { closesocket(Socket); }
  478. return Error;
  479. } // NhCreateRawDatagramSocket
  480. ULONG
  481. NhCreateStreamSocket(
  482. ULONG Address OPTIONAL,
  483. USHORT Port OPTIONAL,
  484. OUT SOCKET* Socketp
  485. )
  486. /*++
  487. Routine Description:
  488. This routine is invoked to create and initialize a stream socket.
  489. The socket will also be bound to a local IP address and port,
  490. unless none is specified.
  491. Arguments:
  492. Address - the local IP address to which the new socket should be bound,
  493. or INADDR_ANY to allow the system to leave the IP address unspecified,
  494. or INADDR_NONE if the socket should not be bound at all.
  495. Port - the port number to which the new socket should be bound,
  496. or 0 if to allow the system to select a port number.
  497. Socketp - receives initialized socket
  498. Return Value:
  499. ULONG - Win32/Winsock2 status code.
  500. --*/
  501. {
  502. ULONG Error;
  503. ULONG Option;
  504. SOCKET Socket;
  505. SOCKADDR_IN SocketAddress;
  506. do {
  507. //
  508. // Create a new stream socket.
  509. //
  510. Socket =
  511. WSASocket(
  512. AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED
  513. );
  514. if (Socket == INVALID_SOCKET) {
  515. Error = WSAGetLastError();
  516. NhTrace(
  517. TRACE_FLAG_SOCKET,
  518. "NhCreateStreamSocket: error %d creating socket", Error
  519. );
  520. break;
  521. }
  522. //
  523. // Associate the socket with our I/O completion port
  524. //
  525. BindIoCompletionCallback((HANDLE)Socket, NhpIoCompletionRoutine, 0);
  526. //
  527. // Disable send and receive buffering in AFD,
  528. // since we will be operating asynchronously with a receive-buffer
  529. // (almost) always outstanding, and since in any case we want
  530. // TCP/IP's flow-control to limit the sender's sending rate properly.
  531. //
  532. Option = 0;
  533. setsockopt(
  534. Socket,
  535. SOL_SOCKET,
  536. SO_SNDBUF,
  537. (PCHAR)&Option,
  538. sizeof(Option)
  539. );
  540. Option = 0;
  541. setsockopt(
  542. Socket,
  543. SOL_SOCKET,
  544. SO_SNDBUF,
  545. (PCHAR)&Option,
  546. sizeof(Option)
  547. );
  548. //
  549. // If the caller has requested that the socket be bound by specifying
  550. // a local IP address, bind the socket now.
  551. //
  552. if (Address != INADDR_NONE) {
  553. SocketAddress.sin_family = AF_INET;
  554. SocketAddress.sin_port = Port;
  555. SocketAddress.sin_addr.s_addr = Address;
  556. Error =
  557. bind(Socket, (PSOCKADDR)&SocketAddress, sizeof(SocketAddress));
  558. if (Error == SOCKET_ERROR) {
  559. Error = WSAGetLastError();
  560. NhTrace(
  561. TRACE_FLAG_SOCKET,
  562. "NhCreateStreamSocket: error %d binding socket", Error
  563. );
  564. break;
  565. }
  566. }
  567. //
  568. // Store the new socket in the caller's output-parameter, and return.
  569. //
  570. *Socketp = Socket;
  571. return NO_ERROR;
  572. } while(FALSE);
  573. if (Socket != INVALID_SOCKET) { closesocket(Socket); }
  574. return Error;
  575. } // NhCreateStreamSocket
  576. VOID
  577. NhDeleteSocket(
  578. SOCKET Socket
  579. )
  580. /*++
  581. Routine Description:
  582. This routine releases network resources for a socket.
  583. Arguments:
  584. Socket - the socket to be deleted
  585. Return Value:
  586. none.
  587. --*/
  588. {
  589. if (Socket != INVALID_SOCKET) { closesocket(Socket); }
  590. } // NhDeleteSocket
  591. ULONG
  592. NhNotifyOnCloseStreamSocket(
  593. PCOMPONENT_REFERENCE Component,
  594. SOCKET Socket,
  595. PNH_BUFFER Bufferp OPTIONAL,
  596. PNH_COMPLETION_ROUTINE CloseNotificationRoutine,
  597. PVOID Context,
  598. PVOID Context2
  599. )
  600. /*++
  601. Routine Description:
  602. This routine is invoked to request notification of a socket's closure.
  603. A reference is made to the given component, if any, if the request is
  604. submitted successfully. This guarantees the component will not be unloaded
  605. before the notification routine runs.
  606. Arguments:
  607. Component - the component to be referenced for the notification routine
  608. Socket - the endpoint for which close-notification is requested
  609. Bufferp - the buffer to be used to hold context-informatio for the request,
  610. or NULL to acquire a new buffer.
  611. CloseNotificationRoutine - the routine to be invoked upon closure of the
  612. socket
  613. Context - the context to be associated with the notification-request;
  614. this can be obtained from 'Bufferp->Context' upon completion.
  615. Context2 - secondary context
  616. Return Value:
  617. ULONG - Win32/Winsock2 status code.
  618. A success code is a guarantee that the notification routine will be invoked.
  619. Conversely, a failure code is a guarantee that the notification routine
  620. will not be invoked.
  621. --*/
  622. {
  623. PNH_CLOSE_BUFFER Contextp;
  624. ULONG Error;
  625. PNH_BUFFER LocalBufferp = NULL;
  626. if (Component) {
  627. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  628. }
  629. if (!Bufferp) {
  630. Bufferp = LocalBufferp = NhAcquireBuffer();
  631. if (!Bufferp) {
  632. if (Component) { DEREFERENCE_COMPONENT(Component); }
  633. return ERROR_NOT_ENOUGH_MEMORY;
  634. }
  635. }
  636. Bufferp->Socket = Socket;
  637. Bufferp->CompletionRoutine = NULL;
  638. Bufferp->Context = Context;
  639. Bufferp->Context2 = Context2;
  640. Contextp = (PNH_CLOSE_BUFFER)Bufferp->Buffer;
  641. Contextp->CloseNotificationRoutine = CloseNotificationRoutine;
  642. Contextp->WaitHandle = NULL;
  643. Contextp->Event = CreateEvent(NULL, FALSE, FALSE, NULL);
  644. if (!Contextp->Event ||
  645. !RegisterWaitForSingleObject(
  646. &Contextp->WaitHandle,
  647. Contextp->Event,
  648. NhpCloseNotificationCallbackRoutine,
  649. Bufferp,
  650. INFINITE,
  651. WT_EXECUTEINIOTHREAD
  652. )) {
  653. Error = GetLastError();
  654. } else {
  655. Error = WSAEventSelect(Socket, Contextp->Event, FD_CLOSE);
  656. if (Error == SOCKET_ERROR) { Error = WSAGetLastError(); }
  657. }
  658. if (Error) {
  659. if (Contextp->WaitHandle) { UnregisterWait(Contextp->WaitHandle); }
  660. if (Contextp->Event) { CloseHandle(Contextp->Event); }
  661. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  662. if (Component) { DEREFERENCE_COMPONENT(Component); }
  663. }
  664. return Error;
  665. } // NhNotifyOnCloseStreamSocket
  666. VOID NTAPI
  667. NhpCloseNotificationCallbackRoutine(
  668. PVOID Context,
  669. BOOLEAN WaitCompleted
  670. )
  671. /*++
  672. Routine Description:
  673. This routine is invoked upon closure of an accepted connection by the
  674. remote endpoint.
  675. It runs in the context of a thread executing a callback-routine associated
  676. with a wait-handle. The wait-handle is registered for the event-handle
  677. that is passed to 'WSAEventSelect' when connection-acceptance is initiated.
  678. Arguments:
  679. Context - context-field associated with the completed wait
  680. WaitCompleted - indicates whether the wait completed or was timed-out
  681. Return Value:
  682. none.
  683. Environment:
  684. Runs in the context of a system wait thread.
  685. --*/
  686. {
  687. PNH_BUFFER Bufferp = (PNH_BUFFER)Context;
  688. PNH_CLOSE_BUFFER Contextp = (PNH_CLOSE_BUFFER)Bufferp->Buffer;
  689. ULONG Error;
  690. WSANETWORKEVENTS NetworkEvents;
  691. //
  692. // Retrieve the network events for which we're being invoked
  693. // When invoked for 'FD_CLOSE', we unregister the wait since there's
  694. // nothing left to wait for.
  695. //
  696. Bufferp->BytesTransferred = 0;
  697. NetworkEvents.lNetworkEvents = 0;
  698. Error =
  699. WSAEnumNetworkEvents(
  700. Bufferp->Socket, Contextp->Event, &NetworkEvents
  701. );
  702. if (Error || !(NetworkEvents.lNetworkEvents & FD_CLOSE)) {
  703. //
  704. // We couldn't determine which events occurred on the socket,
  705. // so call the notification routine with an error, and fall through
  706. // to the cleanup code below.
  707. //
  708. if (Contextp->CloseNotificationRoutine) {
  709. Contextp->CloseNotificationRoutine(
  710. ERROR_OPERATION_ABORTED, 0, Bufferp
  711. );
  712. }
  713. } else {
  714. //
  715. // A close occurred on the socket, so retrieve the error code,
  716. // invoke the close-notification routine if any, and fall through
  717. // to the cleanup code below.
  718. //
  719. Error = NetworkEvents.iErrorCode[FD_CLOSE_BIT];
  720. if (Contextp->CloseNotificationRoutine) {
  721. Contextp->CloseNotificationRoutine(Error, 0, Bufferp);
  722. }
  723. }
  724. UnregisterWait(Contextp->WaitHandle);
  725. CloseHandle(Contextp->Event);
  726. NhReleaseBuffer(Bufferp);
  727. } // NhpCloseNotificationCallbackRoutine
  728. VOID NTAPI
  729. NhpConnectOrCloseCallbackRoutine(
  730. PVOID Context,
  731. BOOLEAN WaitCompleted
  732. )
  733. /*++
  734. Routine Description:
  735. This routine is invoked by upon completion of a connect-operation
  736. or upon closure of the connection by the remote endpoint.
  737. It runs in the context of a thread executing a callback-routine associated
  738. with a wait-handle. The wait-handle is registered for the event-handle
  739. that is passed to 'WSAEventSelect' when a connection-attempt is initiated.
  740. Arguments:
  741. Context - context-field associated with the completed wait
  742. WaitCompleted - indicates whether the wait completed or was timed-out
  743. Return Value:
  744. none.
  745. Environment:
  746. Runs in the context of a system wait thread.
  747. --*/
  748. {
  749. PNH_BUFFER Bufferp = (PNH_BUFFER)Context;
  750. PNH_CONNECT_BUFFER Contextp = (PNH_CONNECT_BUFFER)Bufferp->Buffer;
  751. ULONG Error;
  752. WSANETWORKEVENTS NetworkEvents;
  753. //
  754. // Retrieve the network events for which we're being invoked
  755. // When invoked for 'FD_CONNECT', we unregister the wait if an error
  756. // occurred. When invoked for 'FD_CLOSE', we unregister the wait
  757. // since there's nothing left to wait for.
  758. //
  759. // In essence, our goal is to guarantee that whatever the success
  760. // or failure or sequence of events on the socket, the connect-completion
  761. // and close-notification routines will both be called for the socket,
  762. // in that order.
  763. //
  764. // N.B. Neither routine is allowed to release the connect-buffer,
  765. // since we may need to preserve it on behalf of the close-notification
  766. // routine, if any.
  767. //
  768. // N.B. We may be invoked with both the 'FD_CONNECT' and 'FD_CLOSE' bits
  769. // set, for instance when the socket is closed. In that case we call
  770. // both routines here.
  771. //
  772. Bufferp->BytesTransferred = 0;
  773. NetworkEvents.lNetworkEvents = 0;
  774. Error =
  775. WSAEnumNetworkEvents(
  776. Bufferp->Socket, Contextp->Event, &NetworkEvents
  777. );
  778. if (Error) {
  779. //
  780. // We couldn't determine which events occurred on the socket,
  781. // so call the routines with errors, and fall through
  782. // to the cleanup code below.
  783. //
  784. if (Bufferp->CompletionRoutine) {
  785. Bufferp->CompletionRoutine(ERROR_OPERATION_ABORTED, 0, Bufferp);
  786. Bufferp->CompletionRoutine = NULL;
  787. }
  788. if (Contextp->CloseNotificationRoutine) {
  789. Contextp->CloseNotificationRoutine(
  790. ERROR_OPERATION_ABORTED, 0, Bufferp
  791. );
  792. }
  793. Contextp->CloseNotificationReceived = TRUE;
  794. } else {
  795. if (NetworkEvents.lNetworkEvents & FD_CONNECT) {
  796. //
  797. // The connect completed, so retrieve the error code and invoke
  798. // the connect-completion routine. If the connect failed,
  799. // we may never receive close-notification (unless the bit
  800. // is already set) so we need to simulate close-notification
  801. // here so that the cleanup code below executes.
  802. //
  803. Error = NetworkEvents.iErrorCode[FD_CONNECT_BIT];
  804. if (Bufferp->CompletionRoutine) {
  805. Bufferp->CompletionRoutine(Error, 0, Bufferp);
  806. Bufferp->CompletionRoutine = NULL;
  807. }
  808. if (Error && !(NetworkEvents.lNetworkEvents & FD_CLOSE)) {
  809. if (Contextp->CloseNotificationRoutine) {
  810. Contextp->CloseNotificationRoutine(Error, 0, Bufferp);
  811. }
  812. Contextp->CloseNotificationReceived = TRUE;
  813. }
  814. }
  815. if (NetworkEvents.lNetworkEvents & FD_CLOSE) {
  816. //
  817. // A close occurred on the socket, so retrieve the error code,
  818. // invoke the close-notification routine if any, and fall through
  819. // to the cleanup code below.
  820. //
  821. Error = NetworkEvents.iErrorCode[FD_CLOSE_BIT];
  822. if (Contextp->CloseNotificationRoutine) {
  823. Contextp->CloseNotificationRoutine(Error, 0, Bufferp);
  824. }
  825. Contextp->CloseNotificationReceived = TRUE;
  826. }
  827. }
  828. //
  829. // If both the connect-completion and close-notification routines have run,
  830. // we are done with this wait-handle and buffer.
  831. //
  832. if (!Bufferp->CompletionRoutine && Contextp->CloseNotificationReceived) {
  833. UnregisterWait(Contextp->WaitHandle);
  834. CloseHandle(Contextp->Event);
  835. NhReleaseBuffer(Bufferp);
  836. }
  837. } // NhpConnectOrCloseCallbackRoutine
  838. VOID
  839. NhpIoCompletionRoutine(
  840. ULONG ErrorCode,
  841. ULONG BytesTransferred,
  842. LPOVERLAPPED Overlapped
  843. )
  844. /*++
  845. Routine Description:
  846. This routine is invoked by the I/O system upon completion of an operation.
  847. Arguments:
  848. ErrorCode - system-supplied error code
  849. BytesTransferred - system-supplied byte-count
  850. Overlapped - caller-supplied context area
  851. Return Value:
  852. none.
  853. Environment:
  854. Runs in the context of an RTUTILS.DLL worker thread.
  855. --*/
  856. {
  857. PNH_BUFFER Bufferp = CONTAINING_RECORD(Overlapped, NH_BUFFER, Overlapped);
  858. NTSTATUS status;
  859. Bufferp->ErrorCode = ErrorCode;
  860. Bufferp->BytesTransferred = BytesTransferred;
  861. Bufferp->CompletionRoutine(
  862. Bufferp->ErrorCode,
  863. Bufferp->BytesTransferred,
  864. Bufferp
  865. );
  866. } // NhpIoCompletionRoutine
  867. VOID APIENTRY
  868. NhpIoWorkerRoutine(
  869. PVOID Context
  870. )
  871. /*++
  872. Routine Description:
  873. This routine is invoked to continue processing of completed I/O
  874. in the context of an alertably waiting thread which does not exit idly.
  875. Arguments:
  876. Context - holds the buffer associated with the completed I/O operation.
  877. Return Value:
  878. none.
  879. Environment:
  880. Runs in the context of an RTUTILS.DLL alertable worker thread.
  881. --*/
  882. {
  883. ((PNH_BUFFER)Context)->CompletionRoutine(
  884. ((PNH_BUFFER)Context)->ErrorCode,
  885. ((PNH_BUFFER)Context)->BytesTransferred,
  886. ((PNH_BUFFER)Context)
  887. );
  888. } // NhpIoWorkerRoutine
  889. VOID
  890. NhQueryAcceptEndpoints(
  891. PUCHAR AcceptBuffer,
  892. PULONG LocalAddress OPTIONAL,
  893. PUSHORT LocalPort OPTIONAL,
  894. PULONG RemoteAddress OPTIONAL,
  895. PUSHORT RemotePort OPTIONAL
  896. )
  897. {
  898. PSOCKADDR_IN LocalSockAddr = NULL;
  899. ULONG LocalLength = sizeof(LocalSockAddr);
  900. PSOCKADDR_IN RemoteSockAddr = NULL;
  901. ULONG RemoteLength = sizeof(RemoteSockAddr);
  902. GetAcceptExSockaddrs(
  903. AcceptBuffer,
  904. 0,
  905. sizeof(SOCKADDR_IN) + 16,
  906. sizeof(SOCKADDR_IN) + 16,
  907. (PSOCKADDR*)&LocalSockAddr,
  908. reinterpret_cast<LPINT>(&LocalLength),
  909. (PSOCKADDR*)&RemoteSockAddr,
  910. (LPINT)&RemoteLength
  911. );
  912. if (LocalAddress && LocalSockAddr) {
  913. *LocalAddress = LocalSockAddr->sin_addr.s_addr;
  914. }
  915. if (LocalPort && LocalSockAddr) {
  916. *LocalPort = LocalSockAddr->sin_port;
  917. }
  918. if (RemoteAddress && RemoteSockAddr) {
  919. *RemoteAddress = RemoteSockAddr->sin_addr.s_addr;
  920. }
  921. if (RemotePort && RemoteSockAddr) {
  922. *RemotePort = RemoteSockAddr->sin_port;
  923. }
  924. } // NhQueryAcceptEndpoints
  925. ULONG
  926. NhQueryAddressSocket(
  927. SOCKET Socket
  928. )
  929. /*++
  930. Routine Description:
  931. This routine is invoked to retrieve the IP address associated with
  932. a socket.
  933. Arguments:
  934. Socket - the socket to be queried
  935. Return Value:
  936. ULONG - the IP address retrieved
  937. --*/
  938. {
  939. SOCKADDR_IN Address;
  940. LONG AddressLength;
  941. AddressLength = sizeof(Address);
  942. getsockname(Socket, (PSOCKADDR)&Address, (int*)&AddressLength);
  943. return Address.sin_addr.s_addr;
  944. } // NhQueryAddressSocket
  945. ULONG
  946. NhQueryLocalEndpointSocket(
  947. SOCKET Socket,
  948. PULONG Address OPTIONAL,
  949. PUSHORT Port
  950. )
  951. {
  952. SOCKADDR_IN SockAddr;
  953. LONG Length;
  954. Length = sizeof(SockAddr);
  955. if (getsockname(Socket, (PSOCKADDR)&SockAddr, (int*)&Length) == SOCKET_ERROR) {
  956. return WSAGetLastError();
  957. }
  958. if (Address) { *Address = SockAddr.sin_addr.s_addr; }
  959. if (Port) { *Port = SockAddr.sin_port; }
  960. return NO_ERROR;
  961. } // NhQueryEndpointSocket
  962. USHORT
  963. NhQueryPortSocket(
  964. SOCKET Socket
  965. )
  966. /*++
  967. Routine Description:
  968. This routine retrieves the port number to which a socket is bound.
  969. Arguments:
  970. Socket - the socket to be queried
  971. Return Value:
  972. USHORT - the port number retrieved
  973. --*/
  974. {
  975. SOCKADDR_IN Address;
  976. LONG AddressLength;
  977. AddressLength = sizeof(Address);
  978. getsockname(Socket, (PSOCKADDR)&Address, (int*)&AddressLength);
  979. return Address.sin_port;
  980. } // NhQueryPortSocket
  981. ULONG
  982. NhQueryRemoteEndpointSocket(
  983. SOCKET Socket,
  984. PULONG Address OPTIONAL,
  985. PUSHORT Port OPTIONAL
  986. )
  987. {
  988. SOCKADDR_IN SockAddr;
  989. LONG Length;
  990. Length = sizeof(SockAddr);
  991. if (getpeername(Socket, (PSOCKADDR)&SockAddr, (int*)&Length) == SOCKET_ERROR) {
  992. return WSAGetLastError();
  993. }
  994. if (Address) { *Address = SockAddr.sin_addr.s_addr; }
  995. if (Port) { *Port = SockAddr.sin_port; }
  996. return NO_ERROR;
  997. } // NhQueryRemoteEndpointSocket
  998. ULONG
  999. NhReadDatagramSocket(
  1000. PCOMPONENT_REFERENCE Component,
  1001. SOCKET Socket,
  1002. PNH_BUFFER Bufferp,
  1003. PNH_COMPLETION_ROUTINE CompletionRoutine,
  1004. PVOID Context,
  1005. PVOID Context2
  1006. )
  1007. /*++
  1008. Routine Description:
  1009. This routine is invoked to read a message from a datagram socket.
  1010. The I/O system invokes the provided 'CompletionRoutine' upon completion
  1011. of the read.
  1012. A reference is made to the given component, if any, if the request is
  1013. submitted successfully. This guarantees the component will not be unloaded
  1014. before the completion routine runs.
  1015. Arguments:
  1016. Component - the component to be referenced for the completion routine
  1017. Socket - the endpoint on which to read a message
  1018. Bufferp - the buffer into which the message should be read,
  1019. or NULL to acquire a new buffer. If no buffer is supplied,
  1020. the resulting message is assumed to fit inside a fixed-length buffer
  1021. CompletionRoutine - the routine to be invoked upon completion of the read
  1022. Context - the context to be associated with the read-request;
  1023. this can be obtained from 'Bufferp->Context' upon completion.
  1024. Context2 - secondary context
  1025. Return Value:
  1026. ULONG - Win32/Winsock2 status code.
  1027. A success code is a guarantee that the completion routine will be invoked.
  1028. Conversely, a failure code is a guarantee that the completion routine will
  1029. not be invoked.
  1030. --*/
  1031. {
  1032. ULONG Error;
  1033. PNH_BUFFER LocalBufferp = NULL;
  1034. WSABUF WsaBuf;
  1035. if (Component) {
  1036. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  1037. }
  1038. if (!Bufferp) {
  1039. Bufferp = LocalBufferp = NhAcquireBuffer();
  1040. if (!Bufferp) {
  1041. NhTrace(
  1042. TRACE_FLAG_SOCKET,
  1043. "NhReadDatagramSocket: error allocating buffer for receive"
  1044. );
  1045. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1046. return ERROR_NOT_ENOUGH_MEMORY;
  1047. }
  1048. }
  1049. ZeroMemory(&Bufferp->Overlapped, sizeof(Bufferp->Overlapped));
  1050. Bufferp->Socket = Socket;
  1051. Bufferp->ReceiveFlags = 0;
  1052. Bufferp->CompletionRoutine = CompletionRoutine;
  1053. Bufferp->Context = Context;
  1054. Bufferp->Context2 = Context2;
  1055. Bufferp->AddressLength = sizeof(Bufferp->ReadAddress);
  1056. WsaBuf.buf = reinterpret_cast<char*>(Bufferp->Buffer);
  1057. WsaBuf.len = NH_BUFFER_SIZE;
  1058. Error =
  1059. WSARecvFrom(
  1060. Socket,
  1061. &WsaBuf,
  1062. 1,
  1063. &UnusedBytesTransferred,
  1064. &Bufferp->ReceiveFlags,
  1065. (PSOCKADDR)&Bufferp->ReadAddress,
  1066. (LPINT)&Bufferp->AddressLength,
  1067. &Bufferp->Overlapped,
  1068. NULL
  1069. );
  1070. if (Error == SOCKET_ERROR &&
  1071. (Error = WSAGetLastError()) == WSA_IO_PENDING) {
  1072. Error = NO_ERROR;
  1073. } else if (Error) {
  1074. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1075. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  1076. NhTrace(
  1077. TRACE_FLAG_SOCKET,
  1078. "NhReadDatagramSocket: error %d returned by 'WSARecvFrom'", Error
  1079. );
  1080. }
  1081. return Error;
  1082. } // NhReadDatagramSocket
  1083. ULONG
  1084. NhReadStreamSocket(
  1085. PCOMPONENT_REFERENCE Component,
  1086. SOCKET Socket,
  1087. PNH_BUFFER Bufferp,
  1088. ULONG Length,
  1089. ULONG Offset,
  1090. PNH_COMPLETION_ROUTINE CompletionRoutine,
  1091. PVOID Context,
  1092. PVOID Context2
  1093. )
  1094. /*++
  1095. Routine Description:
  1096. This routine is invoked to read a message from a stream socket.
  1097. The I/O system invokes the provided 'CompletionRoutine' upon completion
  1098. of the read.
  1099. A reference is made to the given component, if any, if the request is
  1100. submitted successfully. This guarantees the component will not be unloaded
  1101. before the completion routine runs.
  1102. Arguments:
  1103. Component - the component to be referenced for the completion routine
  1104. Socket - the endpoint on which to read a message
  1105. Bufferp - the buffer into which the message should be read,
  1106. or NULL to acquire a new buffer
  1107. Length - the maximum number of bytes to be read
  1108. Offset - the offset into the buffer at which the read should begin,
  1109. valid only if 'Bufferp' is provided.
  1110. CompletionRoutine - the routine to be invoked upon completion of the read
  1111. Context - the context to be associated with the read-request;
  1112. this can be obtained from 'Bufferp->Context' upon completion.
  1113. Context2 - secondary context
  1114. Return Value:
  1115. ULONG - Win32/Winsock2 status code.
  1116. A success code is a guarantee that the completion routine will be invoked.
  1117. Conversely, a failure code is a guarantee that the completion routine will
  1118. not be invoked.
  1119. --*/
  1120. {
  1121. ULONG Error;
  1122. PNH_BUFFER LocalBufferp = NULL;
  1123. WSABUF WsaBuf;
  1124. if (Component) {
  1125. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  1126. }
  1127. if (!Bufferp) {
  1128. Offset = 0;
  1129. Bufferp = LocalBufferp = NhAcquireVariableLengthBuffer(Length);
  1130. if (!Bufferp) {
  1131. NhTrace(
  1132. TRACE_FLAG_SOCKET,
  1133. "NhReadStreamSocket: error allocating buffer for receive"
  1134. );
  1135. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1136. return ERROR_NOT_ENOUGH_MEMORY;
  1137. }
  1138. }
  1139. ZeroMemory(&Bufferp->Overlapped, sizeof(Bufferp->Overlapped));
  1140. Bufferp->Socket = Socket;
  1141. Bufferp->ReceiveFlags = 0;
  1142. Bufferp->CompletionRoutine = CompletionRoutine;
  1143. Bufferp->Context = Context;
  1144. Bufferp->Context2 = Context2;
  1145. #if 1
  1146. if (ReadFile(
  1147. (HANDLE)Bufferp->Socket,
  1148. Bufferp->Buffer + Offset,
  1149. Length,
  1150. &UnusedBytesTransferred,
  1151. &Bufferp->Overlapped
  1152. ) ||
  1153. (Error = GetLastError()) == ERROR_IO_PENDING) {
  1154. Error = NO_ERROR;
  1155. } else {
  1156. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1157. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  1158. NhTrace(
  1159. TRACE_FLAG_SOCKET,
  1160. "NhReadStreamSocket: error %d returned by 'ReadFile'", Error
  1161. );
  1162. }
  1163. #else
  1164. WsaBuf.buf = Bufferp->Buffer + Offset;
  1165. WsaBuf.len = Length;
  1166. Error =
  1167. WSARecv(
  1168. Socket,
  1169. &WsaBuf,
  1170. 1,
  1171. &UnusedBytesTransferred,
  1172. &Bufferp->ReceiveFlags,
  1173. &Bufferp->Overlapped,
  1174. NULL
  1175. );
  1176. if (Error == SOCKET_ERROR &&
  1177. (Error = WSAGetLastError()) == WSA_IO_PENDING) {
  1178. Error = NO_ERROR;
  1179. } else if (Error) {
  1180. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1181. if (LocalBufferp) { NhReleaseBuffer(LocalBufferp); }
  1182. NhTrace(
  1183. TRACE_FLAG_SOCKET,
  1184. "NhReadStreamSocket: error %d returned by 'WSARecv'", Error
  1185. );
  1186. }
  1187. #endif
  1188. return Error;
  1189. } // NhReadStreamSocket
  1190. ULONG
  1191. NhWriteDatagramSocket(
  1192. PCOMPONENT_REFERENCE Component,
  1193. SOCKET Socket,
  1194. ULONG Address,
  1195. USHORT Port,
  1196. PNH_BUFFER Bufferp,
  1197. ULONG Length,
  1198. PNH_COMPLETION_ROUTINE CompletionRoutine,
  1199. PVOID Context,
  1200. PVOID Context2
  1201. )
  1202. /*++
  1203. Routine Description:
  1204. This routine is invoked to send a message on a datagram socket.
  1205. A reference is made to the given component, if any, if the request is
  1206. submitted successfully. This guarantees the component will not be unloaded
  1207. before the completion routine runs.
  1208. Arguments:
  1209. Component - the component to be referenced for the completion routine
  1210. Socket - the socket on which to send the message
  1211. Address - the address of the message's destination
  1212. Port - the port of the message's destination
  1213. Bufferp - the buffer containing the message to be sent
  1214. Length - the number of bytes to transfer
  1215. CompletionRoutine - the routine to be invoked upon completion of the send
  1216. Context - passed to the 'CompletionRoutine' upon completion of the send
  1217. Context2 - secondary context
  1218. Return Value:
  1219. ULONG - Win32/Winsock2 status code
  1220. A success code is a guarantee that the completion routine will be invoked.
  1221. Conversely, a failure code is a guarantee that the completion routine will
  1222. not be invoked.
  1223. --*/
  1224. {
  1225. LONG AddressLength;
  1226. ULONG Error;
  1227. WSABUF WsaBuf;
  1228. if (Component) {
  1229. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  1230. }
  1231. ZeroMemory(&Bufferp->Overlapped, sizeof(Bufferp->Overlapped));
  1232. Bufferp->Socket = Socket;
  1233. Bufferp->CompletionRoutine = CompletionRoutine;
  1234. Bufferp->Context = Context;
  1235. Bufferp->Context2 = Context2;
  1236. Bufferp->WriteAddress.sin_family = AF_INET;
  1237. Bufferp->WriteAddress.sin_addr.s_addr = Address;
  1238. Bufferp->WriteAddress.sin_port = Port;
  1239. AddressLength = sizeof(Bufferp->WriteAddress);
  1240. WsaBuf.buf = reinterpret_cast<char*>(Bufferp->Buffer);
  1241. WsaBuf.len = Length;
  1242. Error =
  1243. WSASendTo(
  1244. Socket,
  1245. &WsaBuf,
  1246. 1,
  1247. &UnusedBytesTransferred,
  1248. 0,
  1249. (PSOCKADDR)&Bufferp->WriteAddress,
  1250. AddressLength,
  1251. &Bufferp->Overlapped,
  1252. NULL
  1253. );
  1254. if (Error == SOCKET_ERROR &&
  1255. (Error = WSAGetLastError()) == WSA_IO_PENDING) {
  1256. Error = NO_ERROR;
  1257. } else if (Error) {
  1258. NhTrace(
  1259. TRACE_FLAG_SOCKET,
  1260. "NhWriteDatagramSocket: error %d returned by 'WSASendTo'", Error
  1261. );
  1262. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1263. }
  1264. return Error;
  1265. } // NhWriteDatagramSocket
  1266. ULONG
  1267. NhWriteStreamSocket(
  1268. PCOMPONENT_REFERENCE Component,
  1269. SOCKET Socket,
  1270. PNH_BUFFER Bufferp,
  1271. ULONG Length,
  1272. ULONG Offset,
  1273. PNH_COMPLETION_ROUTINE CompletionRoutine,
  1274. PVOID Context,
  1275. PVOID Context2
  1276. )
  1277. /*++
  1278. Routine Description:
  1279. This routine is invoked to send a message on a stream socket.
  1280. A reference is made to the given component, if any, if the request is
  1281. submitted successfully. This guarantees the component will not be unloaded
  1282. before the completion routine runs.
  1283. Arguments:
  1284. Component - the component to be referenced for the completion routine
  1285. Socket - the socket on which to send the message
  1286. Bufferp - the buffer containing the message to be sent
  1287. Length - the number of bytes to transfer
  1288. Offset - the offset into the buffer at which the data to be sent begins
  1289. CompletionRoutine - the routine to be invoked upon completion of the send
  1290. Context - passed to the 'CompletionRoutine' upon completion of the send
  1291. Context2 - secondary context
  1292. Return Value:
  1293. ULONG - Win32/Winsock2 status code
  1294. A success code is a guarantee that the completion routine will be invoked.
  1295. Conversely, a failure code is a guarantee that the completion routine will
  1296. not be invoked.
  1297. --*/
  1298. {
  1299. ULONG Error;
  1300. WSABUF WsaBuf;
  1301. if (Component) {
  1302. REFERENCE_COMPONENT_OR_RETURN(Component, ERROR_CAN_NOT_COMPLETE);
  1303. }
  1304. ZeroMemory(&Bufferp->Overlapped, sizeof(Bufferp->Overlapped));
  1305. Bufferp->Socket = Socket;
  1306. Bufferp->CompletionRoutine = CompletionRoutine;
  1307. Bufferp->Context = Context;
  1308. Bufferp->Context2 = Context2;
  1309. #if 1
  1310. if (WriteFile(
  1311. (HANDLE)Bufferp->Socket,
  1312. Bufferp->Buffer + Offset,
  1313. Length,
  1314. &UnusedBytesTransferred,
  1315. &Bufferp->Overlapped
  1316. ) ||
  1317. (Error = GetLastError()) == ERROR_IO_PENDING) {
  1318. Error = NO_ERROR;
  1319. } else {
  1320. NhTrace(
  1321. TRACE_FLAG_SOCKET,
  1322. "NhWriteStreamSocket: error %d returned by 'WriteFile'", Error
  1323. );
  1324. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1325. }
  1326. #else
  1327. WsaBuf.buf = Bufferp->Buffer + Offset;
  1328. WsaBuf.len = Length;
  1329. Error =
  1330. WSASend(
  1331. Socket,
  1332. &WsaBuf,
  1333. 1,
  1334. &UnusedBytesTransferred,
  1335. 0,
  1336. &Bufferp->Overlapped,
  1337. NULL
  1338. );
  1339. if (Error == SOCKET_ERROR &&
  1340. (Error = WSAGetLastError()) == WSA_IO_PENDING) {
  1341. Error = NO_ERROR;
  1342. } else if (Error) {
  1343. NhTrace(
  1344. TRACE_FLAG_SOCKET,
  1345. "NhWriteStreamSocket: error %d returned by 'WSASend'", Error
  1346. );
  1347. if (Component) { DEREFERENCE_COMPONENT(Component); }
  1348. }
  1349. #endif
  1350. return Error;
  1351. } // NhWriteStreamSocket