Example #1
0
VOID
SockFreeHelperDlls (
    VOID
    )
{

    PLIST_ENTRY listEntry;
    PWINSOCK_HELPER_DLL_INFO helperDll;

    //
    // Global lock must be owner when this routine is called
    //
    WS_ASSERT (SocketGlobalLock.WriterId==NtCurrentTeb()->ClientId.UniqueThread);

    while ( !IsListEmpty( &SockHelperDllListHead ) ) {

        listEntry = RemoveHeadList( &SockHelperDllListHead );
        helperDll = CONTAINING_RECORD(
                        listEntry,
                        WINSOCK_HELPER_DLL_INFO,
                        HelperDllListEntry
                        );
		SockDereferenceHelper (helperDll);
    }

    return;

} // SockFreeHelperDlls
Example #2
0
ws_result wscArrayBase::InternalGetItem(ws_int index, wsiObject **ret)
{
    WS_ASSERT( ret != WS_NULL );
    WS_ASSERT( (*ret) == WS_NULL );
    WS_ASSERT( m_array != WS_NULL );
    if ((0<=index) && (index<m_size)) {
        t_pobj pobj = m_array[index];
        if (pobj) {
            if ( pobj->AddRef() > 0 ) {
                *ret = pobj;
            }
        }
        return WS_RLT_SUCCESS;
    }
    else {
        return WS_RLT_ARRAY_INDEX_OUT_OF_BOUNDS;
    }
}
Example #3
0
ws_result wscArrayBase::InternalPutItem(ws_int index, wsiObject * pobj)
{
    WS_ASSERT( m_array != WS_NULL );
    if ((index<0) || (m_size<=index)) {
        return WS_RLT_ARRAY_INDEX_OUT_OF_BOUNDS;
    }
    if (pobj) pobj->AddRef();
    ws_runtime::getRuntime()->SwapPtr( (void**)(&pobj) , (void**)(m_array+index) );
    if (pobj) pobj->Release();
    return WS_RLT_SUCCESS;
}
Example #4
0
ws_boolean  wscString::EndsWith(wsiString * suffix) const
{
    WS_ASSERT( m_pdb != WS_NULL );
    if (suffix==WS_NULL) {
        return WS_FALSE;
    }
    const ws_char * const  target_buf = m_pdb->buf;
    const ws_int           target_len = m_pdb->len;
    const ws_char * const  suffix_buf = suffix->GetBuffer();
    const ws_int           suffix_len = suffix->GetLength();
    if ( suffix_len <= target_len ) {
        return (   wspr::ws_memcmp( target_buf+(target_len-suffix_len) , suffix_buf , suffix_len ) ==0  );
    }
    else {
        return WS_FALSE;
    }
}
Example #5
0
ws_result wscString::ToUpperCase(wsiString ** ret) const
{
    if (ret==WS_NULL) {
        return WS_RLT_NULL_POINTER;
    }
    if (*ret) {
        return WS_RLT_NULL_POINTER;
    }
    WS_ASSERT( m_pdb != WS_NULL );
    const ws_char * const buf = m_pdb->buf;
    const ws_int len = m_pdb->len;
    ws_ptr<wsiStringRW> tmp;
    wscString::Allocate( &tmp , len , buf , len );
    ws_char * rw = tmp->GetBufferRW();
    for (ws_int i=(len-1); i>=0; i--) {
        const ws_char c = rw[i];
        if (('a' <= c) && (c <= 'z')) {
            rw[i] = (c - 'a') + 'A';
        }
    }
    *ret = tmp.Detach();
    return WS_RLT_SUCCESS;
}
Example #6
0
BOOL
SockInitialize (
    IN PVOID DllHandle,
    IN ULONG Reason,
    IN PVOID Context OPTIONAL
    )
{
    NTSTATUS status;
    SYSTEM_INFO systemInfo;

    //
    // On a thread detach, set up the context param so that all
    // necessary deallocations will occur.
    //

    if ( Reason == DLL_THREAD_DETACH ) {
        Context = NULL;
    }

    switch ( Reason ) {

    case DLL_PROCESS_ATTACH:

        SockModuleHandle = (HMODULE)DllHandle;

#if DBG
        //
        // If there is a file in the current directory called "wsdebug"
        // open it and read the first line to set the debugging flags.
        //

        {
            HANDLE handle;

            handle = CreateFile(
                         "WsDebug",
                         GENERIC_READ,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         0,
                         NULL
                         );

            if( handle == INVALID_HANDLE_VALUE ) {

                //
                // Set default value.
                //

                WsDebug = WINSOCK_DEBUG_DEBUGGER;

            } else {

                CHAR buffer[11];
                DWORD bytesRead;

                RtlZeroMemory( buffer, sizeof(buffer) );

                if ( ReadFile( handle, buffer, 10, &bytesRead, NULL ) ) {

                    buffer[bytesRead] = '\0';

                    WsDebug = strtoul( buffer, NULL, 16 );

                } else {

                    WS_PRINT(( "read file failed: %ld\n", GetLastError( ) ));
                }

                CloseHandle( handle );
            }
        }
#endif

        IF_DEBUG(INIT) {
            WS_PRINT(( "SockInitialize: process attach, PEB = %lx\n",
                           NtCurrentPeb( ) ));
        }

        //
        // Initialize the lists of sockets and helper DLLs.
        //

        InitializeListHead( &SockHelperDllListHead );
        InitializeListHead( &SocketListHead );

        //
        // Initialize the global post routine pointer.  We have to do it
        // here rather than statically because it otherwise won't be
        // thunked correctly.
        //

        SockPostRoutine = PostMessage;

        //
        // *** lock acquisition order: it is legal to acquire SocketLock
        // while holding an individual socket lock, but not the other way
        // around!
        //

        InitializeCriticalSection( &SocketLock );
        InitializeCriticalSection( &csRnRLock);

#if !defined(USE_TEB_FIELD)
        //
        // Allocate space in TLS so that we can convert global variables
        // to thread variables.
        //

        SockTlsSlot = TlsAlloc( );

        if ( SockTlsSlot == 0xFFFFFFFF ) {

            WS_PRINT(( "SockInitialize: TlsAlloc failed: %ld\n", GetLastError( ) ));
            DeleteCriticalSection( &SocketLock );
            DeleteCriticalSection( &csRnRLock );
            return FALSE;
        }
#endif  // !USE_TEB_FIELD

        //
        // Create private WinSock heap on MP machines.  UP machines
        // just use the process heap.
        //

        GetSystemInfo( &systemInfo );

        if( systemInfo.dwNumberOfProcessors > 1 ) {

            SockPrivateHeap = RtlCreateHeap( HEAP_GROWABLE |    // Flags
                                             HEAP_CLASS_1,
                                             NULL,              // HeapBase
                                             0,                 // ReserveSize
                                             0,                 // CommitSize
                                             NULL,              // Lock
                                             NULL );            // Parameters

        } else {

            WS_ASSERT( SockPrivateHeap == NULL );

        }

        if ( SockPrivateHeap == NULL ) {

            //
            // This is either a UP box, or RtlCreateHeap() failed.  In
            // either case, just use the process heap.
            //

            SockPrivateHeap = RtlProcessHeap();

        }

        break;

    case DLL_PROCESS_DETACH:

        IF_DEBUG(INIT) {
            WS_PRINT(( "SockInitialize: process detach, PEB = %lx\n",
                           NtCurrentPeb( ) ));
        }

        //
        // Only clean up resources if we're being called because of a
        // FreeLibrary().  If this is because of process termination,
        // do not clean up, as the system will do it for us.  Also,
        // if we get called at process termination, it is likely that
        // a thread was terminated while it held a winsock lock, which
        // would cause a deadlock if we then tried to grab the lock.
        //

        if ( Context == NULL ) {
            WSACleanup( );
            GetHostCleanup();
            DeleteCriticalSection( &SocketLock );
            DeleteCriticalSection( &csRnRLock );
        }

        SockProcessTerminating = TRUE;

        // *** lack of break is intentional!

    case DLL_THREAD_DETACH:

        IF_DEBUG(INIT) {
            WS_PRINT(( "SockInitialize: thread detach, TEB = %lx\n",
                           NtCurrentTeb( ) ));
        }

        //
        // If the TLS information for this thread has been initialized,
        // free the thread data buffer.
        //

        if ( Context == NULL &&
             GET_THREAD_DATA() != NULL ) {

            FREE_HEAP( GET_THREAD_DATA() );
            SET_THREAD_DATA( NULL );
        }

        //
        // If this is a process detach, free the TLS slot we're using.
        //

        if ( Reason == DLL_PROCESS_DETACH && Context == NULL ) {

#if !defined(USE_TEB_FIELD)
            if ( SockTlsSlot != 0xFFFFFFFF ) {

                BOOLEAN ret;

                ret = TlsFree( SockTlsSlot );
                WS_ASSERT( ret );

                SockTlsSlot = 0xFFFFFFFF;
            }
#endif  // !USE_TEB_FIELD

            //
            //  Also destroy any private WinSock heap.
            //

            if ( SockPrivateHeap != RtlProcessHeap() ) {

                WS_ASSERT( SockPrivateHeap != NULL );
                RtlDestroyHeap( SockPrivateHeap );
                SockPrivateHeap = NULL;

            }
        }

        break;

    case DLL_THREAD_ATTACH:
        break;

    default:

        WS_ASSERT( FALSE );
        break;
    }

    return TRUE;

} // SockInitialize
Example #7
0
int
WSPAPI
WSPSendTo (
    SOCKET Handle,
    LPWSABUF lpBuffers,
    DWORD dwBufferCount,
    LPDWORD lpNumberOfBytesSent,
    DWORD iFlags,
    const struct sockaddr *SocketAddress,
    int SocketAddressLength,
    LPWSAOVERLAPPED lpOverlapped,
    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
    LPWSATHREADID lpThreadId,
    LPINT lpErrno
    )

