ANSC_STATUS
AnscDstoEngage
    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS                     returnStatus = ANSC_STATUS_SUCCESS;
    PANSC_DAEMON_SERVER_TCP_OBJECT  pMyObject    = (PANSC_DAEMON_SERVER_TCP_OBJECT)hThisObject;
    PANSC_DSTO_WORKER_OBJECT        pWorker      = (PANSC_DSTO_WORKER_OBJECT      )pMyObject->hWorker;
    int                             s_result     = 0;
#ifdef _ANSC_IPV6_COMPATIBLE_
    ansc_addrinfo                   ansc_hints           = {0};
    ansc_addrinfo*                  pansc_local_addrinfo = NULL;
    xskt_addrinfo                   xskt_hints           = {0};
    xskt_addrinfo*                  pxskt_local_addrinfo = NULL;
    USHORT                          usPort               = 0;
    char                            port[6]              = {0};
#else
    /*RDKB-6151, CID-24487,24794; initializing variable before use*/
    ansc_socket_addr_in             local_addr1 = {0};
    xskt_socket_addr_in             local_addr2 = {0};
#endif

    if ( pMyObject->bActive )
    {
        return  ANSC_STATUS_SUCCESS;
    }
    else if ( !pWorker )
    {
        return  ANSC_STATUS_UNAPPLICABLE;
    }
    else
    {
        pWorker->Init(pWorker->hWorkerContext);

        pMyObject->StartTime = AnscGetTickInSecondsAbs();
        pMyObject->bActive   = TRUE;
    }

    /*
     * The underlying socket wrapper may require an explicit startup() call, such is the case on
     * Microsoft windows platforms. The wrapper initialization has to done for each task. On most
     * real-time operating systems, this call is not required.
     */
    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
        AnscStartupXsocketWrapper((ANSC_HANDLE)pMyObject);
    }
    else
    {
        AnscStartupSocketWrapper((ANSC_HANDLE)pMyObject);
    }
    
#ifdef _ANSC_IPV6_COMPATIBLE_

    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
        xskt_hints.ai_family   = AF_UNSPEC;
        xskt_hints.ai_socktype = XSKT_SOCKET_STREAM;
        xskt_hints.ai_flags    = AI_PASSIVE | AI_ADDRCONFIG;

        usPort = pMyObject->GetHostPort((ANSC_HANDLE)pMyObject);
        _ansc_sprintf(port, "%d", usPort);
        CcspTraceInfo(("!!! Host Name: %s, Host Port: %s !!!\n", pMyObject->HostName, port));

        if ( _xskt_getaddrinfo
                (
                    pMyObject->HostName[0] ? pMyObject->HostName : "::", 
                    port,
                    &xskt_hints,
                    &pxskt_local_addrinfo
                ) 
            )
        {
            CcspTraceError(("!!! error 1 !!!\n"));

            returnStatus = ANSC_STATUS_FAILURE;
            
            goto  EXIT1;
        }
        
        pMyObject->pHostAddr2 = pxskt_local_addrinfo;
    }
    else
    {
        ansc_hints.ai_family   = AF_UNSPEC;
        ansc_hints.ai_socktype = ANSC_SOCKET_STREAM;
        ansc_hints.ai_flags    = AI_PASSIVE | AI_ADDRCONFIG;

        usPort = pMyObject->GetHostPort((ANSC_HANDLE)pMyObject);
        _ansc_sprintf(port, "%d", usPort);
        CcspTraceInfo(("!!! Host Name: %s, Host Port: %s !!!\n", pMyObject->HostName, port));

        if ( _ansc_getaddrinfo
                (
                    pMyObject->HostName[0] ? pMyObject->HostName : "::",
                    port,
                    &ansc_hints,
                    &pansc_local_addrinfo
                ) 
            )
        {
            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT1;
        }
        
        pMyObject->pHostAddr1 = pansc_local_addrinfo;
    }

#endif

    /*
     * To engage the Tcp Daemon, we need to perform following acts in the respective order:
     *
     *      (1) create the os-dependent socket
     *      (2) manufacture and start all the engines objects
     *      (3) manufacture the global socket object pool
     *      (4) bind to the socket and listen on it
     */
    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        pMyObject->Socket = _xskt_socket(pxskt_local_addrinfo->ai_family, pxskt_local_addrinfo->ai_socktype, 0);
#else
        pMyObject->Socket = _xskt_socket(XSKT_SOCKET_AF_INET, XSKT_SOCKET_STREAM, 0);
#endif
    }
    else
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        pMyObject->Socket = _ansc_socket(pansc_local_addrinfo->ai_family, pansc_local_addrinfo->ai_socktype, 0);
#else
        pMyObject->Socket = _ansc_socket(ANSC_SOCKET_AF_INET, ANSC_SOCKET_STREAM, 0);
#endif
    }

    if ( ((pMyObject->Socket == XSKT_SOCKET_INVALID_SOCKET) &&  (pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET)) ||
         ((pMyObject->Socket == ANSC_SOCKET_INVALID_SOCKET) && !(pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET)) )
    {
        returnStatus = ANSC_STATUS_FAILURE;

        goto  EXIT1;
    }

    _ansc_en_reuseaddr(pMyObject->Socket);