/*++

Routine Description:

    This routine is normally used on a connectionless socket specified by s
    to send a datagram contained in one or more buffers to a specific peer
    socket identified by the lpTo parameter. On a connection-oriented socket,
    the lpTo and iToLen parameters are ignored; in this case the WSPSendTo()
    is equivalent to WSPSend().

    For overlapped sockets (created using WSPSocket() with flag
    WSA_FLAG_OVERLAPPED) this will occur using overlapped I/O, unless both
    lpOverlapped and lpCompletionRoutine are NULL in which case the socket is
    treated as a non-overlapped socket. A completion indication will occur
    (invocation of the completion routine or setting of an event object) when
    the supplied buffer(s) have been consumed by the transport. If the
    operation does not complete immediately, the final completion status is
    retrieved via the completion routine or WSPGetOverlappedResult().

    For non-overlapped sockets, the parameters lpOverlapped,
    lpCompletionRoutine, and lpThreadId are ignored and WSPSend() adopts the
    regular synchronous semantics. Data is copied from the supplied buffer(s)
    into the transport's buffer. If the socket is non-blocking and stream-
    oriented, and there is not sufficient space in the transport's buffer,
    WSPSend() will return with only part of the supplied buffers having been
    consumed. Given the same buffer situation and a blocking socket, WSPSend()
    will block until all of the supplied buffer contents have been consumed.

    The array of WSABUF structures pointed to by the lpBuffers parameter is
    transient. If this operation completes in an overlapped manner, it is the
    service provider's responsibility to capture these WSABUF structures
    before returning from this call. This enables applications to build stack-
    based WSABUF arrays.

    For message-oriented sockets, care must be taken not to exceed the maximum
    message size of the underlying provider, which can be obtained by getting
    the value of socket option SO_MAX_MSG_SIZE. If the data is too long to
    pass atomically through the underlying protocol the error WSAEMSGSIZE is
    returned, and no data is transmitted.

    Note that the successful completion of a WSPSendTo() does not indicate that
    the data was successfully delivered.

    dwFlags may be used to influence the behavior of the function invocation
    beyond the options specified for the associated socket. That is, the
    semantics of this routine are determined by the socket options and the
    dwFlags parameter. The latter is constructed by or-ing any of the
    following values:

        MSG_DONTROUTE - Specifies that the data should not be subject
        to routing. A WinSock service provider may choose to ignore this
        flag.

        MSG_OOB - Send out-of-band data (stream style socket such as
        SOCK_STREAM only).

        MSG_PARTIAL - Specifies that lpBuffers only contains a partial
        message. Note that the error code WSAEOPNOTSUPP will be returned
        which do not support partial message transmissions.

    If an overlapped operation completes immediately, WSPSendTo() returns a
    value of zero and the lpNumberOfBytesSent parameter is updated with the
    number of bytes sent. If the overlapped operation is successfully
    initiated and will complete later, WSPSendTo() returns SOCKET_ERROR and
    indicates error code WSA_IO_PENDING. In this case, lpNumberOfBytesSent is
    not updated. When the overlapped operation completes the amount of data
    transferred is indicated either via the cbTransferred parameter in the
    completion routine (if specified), or via the lpcbTransfer parameter in
    WSPGetOverlappedResult().

    Providers must allow this routine to be called from within the completion
    routine of a previous WSPRecv(), WSPRecvFrom(), WSPSend() or WSPSendTo()
    function. However, for a given socket, I/O completion routines may not be
    nested. This permits time-sensitive data transmissions to occur entirely
    within a preemptive context.

    The lpOverlapped parameter must be valid for the duration of the
    overlapped operation. If multiple I/O operations are simultaneously
    outstanding, each must reference a separate overlapped structure. The
    WSAOVERLAPPED structure has the following form:

        typedef struct _WSAOVERLAPPED {
            DWORD       Internal;       // reserved
            DWORD       InternalHigh;   // reserved
            DWORD       Offset;         // reserved
            DWORD       OffsetHigh;     // reserved
            WSAEVENT    hEvent;
        } WSAOVERLAPPED, FAR * LPWSAOVERLAPPED;

    If the lpCompletionRoutine parameter is NULL, the service provider signals
    the hEvent field of lpOverlapped when the overlapped operation completes
    if it contains a valid event object handle. The WinSock SPI client can use
    WSPGetOverlappedResult() to wait or poll on the event object.

    If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be
    used by the WinSock SPI client to pass context information to the
    completion routine. It is the service provider's responsibility to arrange
    for invocation of the client-specified completion routine when the
    overlapped operation completes. Since the completion routine must be
    executed in the context of the same thread that initiated the overlapped
    operation, it cannot be invoked directly from the service provider. The
    WinSock DLL offers an asynchronous procedure call (APC) mechanism to
    facilitate invocation of completion routines.

    A service provider arranges for a function to be executed in the proper
    thread by calling WPUQueueApc(). Note that this routine must be invoked
    while in the context of the same process (but not necessarily the same
    thread) that was used to initiate the overlapped operation. It is the
    service provider's responsibility to arrange for this process context to
    be active prior to calling WPUQueueApc().

    WPUQueueApc() takes as input parameters a pointer to a WSATHREADID
    structure (supplied to the provider via the lpThreadId input parameter),
    a pointer to an APC function to be invoked, and a 32 bit context value
    that is subsequently passed to the APC function. Because only a single
    32-bit context value is available, the APC function cannot itself be the
    client-specified completion routine. The service provider must instead
    supply a pointer to its own APC function which uses the supplied context
    value to access the needed result information for the overlapped operation,
    and then invokes the client-specified completion routine.

    The prototype for the client-supplied completion routine is as follows:

        void
        CALLBACK
        CompletionRoutine(
            IN DWORD dwError,
            IN DWORD cbTransferred,
            IN LPWSAOVERLAPPED lpOverlapped,
            IN DWORD dwFlags
            );

        CompletionRoutine is a placeholder for a client supplied function
        name.

        dwError specifies the completion status for the overlapped
        operation as indicated by lpOverlapped.

        cbTransferred specifies the number of bytes sent.

        No flag values are currently defined and the dwFlags value will
        be zero.

        This routine does not return a value.

    The completion routines may be called in any order, not necessarily in
    the same order the overlapped operations are completed. However, the
    service provider guarantees to the client that posted buffers are sent
    in the same order they are supplied.

Arguments:

    s - A descriptor identifying a socket.

    lpBuffers - A pointer to an array of WSABUF structures. Each WSABUF
        structure contains a pointer to a buffer and the length of the
        buffer. This array must remain valid for the duration of the
        send operation.

    dwBufferCount - The number of WSABUF structures in the lpBuffers
        array.

    lpNumberOfBytesSent - A pointer to the number of bytes sent by this
        call.

    dwFlags - Specifies the way in which the call is made.

    lpTo - An optional pointer to the address of the target socket.

    iTolen - The size of the address in lpTo.

    lpOverlapped - A pointer to a WSAOVERLAPPED structure.

    lpCompletionRoutine - A pointer to the completion routine called
        when the send operation has been completed.

    lpThreadId - A pointer to a thread ID structure to be used by the
        provider in a subsequent call to WPUQueueApc(). The provider
        should store the referenced WSATHREADID structure (not the
        pointer to same) until after the WPUQueueApc() function returns.

    lpErrno - A pointer to the error code.

Return Value:

    If no error occurs and the send operation has completed immediately,
    WSPSendTo() returns 0. Note that in this case the completion routine, if
    specified, will have already been queued. Otherwise, a value of
    SOCKET_ERROR is returned, and a specific error code is available in
    lpErrno. The error code WSA_IO_PENDING indicates that the overlapped
    operation has been successfully initiated and that completion will be
    indicated at a later time. Any other error code indicates that no
    overlapped operation was initiated and no completion indication will occur.

--*/