#ifndef _ANSC_IPV6_COMPATIBLE_
    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
        local_addr2.sin_family = XSKT_SOCKET_AF_INET;
        local_addr2.sin_port   = _xskt_htons(pMyObject->HostPort);

        if ( pMyObject->HostAddress.Value == 0 )
        {
            ((pansc_socket_addr_in)&local_addr2)->sin_addr.s_addr = XSKT_SOCKET_ANY_ADDRESS;
        }
        else
        {
            ((pansc_socket_addr_in)&local_addr2)->sin_addr.s_addr = pMyObject->HostAddress.Value;
        }
    }
    else
    {
        local_addr1.sin_family = ANSC_SOCKET_AF_INET;
        local_addr1.sin_port   = _ansc_htons(pMyObject->HostPort);

        if ( pMyObject->HostAddress.Value == 0 )
        {
            local_addr1.sin_addr.s_addr = ANSC_SOCKET_ANY_ADDRESS;
        }
        else
        {
            local_addr1.sin_addr.s_addr = pMyObject->HostAddress.Value;
        }
    }
#endif

#if !defined(_ANSC_KERNEL) || !defined(_ANSC_LINUX)
    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        s_result = _xskt_bind(pMyObject->Socket, pxskt_local_addrinfo->ai_addr, pxskt_local_addrinfo->ai_addrlen);
#else
        AnscTrace("AnscDstoEngage -- the address is 0x%lX:%d, familty %d.\n", _ansc_ntohl(local_addr2.sin_addr.s_addr), _ansc_ntohs(local_addr2.sin_port), local_addr2.sin_family);
        s_result = _xskt_bind(pMyObject->Socket, (xskt_socket_addr*)&local_addr2, sizeof(local_addr2));
#endif
    }
    else
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        s_result = _ansc_bind(pMyObject->Socket, pansc_local_addrinfo->ai_addr, pansc_local_addrinfo->ai_addrlen);
#else
        s_result = _ansc_bind(pMyObject->Socket, (ansc_socket_addr*)&local_addr1, sizeof(local_addr1));
#endif
    }
#else
	if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
        while ( _xskt_bind(pMyObject->Socket, (ansc_socket_addr*)&local_addr2, sizeof(local_addr2)) != 0 )
        {
            AnscTrace
				(
					"AnscDstoEngage -- failure to bind try again !socket %d family %d port %d address %X \n",
					pMyObject->Socket,
					local_addr2.sin_family,
                    local_addr2.sin_port,
					((pansc_socket_addr_in)&local_addr2)->sin_addr.s_addr
				);

            AnscSleep(10);
        }
    }
    else
    {
        while ( _ansc_bind(pMyObject->Socket, (ansc_socket_addr*)&local_addr1, sizeof(local_addr1)) != 0 )
        {
            AnscTrace
				(
					"AnscDstoEngage -- failure to bind try again !socket %d family %d port %d address %X \n",
					pMyObject->Socket,
					local_addr1.sin_family,
                    local_addr1.sin_port,
					local_addr1.sin_addr.s_addr
				);

            AnscSleep(10);
        }
    }
#endif

    if ( s_result != 0 )
    {
		AnscTrace
            (
                "AnscDstoEngage -- failed to bind to the socket, error code is %d!!!\n",
                (pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET) ? _xskt_get_last_error() : _ansc_get_last_error()
            );

        returnStatus = ANSC_STATUS_FAILURE;

        goto  EXIT2;
    }

    pMyObject->ManufactureEnginePool((ANSC_HANDLE)pMyObject);
    pMyObject->ManufactureSocketPool((ANSC_HANDLE)pMyObject);
    pMyObject->StartEngines         ((ANSC_HANDLE)pMyObject);

    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
        s_result = _xskt_listen(pMyObject->Socket, ANSC_SOCKET_BACKLOG_VALUE);
    }
    else
    {
        s_result = _ansc_listen(pMyObject->Socket, ANSC_SOCKET_BACKLOG_VALUE);
    }

    if ( s_result != 0 )
    {
		AnscTrace("AnscDstoEngage -- failed to listen on the socket!\n");

        returnStatus = ANSC_STATUS_FAILURE;

        goto  EXIT2;
    }

    /*
     * If the compilation option '_ANSC_SOCKET_TLS_LAYER_' is enabled, we can simply let the ANSC
     * socket layer to perform the SSL/TLS functionality; otherwise, we need to prepare for doing
     * SSL/TLS internally.
     */
    if ( pMyObject->Mode & ANSC_DSTO_MODE_TLS_ENABLED )
    {
#ifdef _ANSC_USE_OPENSSL_
        pMyObject->bTlsEnabled = TRUE;
        if ( !openssl_init(SSL_SERVER_CALLS) )
        {
        	AnscTrace("AnscSctoEngage - openssl_init() failed!\n");
            returnStatus = ANSC_STATUS_FAILURE;
            goto  EXIT2;
        }

#else
        #ifdef  _ANSC_SOCKET_TLS_LAYER_
        {
            _ansc_en_usetls(pMyObject->Socket);

            pMyObject->bTlsEnabled = FALSE;
        }
        #else
        {
            pMyObject->hTlsScsIf   = (pMyObject->hTlsScsIf != NULL)? pMyObject->hTlsScsIf : AnscSocketTlsGetScsIf();
            pMyObject->bTlsEnabled = TRUE;
            pMyObject->bTlsReqCert = (pMyObject->Mode & ANSC_DSTO_MODE_TLS_REQ_CERT);
        }
        #endif
#endif
    }

    AnscResetEvent(&pMyObject->AcceptEvent);
    returnStatus =
        pMyObject->SpawnTask3
            (
                (ANSC_HANDLE)pMyObject,
                (void*      )pMyObject->AcceptTask,
                (ANSC_HANDLE)pMyObject,
                ANSC_DSTO_ACCEPT_TASK_NAME,
                USER_DEFAULT_TASK_PRIORITY,
                2*USER_DEFAULT_TASK_STACK_SIZE

            );

    return  ANSC_STATUS_SUCCESS;


    /******************************************************************
                GRACEFUL ROLLBACK PROCEDURES AND EXIT DOORS
    ******************************************************************/

EXIT2:

    if ( pMyObject->Mode & ANSC_DSTO_MODE_XSOCKET )
    {
        _xskt_closesocket(pMyObject->Socket);
    }
    else
    {
        _ansc_closesocket(pMyObject->Socket);
    }

EXIT1:

    if ( returnStatus != ANSC_STATUS_SUCCESS )
    {
        pMyObject->bActive = FALSE;
    }

    return  returnStatus;
}
ANSC_STATUS
AnscSctoEngage
    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS                     returnStatus = ANSC_STATUS_SUCCESS;
    PANSC_SIMPLE_CLIENT_TCP_OBJECT  pMyObject    = (PANSC_SIMPLE_CLIENT_TCP_OBJECT)hThisObject;
    PANSC_SCTO_WORKER_OBJECT        pWorker      = (PANSC_SCTO_WORKER_OBJECT      )pMyObject->hWorker;
    int                             s_error      = 0;
    ansc_socket_addr_in             ansc_client_addr;
    ansc_socket_addr_in             ansc_server_addr;
    xskt_socket_addr_in             xskt_client_addr;
    xskt_socket_addr_in             xskt_server_addr;

#ifdef _ANSC_IPV6_COMPATIBLE_
    ansc_addrinfo                   ansc_hints            = {0};
    ansc_addrinfo*                  pansc_server_addrinfo = NULL;
    ansc_addrinfo*                  pansc_client_addrinfo = NULL;
    xskt_addrinfo                   xskt_hints            = {0};
    xskt_addrinfo*                  pxskt_server_addrinfo = NULL;
    xskt_addrinfo*                  pxskt_client_addrinfo = NULL;
    USHORT                          usPort                = 0;
    char                            port[6] = {0};
#endif

    if ( pMyObject->bActive )
    {
        return  ANSC_STATUS_SUCCESS;
    }
    else if ( !pWorker )
    {
        return  ANSC_STATUS_UNAPPLICABLE;
    }
    else
    {
        /*
         * Just like any other socket-based ANSC object, we will create a separate async recv task
         * which is dedicated to receiving packets. This async recv task is controlled by 'bActive'
         * flag. What if at this moment right before we're about to enable the socket operation and
         * setting 'bActive' flag to TRUE, the old recv task created by the last call of Engage()
         * is still running? While it may not cause crash, but it certainly confuses the owner
         * object because all async recv tasks share the same worker interface. The most obvious
         * solution is to wait for previous recv task to exit before creating a new one.
         */
    	while ( pMyObject->EngineTaskCount != 0 )
        {
            AnscSleep(50);
        }

        pMyObject->bActive = TRUE;
        pMyObject->bClosed = FALSE;
    }

    /*
     * The underlying socket wrapper may require an explicit startup() call, such is the case on
     * Microsoft windows platforms. The wrapper initialization has to done for each task. On most
     * real-time operating systems, this call is not required.
     */
    if ( pMyObject->Mode & ANSC_SCTO_MODE_XSOCKET )
    {
        AnscStartupXsocketWrapper((ANSC_HANDLE)pMyObject);
    }
    else
    {
        AnscStartupSocketWrapper((ANSC_HANDLE)pMyObject);
    }

    #ifdef _ANSC_IPV6_COMPATIBLE_

    if ( pMyObject->Mode & ANSC_SCTO_MODE_XSOCKET )
    {
        xskt_hints.ai_family   = AF_UNSPEC;
        xskt_hints.ai_socktype = XSKT_SOCKET_STREAM;
        xskt_hints.ai_flags    = AI_CANONNAME;

        usPort = pMyObject->GetPeerPort((ANSC_HANDLE)pMyObject);
        _ansc_sprintf(port, "%d", usPort);

        AnscTrace("!!! Peer Port: %s !!!\n", port);

        char * pPeerName = pMyObject->GetPeerName((ANSC_HANDLE)pMyObject);

        AnscTrace("Peer Name: %s!!!\n", pPeerName);

/*
        struct addrinfo hints,*res=NULL;
	memset(&hints,0,sizeof(hints));
	hints.ai_family=PF_UNSPEC;
	hints.ai_socktype=SOCK_DGRAM;
	hints.ai_protocol=IPPROTO_UDP;
	s_error=getaddrinfo("127.0.0.1","123",&hints,&res);
*/
/*
         s_error = _xskt_getaddrinfo
                (
                    "10.74.52.92",
                    port,
                    &xskt_hints,
                    &pxskt_server_addrinfo
                );

        AnscTrace("!!!!!! _xskt_getaddrinfo returns: %d %s !!!\n", s_error, gai_strerror(s_error));
*/
        if ( _xskt_getaddrinfo
                (
                    pMyObject->GetPeerName((ANSC_HANDLE)pMyObject), 
                    port,
                    &xskt_hints,
                    &pxskt_server_addrinfo
                ) ||
             _xskt_getaddrinfo
                (
                    "localhost", 
                    NULL,
                    &xskt_hints,
                    &pxskt_client_addrinfo
                )

            )
        {
            AnscTrace("!!! error 1 !!!\n");

            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	            	(
            		    pWorker->hWorkerContext,
            		    ANSC_SCTOWO_EVENT_SOCKET_ERROR,
            		    (ANSC_HANDLE)NULL
            		);
            }

            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT1;
        }

        AnscTrace("!!! after getaddrinfo !!!\n");
    }
    else
    {
        ansc_hints.ai_family   = AF_UNSPEC;
        ansc_hints.ai_socktype = ANSC_SOCKET_STREAM;
        ansc_hints.ai_flags    = AI_CANONNAME;

        usPort = pMyObject->GetPeerPort((ANSC_HANDLE)pMyObject);
        _ansc_sprintf(port, "%d", usPort);

        if ( _ansc_getaddrinfo
                (
                    pMyObject->GetPeerName((ANSC_HANDLE)pMyObject), 
                    port,
                    &ansc_hints,
                    &pansc_server_addrinfo
                ) ||
             _ansc_getaddrinfo
                (
                    "localhost", 
                    NULL,
                    &ansc_hints,
                    &pansc_client_addrinfo
                )
            )
        {
            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	            	(
            		    pWorker->hWorkerContext,
		                ANSC_SCTOWO_EVENT_SOCKET_ERROR,
            	        (ANSC_HANDLE)NULL
	                );
            }

            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT1;
        }
    }