{
    NTSTATUS status;
	PWINSOCK_TLS_DATA	tlsData;
    PSOCKET_INFORMATION socket;
    IO_STATUS_BLOCK localIoStatusBlock;
    PIO_STATUS_BLOCK ioStatusBlock;
    AFD_SEND_DATAGRAM_INFO sendInfo;
    PTRANSPORT_ADDRESS tdiAddress;
    ULONG tdiAddressLength;
    int err;
    UCHAR tdiAddressBuffer[MAX_FAST_TDI_ADDRESS];
    HANDLE event;
    PIO_APC_ROUTINE apcRoutine;
    PVOID apcContext;

    WS_ENTER( "WSPSendTo", (PVOID)Handle, (PVOID)lpBuffers, (PVOID)dwBufferCount, (PVOID)iFlags );

    WS_ASSERT( lpErrno != NULL );

    err = SockEnterApi( &tlsData );

    if( err != NO_ERROR ) {

        WS_EXIT( "WSPSendTo", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    //
    // Set up locals so that we know how to clean up on exit.
    //

    tdiAddress = (PTRANSPORT_ADDRESS)tdiAddressBuffer;

    //
    // Find a pointer to the socket structure corresponding to the
    // passed-in handle.
    //

    socket = SockFindAndReferenceSocket( Handle, TRUE );

    if ( socket == NULL ) {

        err = WSAENOTSOCK;
        goto exit;

    }

    //
    // If this is not a datagram socket, just call send() to process the
    // call.  The address and address length parameters are not checked.
    //

    if ( !IS_DGRAM_SOCK(socket)
		    || ( (socket->State==SocketStateConnected)
                && ( SocketAddress == NULL || SocketAddressLength == 0 ))
        ) {

        INT ret;

        SockDereferenceSocket( socket );

        ret = WSPSend(
                  Handle,
                  lpBuffers,
                  dwBufferCount,
                  lpNumberOfBytesSent,
                  iFlags,
                  lpOverlapped,
                  lpCompletionRoutine,
                  lpThreadId,
                  lpErrno
                  );

        WS_EXIT( "WSPSendTo", ret, (BOOLEAN)(ret == SOCKET_ERROR) );
        return ret;

    }

    IF_DEBUG(SEND) {

        WS_PRINT(( "WSASendTo() on socket %lx to addr", Handle ));
        WsPrintSockaddr( (PSOCKADDR)SocketAddress, &SocketAddressLength );

    }

    //
    // If the socket is not connected, then the Address and AddressLength
    // fields must be specified.
    //

    if ( socket->State != SocketStateConnected ) {

        if ( SocketAddress == NULL ) {

            err = WSAENOTCONN;
            goto exit;

        }

    }

    // Note: we simply truncate sockaddr's > MaxSockaddrLength down below
    if ( SocketAddressLength < socket->HelperDll->MinSockaddrLength ) {

        err = WSAEFAULT;
        goto exit;

    }

    //
    // The legal flags are MSG_OOB, MSG_DONTROUTE, and MSG_PARTIAL.
    // MSG_OOB is not legal on datagram sockets.
    //

    WS_ASSERT( IS_DGRAM_SOCK( socket ) );

    if ( ( (iFlags & ~(MSG_DONTROUTE)) != 0 ) ) {

        err = WSAEOPNOTSUPP;
        goto exit;

    }


    //
    // If data send has been shut down, fail.
    //

    if ( socket->SendShutdown ) {

        err = WSAESHUTDOWN;
        goto exit;

    }

    __try {
        //
        // Make sure that the address family passed in here is the same as
        // was passed in on the socket( ) call.
        //

        if ( (short)socket->AddressFamily != SocketAddress->sa_family ) {

            err = WSAEAFNOSUPPORT;
            goto exit;

        }

        //
        // If this socket has not been set to allow broadcasts, check if this
        // is an attempt to send to a broadcast address.
        //

        if ( !socket->Broadcast ) {

            SOCKADDR_INFO sockaddrInfo;

            err = socket->HelperDll->WSHGetSockaddrType(
                        (PSOCKADDR)SocketAddress,
                        SocketAddressLength,
                        &sockaddrInfo
                        );

            if ( err != NO_ERROR) {

                goto exit;

            }

            //
            // If this is an attempt to send to a broadcast address, reject
            // the attempt.
            //

            if ( sockaddrInfo.AddressInfo == SockaddrAddressInfoBroadcast ) {

                err = WSAEACCES;
                goto exit;

            }

        }

        //
        // If this socket is not yet bound to an address, bind it to an
        // address.  We only do this if the helper DLL for the socket supports
        // a get wildcard address routine--if it doesn't, the app must bind
        // to an address manually.
        //

        if ( socket->State == SocketStateOpen) {
		    if (socket->HelperDll->WSHGetWildcardSockaddr != NULL ) {

			    PSOCKADDR sockaddr;
			    INT sockaddrLength = socket->HelperDll->MaxSockaddrLength;
			    int result;

			    sockaddr = ALLOCATE_HEAP( sockaddrLength );

			    if ( sockaddr == NULL ) {

				    err = WSAENOBUFS;
				    goto exit;

			    }

			    err = socket->HelperDll->WSHGetWildcardSockaddr(
						    socket->HelperDllContext,
						    sockaddr,
						    &sockaddrLength
						    );

			    if ( err != NO_ERROR ) {

				    FREE_HEAP( sockaddr );
				    goto exit;

			    }

			    //
			    // Acquire the lock that protect this sockets.  We hold this lock
			    // throughout this routine to synchronize against other callers
			    // performing operations on the socket we're sending data on.
			    //

			    SockAcquireSocketLockExclusive( socket );

			    //
			    // Recheck socket state under the lock
			    //
			    if (socket->State == SocketStateOpen) {
				    result = WSPBind(
							     Handle,
							     sockaddr,
							     sockaddrLength,
							     &err
							     );
			    }
                else
                    result = ERROR_SUCCESS;

	            SockReleaseSocketLock( socket );
			    FREE_HEAP( sockaddr );

			    if( result == SOCKET_ERROR ) {

				    goto exit;

			    }

	        } else {

			    //
			    // The socket is not bound and the helper DLL does not support
			    // a wildcard socket address.  Fail, the app must bind manually.
			    //

			    err = WSAEINVAL;
			    goto exit;
		    }
        }

        //
        // Allocate enough space to hold the TDI address structure we'll pass
        // to AFD.  Note that is the address is small enough, we just use
        // an automatic in order to improve performance.
        //

        tdiAddressLength =  socket->HelperDll->MaxTdiAddressLength;

        if ( tdiAddressLength > MAX_FAST_TDI_ADDRESS ) {

            tdiAddress = ALLOCATE_HEAP( tdiAddressLength );

            if ( tdiAddress == NULL ) {

                err = WSAENOBUFS;
                goto exit;

            }

        } else {

            WS_ASSERT( (PUCHAR)tdiAddress == tdiAddressBuffer );

        }

        //
        // Convert the address from the sockaddr structure to the appropriate
        // TDI structure.
        //
        // Note: We'll truncate any part of the specifed sock addr beyond
        //       that which the helper considers valid
        //

        err = SockBuildTdiAddress(
            tdiAddress,
            (PSOCKADDR)SocketAddress,
            (SocketAddressLength > socket->HelperDll->MaxSockaddrLength ?
                socket->HelperDll->MaxSockaddrLength :
                SocketAddressLength)
            );

        if (err!=NO_ERROR) {
            goto exit;
        }



        //
        // Set up the AFD_SEND_DATAGRAM_INFO structure.
        //

        sendInfo.BufferArray = lpBuffers;
        sendInfo.BufferCount = dwBufferCount;
        sendInfo.AfdFlags = 0;

        //
        // Set up the TDI_REQUEST structure to send the datagram.
        //

        sendInfo.TdiConnInfo.RemoteAddressLength = tdiAddressLength;
        sendInfo.TdiConnInfo.RemoteAddress = tdiAddress;


        //
        // Determine the appropriate APC routine & context, event handle,
        // and IO status block to use for the request.
        //

        if( lpOverlapped == NULL ) {

            //
            // This a synchronous request, use per-thread event object.
            //

            apcRoutine = NULL;
            apcContext = NULL;

            event = tlsData->EventHandle;

            ioStatusBlock = &localIoStatusBlock;

        } else {

            if( lpCompletionRoutine == NULL ) {

                //
                // No APC, use event object from OVERLAPPED structure.
                //

                event = lpOverlapped->hEvent;

                apcRoutine = NULL;
                apcContext = ( (ULONG_PTR)event & 1 ) ? NULL : lpOverlapped;

            } else {

                //
                // APC, ignore event object.
                //

                event = NULL;

                apcRoutine = SockIoCompletion;
                apcContext = lpCompletionRoutine;

                //
                // Tell AFD to skip fast IO on this request.
                //

                sendInfo.AfdFlags |= AFD_NO_FAST_IO;

            }

            //
            // Use part of the OVERLAPPED structure as our IO_STATUS_BLOCK.
            //

            ioStatusBlock = (PIO_STATUS_BLOCK)&lpOverlapped->Internal;

            //
            // Tell AFD this is an overlapped operation.
            //

            sendInfo.AfdFlags |= AFD_OVERLAPPED;

        }

        ioStatusBlock->Status = STATUS_PENDING;

    }
    __except (SOCK_EXCEPTION_FILTER()) {
        err = WSAEFAULT;
        goto exit;
    }
    //
    // Send the data over the socket.
    //

    status = NtDeviceIoControlFile(
                 socket->HContext.Handle,
                 event,
                 apcRoutine,
                 apcContext,
                 ioStatusBlock,
                 IOCTL_AFD_SEND_DATAGRAM,
                 &sendInfo,
                 sizeof(sendInfo),
                 NULL,
                 0
                 );

    if ( apcRoutine != NULL  &&  !NT_ERROR(status) ) {

        tlsData->PendingAPCCount++;
        InterlockedIncrement( &SockProcessPendingAPCCount );
    }

    //
    // If this request has no overlapped structure, then wait for
    // the operation to complete.
    //

    if ( status == STATUS_PENDING &&
         lpOverlapped == NULL ) {

        BOOL success;

        success = SockWaitForSingleObject(
                      event,
                      Handle,
                      SOCK_CONDITIONALLY_CALL_BLOCKING_HOOK,
                      SOCK_SEND_TIMEOUT
                      );

        //
        // If the wait completed successfully, look in the IO status
        // block to determine the real status code of the request.  If
        // the wait timed out, then cancel the IO and set up for an
        // error return.
        //

        if ( success ) {

            status = ioStatusBlock->Status;

        } else {

            SockCancelIo( Handle );
            status = STATUS_IO_TIMEOUT;
        }

    }

    switch (status) {
    case STATUS_SUCCESS:
        break;

    case STATUS_PENDING:
        err = WSA_IO_PENDING;
        goto exit;

    default:
        if (!NT_SUCCESS(status) ) {
            //
            // Map the NTSTATUS to a WinSock error code.
            //

            err = SockNtStatusToSocketError( status );
            goto exit;
        }
    }

    //
    // The request completed immediately, so return the number of
    // bytes sent to the user.
    // It is possible that application deallocated lpOverlapped 
    // in another thread if completion port was used to receive
    // completion indication. We do not want to confuse the
    // application by returning failure, just pretend that we didn't
    // know about synchronous completion
    //

    __try {
        *lpNumberOfBytesSent = (DWORD)ioStatusBlock->Information;
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        if (lpOverlapped) {
            err = WSA_IO_PENDING;
        }
        else {
            err = WSAEFAULT;
        }
        goto exit;
    }

exit:

    IF_DEBUG(SEND) {

        if ( err != NO_ERROR ) {

            WS_PRINT(( "WSPSendTo on socket %lx (%lx) failed: %ld.\n",
                           Handle, socket, err ));

        } else {

            WS_PRINT(( "WSPSendTo on socket %lx (%lx) succeeded, "
                       "bytes = %ld\n",
                           Handle, socket, ioStatusBlock->Information ));

        }

    }

    if ( socket != NULL ) {

	    if ( SockAsyncSelectCalled && err == WSAEWOULDBLOCK ) {

			SockAcquireSocketLockExclusive( socket );

            SockReenableAsyncSelectEvent( socket, FD_WRITE );

	        SockReleaseSocketLock( socket );
        }

        SockDereferenceSocket( socket );

    }

    if ( tdiAddress != NULL &&
         tdiAddress != (PTRANSPORT_ADDRESS)tdiAddressBuffer ) {

        FREE_HEAP( tdiAddress );

    }

    if ( err != NO_ERROR ) {

        WS_EXIT( "WSPSendTo", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    WS_EXIT( "WSPSendTo", 0, FALSE );
    return 0;

}   // WSPSendTo
Example #8
0
int
WSPAPI
WSPSend (
    SOCKET Handle,
    LPWSABUF lpBuffers,
    DWORD dwBufferCount,
    LPDWORD lpNumberOfBytesSent,
    DWORD iFlags,
    LPWSAOVERLAPPED lpOverlapped,
    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
    LPWSATHREADID lpThreadId,
    LPINT lpErrno
    )

/*++

Routine Description:

    This routine is used to write outgoing data from one or more buffers on a
    connection-oriented socket specified by s. It may also be used, however,
    on connectionless sockets which have a stipulated default peer address
    established via the WSPConnect() function.

    For overlapped sockets (created using WSPSocket() with flag
    WSA_FLAG_OVERLAPPED) this will occur using overlapped I/O, unless both
    lpOverlapped and lpCompletionRoutine are NULL in which case the socket is
    treated as a non-overlapped socket. A completion indication will occur
    (invocation of the completion routine or setting of an event object) when
    the supplied buffer(s) have been consumed by the transport. If the
    operation does not complete immediately, the final completion status is
    retrieved via the completion routine or WSPGetOverlappedResult().

    For non-overlapped sockets, the parameters lpOverlapped,
    lpCompletionRoutine, and lpThreadId are ignored and WSPSend() adopts the
    regular synchronous semantics. Data is copied from the supplied buffer(s)
    into the transport's buffer. If the socket is non-blocking and stream-
    oriented, and there is not sufficient space in the transport's buffer,
    WSPSend() will return with only part of the supplied buffers having been
    consumed. Given the same buffer situation and a blocking socket, WSPSend()
    will block until all of the supplied buffer contents have been consumed.

    The array of WSABUF structures pointed to by the lpBuffers parameter is
    transient. If this operation completes in an overlapped manner, it is the
    service provider's responsibility to capture these WSABUF structures
    before returning from this call. This enables applications to build stack-
    based WSABUF arrays.

    For message-oriented sockets, care must be taken not to exceed the maximum
    message size of the underlying provider, which can be obtained by getting
    the value of socket option SO_MAX_MSG_SIZE. If the data is too long to
    pass atomically through the underlying protocol the error WSAEMSGSIZE is
    returned, and no data is transmitted.

    Note that the successful completion of a WSPSend() does not indicate that
    the data was successfully delivered.

    dwFlags may be used to influence the behavior of the function invocation
    beyond the options specified for the associated socket. That is, the
    semantics of this routine are determined by the socket options and the
    dwFlags parameter. The latter is constructed by or-ing any of the
    following values:

        MSG_DONTROUTE - Specifies that the data should not be subject
        to routing. A WinSock service provider may choose to ignore this
        flag.

        MSG_OOB - Send out-of-band data (stream style socket such as
        SOCK_STREAM only).

        MSG_PARTIAL - Specifies that lpBuffers only contains a partial
        message. Note that the error code WSAEOPNOTSUPP will be returned
        which do not support partial message transmissions.

    If an overlapped operation completes immediately, WSPSend() returns a
    value of zero and the lpNumberOfBytesSent parameter is updated with the
    number of bytes sent. If the overlapped operation is successfully
    initiated and will complete later, WSPSend() returns SOCKET_ERROR and
    indicates error code WSA_IO_PENDING. In this case, lpNumberOfBytesSent is
    not updated. When the overlapped operation completes the amount of data
    transferred is indicated either via the cbTransferred parameter in the
    completion routine (if specified), or via the lpcbTransfer parameter in
    WSPGetOverlappedResult().

    Providers must allow this routine to be called from within the completion
    routine of a previous WSPRecv(), WSPRecvFrom(), WSPSend() or WSPSendTo()
    function. However, for a given socket, I/O completion routines may not be
    nested. This permits time-sensitive data transmissions to occur entirely
    within a preemptive context.

    The lpOverlapped parameter must be valid for the duration of the
    overlapped operation. If multiple I/O operations are simultaneously
    outstanding, each must reference a separate overlapped structure. The
    WSAOVERLAPPED structure has the following form:

        typedef struct _WSAOVERLAPPED {
            DWORD       Internal;       // reserved
            DWORD       InternalHigh;   // reserved
            DWORD       Offset;         // reserved
            DWORD       OffsetHigh;     // reserved
            WSAEVENT    hEvent;
        } WSAOVERLAPPED, FAR * LPWSAOVERLAPPED;

    If the lpCompletionRoutine parameter is NULL, the service provider signals
    the hEvent field of lpOverlapped when the overlapped operation completes
    if it contains a valid event object handle. The WinSock SPI client can use
    WSPGetOverlappedResult() to wait or poll on the event object.

    If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be
    used by the WinSock SPI client to pass context information to the
    completion routine. It is the service provider's responsibility to arrange
    for invocation of the client-specified completion routine when the
    overlapped operation completes. Since the completion routine must be
    executed in the context of the same thread that initiated the overlapped
    operation, it cannot be invoked directly from the service provider. The
    WinSock DLL offers an asynchronous procedure call (APC) mechanism to
    facilitate invocation of completion routines.

    A service provider arranges for a function to be executed in the proper
    thread by calling WPUQueueApc(). Note that this routine must be invoked
    while in the context of the same process (but not necessarily the same
    thread) that was used to initiate the overlapped operation. It is the
    service provider's responsibility to arrange for this process context to
    be active prior to calling WPUQueueApc().

    WPUQueueApc() takes as input parameters a pointer to a WSATHREADID
    structure (supplied to the provider via the lpThreadId input parameter),
    a pointer to an APC function to be invoked, and a 32 bit context value
    that is subsequently passed to the APC function. Because only a single
    32-bit context value is available, the APC function cannot itself be the
    client-specified completion routine. The service provider must instead
    supply a pointer to its own APC function which uses the supplied context
    value to access the needed result information for the overlapped operation,
    and then invokes the client-specified completion routine.

    The prototype for the client-supplied completion routine is as follows:

        void
        CALLBACK
        CompletionRoutine(
            IN DWORD dwError,
            IN DWORD cbTransferred,
            IN LPWSAOVERLAPPED lpOverlapped,
            IN DWORD dwFlags
            );

        CompletionRoutine is a placeholder for a client supplied function
        name.

        dwError specifies the completion status for the overlapped
        operation as indicated by lpOverlapped.

        cbTransferred specifies the number of bytes sent.

        No flag values are currently defined and the dwFlags value will
        be zero.

        This routine does not return a value.

    The completion routines may be called in any order, not necessarily in
    the same order the overlapped operations are completed. However, the
    service provider guarantees to the client that posted buffers are sent
    in the same order they are supplied.

Arguments:

    s - A descriptor identifying a connected socket.

    lpBuffers - A pointer to an array of WSABUF structures. Each WSABUF
        structure contains a pointer to a buffer and the length of the
        buffer. This array must remain valid for the duration of the
        send operation.

    dwBufferCount - The number of WSABUF structures in the lpBuffers array.

    lpNumberOfBytesSent - A pointer to the number of bytes sent by this
        call.

    dwFlags - Specifies the way in which the call is made.

    lpOverlapped - A pointer to a WSAOVERLAPPED structure.

    lpCompletionRoutine - A pointer to the completion routine called when
        the send operation has been completed.

    lpThreadId - A pointer to a thread ID structure to be used by the
        provider in a subsequent call to WPUQueueApc(). The provider should
        store the referenced WSATHREADID structure (not the pointer to same)
        until after the WPUQueueApc() function returns.

    lpErrno - A pointer to the error code.

Return Value:

    If no error occurs and the send operation has completed immediately,
    WSPSend() returns 0. Note that in this case the completion routine, if
    specified, will have already been queued. Otherwise, a value of
    SOCKET_ERROR is returned, and a specific error code is available in
    lpErrno. The error code WSA_IO_PENDING indicates that the overlapped
    operation has been successfully initiated and that completion will be
    indicated at a later time. Any other error code indicates that no
    overlapped operation was initiated and no completion indication will
    occur.

--*/

{
    NTSTATUS status;
	PWINSOCK_TLS_DATA	tlsData;
    IO_STATUS_BLOCK localIoStatusBlock;
    PIO_STATUS_BLOCK ioStatusBlock;
    int err;
    AFD_SEND_INFO sendInfo;
    HANDLE event;
    PIO_APC_ROUTINE apcRoutine;
    PVOID apcContext;
    PSOCKET_INFORMATION socket = NULL;


    WS_ENTER( "WSPSend", (PVOID)Handle, (PVOID)lpBuffers, (PVOID)dwBufferCount, (PVOID)iFlags );

    WS_ASSERT( lpErrno != NULL );

    err = SockEnterApi( &tlsData );

    if( err != NO_ERROR ) {

        WS_EXIT( "WSPSend", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

#ifdef _AFD_SAN_SWITCH_
    if (SockSanEnabled) {
        socket = SockFindAndReferenceSocket( Handle, TRUE );

        if ( socket == NULL ) {
            err = WSAENOTSOCK;
            goto exit;
        }

        if (socket->SanSocket!=NULL) {
            err = SockSanSend (
                    socket,
                    lpBuffers,
                    dwBufferCount,
                    lpNumberOfBytesSent,
                    iFlags,
                    lpOverlapped,
                    lpCompletionRoutine,
                    lpThreadId->ThreadHandle);
            goto exit;
        }
    }
#endif //_AFD_SAN_SWITCH_

    //
    // Set up AFD_SEND_INFO.TdiFlags;
    //

    sendInfo.BufferArray = lpBuffers;
    sendInfo.BufferCount = dwBufferCount;
    sendInfo.AfdFlags = 0;
    sendInfo.TdiFlags = 0;

    if ( iFlags != 0 ) {

        //
        // The legal flags are MSG_OOB, MSG_DONTROUTE and MSG_PARTIAL.
        // MSG_OOB is not legal on datagram sockets.
        //

        if ( ( (iFlags & ~(MSG_OOB | MSG_DONTROUTE | MSG_PARTIAL)) != 0 ) ) {

            err = WSAEOPNOTSUPP;
            goto exit;

        }

        if ( (iFlags & MSG_OOB) != 0 ) {

            sendInfo.TdiFlags |= TDI_SEND_EXPEDITED;

        }

        if ( (iFlags & MSG_PARTIAL) != 0 ) {

            sendInfo.TdiFlags |= TDI_SEND_PARTIAL;

        }

    }

    __try {
        //
        // Determine the appropriate APC routine & context, event handle,
        // and IO status block to use for the request.
        //

        if( lpOverlapped == NULL ) {

            //
            // This a synchronous request, use per-thread event object.
            //

            apcRoutine = NULL;
            apcContext = NULL;

            event = tlsData->EventHandle;

            ioStatusBlock = &localIoStatusBlock;

        } else {

            if( lpCompletionRoutine == NULL ) {

                //
                // No APC, use event object from OVERLAPPED structure.
                //

                event = lpOverlapped->hEvent;

                apcRoutine = NULL;
                apcContext = ( (ULONG_PTR)event & 1 ) ? NULL : lpOverlapped;

            } else {

                //
                // APC, ignore event object.
                //

                event = NULL;

                apcRoutine = SockIoCompletion;
                apcContext = lpCompletionRoutine;

                //
                // Tell AFD to skip fast IO on this request.
                //

                sendInfo.AfdFlags |= AFD_NO_FAST_IO;

            }

            //
            // Use part of the OVERLAPPED structure as our IO_STATUS_BLOCK.
            //

            ioStatusBlock = (PIO_STATUS_BLOCK)&lpOverlapped->Internal;

            //
            // Tell AFD this is an overlapped operation.
            //

            sendInfo.AfdFlags |= AFD_OVERLAPPED;

        }

        ioStatusBlock->Status = STATUS_PENDING;


    }
    __except (SOCK_EXCEPTION_FILTER()) {
        err = WSAEFAULT;
        goto exit;
    }
    //
    // Send the data over the socket.
    //

    status = NtDeviceIoControlFile(
                 (HANDLE)Handle,
                 event,
                 apcRoutine,
                 apcContext,
                 ioStatusBlock,
                 IOCTL_AFD_SEND,
                 &sendInfo,
                 sizeof(sendInfo),
                 NULL,
                 0
                 );

    if ( apcRoutine != NULL  &&  !NT_ERROR(status) ) {

        tlsData->PendingAPCCount++;
        InterlockedIncrement( &SockProcessPendingAPCCount );
    }

    //
    // If this request has no overlapped structure, then wait for
    // the operation to complete.
    //

    if ( status == STATUS_PENDING &&
         lpOverlapped == NULL ) {

        BOOL success;

        success = SockWaitForSingleObject(
                      event,
                      Handle,
                      SOCK_CONDITIONALLY_CALL_BLOCKING_HOOK,
                      SOCK_SEND_TIMEOUT
                      );

        //
        // If the wait completed successfully, look in the IO status
        // block to determine the real status code of the request.  If
        // the wait timed out, then cancel the IO and set up for an
        // error return.
        //

        if ( success ) {

            status = ioStatusBlock->Status;

        } else {

            SockCancelIo( Handle );
            status = STATUS_IO_TIMEOUT;
        }

    }

    switch (status) {
    case STATUS_SUCCESS:
        break;

    case STATUS_PENDING:
        err = WSA_IO_PENDING;
        goto exit;

    default:
        if (!NT_SUCCESS(status) ) {
            //
            // Map the NTSTATUS to a WinSock error code.
            //

            err = SockNtStatusToSocketError( status );
            goto exit;
        }
    }

    //
    // The request completed immediately, so return the number of
    // bytes sent to the user.
    // It is possible that application deallocated lpOverlapped 
    // in another thread if completion port was used to receive
    // completion indication. We do not want to confuse the
    // application by returning failure, just pretend that we didn't
    // know about synchronous completion
    //

    __try {
        *lpNumberOfBytesSent = (DWORD)ioStatusBlock->Information;
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        if (lpOverlapped) {
            err = WSA_IO_PENDING;
        }
        else {
            err = WSAEFAULT;
        }
        goto exit;
    }

exit:

    IF_DEBUG(SEND) {

        if ( err != NO_ERROR ) {

            WS_PRINT(( "WSPSend on socket %lx failed: %ld.\n",
                           Handle, err ));

        } else {

#ifdef _AFD_SAN_SWITCH_
            WS_PRINT(( "WSPSend on socket %lx succeeded, "
                       "bytes = %ld\n", Handle, *lpNumberOfBytesSent ));
#else
            WS_PRINT(( "WSPSend on socket %lx succeeded, "
                       "bytes = %ld\n", Handle, ioStatusBlock->Information ));
#endif //_AFD_SAN_SWITCH_

        }

    }

    //
    // If there is an async thread in this process, get a pointer to the
    // socket information structure and reenable the appropriate event.
    // We don't do this if there is no async thread as a performance
    // optimization.  Also, if we're not going to return WSAEWOULDBLOCK
    // we don't need to reenable FD_WRITE events.
    //

    if ( SockAsyncSelectCalled && err == WSAEWOULDBLOCK ) {
#ifdef _AFD_SAN_SWITCH_
        if (socket==NULL) {
            socket = SockFindAndReferenceSocket( Handle, TRUE );
        }
#else //_AFD_SAN_SWITCH_
        socket = SockFindAndReferenceSocket( Handle, TRUE );
#endif //_AFD_SAN_SWITCH_

        //
        // If the socket was found reenable the right event.  If it was
        // not found, then presumably the socket handle was invalid.
        //

        if ( socket != NULL ) {

            SockAcquireSocketLockExclusive( socket );
            SockReenableAsyncSelectEvent( socket, FD_WRITE );
            SockReleaseSocketLock( socket );

            SockDereferenceSocket( socket );

        } else {

            if ( socket == NULL ) {

                WS_PRINT(( "WSPSend: SockFindAndReferenceSocket failed.\n" ));

            }

        }

    }
#ifdef _AFD_SAN_SWITCH_
    else {
        if (socket!=NULL) {
            SockDereferenceSocket( socket );
        }
    }
#endif //_AFD_SAN_SWITCH_

    if ( err != NO_ERROR ) {

        WS_EXIT( "WSPSend", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    WS_EXIT( "WSPSend", 0, FALSE );
    return 0;

}   // WSPSend
Example #9
0
void   ws_file_win32::Flush(void)
{
    WS_ASSERT(0);
}
Example #10
0
void   ws_file_win32::Write(const void * const buf, const ws_int cb)
{
    WS_ASSERT(0);
}
Example #11
0
SOCKET
WSPAPI
WSPAccept(
    IN SOCKET Handle,
    OUT struct sockaddr *SocketAddress,
    OUT int *SocketAddressLength,
    IN LPCONDITIONPROC lpfnCondition,
    IN DWORD dwCallbackData,
    OUT LPINT lpErrno
    )


/*++

Routine Description:

    This routine extracts the first connection on the queue of pending
    connections on s, and checks it against the condition function, provided
    the condition function is specified (i.e., not NULL). The condition
    function must be executed in the same thread as this routine is. If the
    condition function returns CF_ACCEPT, this routine creates a new socket
    and performs any socket grouping as indicated by the result parameter g
    in the condition function . Newly created sockets have the same
    properties as s including network events registered with WSPAsyncSelect()
    or with WSPEventSelect(), but not including the listening socket's group
    ID, if any.

    If the condition function returns CF_REJECT, this routine rejects the
    connection request. If the client's accept/reject decision cannot be made
    immediately, the condition function will return CF_DEFER to indicate that
    no decision has been made, and no action about this connection request is
    to be taken by the service provider. When the client is ready to take
    action on the connection request, it will invoke WSPAccept() again and
    return either CF_ACCEPT or CF_REJECT as a return value from the condition
    function.

    For sockets which are in the (default) blocking mode, if no pending
    connections are present on the queue, WSPAccept() blocks the caller until
    a connection is present. For sockets in a non-blocking mode, if this
    function is called when no pending connections are present on the queue,
    WSPAccept() returns the error code WSAEWOULDBLOCK as described below. The
    accepted socket may not be used to accept more connections. The original
    socket remains open.

    The argument addr is a result parameter that is filled in with the address
    of the connecting entity, as known to the service provider. The exact
    format of the addr parameter is determined by the address family in which
    the communication is occurring. The addrlen is a value-result parameter;
    it will initially contain the amount of space pointed to by addr. On
    return, it must contain the actual length (in bytes) of the address
    returned by the service provider. This call is used with connection-
    oriented socket types such as SOCK_STREAM. If addr and/or addrlen are
    equal to NULL, then no information about the remote address of the
    accepted socket is returned. Otherwise, these two parameters shall be
    filled in regardless of whether the condition function is specified or
    what it returns.

    The prototype of the condition function is as follows:

        int
        CALLBACK
        ConditionFunc(
            IN LPWSABUF lpCallerId,
            IN LPWSABUF lpCallerData,
            IN OUT LPQOS lpSQOS,
            IN OUT LPQOS lpGQOS,
            IN LPWSABUF lpCalleeId,
            IN LPWSABUF lpCalleeData,
            OUT GROUP FAR * g,
            IN DWORD dwCallbackData
            );

        The lpCallerId and lpCallerData are value parameters which must
        contain the address of the connecting entity and any user data
        that was sent along with the connection request, respectively.
        If no caller ID or caller data is available, the corresponding
        parameter will be NULL.

        lpSQOS references the flow specs for socket s specified by the
        caller, one for each direction, followed by any additional
        provider-specific parameters. The sending or receiving flow spec
        values will be ignored as appropriate for any unidirectional
        sockets. A NULL value for lpSQOS indicates no caller supplied
        QOS. QOS information may be returned if a QOS negotiation is to
        occur.

        lpGQOS references the flow specs for the socket group the caller
        is to create, one for each direction, followed by any additional
        provider-specific parameters. A NULL value for lpGQOS indicates
        no caller-supplied group QOS. QOS information may be returned if
        a QOS negotiation is to occur.

        The lpCalleeId is a value parameter which contains the local
        address of the connected entity. The lpCalleeData is a result
        parameter used by the condition function to supply user data back
        to the connecting entity. The storage for this data must be
        provided by the service provider. lpCalleeData->len initially
        contains the length of the buffer allocated by the service
        provider and pointed to by lpCalleeData->buf. A value of zero
        means passing user data back to the caller is not supported. The
        condition function will copy up to lpCalleeData->len  bytes of
        data into lpCalleeData->buf , and then update lpCalleeData->len
        to indicate the actual number of bytes transferred. If no user
        data is to be passed back to the caller, the condition function
        will set lpCalleeData->len to zero. The format of all address and
        user data is specific to the address family to which the socket
        belongs.

        The result parameter g is assigned within the condition function
        to indicate the following actions:

            if &g is an existing socket group ID, add s to this
            group, provided all the requirements set by this group
            are met; or

            if &g = SG_UNCONSTRAINED_GROUP, create an unconstrained
            socket group and have s as the first member; or

            if &g = SG_CONSTRAINED_GROUP, create a constrained
            socket group and have s as the first member; or

            if &g = zero, no group operation is performed.

        Any set of sockets grouped together must be implemented by a
        single service provider. For unconstrained groups, any set of
        sockets may be grouped together. A constrained socket group may
        consist only of connection-oriented sockets, and requires that
        connections on all grouped sockets be to the same address on the
        same host. For newly created socket groups, the new group ID
        must be available for the WinSock SPI client to retrieve by
        calling WSPGetSockOpt() with option SO_GROUP_ID. A socket group
        and its associated ID remain valid until the last socket
        belonging to this socket group is closed. Socket group IDs are
        unique across all processes for a given service provider.

        dwCallbackData is supplied to the condition function exactly as
        supplied by the caller of WSPAccept().

Arguments:

    s - A descriptor identifying a socket which is listening for connections
        after a WSPListen().

    addr - An optional pointer to a buffer which receives the address of the
        connecting entity, as known to the service provider. The exact
        format of the addr argument is determined by the address family
        established when the socket was created.

    addrlen - An optional pointer to an integer which contains the length of
        the address addr.

    lpfnCondition - The procedure instance address of an optional, WinSock 2
        client- supplied condition function which will make an accept/reject
        decision based on the caller information passed in as parameters,
        and optionally create and/or join a socket group by assigning an
        appropriate value to the result parameter, g, of this routine.

    dwCallbackData - Callback data to be passed back to the WinSock 2 client
        as a condition function parameter. This parameter is not interpreted
        by the service provider.

    lpErrno - A pointer to the error code.

Return Value:

    If no error occurs, WSPAccept() returns a value of type SOCKET which is
        a descriptor for the accepted socket. Otherwise, a value of
        INVALID_SOCKET is returned, and a specific error code is available
        in lpErrno.

--*/

{

    NTSTATUS status;
    PSOCKET_INFORMATION socketInfo;
    IO_STATUS_BLOCK ioStatusBlock;
    PAFD_LISTEN_RESPONSE_INFO afdListenResponse;
    ULONG afdListenResponseLength;
    AFD_ACCEPT_INFO afdAcceptInfo;
    int err;
    SOCKET newSocketHandle;
    PSOCKET_INFORMATION newSocket;
    INT socketAddressLength;
    WSAPROTOCOL_INFOW protocolInfo;
    GROUP newGroup;
    BYTE afdLocalListenResponse[MAX_FAST_LISTEN_RESPONSE];

    WS_ENTER( "WSPAccept", (PVOID)Handle, SocketAddress, (PVOID)SocketAddressLength, lpfnCondition );

    WS_ASSERT( lpErrno != NULL );

    IF_DEBUG(ACCEPT) {
        WS_PRINT(( "WSPAccept() on socket %lx addr %ld addrlen *%lx == %ld\n",
                       Handle, SocketAddress, SocketAddressLength,
                       SocketAddressLength ? *SocketAddressLength : 0 ));
    }

    err = SockEnterApi( TRUE, TRUE, FALSE );

    if( err != NO_ERROR ) {

        WS_EXIT( "WSPAccept", INVALID_SOCKET, TRUE );
        *lpErrno = err;
        return INVALID_SOCKET;

    }

    //
    // Set up local variables so that we know how to clean up on exit.
    //

    socketInfo = NULL;
    afdListenResponse = NULL;
    newSocket = NULL;
    newSocketHandle = INVALID_SOCKET;
    newGroup = 0;

    //
    // Find a pointer to the socket structure corresponding to the
    // passed-in handle.
    //

    socketInfo = SockFindAndReferenceSocket( Handle, TRUE );

    if ( socketInfo == NULL ) {

        err = WSAENOTSOCK;
        goto exit;

    }

    //
    // Acquire the lock that protects sockets.  We hold this lock
    // throughout this routine to synchronize against other callers
    // performing operations on the socket we're doing the accept on.
    //

    SockAcquireSocketLockExclusive( socketInfo );

    //
    // If this is a datagram socket, fail the request.
    //

    if ( IS_DGRAM_SOCK(socketInfo->SocketType) ) {

        err = WSAEOPNOTSUPP;
        goto exit;

    }

    //
    // If the socket is not listening for connection attempts, fail this
    // request.
    //

    if ( socketInfo->State != SocketStateListening ) {

        err = WSAEINVAL;
        goto exit;

    }

    //
    // Make sure that the length of the address buffer is large enough
    // to hold a sockaddr structure for the address family of this
    // socket.
    //

    if ( ARGUMENT_PRESENT( SocketAddressLength ) &&
             socketInfo->HelperDll->MinSockaddrLength > *SocketAddressLength ) {

        err = WSAEFAULT;
        goto exit;

    }

    //
    // Allocate space to hold the listen response structure.  This
    // buffer must be large enough to hold a TRANSPORT_STRUCTURE for the
    // address family of this socket.
    //

    afdListenResponseLength = sizeof(AFD_LISTEN_RESPONSE_INFO) -
                                  sizeof(TRANSPORT_ADDRESS) +
                                  socketInfo->HelperDll->MaxTdiAddressLength;

    if ( afdListenResponseLength <= sizeof(afdLocalListenResponse) ) {

        afdListenResponse = (PAFD_LISTEN_RESPONSE_INFO)afdLocalListenResponse;

    } else {

        afdListenResponse = ALLOCATE_HEAP( afdListenResponseLength );

        if ( afdListenResponse == NULL ) {

            err = WSAENOBUFS;
            goto exit;

        }

    }

    //
    // If the socket is non-blocking, determine whether data exists on
    // the socket.  If not, fail the request.
    //

    if ( socketInfo->NonBlocking ) {

        struct fd_set readfds;
        struct timeval timeout;
        int returnCode;

        FD_ZERO( &readfds );
        FD_SET( socketInfo->Handle, &readfds );
        timeout.tv_sec = 0;
        timeout.tv_usec = 0;

        returnCode = WSPSelect(
                         1,
                         &readfds,
                         NULL,
                         NULL,
                         &timeout,
                         lpErrno
                         );

        if ( returnCode == SOCKET_ERROR ) {

            err = *lpErrno;
            goto exit;

        }

        if ( !FD_ISSET( socketInfo->Handle, &readfds ) ) {

            WS_ASSERT( returnCode == 0 );
            err = WSAEWOULDBLOCK;
            goto exit;

        }

        WS_ASSERT( returnCode == 1 );

    }

    //
    // Wait for a connection attempt to arrive.
    //

    status = NtDeviceIoControlFile(
                 (HANDLE)socketInfo->Handle,
                 SockThreadEvent,
                 NULL,                   // APC Routine
                 NULL,                   // APC Context
                 &ioStatusBlock,
                 IOCTL_AFD_WAIT_FOR_LISTEN,
                 NULL,
                 0,
                 afdListenResponse,
                 afdListenResponseLength
                 );

    if ( status == STATUS_PENDING ) {

        SockReleaseSocketLock( socketInfo );
        SockWaitForSingleObject(
            SockThreadEvent,
            socketInfo->Handle,
            SOCK_CONDITIONALLY_CALL_BLOCKING_HOOK,
            SOCK_NO_TIMEOUT
            );
        SockAcquireSocketLockExclusive( socketInfo );
        status = ioStatusBlock.Status;

    }

    if ( !NT_SUCCESS(status) ) {

        err = SockNtStatusToSocketError( status );
        goto exit;

    }

    //
    // If a condition function was specified, then give the user the
    // opportunity to accept/reject the incoming connection.
    //

    if( lpfnCondition != NULL ) {

        WSABUF callerId;
        WSABUF callerData;
        WSABUF calleeId;
        WSABUF calleeData;
        INT result;
        BYTE fastAddressBuffer[sizeof(SOCKADDR_IN)];
        PBYTE addressBuffer;
        ULONG addressBufferLength;
        INT remoteAddressLength;
        BOOLEAN isValidGroup;
        PCHAR connectDataBuffer;
        INT connectDataBufferLength;

        //
        // Allocate space for the remote address.
        //

        addressBufferLength = socketInfo->HelperDll->MaxSockaddrLength;

        if( addressBufferLength <= sizeof(fastAddressBuffer) ) {

            addressBuffer = fastAddressBuffer;

        } else {

            addressBuffer = ALLOCATE_HEAP( addressBufferLength );

            if( addressBuffer == NULL ) {

                err = WSAENOBUFS;
                goto exit;

            }

        }

        connectDataBufferLength = 0;
        connectDataBuffer = NULL;

        if( ( socketInfo->ServiceFlags1 & XP1_CONNECT_DATA ) != 0 ) {

            AFD_UNACCEPTED_CONNECT_DATA_INFO connectInfo;

            //
            // Determine the size of the incoming connect data.
            //

            connectInfo.Sequence = afdListenResponse->Sequence;
            connectInfo.LengthOnly = TRUE;

            status = NtDeviceIoControlFile(
                         (HANDLE)socketInfo->Handle,
                         SockThreadEvent,
                         NULL,
                         NULL,
                         &ioStatusBlock,
                         IOCTL_AFD_GET_UNACCEPTED_CONNECT_DATA,
                         &connectInfo,
                         sizeof(connectInfo),
                         &connectInfo,
                         sizeof(connectInfo)
                         );

            if( status == STATUS_PENDING ) {

                SockWaitForSingleObject(
                    SockThreadEvent,
                    socketInfo->Handle,
                    SOCK_NEVER_CALL_BLOCKING_HOOK,
                    SOCK_NO_TIMEOUT
                    );

                status = ioStatusBlock.Status;

            }

            if( !NT_SUCCESS(status) ) {

                err = SockNtStatusToSocketError( status );
                goto exit;

            }

            //
            // If there is data on the connection, get it.
            //

            connectDataBufferLength = ioStatusBlock.Information;

            if( connectDataBufferLength > 0 ) {

                connectDataBuffer = ALLOCATE_HEAP( connectDataBufferLength );

                if( connectDataBuffer == NULL ) {

                    err = WSAENOBUFS;
                    goto exit;

                }

                //
                // Retrieve the data.
                //

                connectInfo.Sequence = afdListenResponse->Sequence;
                connectInfo.LengthOnly = FALSE;

                status = NtDeviceIoControlFile(
                             (HANDLE)socketInfo->Handle,
                             SockThreadEvent,
                             NULL,
                             NULL,
                             &ioStatusBlock,
                             IOCTL_AFD_GET_UNACCEPTED_CONNECT_DATA,
                             &connectInfo,
                             sizeof(connectInfo),
                             connectDataBuffer,
                             connectDataBufferLength
                             );

                if( status == STATUS_PENDING ) {

                    SockWaitForSingleObject(
                        SockThreadEvent,
                        socketInfo->Handle,
                        SOCK_NEVER_CALL_BLOCKING_HOOK,
                        SOCK_NO_TIMEOUT
                        );

                    status = ioStatusBlock.Status;

                }

                if( !NT_SUCCESS(status) ) {

                    err = SockNtStatusToSocketError( status );
                    FREE_HEAP( connectDataBuffer );
                    goto exit;

                }

            }

        }

        //
        // Build the addresses.
        //

        calleeId.buf = (CHAR *)socketInfo->LocalAddress;
        calleeId.len = (ULONG)socketInfo->LocalAddressLength;

        SockBuildSockaddr(
            (PSOCKADDR)addressBuffer,
            &remoteAddressLength,
            &afdListenResponse->RemoteAddress
            );

        callerId.buf = (CHAR *)addressBuffer;
        callerId.len = (ULONG)remoteAddressLength;

        //
        // Build the caller/callee data.
        //
        // Unfortunately, since we're "faking" this deferred accept
        // stuff (meaning that AFD has already fully accepted the
        // connection before the DLL ever sees it) there's no way
        // to support "callee data" in the condition function.
        //

        callerData.buf = connectDataBuffer;
        callerData.len = connectDataBufferLength;

        calleeData.buf = NULL;
        calleeData.len = 0;

        result = (lpfnCondition)(
                     &callerId,                 // lpCallerId
                     callerData.buf == NULL     // lpCallerData
                        ? NULL
                        : &callerData,
                     NULL,                      // lpSQOS
                     NULL,                      // lpGQOS
                     &calleeId,                 // lpCalleeId
                     calleeData.buf == NULL     // lpCalleeData
                        ? NULL
                        : &calleeData,
                     &newGroup,                 // g
                     dwCallbackData             // dwCallbackData
                     );

        //
        // Before we free the buffers, validate the group ID returned
        // by the condition function.
        //

        isValidGroup = TRUE;

        if( result == CF_ACCEPT &&
            newGroup != 0 &&
            newGroup != SG_UNCONSTRAINED_GROUP &&
            newGroup != SG_CONSTRAINED_GROUP ) {

            isValidGroup = SockIsAddressConsistentWithConstrainedGroup(
                               socketInfo,
                               newGroup,
                               (PSOCKADDR)addressBuffer,
                               remoteAddressLength
                               );

        }

        if( addressBuffer != fastAddressBuffer ) {

            FREE_HEAP( addressBuffer );

        }

        if( connectDataBuffer != NULL ) {

            FREE_HEAP( connectDataBuffer );

        }

        if( result == CF_ACCEPT ) {

            if( !isValidGroup ) {

                err = WSAEINVAL;
                goto exit;

            }

        } else {

            //
            // If the condition function returned any value other than
            // CF_ACCEPT, then we'll need to tell AFD to deal with this,
            // and we may also need to retry the wait for listen.
            //

            AFD_DEFER_ACCEPT_INFO deferAcceptInfo;

            if( result != CF_DEFER && result != CF_REJECT ) {

                err = WSAEINVAL;
                goto exit;

            }

            deferAcceptInfo.Sequence = afdListenResponse->Sequence;
            deferAcceptInfo.Reject = ( result == CF_REJECT );

            status = NtDeviceIoControlFile(
                         (HANDLE)socketInfo->Handle,
                         SockThreadEvent,
                         NULL,                   // APC Routine
                         NULL,                   // APC Context
                         &ioStatusBlock,
                         IOCTL_AFD_DEFER_ACCEPT,
                         &deferAcceptInfo,
                         sizeof(deferAcceptInfo),
                         NULL,
                         0
                         );

            //
            // IOCTL_AFD_DEFER_ACCEPT should never pend.
            //

            WS_ASSERT( status != STATUS_PENDING );

            if ( !NT_SUCCESS(status) ) {

                err = SockNtStatusToSocketError( status );
                goto exit;

            }

            //
            // The condition function returned either CF_REJECT or
            // CF_DEFER, so fail the WSPAccept() call with the
            // appropriate error code.
            //

            if( result == CF_REJECT ) {

                err = WSAECONNREFUSED;

            } else {

                WS_ASSERT( result == CF_DEFER );
                err = WSATRY_AGAIN;

            }

            goto exit;

        }

    }

    //
    // Create a new socket to use for the connection.
    //

    RtlZeroMemory( &protocolInfo, sizeof(protocolInfo) );

    protocolInfo.iAddressFamily = socketInfo->AddressFamily;
    protocolInfo.iSocketType = socketInfo->SocketType;
    protocolInfo.iProtocol = socketInfo->Protocol;
    protocolInfo.dwCatalogEntryId = socketInfo->CatalogEntryId;
    protocolInfo.dwServiceFlags1 = socketInfo->ServiceFlags1;
    protocolInfo.dwProviderFlags = socketInfo->ProviderFlags;

    newSocketHandle = WSPSocket(
                          socketInfo->AddressFamily,
                          socketInfo->SocketType,
                          socketInfo->Protocol,
                          &protocolInfo,
                          newGroup,
                          socketInfo->CreationFlags,
                          &err
                          );

    if ( newSocketHandle == INVALID_SOCKET ) {

        WS_ASSERT( err != NO_ERROR );
        goto exit;

    }

    //
    // Find a pointer to the new socket and reference the socket.
    //

    newSocket = SockFindAndReferenceSocket( newSocketHandle, FALSE );

    if( newSocket == NULL ) {

        //
        // Cannot find the newly created socket. This usually means the
        // app has closed a random socket handle that just happens to
        // be the one we just created.
        //

        err = WSAENOTSOCK;
        goto exit;

    }

    //
    // Set up to accept the connection attempt.
    //

    afdAcceptInfo.Sequence = afdListenResponse->Sequence;
    afdAcceptInfo.AcceptHandle = (HANDLE)newSocketHandle;

    //
    // Do the actual accept.  This associates the new socket we just
    // opened with the connection object that describes the VC that
    // was just initiated.
    //

    status = NtDeviceIoControlFile(
                 (HANDLE)socketInfo->Handle,
                 SockThreadEvent,
                 NULL,                   // APC Routine
                 NULL,                   // APC Context
                 &ioStatusBlock,
                 IOCTL_AFD_ACCEPT,
                 &afdAcceptInfo,
                 sizeof(afdAcceptInfo),
                 NULL,
                 0
                 );

    if ( status == STATUS_PENDING ) {

        SockReleaseSocketLock( socketInfo );
        SockWaitForSingleObject(
            SockThreadEvent,
            socketInfo->Handle,
            SOCK_CONDITIONALLY_CALL_BLOCKING_HOOK,
            SOCK_NO_TIMEOUT
            );
        SockAcquireSocketLockExclusive( socketInfo );
        status = ioStatusBlock.Status;

    }

    if ( !NT_SUCCESS(status) ) {

        err = SockNtStatusToSocketError( status );
        goto exit;

    }

    //
    // Notify the helper DLL that the socket has been accepted.
    //

    err = SockNotifyHelperDll( newSocket, WSH_NOTIFY_ACCEPT );

    if ( err != NO_ERROR ) {

        goto exit;

    }

    //
    // Remember the address of the remote client in the new socket,
    // and copy the local address of the newly created socket into
    // the new socket.
    //

    SockBuildSockaddr(
        newSocket->RemoteAddress,
        &socketAddressLength,
        &afdListenResponse->RemoteAddress
        );

    RtlCopyMemory(
        newSocket->LocalAddress,
        socketInfo->LocalAddress,
        socketInfo->LocalAddressLength
        );

    newSocket->LocalAddressLength = socketInfo->LocalAddressLength;

    //
    // Copy the remote address into the caller's address buffer, and
    // indicate the size of the remote address.
    //

    if ( ARGUMENT_PRESENT( SocketAddress ) &&
             ARGUMENT_PRESENT( SocketAddressLength ) ) {

        SockBuildSockaddr(
            SocketAddress,
            SocketAddressLength,
            &afdListenResponse->RemoteAddress
            );

    }

    //
    // Do the core operations in accepting the socket.
    //

    err = SockCoreAccept( socketInfo, newSocket );

    if ( err != NO_ERROR ) {

        goto exit;

    }

exit:

    IF_DEBUG(ACCEPT) {

        if ( err != NO_ERROR ) {

            WS_PRINT(( "    accept on socket %lx (%lx) failed: %ld\n",
                           Handle, socketInfo, err ));

        } else {

            WS_PRINT(( "    accept on socket %lx (%lx) returned socket "
                       "%lx (%lx), remote", Handle,
                       socketInfo, newSocketHandle, newSocket ));

            WsPrintSockaddr( newSocket->RemoteAddress, &newSocket->RemoteAddressLength );

        }

    }

    if ( socketInfo != NULL ) {

        if ( SockAsyncThreadInitialized ) {

            SockReenableAsyncSelectEvent( socketInfo, FD_ACCEPT );

        }

        SockReleaseSocketLock( socketInfo );
        SockDereferenceSocket( socketInfo );

    }

    if ( newSocket != NULL ) {

        SockDereferenceSocket( newSocket );

    }

    if ( afdListenResponse != (PAFD_LISTEN_RESPONSE_INFO)afdLocalListenResponse &&

        afdListenResponse != NULL ) {
        FREE_HEAP( afdListenResponse );

    }

    if ( err != NO_ERROR ) {

        if ( newSocketHandle != INVALID_SOCKET ) {

            int errTmp;

            WSPCloseSocket( newSocketHandle, &errTmp );

        }

        *lpErrno = err;
        return INVALID_SOCKET;

    }

    WS_EXIT( "accept", newSocketHandle, FALSE );
    return newSocketHandle;

} // WSPAccept
Example #12
0
int PASCAL
WSARecvEx (
    IN SOCKET Handle,
    IN char *Buffer,
    IN int BufferLength,
    IN OUT int *ReceiveFlags
    )

/*++

Routine Description:

    This is an extended API to allow better Windows Sockets support over
    message-based transports.  It is identical to recv() except that the
    ReceiveFlags parameter is an IN-OUT parameter that sets MSG_PARTIAL
    is the TDI provider returns STATUS_RECEIVE_PARTIAL,
    STATUS_RECEIVE_PARTIAL_EXPEDITED or STATUS_BUFFER_OVERFLOW.

Arguments:

    s - A descriptor identifying a connected socket.

    buf - A buffer for the incoming data.

    len - The length of buf.

    flags - Specifies the way in which the call is made.

Return Value:

    If no error occurs, recv() returns the number of bytes received.  If
    the connection has been closed, it returns 0.  Otherwise, a value of
    SOCKET_ERROR is returned, and a specific error code may be retrieved
    by calling WSAGetLastError().

--*/

{

    WSABUF wsaBuf;
    DWORD bytesRead;
    int result;

    //
    // Build a WSABUF describing the (single) recv buffer.
    //

    wsaBuf.len = BufferLength;
    wsaBuf.buf = Buffer;

    //
    // Setup.
    //

    *ReceiveFlags = 0;
    bytesRead = 0;

    //
    // Let WSARecv() do the dirty work.
    //

    result = WSARecv(
                 Handle,
                 &wsaBuf,
                 1,
                 &bytesRead,
                 ReceiveFlags,
                 NULL,
                 NULL
                 );

    if( result == 0 ) {

        //
        // Success.
        //

        result = (int)bytesRead;
        WS_ASSERT( result >= 0 );
        WS_ASSERT( result <= BufferLength );

    } else if( GetLastError() == WSAEMSGSIZE ) {

        //
        // Partial message received. The provider will return a
        // negative bytesRead length. Not anymore.
        //

        result = (int)bytesRead;
        *ReceiveFlags |= MSG_PARTIAL;
        WS_ASSERT( result >= 0 );
        WS_ASSERT( result <= BufferLength );

    }

    return result;

} // WSARecvEx
Example #13
0
char * PASCAL
inet_ntoa(
    IN  struct in_addr  in
    )

/*++

Routine Description:

    This function takes an Internet address structure specified by the
    in parameter.  It returns an ASCII string representing the address
    in ".'' notation as "a.b.c.d".  Note that the string returned by
    inet_ntoa() resides in memory which is allocated by the Windows
    Sockets implementation.  The application should not make any
    assumptions about the way in which the memory is allocated.  The
    data is guaranteed to be valid until the next Windows Sockets API
    call within the same thread, but no longer.

Arguments:

    in - A structure which represents an Internet host address.

Return Value:

    If no error occurs, inet_ntoa() returns a char pointer to a static
    buffer containing the text address in standard "." notation.
    Otherwise, it returns NULL.  The data should be copied before
    another Windows Sockets call is made.

--*/

{
    PUCHAR p;
    PUCHAR buffer;
    PUCHAR b;

    WS_ENTER( "inet_ntoa", (PVOID)in.s_addr, NULL, NULL, NULL );

    //
    // A number of applications apparently depend on calling inet_ntoa()
    // without first calling WSAStartup(). Because of this, we must perform
    // our own explicit thread initialization check here.
    //

    if( GET_THREAD_DATA() == NULL ) {

        if( !SockThreadInitialize() ) {

            SetLastError( WSAENOBUFS );
            WS_EXIT( "inet_ntoa", (INT)NULL, TRUE );
            return NULL;

        }

    }

    WS_ASSERT( GET_THREAD_DATA() != NULL );

    buffer = INTOA_Buffer;
    b = buffer;

    //
    // In an unrolled loop, calculate the string value for each of the four
    // bytes in an IP address.  Note that for values less than 100 we will
    // do one or two extra assignments, but we save a test/jump with this
    // algorithm.
    //

    p = (PUCHAR)&in;

    *b = NToACharStrings[*p][0];
    *(b+1) = NToACharStrings[*p][1];
    *(b+2) = NToACharStrings[*p][2];
    b += NToACharStrings[*p][3];
    *b++ = '.';

    p++;
    *b = NToACharStrings[*p][0];
    *(b+1) = NToACharStrings[*p][1];
    *(b+2) = NToACharStrings[*p][2];
    b += NToACharStrings[*p][3];
    *b++ = '.';

    p++;
    *b = NToACharStrings[*p][0];
    *(b+1) = NToACharStrings[*p][1];
    *(b+2) = NToACharStrings[*p][2];
    b += NToACharStrings[*p][3];
    *b++ = '.';

    p++;
    *b = NToACharStrings[*p][0];
    *(b+1) = NToACharStrings[*p][1];
    *(b+2) = NToACharStrings[*p][2];
    b += NToACharStrings[*p][3];
    *b = '\0';

    WS_EXIT( "inet_ntoa", (INT)INTOA_Buffer, FALSE );
    return(buffer);
}
Example #14
0
int
WSPAPI
WSPSendDisconnect (
    SOCKET Handle,
    LPWSABUF lpOutboundDisconnectData,
    LPINT lpErrno
    )

/*++

Routine Description:

    This routine is used on connection-oriented sockets to disable
    transmission, and to initiate termination of the connection along with the
    transmission of disconnect data, if any.

    After this routine has been successfully issued, subsequent sends are
    disallowed.

    lpOutboundDisconnectData, if not NULL, points to a buffer containing the
    outgoing disconnect data to be sent to the remote party.

    Note that WSPSendDisconnect() does not close the socket, and resources
    attached to the socket will not be freed until WSPCloseSocket() is invoked.

    WSPSendDisconnect() does not block regardless of the SO_LINGER setting on
    the socket.

    A WinSock SPI client should not rely on being able to re-use a socket after
    it has been WSPSendDisconnect()ed. In particular, a WinSock provider is not
    required to support the use of WSPConnect() on such a socket.

Arguments:

    s - A descriptor identifying a socket.

    lpOutboundDisconnectData - A pointer to the outgoing disconnect data.

    lpErrno - A pointer to the error code.

Return Value:

    If no error occurs, WSPSendDisconnect() returns 0. Otherwise, a value of
        SOCKET_ERROR is returned, and a specific error code is available in
        lpErrno.

--*/

{

    NTSTATUS status;
	PWINSOCK_TLS_DATA	tlsData;
    PSOCKET_INFORMATION socket;
    IO_STATUS_BLOCK ioStatusBlock;
    int err;
    AFD_PARTIAL_DISCONNECT_INFO disconnectInfo;

    WS_ENTER( "WSPSendDisconnect", (PVOID)Handle, (PVOID)lpOutboundDisconnectData, NULL, NULL );

    WS_ASSERT( lpErrno != NULL );

    err = SockEnterApi( &tlsData );

    if( err != NO_ERROR ) {

        WS_EXIT( "WSPSendDisconnect", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    //
    // Set up locals so that we know how to clean up on exit.
    //

    socket = NULL;

    //
    // Find a pointer to the socket structure corresponding to the
    // passed-in handle.
    //

    socket = SockFindAndReferenceSocket( Handle, TRUE );

    if ( socket == NULL ) {

        err = WSAENOTSOCK;
        goto exit;

    }

    //
    // Acquire the lock that protect this socket.
    //

    SockAcquireSocketLockExclusive( socket );

    //
    // If this is not a datagram socket, then it must be connected in order
    // for WSPSendDisconnect() to be a legal operation.
    //

    if ( !IS_DGRAM_SOCK(socket) &&
             !SockIsSocketConnected( socket ) ) {

        err = WSAENOTCONN;
        goto exit;

    }

#ifdef _AFD_SAN_SWITCH_
	//
	// Handle SAN disconnect first
	//
	if (SockSanEnabled && socket->SanSocket &&
		socket->SanSocket->IsConnected == CONNECTED) {

		socket->SendShutdown = TRUE;

		SockSanShutdown(socket, SD_SEND);

		goto exit;
	}
#endif //_AFD_SAN_SWITCH_

    //
    // Setup the disconnect info.
    //

    disconnectInfo.DisconnectMode = AFD_PARTIAL_DISCONNECT_SEND;
    disconnectInfo.Timeout = RtlConvertLongToLargeInteger( -1 );

    // !!! temporary HACK for tp4!

    if( socket->AddressFamily == AF_OSI ) {

        disconnectInfo.DisconnectMode = AFD_ABORTIVE_DISCONNECT;

    }

    __try {
        if( lpOutboundDisconnectData != NULL &&
            lpOutboundDisconnectData->buf != NULL &&
            lpOutboundDisconnectData->len > 0 ) {

            INT bufferLength;

            //
            // Set the disconnect data on the socket.
            //

            bufferLength = (INT)lpOutboundDisconnectData->len;

            err = SockSetConnectData(
                      socket,
                      IOCTL_AFD_SET_DISCONNECT_DATA,
                      (PCHAR)lpOutboundDisconnectData->buf,
                      bufferLength,
                      &bufferLength
                      );

            if( err != NO_ERROR ) {

                goto exit;

            }

        }
    }
    __except (SOCK_EXCEPTION_FILTER()) {
        err = WSAEFAULT;
        goto exit;
    }

    //
    // Note in the socket state that sends are shutdown.
    //

    socket->SendShutdown = TRUE;

    IF_DEBUG(SHUTDOWN) {

        WS_PRINT(( "starting WSPSendDisconnect for socket %lx\n", Handle ));

    }

    //
    // Send the IOCTL to AFD for processing.
    //

    status = NtDeviceIoControlFile(
                 socket->HContext.Handle,
                 tlsData->EventHandle,
                 NULL,                      // APC Routine
                 NULL,                      // APC Context
                 &ioStatusBlock,
                 IOCTL_AFD_PARTIAL_DISCONNECT,
                 &disconnectInfo,
                 sizeof(disconnectInfo),
                 NULL,                      // OutputBuffer
                 0L                         // OutputBufferLength
                 );

    if ( status == STATUS_PENDING ) {

        SockReleaseSocketLock( socket );
        SockWaitForSingleObject(
            tlsData->EventHandle,
            Handle,
            SOCK_NEVER_CALL_BLOCKING_HOOK,
            SOCK_NO_TIMEOUT
            );
        SockAcquireSocketLockExclusive( socket );
        status = ioStatusBlock.Status;

    }

    if ( !NT_SUCCESS(status) ) {

        err = SockNtStatusToSocketError( status );
        goto exit;

    }

    //
    // Notify the helper DLL that the socket has been shut down.
    //

    err = SockNotifyHelperDll( socket, WSH_NOTIFY_SHUTDOWN_SEND );

    if ( err != NO_ERROR ) {

        goto exit;

    }

exit:

    IF_DEBUG(SHUTDOWN) {

        if ( err != NO_ERROR ) {

            WS_PRINT(( "WSPSendDisconnect() on socket %lx (%lx) failed: %ld.\n",
                           Handle, socket, err ));

        } else {

            WS_PRINT(( "WSPSendDisconnect() on socket %lx (%lx) succeeded.\n",
                           Handle, socket ));

        }

    }

    if ( socket != NULL ) {

        SockReleaseSocketLock( socket );
        SockDereferenceSocket( socket );

    }

    if ( err != NO_ERROR ) {

        WS_EXIT( "WSPSendDisconnect", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    WS_EXIT( "WSPSendDisconnect", NO_ERROR, FALSE );
    return NO_ERROR;

}   // WSPSendDisconnect
Example #15
0
int
WSPAPI
WSPShutdown(
    IN SOCKET Handle,
    IN int HowTo,
    OUT LPINT lpErrno
    )

/*++

Routine Description:

    This routine is used on all types of sockets to disable reception,
    transmission, or both.

    If how is SD_RECEIVE, subsequent receives on the socket will be
    disallowed. This has no effect on the lower protocol layers. For TCP
    sockets, if there is still data queued on the socket waiting to be
    received, or data arrives subsequently, the connection is reset, since the
    data cannot be delivered to the user. For UDP sockets, incoming datagrams
    are accepted and queued. In no case will an ICMP error packet
    be generated.

    If how is SD_SEND, subsequent sends on the socket are disallowed. For TCP
    sockets, a FIN will be sent. Setting how to SD_BOTH disables both sends
    and receives as described above.

    Note that WSPShutdown() does not close the socket, and resources attached
    to the socket will not be freed until WSPCloseSocket() is invoked.

    WSPShutdown() does not block regardless of the SO_LINGER setting on the
    socket. A WinSock SPI client should not rely on being able to re-use a
    socket after it has been shut down. In particular, a WinSock service
    provider is not required to support the use of WSPConnect() on such a
    socket.

Arguments:

    s - A descriptor identifying a socket.

    how - A flag that describes what types of operation will no longer be
        allowed.

    lpErrno - A pointer to the error code.

Return Value:

    If no error occurs, WSPShutdown() returns 0. Otherwise, a value of
        SOCKET_ERROR is returned, and a specific error code is available
        in lpErrno.

--*/

{

    NTSTATUS status;
	PWINSOCK_TLS_DATA	tlsData;
    PSOCKET_INFORMATION socket;
    IO_STATUS_BLOCK ioStatusBlock;
    int err;
    AFD_PARTIAL_DISCONNECT_INFO disconnectInfo;
    DWORD notificationEvent;

    WS_ENTER( "WSPShutdown", (PVOID)Handle, (PVOID)HowTo, NULL, NULL );

    WS_ASSERT( lpErrno != NULL );

    err = SockEnterApi( &tlsData );

    if( err != NO_ERROR ) {

        WS_EXIT( "WSPShutdown", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    //
    // Set up locals so that we know how to clean up on exit.
    //

    socket = NULL;

    //
    // Find a pointer to the socket structure corresponding to the
    // passed-in handle.
    //

    socket = SockFindAndReferenceSocket( Handle, TRUE );

    if ( socket == NULL ) {

        err = WSAENOTSOCK;
        goto exit;

    }

    //
    // Acquire the lock that protect this socket.
    //

    SockAcquireSocketLockExclusive( socket );

    //
    // If this is not a datagram socket, then it must be connected in order
    // for WSPShutdown() to be a legal operation.
    //

    if ( !IS_DGRAM_SOCK(socket) &&
             !SockIsSocketConnected( socket ) ) {

        err = WSAENOTCONN;
        goto exit;

    }

    //
    // Translate the How parameter into the AFD disconnect information
    // structure.
    //

    switch ( HowTo ) {

    case SD_RECEIVE:

        disconnectInfo.DisconnectMode = AFD_PARTIAL_DISCONNECT_RECEIVE;
        socket->ReceiveShutdown = TRUE;
        notificationEvent = WSH_NOTIFY_SHUTDOWN_RECEIVE;
        break;

    case SD_SEND:

        disconnectInfo.DisconnectMode = AFD_PARTIAL_DISCONNECT_SEND;
        socket->SendShutdown = TRUE;
        notificationEvent = WSH_NOTIFY_SHUTDOWN_SEND;
        break;

    case SD_BOTH:

        disconnectInfo.DisconnectMode =
            AFD_PARTIAL_DISCONNECT_RECEIVE | AFD_PARTIAL_DISCONNECT_SEND;
        socket->ReceiveShutdown = TRUE;
        socket->SendShutdown = TRUE;
        notificationEvent = WSH_NOTIFY_SHUTDOWN_ALL;
        break;

    default:

        err = WSAEINVAL;
        goto exit;

    }


#ifdef _AFD_SAN_SWITCH_
	//
	// If we have a SAN socket open, close that first
	//
	if (SockSanEnabled && socket->SanSocket &&
		socket->SanSocket->IsConnected == CONNECTED) {

		err = SockSanShutdown(socket, HowTo);
		
		goto exit;
	}
#endif //_AFD_SAN_SWITCH_


    // !!! temporary HACK for tp4!

    if ( (HowTo == 1 || HowTo == 2) && socket->AddressFamily == AF_OSI ) {

        disconnectInfo.DisconnectMode = AFD_ABORTIVE_DISCONNECT;

    }

    //
    // This routine should complete immediately, not when the remote client
    // acknowledges the disconnect.
    //

    disconnectInfo.Timeout = RtlConvertLongToLargeInteger( -1 );

    IF_DEBUG(CLOSE) {

        WS_PRINT(( "starting WSPShutdown for socket %lx\n", Handle ));

    }

    //
    // Send the IOCTL to AFD for processing.
    //

    status = NtDeviceIoControlFile(
                 socket->HContext.Handle,
                 tlsData->EventHandle,
                 NULL,                      // APC Routine
                 NULL,                      // APC Context
                 &ioStatusBlock,
                 IOCTL_AFD_PARTIAL_DISCONNECT,
                 &disconnectInfo,
                 sizeof(disconnectInfo),
                 NULL,                      // OutputBuffer
                 0L                         // OutputBufferLength
                 );

    if ( status == STATUS_PENDING ) {

        SockReleaseSocketLock( socket );
        SockWaitForSingleObject(
            tlsData->EventHandle,
            Handle,
            SOCK_NEVER_CALL_BLOCKING_HOOK,
            SOCK_NO_TIMEOUT
            );
        SockAcquireSocketLockExclusive( socket );
        status = ioStatusBlock.Status;

    }

    if ( !NT_SUCCESS(status) ) {

        err = SockNtStatusToSocketError( status );
        goto exit;

    }

    //
    // Notify the helper DLL that the socket has been shut down.
    //

    err = SockNotifyHelperDll( socket, notificationEvent );

    if ( err != NO_ERROR ) {

        goto exit;

    }

exit:

    IF_DEBUG(SHUTDOWN) {

        if ( err != NO_ERROR ) {

            WS_PRINT(( "WSPShutdown(%ld) on socket %lx (%lx) failed: %ld.\n",
                           HowTo, Handle, socket, err ));

        } else {

            WS_PRINT(( "WSPShutdown(%ld) on socket %lx (%lx) succeeded.\n",
                           HowTo, Handle, socket ));

        }

    }

    if ( socket != NULL ) {

        SockReleaseSocketLock( socket );
        SockDereferenceSocket( socket );

    }

    if ( err != NO_ERROR ) {

        WS_EXIT( "WSPShutdown", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    WS_EXIT( "WSPShutdown", NO_ERROR, FALSE );
    return NO_ERROR;

}   // WSPShutdown
Example #16
0
int
WSPAPI
WSPBind(
    IN SOCKET Handle,
    IN const struct sockaddr *SocketAddress,
    IN int SocketAddressLength,
    OUT LPINT lpErrno
    )

/*++

Routine Description:

    This routine is used on an unconnected datagram or stream socket,
    before subsequent connect()s or listen()s.  When a socket is created
    with socket(), it exists in a name space (address family), but it
    has no name assigned.  bind() establishes the local association
    (host address/port number) of the socket by assigning a local name
    to an unnamed socket.

    If an application does not care what address is assigned to it, it
    may specify an Internet address and port equal to 0.  If this is the
    case, the Windows Sockets implementation will assign a unique
    address to the application.  The application may use getsockname()
    after bind() to learn the address that has been assigned to it.

    In the Internet address family, a name consists of several
    components.  For SOCK_DGRAM and SOCK_STREAM, the name consists of
    three parts: a host address, the protocol number (set implicitly to
    UDP or TCP, respectively), and a port number which identifies the
    application. The port is ignored for SOCK_RAW.

Arguments:

    s - A descriptor identifying an unbound socket.

    name - The address to assign to the socket.  The sockaddr structure
       is defined as follows:

              struct sockaddr {
                   u_short   sa_family;
                   char sa_data[14];
              };

    namelen - The length of the name.

Return Value:

--*/

{
    NTSTATUS status;
    PSOCKET_INFORMATION socket;
    IO_STATUS_BLOCK ioStatusBlock;
    PTRANSPORT_ADDRESS tdiAddress;
    ULONG tdiAddressLength;
    int err;
    PVOID reuseAddressBuffer;
    ULONG reuseAddressLength;
    SOCKADDR_INFO sockaddrInfo;

    WS_ENTER( "WSPBind", (PVOID)Handle, (PVOID)SocketAddress, (PVOID)SocketAddressLength, lpErrno );

    WS_ASSERT( lpErrno != NULL );

    IF_DEBUG(BIND) {

        WS_PRINT(( "WSPBind() on socket %lx addr %lx addrlen %ld\n"
                   "    req",
                       Handle, SocketAddress, SocketAddressLength ));

        WsPrintSockaddr( (PSOCKADDR)SocketAddress, &SocketAddressLength );

    }

    err = SockEnterApi( TRUE, TRUE, FALSE );

    if( err != NO_ERROR ) {

        WS_EXIT( "WSPBind", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    //
    // Set up local variables so that we know how to clean up on exit.
    //

    socket = NULL;
    tdiAddress = NULL;

    //
    // Find a pointer to the socket structure corresponding to the
    // passed-in handle.
    //

    socket = SockFindAndReferenceSocket( Handle, TRUE );

    if ( socket == NULL ) {

        err = WSAENOTSOCK;
        goto exit;

    }

    //
    // Acquire the lock that protects sockets.  We hold this lock
    // throughout this routine to synchronize against other callers
    // performing operations on the socket we're binding.
    //

    SockAcquireSocketLockExclusive( socket );

    //
    // If the socket has been initialized at all then this is not a
    // legal request.
    //

    if ( socket->State != SocketStateOpen ) {

        err = WSAEINVAL;
        goto exit;

    }

    //
    // If the buffer passed in is larger than needed for a socket address,
    // just truncate it.  Otherwise, the TDI address buffer we allocate
    // may not be large enough.
    //

    if ( SocketAddressLength > socket->HelperDll->MaxSockaddrLength ) {

        SocketAddressLength = socket->HelperDll->MaxSockaddrLength;

    }

    //
    // Make sure that the address structure passed in is legitimate,
    // and determine the type of address we're binding to.
    //

    err = socket->HelperDll->WSHGetSockaddrType(
                (PSOCKADDR)SocketAddress,
                SocketAddressLength,
                &sockaddrInfo
                );

    if ( err != NO_ERROR) {

        goto exit;

    }

    //
    // Hack?  If this is a wildcard address, and the caller set the
    // super secret "don't use wildcard" option, put non zero information
    // in the reserved field so that UDP knows that we really want to
    // bind to the zero address (0.0.0.0).
    //

    if ( socket->DontUseWildcard &&
         sockaddrInfo.AddressInfo == SockaddrAddressInfoWildcard ) {

        *(UNALIGNED ULONG *)(SocketAddress->sa_data + 6) = 0x12345678;

    }

    // !!! test for reserved port?

    //
    // Allocate enough space to hold the TDI address structure we'll pass
    // to AFD.
    //

    tdiAddressLength = socket->HelperDll->MaxTdiAddressLength;

    tdiAddress = ALLOCATE_HEAP( tdiAddressLength + 4 );

    if ( tdiAddress == NULL ) {

        err = WSAENOBUFS;
        goto exit;

    }

    //
    // Convert the address from the sockaddr structure to the appropriate
    // TDI structure.
    //

    SockBuildTdiAddress(
        tdiAddress,
        (PSOCKADDR)SocketAddress,
        SocketAddressLength
        );

    //
    // If this is not a wildcard address and the socket is not set up to
    // reuse addresses, indicate to AFD that this should be a unique address.
    //

    if ( sockaddrInfo.EndpointInfo != SockaddrEndpointInfoWildcard &&
             !socket->ReuseAddresses ) {

        reuseAddressBuffer = &reuseAddressLength;
        reuseAddressLength = sizeof(reuseAddressLength);

    } else {

        reuseAddressBuffer = NULL;
        reuseAddressLength = 0;

    }

    //
    // Call AFD to perform the actual bind operation.  AFD will open a
    // TDI address object through the proper TDI provider for this
    // socket.
    //

    status = NtDeviceIoControlFile(
                 (HANDLE)socket->Handle,
                 SockThreadEvent,
                 NULL,                   // APC Routine
                 NULL,                   // APC Context
                 &ioStatusBlock,
                 IOCTL_AFD_BIND,
                 tdiAddress,
                 tdiAddressLength,
                 reuseAddressBuffer,
                 reuseAddressLength
                 );

    if ( status == STATUS_PENDING ) {

        SockReleaseSocketLock( socket );
        SockWaitForSingleObject(
            SockThreadEvent,
            socket->Handle,
            SOCK_NEVER_CALL_BLOCKING_HOOK,
            SOCK_NO_TIMEOUT
            );
        SockAcquireSocketLockExclusive( socket );
        status = ioStatusBlock.Status;

    }

    if ( !NT_SUCCESS(status) ) {

        err = SockNtStatusToSocketError( status );
        goto exit;

    }

    //
    // Notify the helper DLL that the socket is now bound.
    //

    err = SockNotifyHelperDll( socket, WSH_NOTIFY_BIND );

    if ( err != NO_ERROR ) {

        goto exit;

    }

    //
    // Get the actual address we bound to.  It is possible on some
    // transports to partially specify an address, in which case the
    // transport will assign an address for use.  This IOCTL obtains the
    // real address for the endpoint.
    //

    status = NtDeviceIoControlFile(
                 (HANDLE)socket->Handle,
                 SockThreadEvent,
                 NULL,                   // APC Routine
                 NULL,                   // APC Context
                 &ioStatusBlock,
                 IOCTL_AFD_GET_ADDRESS,
                 NULL,
                 0,
                 tdiAddress,
                 tdiAddressLength + 4
                 );

    if ( status == STATUS_PENDING ) {

        SockReleaseSocketLock( socket );
        SockWaitForSingleObject(
            SockThreadEvent,
            socket->Handle,
            SOCK_NEVER_CALL_BLOCKING_HOOK,
            SOCK_NO_TIMEOUT
            );
        SockAcquireSocketLockExclusive( socket );
        status = ioStatusBlock.Status;

    }

    //
    // Convert the actual address that was bound to this socket to the
    // sockaddr format in order to store it.
    //

    if ( NT_SUCCESS(status) ) {

        SockBuildSockaddr(
            socket->LocalAddress,
            &SocketAddressLength,
            (PTRANSPORT_ADDRESS)( (PCHAR)tdiAddress + 4 )
            );

    } else {

        WS_PRINT((
            "IOCTL_AFD_GET_ADDRESS failed, status %08lx\n",
            status
            ));

    }

    //
    // Indicate that the socket is now bound to a specific address;
    //

    socket->State = SocketStateBound;

    //
    // Remember the changed state of this socket.
    //

    err = SockSetHandleContext( socket );

    if ( err != NO_ERROR ) {

        goto exit;

    }

    //
    // If the application changed the send or receive buffers and this
    // is a datagram socket, tell AFD about the new buffer sizes.
    //

    err = SockUpdateWindowSizes( socket, FALSE );

    if ( err != NO_ERROR ) {

        goto exit;

    }

exit:

    IF_DEBUG(BIND) {

        if ( err != NO_ERROR ) {

            WS_PRINT(( "WSPBind on socket %lx (%lx) failed: %ld\n",
                           Handle, socket, err ));

        } else {

            WS_PRINT(( "    WSPBind on socket %lx (%lx), granted",
                           Handle, socket ));
            WsPrintSockaddr( socket->LocalAddress, &socket->LocalAddressLength );

        }

    }

    //
    // Perform cleanup--dereference the socket if it was referenced,
    // free allocated resources.
    //

    if ( socket != NULL ) {

        SockReleaseSocketLock( socket );
        SockDereferenceSocket( socket );

    }

    if ( tdiAddress != NULL ) {

        FREE_HEAP( tdiAddress );

    }

    //
    // Return an error if appropriate.
    //

    if ( err != NO_ERROR ) {

        WS_EXIT( "WSPBind", SOCKET_ERROR, TRUE );
        *lpErrno = err;
        return SOCKET_ERROR;

    }

    WS_EXIT( "WSPBind", NO_ERROR, FALSE );
    return NO_ERROR;

} // WSPBind