#endif

    /*
     * To engage the Tcp Client, we need to perform following acts in the respective order:
     *
     *      (1) create the os-dependent socket
     *      (2) bind to the newly socket
     *      (3) connect to the specified  server address
     *      (4) allocate a buffer for receiving
     *      (5) spawn a separate thread and start receiving
     */
    if ( pMyObject->Mode & ANSC_SCTO_MODE_XSOCKET )
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        pMyObject->Socket = (ANSC_SOCKET)_xskt_socket(pxskt_server_addrinfo->ai_family, pxskt_server_addrinfo->ai_socktype, 0);
#else
        pMyObject->Socket = (ANSC_SOCKET)_xskt_socket(XSKT_SOCKET_AF_INET, XSKT_SOCKET_STREAM, 0);
#endif

        if ( (XSKT_SOCKET)pMyObject->Socket == XSKT_SOCKET_INVALID_SOCKET )
        {
            AnscTrace("!!!!!!!!!! _xskt_socket error !!!!!!!!!!\n");
            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	    			(
		    			pWorker->hWorkerContext,
			    		ANSC_SCTOWO_EVENT_SOCKET_ERROR,
				    	(ANSC_HANDLE)NULL
    				);
            }

            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT1;
        }
        else  AnscTrace("Opening IPv4 socket Ok\n");
    }
    else
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        pMyObject->Socket = _ansc_socket(pansc_server_addrinfo->ai_family, pansc_server_addrinfo->ai_socktype, 0);
#else
        pMyObject->Socket = _ansc_socket(ANSC_SOCKET_AF_INET, ANSC_SOCKET_STREAM, 0);
#endif

        if ( pMyObject->Socket == ANSC_SOCKET_INVALID_SOCKET )
        {
            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	    			(
		    			pWorker->hWorkerContext,
			    		ANSC_SCTOWO_EVENT_SOCKET_ERROR,
				    	(ANSC_HANDLE)NULL
    				);
            }

            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT1;
        }
    }
    /*
     * Normally we don't need to know which local network interface we shall bind to, and the
     * underlying operating system usually supports such notation as "any address".
     */
#ifndef _ANSC_IPV6_COMPATIBLE_
    if ( pMyObject->Mode & ANSC_SCTO_MODE_XSOCKET )
    {
        xskt_client_addr.sin_family = XSKT_SOCKET_AF_INET;
        xskt_client_addr.sin_port   = _xskt_htons(pMyObject->HostPort);

        if (pMyObject->bSocketBindToDevice && *(pMyObject->SocketDeviceName)) 
        {
            if (_xskt_setsocketopt
                    (
                         pMyObject->Socket, 
                         XSKT_SOCKET_SOL_SOCKET, 
                         XSKT_SOCKET_SO_BINDTODEVICE, 
                         pMyObject->SocketDeviceName, 
                         _ansc_strlen(pMyObject->SocketDeviceName) + 1
                    )
                < 0)
            {
                perror("setsockopt-SOL_SOCKET-SO_BINDTODEVICE");
                returnStatus = ANSC_STATUS_FAILURE;
                goto EXIT2;
            }
        }
        //        fprintf(stderr, "<RT XSKT> Binding socket to Device '%s'.\n", pMyObject->SocketDeviceName); 

        if ( pMyObject->HostAddress.Value == 0 )
        {
            ((pansc_socket_addr_in)&xskt_client_addr)->sin_addr.s_addr = XSKT_SOCKET_ANY_ADDRESS;
        }
        else
        {
            ((pansc_socket_addr_in)&xskt_client_addr)->sin_addr.s_addr = pMyObject->HostAddress.Value;
        }

        if ( _xskt_bind((XSKT_SOCKET)pMyObject->Socket, (xskt_socket_addr*)&xskt_client_addr, sizeof(xskt_client_addr)) != 0 )
        {
            AnscTrace("!!!!!!!!!! _xskt_bind error: socket=%d, error=%d !!!!!!!!!!\n", (XSKT_SOCKET)pMyObject->Socket, errno);
            {
                int j;                 
                char s[256];
                char *ptr1 = ((xskt_socket_addr*)(&xskt_client_addr))->sa_data;
                char stmp[16];

                s[0] = '\0';                  
                for(j=0; j<13; j++) {
                    sprintf(stmp, "%.2x:", *(ptr1++));
                    strcat(s, stmp);
                }
                sprintf(stmp, "%.2x", *ptr1); 
                strcat(s, stmp);
                AnscTrace("!!!!!!!!!! _xskt_bind error: client_addr=%s\n", s);
            }
            perror("_xskt_bind error");

            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	    			(
		    			pWorker->hWorkerContext,
			    		ANSC_SCTOWO_EVENT_SOCKET_ERROR,
				    	(ANSC_HANDLE)NULL
    				);
            }
            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT2;
        }
    }
    else
    {
        ansc_client_addr.sin_family = ANSC_SOCKET_AF_INET;
        ansc_client_addr.sin_port   = _ansc_htons(pMyObject->HostPort);

        if (pMyObject->bSocketBindToDevice && *(pMyObject->SocketDeviceName)) 
        {
            if (_xskt_setsocketopt
                    (
                         pMyObject->Socket, 
                         ANSC_SOCKET_SOL_SOCKET, 
                         ANSC_SOCKET_SO_BINDTODEVICE, 
                         pMyObject->SocketDeviceName, 
                         _ansc_strlen(pMyObject->SocketDeviceName) + 1
                    )
                < 0)
            {
                perror("setsockopt-SOL_SOCKET-SO_BINDTODEVICE");
                returnStatus = ANSC_STATUS_FAILURE;
                goto EXIT2;
            }
        }
        // fprintf(stderr, "<RT AnscSKT> Binding socket to Device '%s'.\n", pMyObject->SocketDeviceName); 


        if ( pMyObject->HostAddress.Value == 0 )
        {
            ansc_client_addr.sin_addr.s_addr = ANSC_SOCKET_ANY_ADDRESS;
        }
        else
        {
            ansc_client_addr.sin_addr.s_addr = pMyObject->HostAddress.Value;
        }

        if ( _ansc_bind(pMyObject->Socket, (ansc_socket_addr*)&ansc_client_addr, sizeof(ansc_client_addr)) != 0 )
        {
            AnscTrace("!!!!!!!!!! _ansc_bind error: socket=%d, error=%d !!!!!!!!!!\n", (XSKT_SOCKET)pMyObject->Socket, errno);
            {
                int j;                 
                char s[256];
                char *ptr1 = ((ansc_socket_addr*)(&ansc_client_addr))->sa_data;
                char stmp[16];

                s[0] = '\0';                  
                for(j=0; j<13; j++) {
                    sprintf(stmp, "%.2x:", *(ptr1++));
                    strcat(s, stmp);
                }
                sprintf(stmp, "%.2x", *ptr1); 
                strcat(s, stmp);
                AnscTrace("!!!!!!!!!! _ansc_bind error: client_addr=%s\n", s);
            }
            perror("_ansc_bind error");

            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	    			(
		    			pWorker->hWorkerContext,
			    		ANSC_SCTOWO_EVENT_SOCKET_ERROR,
				    	(ANSC_HANDLE)NULL
    				);
            }

            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT2;
        }
    }
#endif

    /*
     * As a Tcp client application, we now try to connect the network server, whose address is
     * specified by the "peer address" and "peer port" fields.
     */
    if ( pMyObject->Mode & ANSC_SCTO_MODE_XSOCKET )
    {
#ifdef _ANSC_IPV6_COMPATIBLE_
        BOOL                        bNoConn = TRUE;
#endif

        _ansc_memset(&xskt_server_addr, 0, sizeof(xskt_server_addr));
    	xskt_server_addr.sin_family                                 = XSKT_SOCKET_AF_INET;
        xskt_server_addr.sin_addr.s_addr  = pMyObject->PeerAddress.Value;
        xskt_server_addr.sin_port                                   = _xskt_htons(pMyObject->PeerPort);

#ifdef _ANSC_IPV6_COMPATIBLE_
        while ( bNoConn && pxskt_server_addrinfo )
        {
            if ( _xskt_connect((XSKT_SOCKET)pMyObject->Socket, pxskt_server_addrinfo->ai_addr, pxskt_server_addrinfo->ai_addrlen) != 0 )
            {
                pxskt_server_addrinfo = pxskt_server_addrinfo->ai_next;     /* try next ip address */
            }
            else
            {
                bNoConn = FALSE;
                break;
            }
        }

        if ( bNoConn )
#else
            if ( _xskt_connect((XSKT_SOCKET)pMyObject->Socket, (xskt_socket_addr*)&xskt_server_addr, sizeof(xskt_server_addr)) != 0 )
#endif
        {
            AnscTrace("!!!!!!!!!! _xskt_connect error: socket=%d, error=%d !!!!!!!!!!\n", (XSKT_SOCKET)pMyObject->Socket, errno);
            {
                int j;                 
                char s[256];
                char *ptr1 = ((xskt_socket_addr*)(&xskt_server_addr))->sa_data;
                char stmp[16];

                s[0] = '\0';                  
                for(j=0; j<13; j++) {
                    sprintf(stmp, "%.2x:", *(ptr1++));
                    strcat(s, stmp);
                }
                sprintf(stmp, "%.2x", *ptr1); 
                strcat(s, stmp);
                AnscTrace("!!!!!!!!!! _xskt_connect error: server_addr=%s\n", s);
            }
            perror("_xskt_connect error");

            s_error = _xskt_get_last_error();

            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
	    			(
		    			pWorker->hWorkerContext,
			    		ANSC_SCTOWO_EVENT_SOCKET_TIMEOUT,
				    	(ANSC_HANDLE)NULL
    				);
            }
            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT2;
        }
    }
    else
    {
        _ansc_memset(&ansc_server_addr, 0, sizeof(ansc_server_addr));
        ansc_server_addr.sin_family      = ANSC_SOCKET_AF_INET;
        ansc_server_addr.sin_addr.s_addr = pMyObject->PeerAddress.Value;
        ansc_server_addr.sin_port        = _ansc_htons(pMyObject->PeerPort);

#ifdef _ANSC_IPV6_COMPATIBLE_
        if ( _ansc_connect(pMyObject->Socket, pansc_server_addrinfo->ai_addr, pansc_server_addrinfo->ai_addrlen) != 0 )
#else
        if ( _ansc_connect(pMyObject->Socket, (ansc_socket_addr*)&ansc_server_addr, sizeof(ansc_server_addr)) != 0 )
#endif
        {
            s_error = _ansc_get_last_error();

            AnscTrace("!!! Connect error: %d, %s !!!\n", s_error, strerror(s_error));

            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
				    (
			    		pWorker->hWorkerContext,
		    			ANSC_SCTOWO_EVENT_SOCKET_TIMEOUT,
	    				(ANSC_HANDLE)NULL
    				);
            }

            returnStatus = ANSC_STATUS_FAILURE;

            goto  EXIT2;
        }
    }

    /*
     * We have gone so far that all socket operations succeeded, we want to allocate a buffer that
     * is big enough for any incoming message.
     */
    if ( !pMyObject->RecvBuffer && !(pMyObject->Mode & ANSC_SCTO_MODE_FOREIGN_BUFFER) )
    {
        pMyObject->RecvBuffer     = AnscAllocateMemory(pMyObject->RecvBufferSize);
        pMyObject->RecvPacketSize = 0;
        pMyObject->RecvOffset     = 0;

        if ( !pMyObject->RecvBuffer )
        {
            returnStatus = ANSC_STATUS_RESOURCES;

            goto  EXIT2;
        }
    }

    pMyObject->RecvBytesCount = 0;
    pMyObject->SendBytesCount = 0;
    pMyObject->LastRecvAt     = AnscGetTickInSeconds();
    pMyObject->LastSendAt     = AnscGetTickInSeconds();

    /*
     * If the compilation option '_ANSC_SOCKET_TLS_LAYER_' is enabled, we can simply let the ANSC
     * socket layer to perform the SSL/TLS functionality; otherwise, we need to prepare for doing
     * SSL/TLS internally.
     */
    if ( pMyObject->Mode & ANSC_SCTO_MODE_TLS_ENABLED )
    {
#ifdef _ANSC_USE_OPENSSL_
        pMyObject->bTlsEnabled = TRUE;
        if ( !openssl_init(SSL_CLIENT_CALLS) )
        {
            AnscTrace("AnscSctoEngage - openssl_init() failed!\n");
            returnStatus = ANSC_STATUS_FAILURE;
            goto  EXIT2;
        }

#else
        #ifdef  _ANSC_SOCKET_TLS_LAYER_
        {
            _ansc_en_usetls(pMyObject->Socket);

            pMyObject->bTlsEnabled = FALSE;
        }
        #else
        {
            pMyObject->hTlsScsIf   = (pMyObject->hTlsScsIf != NULL)? pMyObject->hTlsScsIf : AnscSocketTlsGetScsIf();
            pMyObject->bTlsEnabled = TRUE;
        }
        #endif
#endif
    }

    /*
     * To save the worker object from having to deal with blocking/non-blocking/async receiving
     * functions provided by underlying socket layer, we create a separate task to do that.
     */
    returnStatus =
        pMyObject->SpawnTask3
            (
                (ANSC_HANDLE)pMyObject,
                (void*      )pMyObject->RecvTask,
                (ANSC_HANDLE)pMyObject,
                ANSC_SCTO_RECV_TASK_NAME,
                USER_DEFAULT_TASK_PRIORITY,
                11*USER_DEFAULT_TASK_STACK_SIZE

            );
#ifdef _ANSC_USE_OPENSSL_
    if ( pMyObject->bTlsEnabled )
    {
   	    SSL *ssl = NULL;
   	    ssl = openssl_connect (pMyObject->Socket);
	    if ( !ssl )
		{

	        pMyObject->bTlsConnected = FALSE;
	        returnStatus = ANSC_STATUS_FAILURE;

	        //PANSC_SCTO_WORKER_OBJECT        pWorker      = (PANSC_SCTO_WORKER_OBJECT)pMyObject->hWorker;
            if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
            {
                pWorker->Notify
                    (
                        pWorker->hWorkerContext,
                        ANSC_SCTOWO_EVENT_TLS_ERROR,
                        (ANSC_HANDLE)0L
                    );
            }
		}
	    else
	    {
			s_error = openssl_validate_certificate (pMyObject->Socket, pMyObject->HostName, ssl, SSL_CLIENT_CALLS);
		    if ( s_error == 0 )
		    {
		        AnscTrace("AnscSctoEngage - openssl_validate_certificate() failed %p.\n", ssl);

		        //PANSC_SCTO_WORKER_OBJECT        pWorker      = (PANSC_SCTO_WORKER_OBJECT      )pMyObject->hWorker;
                if ( pMyObject->Mode & ANSC_SCTO_MODE_NO_BSP_NOTIFY_CONN_ERR == 0 )
                {
	                pWorker->Notify
	                    (
	                        pWorker->hWorkerContext,
	                        ANSC_SCTOWO_EVENT_TLS_ERROR,
	                        (ANSC_HANDLE)NULL
	                    );
                }
		        returnStatus = ANSC_STATUS_FAILURE;
		    }

		    pMyObject->hTlsConnection = ssl;
		    pMyObject->bTlsConnected = TRUE;
	    }
    }
#else
    /*
     * If SSL/TLS is enabled, we should complete TLS handshake before returning from Engage(). This
     * behavior allows a single consistent API to used between this object and the worker object.
     * Since the handshake will take multiple messages to complete, we need to block the current
     * task until being notified by the TLS module.
     */
    if ( pMyObject->bTlsEnabled && pMyObject->hTlsScsIf )
    {
        pMyObject->bTlsConnected = FALSE;

        pMyObject->InitTlsClient((ANSC_HANDLE)pMyObject);
    }
#endif

    if ( returnStatus != ANSC_STATUS_SUCCESS )
    {
    	goto  EXIT2;
    }

    return  ANSC_STATUS_SUCCESS;


    /******************************************************************
                GRACEFUL ROLLBACK PROCEDURES AND EXIT DOORS
    ******************************************************************/

EXIT2:

	AnscTrace("AnscSctoEngage - failed with status %lu, socket error %d!\n", returnStatus, s_error);

    if ( pMyObject->Mode & ANSC_SCTO_MODE_XSOCKET )
    {
        _xskt_closesocket((XSKT_SOCKET)pMyObject->Socket);
    }
    else
    {
        _ansc_closesocket(pMyObject->Socket);
    }

EXIT1:

    if ( returnStatus != ANSC_STATUS_SUCCESS )
    {
        pMyObject->bActive = FALSE;

        pMyObject->Reset((ANSC_HANDLE)pMyObject);
    }

    return  returnStatus;
}
ANSC_STATUS
bbhmDownloadStartDiagTask

    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS                     returnStatus       = ANSC_STATUS_SUCCESS;
    PBBHM_DOWNLOAD_DIAG_OBJECT      pMyObject          = (PBBHM_DOWNLOAD_DIAG_OBJECT)hThisObject;
    PDSLH_TR143_DOWNLOAD_DIAG_STATS pStats             = (PDSLH_TR143_DOWNLOAD_DIAG_STATS)&pMyObject->DownloadDiagStats;
    char                            ipv6ref[64]        = {0};
    char*                           pHost              = NULL;
    char*                           pServ              = NULL;
    char*                           pPath              = NULL;
    ULONG                           uCount             = 500;  /* half second */
    XSKT_SOCKET                     aSocket            = XSKT_SOCKET_INVALID_SOCKET;
    int                             s_result           = 0;
    char                            buffer[1024]       = { 0 };
    ULONG                           ulSize             = 0;
    char*                           recv_buffer        = NULL;
    ULONG                           recv_size          = 0;
	int								tos				   = 0;
    xskt_addrinfo                   hints;
    xskt_addrinfo                   *servInfo   	   = NULL;
    xskt_addrinfo                   *cliInfo    	   = NULL;

    if ( !pMyObject->bActive )
    {
        return  ANSC_STATUS_FAILURE;
    }

    pMyObject->bDownNotifyNeeded = FALSE;

    /* make sure previous diag is done */
    while( pMyObject->bDownDiagOn )
    {
        AnscSleep(uCount);

        if ( !pMyObject->bActive )
        {
            returnStatus = ANSC_STATUS_FAILURE;

            goto done;
        }
    }

    /* init socket wrapper */
    AnscStartupXsocketWrapper((ANSC_HANDLE)pMyObject);

    /* turn on the diag */
    pMyObject->bDownDiagOn         = TRUE;
    
    /* reset the stats */
    DslhResetDownloadDiagStats((pStats));

    pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Requested;

    if ( pMyObject->bStopDownDiag )
    {
        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

    /* parse the download http url */
    if (ParseHttpURL(pMyObject->DownloadDiagInfo.DownloadURL,
                &pHost, &pServ, &pPath) != 0)
    {
		/* if the function fail, memory should not allcated, 
		 * but the the Pointer's value is uncertain */
		pHost = pServ = pPath = NULL;
		
        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_InitConnectionFailed;

        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

	/* resolution the HTTP server's hostname/service to sockaddrinfo */
    AnscZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC; /* XXX: xsocket wrapper has no XSKT_SOCKET_AF_UNSPEC */
    hints.ai_socktype = SOCK_STREAM;
    if (_xskt_getaddrinfo(pHost, pServ, &hints, &servInfo) != 0)
    {
		servInfo = NULL;

        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_InitConnectionFailed;

        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

    /* create the socket */
    aSocket = (XSKT_SOCKET)_xskt_socket(servInfo->ai_family, 
    		servInfo->ai_socktype, servInfo->ai_protocol);
    if ( aSocket == XSKT_SOCKET_INVALID_SOCKET )
    {
        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_InitConnectionFailed;

        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

	/* bind local address if need */
#if 0
    if (GetAddressByDmlPath(pMyObject->DownloadDiagInfo.Interface, 
			localAddr, sizeof(localAddr)) == 0)
#else
	if (_ansc_strlen(pMyObject->DownloadDiagInfo.IfAddrName) > 0)
#endif
	{
        AnscZeroMemory(&hints, sizeof(hints));
		hints.ai_family = servInfo->ai_family;
		hints.ai_socktype = servInfo->ai_socktype;

		if ((s_result = _xskt_getaddrinfo(pMyObject->DownloadDiagInfo.IfAddrName, "", &hints, &cliInfo)) != 0
				|| _xskt_bind(aSocket, cliInfo->ai_addr, cliInfo->ai_addrlen) != 0)
		{
			if (s_result != 0)
				cliInfo = NULL;
			
	        pMyObject->bDownNotifyNeeded = TRUE;
	        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_InitConnectionFailed;

	        returnStatus = ANSC_STATUS_FAILURE;
	        goto done;
	    }
	}
	
	/* DSCP */
	if (pMyObject->DownloadDiagInfo.DSCP > 0 && pMyObject->DownloadDiagInfo.DSCP < 64)
	{
		/* 6bits DSCP, and 2bits ENC */
		tos = pMyObject->DownloadDiagInfo.DSCP << 2;
		
		/* XXX: no XSKT_SOCKET_SOL_IP_TOS or XSKT_SOCKET_IP_TOS
		 * and infact IPPROTO_IP and SOL_XXX is not same level,
		 * so the name XSKT_SOCKET_SOL_IPPROTO_IP is not approciate.*/

		if (servInfo->ai_family == XSKT_SOCKET_AF_INET)
		{
			if (_xskt_setsocketopt(aSocket, XSKT_SOCKET_SOL_IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) != 0)
				AnscTraceWarning(("Fail to set IPv4 DSCP.\n"));
		}
		else if (servInfo->ai_family == XSKT_SOCKET_AF_INET6)
		{
			if (_xskt_setsocketopt(aSocket, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) != 0)
				AnscTraceWarning(("Fail to set IPv6 DSCP.\n"));
		}
	}

	/* ethernet priority */
	/* TODO: need 802.1d support */

    AnscGetSystemTime(&pStats->TCPOpenRequestTime);

	/* connect HTTP server */
    if ( _xskt_connect(aSocket, servInfo->ai_addr, servInfo->ai_addrlen) != 0 )
    {
        /* failed to connect the server */
        AnscTraceWarning(("Unable to connect to the http server.\n"));

        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_NoResponse;

        returnStatus = ANSC_STATUS_FAILURE;

        AnscGetSystemTime(&pStats->TCPOpenResponseTime);
        
        goto done;
    }
    
    AnscGetSystemTime(&pStats->TCPOpenResponseTime);

    /* record HTTP request time */
    AnscGetSystemTime(&pStats->ROMTime);

	/*
	 * according to RFC2396, "host" field in HTTP header for IPv6 addresss 
	 * should be a IPv6 Reference. 
	 * 
	 * 	 host		   = hostname | IPv4address | IPv6reference
	 *   ipv6reference = "[" IPv6address "]"
	 */
	if (IsIPv6Address(pHost))
	{
		snprintf(ipv6ref, sizeof(ipv6ref), "[%s]", pHost);
		_ansc_sprintf(buffer, http_get_request2, pPath, ipv6ref, pServ);
	}
	else
	{
		_ansc_sprintf(buffer, http_get_request2, pPath, pHost, pServ);
	}

	/* send the HTTP request */
    ulSize   = AnscSizeOfString(buffer);
    s_result = _xskt_send(aSocket, buffer, (int)ulSize, 0);

#ifdef _DEBUG

    AnscTraceWarning(("******** Download Request **************\n"));
    AnscTraceWarning((buffer));
    AnscTraceWarning(("\n******************************************\n"));

#endif

    if ( s_result == XSKT_SOCKET_ERROR || s_result < (int)ulSize )
    {
        /* failed to send the request */
        AnscTraceWarning(("Failed to send request to the http server.\n"));

        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_InitConnectionFailed;

        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

    /* receive the response */
    recv_buffer = (char*)AnscAllocateMemory(DOWNLOAD_SINGLE_BUFFER_SIZE + 1);

    if ( recv_buffer == NULL )
    {
        /* failed to send the request */
        AnscTraceWarning(("Failed to allocate memory.\n"));

        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_InitConnectionFailed;

        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

    recv_size   = DOWNLOAD_SINGLE_BUFFER_SIZE;
    s_result    = _xskt_recv(aSocket, recv_buffer, recv_size, 0);

    AnscGetSystemTime(&pStats->BOMTime);

    /* check whether it succededd or not */
    if ( s_result <= 0 || _ansc_strstr(recv_buffer, "HTTP/1.1 2") != recv_buffer )
    {
        /* failed to receive the request */
        AnscTraceWarning(("Failed to recv or not 200 OK.\n"));

        pMyObject->bDownNotifyNeeded = TRUE;
        pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_TransferFailed;

        returnStatus = ANSC_STATUS_FAILURE;
        goto done;
    }

    while(s_result > 0)
    {
#if _DEBUG
		recv_buffer[s_result] = '\0'; /* allocated one more byte, so no problem */
		AnscTraceWarning(("%s", recv_buffer));
#endif

        AnscGetSystemTime(&pStats->EOMTime);
        pStats->TestBytesReceived += s_result;
        if ( pMyObject->bStopDownDiag )
        {
            returnStatus = ANSC_STATUS_FAILURE;
            goto done;
        }

        recv_size   = DOWNLOAD_SINGLE_BUFFER_SIZE;
        s_result    = _xskt_recv(aSocket, recv_buffer, recv_size, 0);

        if ( s_result < 0 )
        {
            /* failed to receive the request */
            AnscTraceWarning(("Failed to recv packet.\n"));

            pMyObject->bDownNotifyNeeded = TRUE;
            pStats->DiagStates = DSLH_TR143_DIAGNOSTIC_Error_TransferFailed;

            returnStatus = ANSC_STATUS_FAILURE;
            goto done;
        }
    }

    /* succeeded */
    pMyObject->bDownNotifyNeeded = TRUE;
    pStats->DiagStates           = DSLH_TR143_DIAGNOSTIC_Completed;

done:
    /* clear resources if need */
    if (aSocket != XSKT_SOCKET_INVALID_SOCKET)
        _xskt_closesocket(aSocket);
    if (recv_buffer != NULL)
        AnscFreeMemory(recv_buffer);
    if (servInfo)
        _xskt_freeaddrinfo(servInfo);
    if (cliInfo)
        _xskt_freeaddrinfo(cliInfo);
	if (pHost)
		AnscFreeMemory(pHost);
	if (pServ)
		AnscFreeMemory(pServ);
	if (pPath)
		AnscFreeMemory(pPath);
    
    if ( pMyObject->bDownNotifyNeeded )
    {
        CosaSendDiagCompleteSignal();
    }

    /* if the task is stopped, reset the stats */
    if ( pMyObject->bStopDownDiag )
    {
        DslhResetDownloadDiagStats((&pMyObject->DownloadDiagStats));        
    }

    pMyObject->DownloadDiagInfo.DiagnosticsState = pStats->DiagStates;
        
    /* clear flags */
    pMyObject->bDownNotifyNeeded   = FALSE;
    pMyObject->bDownDiagOn         = FALSE; 
    pMyObject->bStopDownDiag       = FALSE;

    return returnStatus;
}