/*
 * <insert one-line description of what the program does>
 * Copyright (c) <2008-2009>, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.

File Name:          ConnMgmt.c

Description:

    This file implements ConnMgmt module

         This module has following functions.

         1. downlaod boot cert.
         
         2. update device status
 

Environment (opt):

    OS: metasys/mandriva

    SE: gcc

 

Notes (opt):

  =====================================================================

  Revision   Revision History                             Date

  =====================================================================
  1.1         porting from windows betaCan       20060814
  1.11       T_ConnMgmt_ALPHA                     20060913

  =====================================================================

 

****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#include "ConnMgmt/ConnMgmt.h"
#include "GUI/error.h"

#include "AgentDeviceSoapBinding.nsmap"
///for test
#ifdef ConnMgmt_DEBUGH 
#include "ConnMgmt/TestInfo.h"    
#else
#include "InfoMgmt/InfoMgmt.h"  
#endif  

#define FAILED 1

#include "soapH.h"

const char URLPOSTFIX[] = "/axis/services/AgentDevice";
const int TIMEOUT = 60000; //60 seconds
//const int TIMEOUT = 6000; //for quick test it's good, 6 seconds
int ConnMgmt_SSL_Enabled = 1;

typedef enum Protocol_Errcode_enum                                                                                                                                                                                                                                                                                                                  
{                                                                                                                                                                                                                                                                                                                                                   
    Protocol_Errcode_Successful         = 0,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_HWIDError          = 1,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_BootTickError      = 2,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_CertKindError      = 3,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_IPError            = 4,                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_DNSError           = 5,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_WINSError          = 6,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_GatewayError       = 7,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_ProxyError         = 8,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_LocalTimeError     = 9,                                                                                                                                                                                                                                                                                                            
    Protocol_Errcode_ServerInnerError   = 255                                                                                                                                                                                                                                                                                                           
} Protocol_Errcode;                                                                                                                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Stolen flag value                                                                                                                                                                                                                                                                                                                               
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum Protocol_StolenInfo_enum                                                                                                                                                                                                                                                                                                
{                                                                                                                                                                                                                                                                                                                                                   
    Protocol_StolenInfo_Normal  = 0,                                                                                                                                                                                                                                                                                                                    
    Protocol_StolenInfo_Stolen  = 1                                                                                                                                                                                                                                                                                                                    
} Protocol_StolenInfo;                                                                                                                                                                                                                                                                                                                              
             
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Stolen flag value                                                                                                                                                                                                                                                                                                                               
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum Protocol_ApprovedInfo_enum                                                                                                                                                                                                                                                                                                
{                                                                                                                                                                                                                                                                                                                                                   
     Protocol_ApprovedInfo_No  = 0,                                                                                                                                                                                                                                                                                                                    
   Protocol_ApprovedInfo_Normal  = 1                                                                                                                                                                                                                                                                                                                    
} Protocol_ApprovedInfo;    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Refuse service flag value                                                                                                                                                                                                                                                                                                                       
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum Protocol_RefuseInfo_enum                                                                                                                                                                                                                                                                                               
{                                                                                                                                                                                                                                                                                                                                                   
    Protocol_RefuseInfo_Tolerance                = 0, 
	Protocol_RefuseInfo_NoRefuse        = 1, 
 //   Protocol_RefuseInfo_HWIDInvalidation        = 1,                                                                                                                                                                                                                                                                                                    
    Protocol_RefuseInfo_BootTickInvalidation    = 2,                                                                                                                                                                                                                                                                                             
    //Protocol_RefuseInfo_DeviceStolen            = 3                                                                                                                                                                                                                                                                                                     
} Protocol_RefuseInfo;                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Cert kind                                                                                                                                                                                                                                                                                                                                       
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum Protocol_CertKind_enum                                                                                                                                                                                                                                                                                                  
{                                                                                                                                                                                                                                                                                                                                                   
    Protocol_CertKind_NoCert            = 0,                                                                                                                                                                                                                                                                                                            
    Protocol_CertKind_SpecialBootCert   = 1,                                                                                                                                                                                                                                                                                                            
    Protocol_CertKind_NormalBootCert    = 2,                                                                                                                                                                                                                                                                                                            
    Protocol_CertKind_SharedSecret      = 3,
	Protocol_CertKind_ServerPublicKey      = 4,
	Protocol_CertKind_IntelPublicKey	     = 5,
	Protocol_CertKind_AutoProvisionPackage = 6,
	Protocol_CertKind_CAPackage            = 7
} Protocol_CertKind;                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Expire information exist flag                                                                                                                                                                                                                                                                                                                   
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum Protocol_ExpireInfoExist_enum                                                                                                                                                                                                                                                                                           
{                                                                                                                                                                                                                                                                                                                                                   
    Protocol_ExpireInfoExist_NoExist    = 0,                                                                                                                                                                                                                                                                                                               
    Protocol_ExpireInfoExist_Exist      = 1                                                                                                                                                                                                                                                                                                                 
} Protocol_ExpireInfoExist;                                                                                                                                                                                                                                                                                                                         
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Shared secret update result                                                                                                                                                                                                                                                                                                                     
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum Protocol_UpdateResult_enum                                                                                                                                                                                                                                                                                                       
{                                                                                                                                                                                                                                                                                                                                                   
    Protocol_UpdateResult_Fail          = 0,                                                                                                                                                                                                                                                                                                     
    Protocol_UpdateResult_SharedSecret  = 1,                                                                                                                                                                                                                                                                                                            
    Protocol_UpdateResult_SpecialCert   = 2                                                                                                                                                                                                                                                                                                         
} Protocol_UpdateResult;                                                                                                                                                                                                                                                                                                                            
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// download kind from web service                                                                                                                                                                                                                                                                                                                  
/// </summary>                                                                                                                                                                                                                                                                                                                                      
typedef enum DownloadKind_enum                                                                                                                                                                                                                                                                                                                
{                                                                                                                                                                                                                                                                                                                                                   
    // donwload index: Intel public key, Server public key, shared secret, special cert
			DownloadKind_PushCert = 0,
			// download index: Intel public key, Server public key, shared secret, special cert, Normal cert
			DownloadKind_PullCert = 1,
		
	//DownloadKind_ProvisonPacket = 3,
	//DownloadKind_CACert = 4
} DownloadKind;                                                                                                                                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse error code data from web service                                                                                                                                                                                                                                                                                                          
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">Error code data</param>  
/// <returns>0: success; !0: failed</returns> 
int ParseErrcode(unsigned char * bzData)                                                                                                                                                                                                                                                                                                   
{                                                                                                                                                                                                                                                                                                                                                   
    if (bzData == NULL) return FAILED;
    int iRet = 1;                                                                                                                                                                                                                                                                                                                                       
    switch((Protocol_Errcode)bzData[0])                                                                                                                                                                                                                                                                                                            
    {                                                                                                                                                                                                                                                                                                                                                   
        // Server internal error                                                                                                                                                                                                                                                                                                                            
        case Protocol_Errcode_ServerInnerError:                                                                                                                                                                                                                                                                                                             
            #ifdef ConnMgmt_DEBUG
            printf("webserviceInnerError\n");  
            #endif
            iRet = ConnMgmt_ExceptionStatus_WebServiceInnerError;                                                                                                                                                                                                                                                                                               
            break;                                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                                            
        // Send parameter error                                                                                                                                                                                                                                                                                                                             
        case Protocol_Errcode_HWIDError: 
            #ifdef ConnMgmt_DEBUG 
            printf("hwid error\n"); 
            #endif
        case Protocol_Errcode_BootTickError: 
            #ifdef ConnMgmt_DEBUG 
            printf("boottick error \n"); 
            #endif                                                                                                                                                                                                                                                                                  
        case Protocol_Errcode_CertKindError: 
            #ifdef ConnMgmt_DEBUG 
            printf("certkind error \n"); 
            #endif                                                                                                                                                                                                                                                                                  
        case Protocol_Errcode_IPError: 
            #ifdef ConnMgmt_DEBUG 
            printf("ip error \n"); 
            #endif                                                                                                                                                                                                                                                                                               
        case Protocol_Errcode_DNSError: 
            #ifdef ConnMgmt_DEBUG 
            printf("dns error \n"); 
            #endif                                                                                                                                                                                                                                                                                             
        case Protocol_Errcode_WINSError: 
            #ifdef ConnMgmt_DEBUG 
            printf("wins error \n"); 
            #endif                                                                                                                                                                                                                                                                                           
        case Protocol_Errcode_GatewayError: 
            #ifdef ConnMgmt_DEBUG 
            printf("gateway error \n"); 
            #endif                                                                                                                                                                                                                                                                                    
        case Protocol_Errcode_ProxyError: 
            #ifdef ConnMgmt_DEBUG 
            printf("proxy error \n"); 
            #endif                                                                                                                                                                                                                                                                                        
        case Protocol_Errcode_LocalTimeError: 
            #ifdef ConnMgmt_DEBUG 
            printf("time error \n"); 
            #endif  
                                                                                                                                                                                                                                                                                               
            #ifdef ConnMgmt_DEBUG 
            printf("webserviceParameterError\n");
            #endif
            iRet = ConnMgmt_ExceptionStatus_ParameterError;                                                                                                                                                                                                                                                                                                     
            break;    
                                                                                                                                                                                                                                                                                                                                                  
        // OK                                                                                                                                                                                                                                                                                                                                               
        case Protocol_Errcode_Successful: 
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                   
            printf("protocl_errcode_successful\n");  
            #endif                                                                                                                                                                                                                                                                                                           
            //iRet = ConnMgmt_ExceptionStatus_Success; //this value not equal to 0, so delete this line;                                                                                                                                                                                                                                                          
            iRet = 0;
            break;                                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                                            
        // Invalid data                                                                                                                                                                                                                                                                                                                                     
        default:          
            #ifdef ConnMgmt_DEBUG 
            printf("webserviceReturnDataInvalidation in ParseErrcode()\n"); 
            #endif  
            iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;                                                                                                                                                                                                                                                                                          
    }    
	
    if (iRet != 0 ) 
    {
        WriteLog(iRet);  
    }
    return iRet;                                                                                                                                                                                                                                                                                                                                     
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse approved flag data from web service                                                                                                                                                                                                                                                                                                  
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">Device approved flag data</param>     
/// <returns>0: success; !0: failed</returns> 
int ParseApprovedFlag(unsigned char * bzData)                                                                                                                                                                                                                                                                                                         
{ //the  flag is set to mean if the student account is activated as Normal account im CMPC 1.5
    if (bzData == NULL) return FAILED;
    int iRet = 1;                        
    int approved=0; 
	OtherInfo otherInfo;
	iRet = OtherInfo_Construct(&otherInfo);

    // Parse approved flag                                                                                                                                                                                                                                                                                                                                
    switch((Protocol_ApprovedInfo)bzData[0])                                                                                                                                                                                                                                                                                                         
    {                                                                                                                                                                                                                                                                                                                                                   
        //approved                                                                                                                                                                                                                                                                                                                                           
        case Protocol_ApprovedInfo_Normal:                                                                                                                                                                                                                                                                                                                    
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                              
            printf("approved\n");   
            #endif  
			approved=1;
			OtherInfo_Actived(&approved,"SET");
            break;        
                                                                                                                                                                                                                                                                                                                                              
        //not approved                                                                                                                                                                                                                                                                                                                                          
        case Protocol_ApprovedInfo_No:                                                                                                                                                                                                                                                                                                                
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                              
            printf("not approved\n");      
            #endif   
			approved=0;
			OtherInfo_Actived(&approved,"SET");
            break;    
                                                                                                                                                                                                                                                                                                                                                  
        // Reserve                                                                                                                                                                                                                                                                                                                                          
        default:                                                                                                                                                                                                                                                                                                                                            
            #ifdef ConnMgmt_DEBUG 
            printf("device approved flag unkonw, returnDataInvalidate\n"); 
            #endif                                                                                                                                                                                                                                                                                
            iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation; 
	     WriteLog(iRet);
	     return iRet;
    }                                                                                                                                                                                                                                                                                                                                                   
    iRet=0;  
    return iRet;
}
                                                                
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse refuse service data form web service                                                                                                                                                                                                                                                                                                      
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">Refuse service data</param>    
/// <returns>0: success; !0: failed</returns> 
int ParseRefuseFlag(unsigned char * bzData)                                                                                                                                                                                                                                                                                                         
{ 
    if (bzData == NULL) return FAILED;
    int iRet = 1;                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                       
    // Parse Refulse service flag                                                                                                                                                                                                                                                                                                                             
    switch((Protocol_RefuseInfo)bzData[0])                                                                                                                                                                                                                                                                                                         
    {                                                                                                                                                                                                                                                                                                                                                   
        // Normal   Boot Tick ==                                                                                                                                                                                                                                                                                                                                        
        case Protocol_RefuseInfo_NoRefuse: 
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                              
            printf("not refuse service\n");
            #endif       
	     iRet = 0;
            break;                                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                                            
             // 0 ¨C Boot Tick > 1 ~ 5                                                                                                                                                                                                                                                                                                                                           
        case Protocol_RefuseInfo_Tolerance: 
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                              
            printf("not refuse service,Boot Tick > 1 ~ 5\n");
            #endif       
	     iRet = 0;
            break;                                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                            
        // Boot_Tick Invalidation                                                                                                                                                                                                                                                                                                                           
        case Protocol_RefuseInfo_BootTickInvalidation:                                                                                                                                                                                                                                                                                                   
            #ifdef ConnMgmt_DEBUG 
            printf("refuse service -- boottick invalid\n"); 
            #endif                                                                                                                                                                                                                                                                                                    
            iRet = ConnMgmt_RefuseServiceExceptionReason_BootTickInvalid;                                                                                                                                                                                                                                                                                       
            break;                                                                                                                                                                                                                                                                                                                                    
        

		/* 	 // HWID Invalidation                                                                                                                                                                                                                                                                                                                                
        case Protocol_RefuseInfo_HWIDInvalidation:
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                           
            printf("refuse service -- hwid invalid\n"); 
            #endif                                                                                                                                                                                                                                                                                                        
            iRet = ConnMgmt_RefuseServiceExceptionReason_HWIDInvalid;                                                                                                                                                                                                                                                                                           
            break;     
        // Device stolen                                                                                                                                                                                                                                                                                                                                    
       case Protocol_RefuseInfo_DeviceStolen:                                                                                                                                                                                                                                                                                                              
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                              
            printf("refuse service -- device stolen\n"); 
            #endif                                                                                                                                                                                                                                                                                                       
            iRet = ConnMgmt_RefuseServiceExceptionReason_DeviceStolen;                                                                                                                                                                                                                                                                                          
            break;                                                                                                                                                                                                                                                                                                                                   
           */                                                                                                                                                                                                                                                                                                                                                 
        // Reserve                                                                                                                                                                                                                                                                                                                                          
        default:    
            #ifdef ConnMgmt_DEBUG 
            printf("returnDataInvalidate in ParseRefuseFlag()\n");
            #endif                                                                                                                                                                                                                                                                                  
            iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;                                                                                                                                                                                                                                                                                             
    } 
    if (iRet != 0 ) 
    {
        WriteLog(iRet);  
    } 
    return iRet;                                                                                                                                                                                                                                                                                                                                        
    //else printf("parse errcode strlen < 0\n");                                                                                                                                                                                                                                                                                                       
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse student id                                                                                                                                                                                                                                                                                                      
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">Student id data</param>   
/// <returns>0: success; !0: failed</returns> 
int ParseStudentId(unsigned char * bzData)                                                                                                                                                                                                                                                                                                          
{ 
    if (bzData == NULL) return FAILED;
    int iRet = 1;              
	
    // Get student id, from byte[] to string                                                                                                                                                                                                                                                                                                 
    //m_currentState.StudentId = System.Text.Encoding.ASCII.GetString(bzData); //in pathpatch version, ASCII become UTF8
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                              
    printf("student id= %s\n", bzData); 
    #endif           

    
    DeviceInfo deviceInfo;
    iRet = DeviceInfo_Construct(&deviceInfo);
    if (iRet != 0) 
    {
        iRet = ConnMgmt_invoke_DeviceInfo_Construct_Error;
	 WriteLog(iRet);
        return 0; //do not handle anything if error occured
    }

    iRet = DeviceInfo_StudentID(bzData, "SET");
    if (iRet != 0)
    {
        iRet = ConnMgmt_invoke_DeviceInfo_StudentID_Error;
	 WriteLog(iRet); 
        return 0; //do not handle anything if error occured
    }
    
    return 0;
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse cert kind data from web service                                                                                                                                                                                                                                                                                                           
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">cert kind data</param>                                                                                                                                                                                                                                                                                                     
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                                 
int ParseCertKind(unsigned char * bzData,  BootCert * pBootCert)                                                                                                                                                                                                                                                                                    
{ 
    if (bzData == NULL) return FAILED;
    if (pBootCert == NULL) return FAILED;
    int iRet=1;
	
    // parse cert kind                                                                                                                                                                                                                                                                                                                                  
    switch((Protocol_CertKind)bzData[0])                                                                                                                                                                                                                                                                                                           
    {                                                                                                                                                                                                                                                                                                                                                   
        // No cert                                                                                                                                                                                                                                                                                                                                          
        case Protocol_CertKind_NoCert:                                                                                                                                                                                                                                                                                                                      
            pBootCert->CertKind = NoCert; 
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                       
            printf("noCert\n");     
            #endif                                                                                                                                                                                                                                                                                                                            
            break;   
                                                                                                                                                                                                                                                                                                                                                   
        // Normal boot cert                                                                                                                                                                                                                                                                                                                                 
        case Protocol_CertKind_NormalBootCert:                                                                                                                                                                                                                                                                                                              
            pBootCert->CertKind = NormalCert;
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                    
            printf("normalbootCert\n");
            #endif                                                                                                                                                                                                                                                                                                                         
            break;  
                                                                                                                                                                                                                                                                                                                                                    
        // Shared Secret                                                                                                                                                                                                                                                                                                                                    
        case Protocol_CertKind_SharedSecret:                                                                                                                                                                                                                                                                                                                
            pBootCert->CertKind = SharedSecret;                                                                                                                                                                                                                                                                                                                 
            #ifdef ConnMgmt_DEBUG 
            printf("shared secret\n"); 
            #endif                                                                                                                                                                                                                                                                                                                         
            break;               
                                                                                                                                                                                                                                                                                                                                       
        // Special boot cert                                                                                                                                                                                                                                                                                                                                
        case Protocol_CertKind_SpecialBootCert:                                                                                                                                                                                                                                                                                                             
            pBootCert->CertKind = SpecialCert;                                                                                                                                                                                                                                                                                                                  
            #ifdef ConnMgmt_DEBUG 
            printf("specialbootCert\n"); 
            #endif                                                                                                                                                                                                                                                                                                                       
            break;                  
		case Protocol_CertKind_ServerPublicKey:
			 pBootCert->CertKind = ServerPublicKey;                                                                                                                                                                                                                                                                                                                  
            #ifdef ConnMgmt_DEBUG 
            printf("ServerPublicKey\n"); 
            #endif                                                                                                                                                                                                                                                                                                                       
            break;     

		case Protocol_CertKind_IntelPublicKey:
			 pBootCert->CertKind = IntelPublicKey;                                                                                                                                                                                                                                                                                                                  
            #ifdef ConnMgmt_DEBUG 
            printf("IntelPublicKey\n"); 
            #endif                                                                                                                                                                                                                                                                                                                       
            break;     
		
        // Reserve                                                                                                                                                                                                                                                                                                                                          
        default:                                                                                                                                                                                                                                                                                                                                            
            iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;     
	     WriteLog(iRet);
            return iRet;
    }                                                                                                                                                                                                                                                                                                                                                   
    iRet=0;  
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse expire information exist or not flag                                                                                                                                                                                                                                                                                                      
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">Expire exist flag data</param> 
/// <param name="bRet">1:true:exist; 0:false:not exist</param> 
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                          
int ParseExpireExistFlag(unsigned char * bzData, unsigned int * bRet)                                                                                                                                                                                                                                                                               
{ 
    if (bzData == NULL) return FAILED;
    if (bRet == NULL) return FAILED;
    int iRet = 1;                                                                                                                                                                                                                                                                                                                                       
    *bRet= 0;  //0, false, not exist                                                                                                                                                                                                                                                                                                                                         
	
    // Parse expire exist data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
    switch((Protocol_ExpireInfoExist)bzData[0])                                                                                                                                                                                                                                                                                                    
    {                                                                                                                                                                                                                                                                                                                                                   
        case Protocol_ExpireInfoExist_Exist:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
            *bRet = 1;   
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                                        
            printf("parse expire exist flg = exist\n"); 
            #endif                                                                                                                                                                                                                                                                                                        
            break;       
                                                                                                                                                                                                                                                                                                                                               
        case Protocol_ExpireInfoExist_NoExist:                                                                                                                                                                                                                                                                                                              
            *bRet = 0;    
            #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                                       
            printf("parse expire exist flg = noexist\n"); 
            #endif                                                                                                                                                                                                                                                                                                      
            break;                  
                                                                                                                                                                                                                                                                                                                                    
        default:                                                                                                                                                                                                                                                                                                                                            
            #ifdef ConnMgmt_DEBUG 
            printf("returnDataInvalid\n"); 
            #endif                                                                                                                                                                                                                                                                                                                     
            iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;    
            WriteLog(iRet);
            return iRet;
    }                                                                                                                                                                                                                                                                                                                                                   
    iRet=0;  
    return iRet;  
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse expire information data, include expire date, boot count.                                                                                                                                                                                                                                                                                 
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">Expire information data</param> 
/// <param name="pBootCert">the expire info need to be saved into this struct</param> 
/// <returns>0: success; !0: failed</returns> 
int ParseExpireInfo(unsigned char * bzData, BootCert * pBootCert)                                                                                                                                                                                                                                                                                   
{
    if (bzData == NULL) return FAILED;
    if (pBootCert == NULL) return FAILED;
    int iRet = 1;                                                                                                                                                                                                                                                                                                                                       
    int nIndex = 0;                                                                                                                                                                                                                                                                                                                                         
                                                                                                                                                                                                                                                                                                                                        
    /* Get year of expiration */                                                                                                                                                                                                                                                                                                                                  
    unsigned char btYear[2+1];                                                                                                                                                                                                                                                                                                                          
    memcpy(btYear, &bzData[nIndex], 2);                                                                                                                                                                                                                                                                                                                 
    btYear[2] = '\0';             
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                       
    printf("year = %s\n", btYear);                                                                                                                                                                                                                                                                                                                      
    printf("byte year = %d %d \n", btYear[0], btYear[1]); 
    #endif        
    int iYear = 2000 + atoi(btYear); 
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                    
    printf("iyear = %d  \n", iYear); 
    #endif    
	
    /* Get month of expiration */
    nIndex += 2;
    unsigned char btMonth[2+1];                                                                                                                                                                                                                                                                                                                         
    memcpy(btMonth, &bzData[nIndex], 2);                                                                                                                                                                                                                                                                                                                
    btMonth[2] = '\0';  
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                                 
    printf("month = %s\n", btMonth);
    printf("byte month = %d %d \n", btMonth[0], btMonth[1]);
    #endif
    int iMonth = atoi(btMonth); 
    #ifdef ConnMgmt_DEBUG
    printf("iMonth = %d  \n", iMonth); 
    #endif                                                                                                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                                                                                                                                        
    /* Get day of expiratione */                                                                                                                                                                                                                                                                                                                        
    nIndex += 2;                                                                                                                                                                                                                                                                                                                                        
    unsigned char btDay[2+1];                                                                                                                                                                                                                                                                                                                           
    memcpy(btDay, &bzData[nIndex], 2);                                                                                                                                                                                                                                                                                                                  
    btDay[2] = '\0';             
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                        
    printf("day = %s\n", btDay);
    printf("byte day= %d %d \n", btDay[0], btDay[1]);
    #endif                                                                                                                                                                                                                                                                                                                       
    int iDay = atoi(btDay);      
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                        
    printf("iDay = %d  \n", iDay);
    #endif                                                                                                                                                                                                                                                                                                                      
                                                                                                                                                                                                                                                                                                                                                      
    // Save expiration date                                                                                                                                                                                                                                                                                                                             
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                     
    printf("expiredat %d %d %d\n", iYear, iMonth, iDay); 
    #endif
    DateTime tempT;                                                                                                                                                                                                                                                                                                                                     
    tempT.Year = iYear;      //year since 1900                                                                                                                                                                                                                                                                                                       
    tempT.Month = iMonth;  //mon[1~12]                                                                                                                                                                                                                                                                                                                 
    tempT.Day= iDay; //mday[1~31]                                                                                                                                                                                                                                                                                                                  
    pBootCert->ExpirationDate = tempT;                                                                                                                                                                                                                                                                                                                  
                                                                                                                                                                                                                                                                                                                                                        
    /* Get boot count of current cert */                                                                                                                                                                                                                                                                                                                
    nIndex += 2;                                                                                                                                                                                                                                                                                                                                        
    unsigned char btBootCount[3+1];                                                                                                                                                                                                                                                                                                                     
    memcpy(btBootCount, &bzData[nIndex], 3);                                                                                                                                                                                                                                                                                     
    btBootCount[3] = '\0';                                                                                                                                                                                                                                                                                                                              
    // Parse boot count                                                                                                                                                                                                                                                                                                                                 
    int iBootCount;                                                                                                                                                                                                                                                                                                                                     
//    iBootCount =  *(int*)btBootCount;    
    iBootCount = btBootCount[0]*256*256 + btBootCount[1]*256 + btBootCount[2];
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                            
    printf("byte bootcount = %d %d %d\n", btBootCount[0], btBootCount[1], btBootCount[2]);                                                                                                                                                                                                                                                                   
    printf("iBootCount = %d\n", iBootCount); 
    #endif                                                                                                                                                                                                                                                                                                           
    pBootCert->BootCount = iBootCount;                                                                                                                                                                                                                                                                                                                  
    iRet=0;  


	char tmp[20];

	sprintf(tmp,"%4d-%2d-%2d",tempT.Year,tempT.Month,tempT.Day);
	iRet = OtherInfo_LastDate(tmp,"SET");
	WritestrLog(MODULE_CONNMGMT,"otherinfo_lastdate:");
	WritestrLog(MODULE_CONNMGMT,tmp);
	if (iRet) WriteLog(iRet);
	sprintf(tmp,"%d",iBootCount);
	WritestrLog(MODULE_CONNMGMT,tmp);

	iRet = OtherInfo_LastTimes(tmp,"SET");
	if (iRet) WriteLog(iRet);

    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse cert data                                                                                                                                                                                                                                                                                                                                 
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzData">cert data</param>   
/// <param name="pBootCert">cert data will be saved to this struct,also ther pvosion number of server public key will be saved</param>
/// <param name="nSize">length of certdata</param>
/// <returns>0: success; !0: failed</returns> 
int ParseCert(unsigned char * bzData, BootCert * pBootCert, int nSize)                                                                                                                                                                                                                                                                              
{                                                                                                                                                                                                                                                                                                                                                   
    if (bzData == NULL) return FAILED;
    if (pBootCert == NULL) return FAILED;
	
    int iRet = 1;
    if (nSize > 0)                                                                                                                                                                                                                                                                                                                                      
    {                       
		
		if (pBootCert->CertKind == ServerPublicKey ||pBootCert->CertKind == IntelPublicKey )//the last 20 bytes are provision number
		{
			char   provision_number[30]={0};
			int PROVISION_NUMBER_LEN = 20;
			if( nSize < PROVISION_NUMBER_LEN)   return iRet;
			memcpy(pBootCert->Cert, bzData, nSize-PROVISION_NUMBER_LEN);
			memcpy(provision_number, bzData + nSize-PROVISION_NUMBER_LEN, PROVISION_NUMBER_LEN);
			OtherInfo_ProvisionNumber( provision_number, "SET" );		
		}
		else
			memcpy(pBootCert->Cert, bzData, nSize);   
    }                                                                                                                                                                                                                                                                                                                                                   
    iRet=0;  
    return iRet;
}                                                                                                                                                                                                                                                                                                                                                   
 
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Parse the return binary from web service                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="bzReturn">return data</param>    
/// <param name="nSize">the length of return data</param> 
/// <param name="pBootCert">after parsing the return data, it will be saved to this struct</param> 
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                                         
int Parse(unsigned char * bzReturn, int nSize, BootCert * pBootCert)                                                                                                                                                                                                                                                                    
{
    int iRet = 1;                                                                                                                                                                                                                                                                                                                                       
    if(nSize == 0)                                                                                                                                                                                                                                                                                                                                      
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG  
        printf("returndatainvalid, parsesize\n");
        #endif 
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;      
        WriteLog(iRet);       
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                        
    int nPos = 0;       // Index of return data                                                                                                                                                                                                                                                                                                             
    unsigned char bzField[MAXSTRLEN];
	
    /* Get Error code */                                                                                                                                                                                                                                                                                                                                
    // Error code data length                                                                                                                                                                                                                                                                                                                           
    const int DATALEN_ERRCODE = 1;                                                                                                                                                                                                                                                                                                                      
    memcpy(bzField, &bzReturn[nPos], DATALEN_ERRCODE);                                                                                                                                                                                                                                                                                                  
    bzField[DATALEN_ERRCODE] = '\0';                                                                                                                                                                                                                                                                                                                    
    iRet = ParseErrcode(bzField);                                                                                                                                                                                                                                                                                                                       
    if (iRet != 0) return iRet;                                                                                                                                                                                                                                                                                                                         
                                                                                                                                                                                                                                                                                                                                                        
    /* Get device stolen flag */                                                                                                                                                                                                                                                                                                                        
    // Start position of device stolen flag                                                                                                                                                                                                                                                                                                             
    nPos = 1;                                                                                                                                                                                                                                                                                                                                           
    // Device stolen flag data length                                                                                                                                                                                                                                                                                                                   
    const int DATALEN_STOLENFLAG = 1;                                                                                                                                                                                                                                                                                                                   
    // Check data length                                                                                                                                                                                                                                                                                                                                
    if(nSize< nPos + DATALEN_STOLENFLAG)                                                                                                                                                                                                                                                                                                                
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG
        printf("returndatainvalid DATALEN_STOLENFLAG\n");                                                                                                                                                                                                                                                                                                   
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation; 
        WriteLog(iRet);   
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
    memcpy(bzField, &bzReturn[nPos], DATALEN_STOLENFLAG);                                                                                                                                                                                                                                                                                               
    bzField[DATALEN_ERRCODE] = '\0';                                                                                                                                                                                                                                                                                                                    
    // Parse device stolen flag data                                                                                                                                                                                                                                                                                                                    
    iRet = ParseApprovedFlag(bzField);                                                                                                                                                                                                                                                                                                                    
    if (iRet !=0) return iRet;                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                        
    /* Get refuse service flag */                                                                                                                                                                                                                                                                                                                       
    // Start position of refuse service flag data                                                                                                                                                                                                                                                                                                       
    nPos = 2;                                                                                                                                                                                                                                                                                                                                           
    // Refuse sevice flag data length                                                                                                                                                                                                                                                                                                                   
    const int DATALEN_REFUSEFLAG = 1;                                                                                                                                                                                                                                                                                                                   
    // Check data length                                                                                                                                                                                                                                                                                                                                
    if(nSize < nPos + DATALEN_REFUSEFLAG)                                                                                                                                                                                                                                                                                                               
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG
        printf("ReturnDataInvalid DATALEN_REFUSEFLAG\n");                                                                                                                                                                                                                                                                                                   
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
    memcpy(bzField, &bzReturn[nPos], DATALEN_REFUSEFLAG);                                                                                                                                                                                                                                                                                               
    bzField[DATALEN_ERRCODE] = '\0';                                                                                                                                                                                                                                                                                                                    
    // Parse refuse flag data                                                                                                                                                                                                                                                                                                                           
    iRet = ParseRefuseFlag(bzField);                                                                                                                                                                                                                                                                                                                    
    if (iRet !=0) return iRet;                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                        
    /* Get student ID */                                                                                                                                                                                                                                                                                                                                
    // Start position of student ID data length                                                                                                                                                                                                                                                                                                         
    nPos = 3;                                                                                                                                                                                                                                                                                                                                           
    // length of data that student ID data length                                                                                                                                                                                                                                                                                                       
    const int DATALEN_STUIDLENGTH = 1;                                                                                                                                                                                                                                                                                                                  
    // Check data length                                                                                                                                                                                                                                                                                                                                
    if(nSize< nPos + DATALEN_STUIDLENGTH)                                                                                                                                                                                                                                                                                                               
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG
        printf("ReturnDataInvalid in DATALEN_STUIDLENGTH\n");                                                                                                                                                                                                                                                                                               
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
    // Get length of student ID                                                                                                                                                                                                                                                                                                                         
    short siStuIdLen = bzReturn[nPos];
    #ifdef ConnMgmt_DEBUG
    printf("siStuIdLen = %d\n", siStuIdLen);                                                                                                                                                                                                                                                                                                            
    #endif
    // Get data of student ID                                                                                                                                                                                                                                                                                                                           
    // Start position of student ID data                                                                                                                                                                                                                                                                                                                
    nPos = 4;                                                                                                                                                                                                                                                                                                                                           
    // Check length of student ID and length of data                                                                                                                                                                                                                                                                                                    
    if(siStuIdLen < 0 || nSize< nPos + siStuIdLen)  //allow stuid len =0                                                                                                                                                                                                                                                                                                   
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG
        printf("ReturnDataInvalid siStuIdLen\n");                                                                                                                                                                                                                                                                                                           
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }         
	if (siStuIdLen>0)
	{ 
		memcpy(bzField, &bzReturn[nPos], siStuIdLen);                                                                                                                                                                                                                                                                                                       
		bzField[siStuIdLen] = '\0';                                                                                                                                                                                                                                                                                                                         
	  // Parse student id                                                                                                                                                                                                                                                                                                                                 
	   iRet = ParseStudentId(bzField);  
	   if (iRet !=0) return iRet;                                                                                                                                                                                                                                                                                                                          
	  
		// Move to the end of student id data                                                                                                                                                                                                                                                                                                               
	}
	nPos += siStuIdLen - 1;                                                                                                                                                                                                                                                                                                                             
 	
                                                                                                                                                                                                                                                                                                                                                        
    /* Get cert flag */                                                                                                                                                                                                                                                                                                                                 
    // Start position of cert flag data                                                                                                                                                                                                                                                                                                                 
    nPos++;                                                                                                                                                                                                                                                                                                                                             
    // Length of cert flag data                                                                                                                                                                                                                                                                                                                         
    const int DATALEN_CERTKIND = 1;                                                                                                                                                                                                                                                                                                                     
    // Check data length                                                                                                                                                                                                                                                                                                                                
    if(nSize< nPos + DATALEN_CERTKIND)                                                                                                                                                                                                                                                                                                                  
    {
        #ifdef ConnMgmt_DEBUG
        printf("ReturnDataInvalid DATALEN_CERTKIND\n");                                                                                                                                                                                                                                                                                                     
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation; 
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }
    memcpy(bzField, &bzReturn[nPos], DATALEN_CERTKIND);                                                                                                                                                                                                                                                                                                 
    bzField[DATALEN_CERTKIND] = '\0';                                                                                                                                                                                                                                                                                                                   
    // Parse cert kind data                                                                                                                                                                                                                                                                                                                             
    iRet = ParseCertKind(bzField, pBootCert);                                                                                                                                                                                                                                                                                                           
    if (iRet != 0) return iRet;
    if (pBootCert->CertKind == NoCert) return iRet=0;                                                                                                                                                                                                                                                                                                                         
                                                                                                                                                                                                                                                                                                                                                        
    /* Get expiration date of current cert */                                                                                                                                                                                                                                                                                                           
    // Start position of expire information exist flag                                                                                                                                                                                                                                                                                                  
    nPos++;                                                                                                                                                                                                                                                                                                                                             
    // Length of expire information exist flag data                                                                                                                                                                                                                                                                                                     
    const int DATALEN_EXPIREFLAG = 1;                                                                                                                                                                                                                                                                                                                   
    // Check data length                                                                                                                                                                                                                                                                                                                                
    if(nSize < nPos + DATALEN_EXPIREFLAG)                                                                                                                                                                                                                                                                                                               
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG
        printf("ReturnDataInvalid DATALEN_EXPIREFLAG\n");                                                                                                                                                                                                                                                                                                   
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;  
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
    memcpy(bzField, &bzReturn[nPos], DATALEN_EXPIREFLAG);                                                                                                                                                                                                                                                                                               
    bzField[DATALEN_EXPIREFLAG] = '\0';                                                                                                                                                                                                                                                                                                                 
    // Parse expire information flag data                                                                                                                                                                                                                                                                                                               
    unsigned int expireExist = 0;     //0, false, noexist                                                                                                                                                                                                                                                                                                                  
    iRet = ParseExpireExistFlag(bzField, &expireExist );                                                                                                                                                                                                                                                                                                

    // Parse expire information                                                                                                                                                                                                                                                                                                                         
    if(expireExist)                                                                                                                                                                                                                                                                                                               
    {                                                                                                                                                                                                                                                                                                                                                   
        // Start position of expire information data                                                                                                                                                                                                                                                                                                        
        nPos++;                                                                                                                                                                                                                                                                                                                                             
        // Length of expire information data                                                                                                                                                                                                                                                                                                                
        const int DATALEN_EXPIREINFO = 9;                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                            
        // Check data length                                                                                                                                                                                                                                                                                                                                
        if(nSize< nPos + DATALEN_EXPIREINFO)                                                                                                                                                                                                                                                                                                                
        {                                                                                                                                                                                                                                                                                                                                                   
            #ifdef ConnMgmt_DEBUG
            printf("ReturnDataInvalid DATALEN_EXPIREINFO\n");                                                                                                                                                                                                                                                                                                   
            #endif
            iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;
            WriteLog(iRet);   
            return iRet;                                                                                                                                                                                                                                                                                                                                        
        }
        memcpy(bzField, &bzReturn[nPos], DATALEN_EXPIREINFO);                                                                                                                                                                                                                                                                                               
        bzField[DATALEN_EXPIREINFO] = '\0';                                                                                                                                                                                                                                                                                                                 
        // Parse expire information data                                                                                                                                                                                                                                                                                                                    
        iRet = ParseExpireInfo(bzField, pBootCert);                                                                                                                                                                                                                                                                                                         
        if (iRet !=0) return iRet;                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                            
        // Move to the end of expire information data                                                                                                                                                                                                                                                                                                       
        nPos += DATALEN_EXPIREINFO - 1;                                                                                                                                                                                                                                                                                                                     
    }                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                        
    /* Get boot cert */                                                                                                                                                                                                                                                                                                                                 
    // Start position of cert data length                                                                                                                                                                                                                                                                                                               
    nPos++;                                                                                                                                                                                                                                                                                                                                             
    // Length of cert data length                                                                                                                                                                                                                                                                                                                       
    const int DATALEN_CERTLENGTH = 2;                                                                                                                                                                                                                                                                                                                   
    // Check data length                                                                                                                                                                                                                                                                                                                                
    if(nSize< nPos + DATALEN_CERTLENGTH)                                                                                                                                                                                                                                                                                                                
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG
        printf("ReturnDataInvalid\n");                                                                                                                                                                                                                                                                                                                      
        #endif
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation; 
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
    memcpy(bzField, &bzReturn[nPos], DATALEN_CERTLENGTH);                                                                                                                                                                                                                                                                                               
    bzField[DATALEN_CERTLENGTH] = '\0';                                                                                                                                                                                                                                   
    short sCertLen = *(short *)bzField;	
    #ifdef ConnMgmt_DEBUG
    printf("cCertlen %d %d \n", bzField[0], bzField[1]);	
    printf("sCertLen = %d\n", sCertLen); 
    #endif
	
    // Get cert data                                                                                                                                                                                                                                                                                                                                    
    // Start position of cert data                                                                                                                                                                                                                                                                                                                      
    nPos += 2;                                                                                                                                                                                                                                                                                                                                          
    // Check length of data                                                                                                                                                                                                                                                                                                                             
    if(sCertLen <= 0 || nSize< nPos + sCertLen)                                                                                                                                                                                                                                                                                                         
    {                                                                                                                                                                                                                                                                                                                                                   
        //throw new ConnMgmtException(ConnMgmtExceptionStatus.ReturnDataInvalidation);                                                                                                                                                                                                                                                                      
        printf("ReturnDataInvalid\n");                                                                                                                                                                                                                                                                                                                      
        iRet = ConnMgmt_ExceptionStatus_ReturnDataInvalidation;                                                                                                                                                                                                                                                                                             
        WriteLog(iRet);   		
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                   
    memcpy(bzField, &bzReturn[nPos], sCertLen);                                                                                                                                                                                                                                                                                                         
    bzField[sCertLen] = '\0';                                                                                                                                                                                                                                                                                                                           

	// Save cert                                
    iRet = ParseCert(bzField, pBootCert, sCertLen);                                                                                                                                                                                                                                                                                                     
    if (iRet != 0) return iRet;
    #ifdef ConnMgmt_DEBUG
    printf("end of Parse\n");   
    #endif
    iRet=0;  
    return iRet;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
}                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Download cert form the web service                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="certKind">kind of cert: 1 PushCert 2 PullCert 3 ProvisonPacket 4 CA</param> 
/// <param name="pBootCert">the cert will be saved to this structl</param>   
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                                                                                     
int DownloadCert(DownloadKind certKind, BootCert * pBootCert)                                                                                                                                                                                                                                                                                       
{      
    int iRet=1;                                                                                                                                                                                                                                                                                                                                         
    struct soap soap;                                                                                                                                                                                                                                                                                                                                   
    char soap_endpoint[MAXSTRLEN] = "", soap_action[MAXSTRLEN], temp[MAXSTRLEN], *temp2, proxyServer[MAXSTRLEN], proxyPort[MAXSTRLEN] ; 
    struct xsd__base64Binary exchangeDataReturn;    
    int i=0;  
    char localTime[MAXSTRLEN] = "";  
    //------------------------------->
    DeviceInfo deviceInfo;
    iRet = DeviceInfo_Construct(&deviceInfo);
    if (iRet != 0) 
    { 
        iRet = ConnMgmt_invoke_DeviceInfo_Construct_Error;
        WriteLog(iRet);
        //return iRet; 
    }

    OtherInfo otherInfo;
    iRet = OtherInfo_Construct(&otherInfo);
    if(iRet != 0)
    { 
        iRet = ConnMgmt_invoke_OtherInfo_Construct_Error;
        WriteLog(iRet);
        //return iRet; 
    }
	
    ServerInfo serverInfo;
    iRet = ServerInfo_Construct(&serverInfo);
    if(iRet != 0)
    { 
        iRet = ConnMgmt_invoke_ServerInfo_Construct_Error;
        WriteLog(iRet);
        return iRet; 
    }

    strncpy(temp, serverInfo.ServerAddress, 8);                                                                                                                                                                                                                                                                                                                     
    for(i=0;i<8;i++)                                                                                                                                                                                                                                                                                                                                    
    {                                                                                                                                                                                                                                                                                                                                                   
        temp[i] = tolower(temp[i]);                                                                                                                                                                                                                                                                                                                         
    }                                                                                                                                                                                                                                                                                                                                                   
    if(strcmp(temp, "https://")!=0) //not equal                                                                                                                                                                                                                                                                                                         
    {                                                                                                                                                                                                                                                                                                                                                   
        strcpy(soap_endpoint, "https://");                                                                                                                                                                                                                                                                                                                  
    }                                                                                                                                                                                                                                                                                                                                                   
    strcat(soap_endpoint, serverInfo.ServerAddress); 
	strcat(soap_endpoint, URLPOSTFIX); 
    
    //judge if serverIP is "/", "", ":"
    if ( (!strncmp(soap_endpoint, "https:///", 9)) || (!strncmp(soap_endpoint, "https://:", 9)) )
    {      
           iRet = ConnMgmt_SOAP_HTTP_ERROR ;
           WriteLog(iRet);
           return iRet;   
    }
    

    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                 
    printf("connect to server %s\n", soap_endpoint);    
    #endif   
    //<-------------------------------
    WritestrLog (MODULE_CONNMGMT,  soap_endpoint);                                                                                                                                                                                                                                                                                                              
    strcpy(soap_action, "");                                                                                                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                                                                                                    
    struct tm *timenow;                                                                                                                                                                                                                                                                                                                                  
    struct timeval tv;                                                                                                                                                                                                                                                                                                                                  
    struct timezone tz;                                                                                                                                                                                                                                                                                                                                 
    gettimeofday(&tv, &tz);                                                                                                                                                                                                                                                                                                                             
    timenow = localtime(&tv.tv_sec);                                                                                                                                                                                                                                                                                                                    
    strftime(localTime, MAXSTRLEN, "%F %T.", timenow);                                                                                                                                                                                                                                                                                                  
    float tempf = 0;                                                                                                                                                                                                                                                                                                                                        
    tempf=(float)tv.tv_usec/1000000;                                                                                                                                                                                                                                                                                                                    
    sprintf(temp, "%.3f", tempf);                                                                                                                                                                                                                                                                                                                       
    strcat(localTime, temp+2); 
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                       
    printf("LocalTime = %s \n", localTime); 
    #endif                                                                                                                                                                                                                                                                                                            

    soap_init(&soap);                                                                                                                                                                                                                                                                                                                                   
    //Indicates the time an XML Web service client waits for a synchronous XML Web service request to complete (in milliseconds).                                                                                                                                                                              
    soap.connect_timeout = TIMEOUT/1000; //unit is second   

    if (serverInfo.UseProxy && strcmp(serverInfo.ProxyAddress, "") != 0)
    {       
        strcpy(proxyServer, serverInfo.ProxyAddress); 
        temp2 = strchr(proxyServer, ':');
	 if (temp2 == NULL) 
	 {
	    return iRet = ConnMgmt_ExceptionStatus_ProxyNameResolutionFailure;
        }
        temp2[0] = '\0';
        soap.proxy_host = proxyServer;
		
        strcpy(proxyPort, serverInfo.ProxyAddress);
        temp2 = strchr(proxyPort, ':');	
        soap.proxy_port = atoi(temp2+1);

        soap.proxy_userid = serverInfo.ProxyUser;
        soap.proxy_passwd = serverInfo.ProxyPwd;
    }

    if (ConnMgmt_SSL_Enabled)                                                                                                                                                                                                                                                                                     
    {
        if(soap_ssl_client_context(&soap, SOAP_SSL_DEFAULT, NULL, NULL, otherInfo.CARoot, NULL, NULL))                                                                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                                                                                                                   
            #ifdef ConnMgmt_DEBUG 
            printf("----------------1 soap error %d-----------\n", soap.error);
            soap_print_fault(&soap, stderr);
            #endif  
           
			WritestrLog (MODULE_CONNMGMT, *soap_faultstring(&soap) );  
			WritestrLog (MODULE_CONNMGMT, *soap_faultdetail(&soap) );  

            if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                                                                                                                                   
            else                                                                                                                                                                                                                                                                                                                                                
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
            } 
            WriteLog(iRet);
		    return iRet;                                                                                                                                                                                                                                                                                                                 
        }
    }                                                                                                                                                                                                                                                                                                                                                  
    else
    {
        if(soap_ssl_client_context(&soap, SOAP_SSL_NO_AUTHENTICATION, NULL, NULL, NULL, NULL, NULL))                                                                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                                                                                                                   
            #ifdef ConnMgmt_DEBUG 
            printf("----------------1  soap error %d-----------\n", soap.error);
            soap_print_fault(&soap, stderr);
            #endif  
                                                                                                                                                                                                                                                                                                                              
            if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                                                                                                                                   
            else                                                                                                                                                                                                                                                                                                                                                
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
            }
            WriteLog(iRet);
            return iRet;                                                                                                                                                                                                                                                                                                                           
        }        
    }

    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                                                     
    printf("HWId = %s \n", deviceInfo.HardwareID);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
    #endif       
                                                                                                                                                                                                                                                                                                                                                 
    soap_call_ns1__exchangeDataEx(&soap, soap_endpoint, soap_action, deviceInfo.HardwareID, deviceInfo.BootTick, (int)certKind, deviceInfo.IPAddress, deviceInfo.LocDns, deviceInfo.Wins, deviceInfo.GateWay, deviceInfo.Proxy, localTime, deviceInfo.HostName,&exchangeDataReturn);                                                                                                  
                                                                                                                                                                                                                                                                                                                                                      
    if (soap.error)                                                                                                                                                                                                                                                                                                                                     
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG 
        printf("----------------2  soap error %d-----------\n", soap.error);
        soap_print_fault(&soap, stderr);
        #endif  
                                                                                                                                                                                                                                                                                                                          
        if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
        {                                                                                                                                                                                                                                                                                                                                                   
            iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
        }                                                                                                                                                                                                                                                                                                                                                   
        else                                                                                                                                                                                                                                                                                                                                                
        {                                                                                                                                                                                                                                                                                                                                                   
            iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
        }
        WriteLog(iRet);
        return iRet;                                                                                                                                                                                                                                                                                                                                         
    }                                                                                                                                                                                                                                                                                                                                                   
    else                                                                                                                                                                                                                                                                                                                                                
    {
        #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                         
        for(i=0;i<exchangeDataReturn.__size;i++)                                                                                                                                                                                                                                                                                                            
        {
            //printf("%d=%d;", i, exchangeDataReturn.__ptr[i]);                                                                                                                                                                                                                                                                                                 
            printf("%4d",exchangeDataReturn.__ptr[i]); 
        }
        printf("\n");                                                                                                                                                                                                                                                                                                                                       
        printf("result size = %d \n", exchangeDataReturn.__size);                                                                                                                                                                                                                                                                                           
        printf("result id = %s \n", exchangeDataReturn.id);                                                                                                                                                                                                                                                                                                 
        printf("result type = %s \n", exchangeDataReturn.type);                                                                                                                                                                                                                                                                                             
        printf("result options = %s \n", exchangeDataReturn.options);
        #endif                                                                                                                                                                                                                                                                                       
        iRet = Parse(exchangeDataReturn.__ptr, exchangeDataReturn.__size, pBootCert);                                                                                                                                                                                                                                                           
    }                                                                                                                                                                                                                                                                                                                                                   
    soap_destroy(&soap);                                                                                                                                                                                                                                                                                                                                
    soap_end(&soap);                                                                                                                                                                                                                                                                                                                                    
    soap_done(&soap);
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                      


int ConnMgmt_HTTPDownload(BootCert * pBootCert,int certKind,unsigned char *ServerPKCert, unsigned char *IntelPKCert)
{
    int iRet=1;                                                                                                                                                                                                                                                                                                                                         
    struct soap soap;                                                                                                                                                                                                                                                                                                                                   
    char soap_endpoint[MAXSTRLEN] = "", soap_action[MAXSTRLEN], temp[MAXSTRLEN], *temp2, proxyServer[MAXSTRLEN], proxyPort[MAXSTRLEN] ; 
    struct xsd__base64Binary exchangeDataReturn;    
    int i=0;  
    char localTime[MAXSTRLEN] = "";  
    //------------------------------->
    DeviceInfo deviceInfo;
    iRet = DeviceInfo_Construct(&deviceInfo);
    if (iRet != 0) 
    { 
        iRet = ConnMgmt_invoke_DeviceInfo_Construct_Error;
        WriteLog(iRet);
        //return iRet; 
    }
   
    OtherInfo otherInfo;
    iRet = OtherInfo_Construct(&otherInfo);
    if(iRet != 0)
    { 
        iRet = ConnMgmt_invoke_OtherInfo_Construct_Error;
        WriteLog(iRet);
        //return iRet; 
    }
	
    ServerInfo serverInfo;
    iRet = ServerInfo_Construct(&serverInfo);
    if(iRet != 0)
    { 
        iRet = ConnMgmt_invoke_ServerInfo_Construct_Error;
        WriteLog(iRet);
        return iRet; 
    }

    strncpy(temp, serverInfo.ServerAddress, 7);                                                                                                                                                                                                                                                                                                                     
    for(i=0;i<7;i++)                                                                                                                                                                                                                                                                                                                                    
    {                                                                                                                                                                                                                                                                                                                                                   
        temp[i] = tolower(temp[i]);                                                                                                                                                                                                                                                                                                                         
    }                                                                                                                                                                                                                                                                                                                                                   
    if(strcmp(temp, "http://")!=0) //not equal                                                                                                                                                                                                                                                                                                         
    {                                                                                                                                                                                                                                                                                                                                                   
        strcpy(soap_endpoint, "http://");                                                                                                                                                                                                                                                                                                                  
    }                                                                                                                                                                                                                                                                                                                                                   
    strcat(soap_endpoint, serverInfo.ServerAddress); 
	strcat(soap_endpoint, URLPOSTFIX); 
    
    //judge if serverIP is "/", "", ":"
    if ( (!strncmp(soap_endpoint, "http:///", 8)) || (!strncmp(soap_endpoint, "http://:", 8)) )
    {      
           iRet = ConnMgmt_SOAP_HTTP_ERROR ;
           WriteLog(iRet);
           return iRet;   
    }
    

    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                 
    printf("connect to server %s\n", soap_endpoint);    
    #endif   
    //<-------------------------------
    WritestrLog (MODULE_CONNMGMT,  soap_endpoint);                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                     
    strcpy(soap_action, "");                                                                                                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                                                                                                    
    struct tm *timenow;                                                                                                                                                                                                                                                                                                                                  
    struct timeval tv;                                                                                                                                                                                                                                                                                                                                  
    struct timezone tz;                                                                                                                                                                                                                                                                                                                                 
    gettimeofday(&tv, &tz);                                                                                                                                                                                                                                                                                                                             
    timenow = localtime(&tv.tv_sec);                                                                                                                                                                                                                                                                                                                    
    strftime(localTime, MAXSTRLEN, "%F %T.", timenow);                                                                                                                                                                                                                                                                                                  
    float tempf = 0;                                                                                                                                                                                                                                                                                                                                        
    tempf=(float)tv.tv_usec/1000000;                                                                                                                                                                                                                                                                                                                    
    sprintf(temp, "%.3f", tempf);                                                                                                                                                                                                                                                                                                                       
    strcat(localTime, temp+2); 
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                       
    printf("LocalTime = %s \n", localTime); 
    #endif                                                                                                                                                                                                                                                                                                            

    soap_init(&soap);                                                                                                                                                                                                                                                                                                                                   
    //Indicates the time an XML Web service client waits for a synchronous XML Web service request to complete (in milliseconds).                                                                                                                                                                              
    soap.connect_timeout = TIMEOUT/1000; //unit is second   

    if (serverInfo.UseProxy && strcmp(serverInfo.ProxyAddress, "") != 0)
    {       
        strcpy(proxyServer, serverInfo.ProxyAddress); 
        temp2 = strchr(proxyServer, ':');
		 if (temp2 == NULL) 
		 {
			return iRet = ConnMgmt_ExceptionStatus_ProxyNameResolutionFailure;
			}
			temp2[0] = '\0';
			soap.proxy_host = proxyServer;
			
			strcpy(proxyPort, serverInfo.ProxyAddress);
			temp2 = strchr(proxyPort, ':');	
			soap.proxy_port = atoi(temp2+1);

			soap.proxy_userid = serverInfo.ProxyUser;
			soap.proxy_passwd = serverInfo.ProxyPwd;
		}

 
        if(soap_ssl_client_context(&soap, SOAP_SSL_NO_AUTHENTICATION, NULL, NULL, NULL, NULL, NULL))                                                                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                                                                                                                   
            #ifdef ConnMgmt_DEBUG 
            printf("----------------1  soap error %d-----------\n", soap.error);
            soap_print_fault(&soap, stderr);
            #endif  
                                                                                                                                                                                                                                                                                                                              
            if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                                                                                                                                   
            else                                                                                                                                                                                                                                                                                                                                                
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
            }
            WriteLog(iRet);
            return iRet;                                                                                                                                                                                                                                                                                                                           
        }        
 
    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                                                     
    printf("HWId = %s \n", deviceInfo.HardwareID);                                                                                                                                                                                                                                                                                                                            
 
    #endif       
                                                                                                                                                                                                                                                                                                                                 
    soap_call_ns1__exchangeDataHttp(&soap, soap_endpoint, soap_action, deviceInfo.HardwareID, deviceInfo.BootTick,certKind, deviceInfo.IPAddress, deviceInfo.LocDns, deviceInfo.Wins, deviceInfo.GateWay, deviceInfo.Proxy, localTime, deviceInfo.HostName,&exchangeDataReturn);                                                                                                  
                                                                                                                                                                                                                                                                                                                                                        
    if (soap.error)                                                                                                                                                                                                                                                                                                                                     
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG 
        printf("----------------2  soap error %d-----------\n", soap.error);
        soap_print_fault(&soap, stderr);
        #endif  
                                                                                                                                                                                                                                                                                                                          
        if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
        {                                                                                                                                                                                                                                                                                                                                                   
            iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
        }                                                                                                                                                                                                                                                                                                                                                   
        else                                                                                                                                                                                                                                                                                                                                                
        {                                                                                                                                                                                                                                                                                                                                                   
            iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
        }
        WriteLog(iRet);
        return iRet;                                                                                                                                                                                                                                                                                                                                         
    }                                                                                                                                                                                                                                                                                                                                                   
    else                                                                                                                                                                                                                                                                                                                                                
    {
        #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                         
        for(i=0;i<exchangeDataReturn.__size;i++)                                                                                                                                                                                                                                                                                                            
        {
            //printf("%d=%d;", i, exchangeDataReturn.__ptr[i]);                                                                                                                                                                                                                                                                                                 
            printf("%4d",exchangeDataReturn.__ptr[i]); 
        }
        printf("\n");                                                                                                                                                                                                                                                                                                                                       
        printf("result size = %d \n", exchangeDataReturn.__size);                                                                                                                                                                                                                                                                                           
        printf("result id = %s \n", exchangeDataReturn.id);                                                                                                                                                                                                                                                                                                 
        printf("result type = %s \n", exchangeDataReturn.type);                                                                                                                                                                                                                                                                                             
        printf("result options = %s \n", exchangeDataReturn.options);
        #endif                                                                                                                                                                                                                                                                                       
        
		iRet = ParseHttpPacket(exchangeDataReturn.__ptr, exchangeDataReturn.__size,pBootCert, ServerPKCert,IntelPKCert); 


 #ifdef ConnMgmt_DEBUG                                                                                                                                                 
FILE* file=NULL;
if ((file= fopen("provision.bin","wb"))!=NULL)
{
if (certKind==1)
{        for(i=0;i<284;i++)                                                                                                                              
        {
	
	printf("0x%02x	",ServerPKCert[i]);
	if (i%8==7)
	printf("\n");

	fprintf(file,"%02X ", ServerPKCert[i]);
	}
        printf("\n");     
	for(i=0;i<284;i++)
        {
        printf("0x%2x	",IntelPKCert[i]);
	if (i%8==7)
	printf("\n");
	fprintf(file,"%02X ", IntelPKCert[i]);
        }
        printf("\n");
}
fclose(file);
}
#endif
    }                                                                                                                                                                                                                                                                                                                                                   
    soap_destroy(&soap);                                                                                                                                                                                                                                                                                                                                
    soap_end(&soap);                                                                                                                                                                                                                                                                                                                                    
    soap_done(&soap);
    return iRet;  
}
                                                                                                                                                                                                                                                                                                                                                    
/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// send got cert info to web service                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="updateResultKind">0:update failed; 1:shared secret; 2:special cert</param>                                                                                                                                                                                                                                                                                 
/// <returns>0: success; !0: failed</returns> 
int SendUpdateResult(Protocol_UpdateResult updateResultKind)                                                                                                                                                                                                                                                                                        
{                                                                                                                                                                                                                                                                                                                                                   
    int iRet=1;                                                                                                                                                                                                                                                                                                                                         
    struct soap soap;                                                                                                                                                                                                                                                                                                                                   
    char soap_endpoint[MAXSTRLEN] = "", soap_action[MAXSTRLEN], temp[MAXSTRLEN], *temp2, proxyServer[MAXSTRLEN], proxyPort[MAXSTRLEN] ; 
    struct ns1__UpdateResultResponse UpdateResultResponse;                                                                                                                                                                                                                                                                                            
    int i;
	
    DeviceInfo deviceInfo;                                                                                                                                                                                                                                                                                                                     
    iRet = DeviceInfo_Construct(&deviceInfo);                                                                                                                                                                                                                                                                                                                  
    if (iRet != 0) 
    { 
        iRet = ConnMgmt_invoke_DeviceInfo_Construct_Error;
        WriteLog(iRet);
        //return iRet; 
    }

    OtherInfo otherInfo;
    iRet = OtherInfo_Construct(&otherInfo);
    if (iRet != 0) 
    { 
        iRet = ConnMgmt_invoke_OtherInfo_Construct_Error;
        WriteLog(iRet);
        //return iRet; 
    } 

    ServerInfo serverInfo;
    iRet = ServerInfo_Construct(&serverInfo);
    if (iRet != 0) 
    { 
        iRet = ConnMgmt_invoke_ServerInfo_Construct_Error;
        WriteLog(iRet);
        return iRet; 
    }

    strncpy(temp, serverInfo.ServerAddress, 8);                                                                                                                                                                                                                                                                                                                     
    for(i=0;i<8;i++)                                                                                                                                                                                                                                                                                                                                    
    {                                                                                                                                                                                                                                                                                                                                                   
        temp[i] = tolower(temp[i]);                                                                                                                                                                                                                                                                                                                         
    }                                                                                                                                                                                                                                                                                                                                                   
    if(strcmp(temp, "https://")!=0) //not equal                                                                                                                                                                                                                                                                                                         
    {                                                                                                                                                                                                                                                                                                                                                   
        strcpy(soap_endpoint, "https://");                                                                                                                                                                                                                                                                                                                  
    }                                                                                                                                                                                                                                                                                                                                                   
    strcat(soap_endpoint, serverInfo.ServerAddress);                                                                                                                                                                                                                                                                                                                
    strcat(soap_endpoint, URLPOSTFIX); 

    //judge if serverIP is "/", "", ":"
    if ( (!strncmp(soap_endpoint, "https:///", 9)) || (!strncmp(soap_endpoint, "https://:", 9)) )
    { 	   
	   iRet = ConnMgmt_SOAP_HTTP_ERROR ;
           WriteLog(iRet);
	   return iRet;
    }

    #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                 
    printf("connect to server %s\n", soap_endpoint);    
    #endif     
                                                                                                                                                                                                                                                                                                              
    strcpy(soap_action, "");                                                                                                                                                                                                                                                                                                                  
    soap_init(&soap);                                                                                                                                                                                                                                                                           
    

    //Indicates the time an XML Web service client waits for a synchronous XML Web service request to complete (in milliseconds).                                                                                                                                                                              
    soap.connect_timeout = TIMEOUT/1000; //unit is second    
    
    if (strcmp(serverInfo.ProxyAddress, "") != 0)
    {       
        strcpy(proxyServer, serverInfo.ProxyAddress); 
	 temp2 = strchr(proxyServer, ':');
        if (temp2 == NULL) 
	 {
	    return iRet = ConnMgmt_ExceptionStatus_ProxyNameResolutionFailure;
        }
        temp2[0] = '\0';
        soap.proxy_host = proxyServer;
		
        strcpy(proxyPort, serverInfo.ProxyAddress);
	 temp2 = strchr(proxyPort, ':');	
        soap.proxy_port = atoi(temp2+1);

        soap.proxy_userid = serverInfo.ProxyUser;
        soap.proxy_passwd = serverInfo.ProxyPwd;
    }
   
    if (ConnMgmt_SSL_Enabled)                                                                                                                                                                                                                                                                                     
    {
        if(soap_ssl_client_context(&soap, SOAP_SSL_DEFAULT, NULL, NULL, otherInfo.CARoot, NULL, NULL))                                                                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                                                                                                                 
            #ifdef ConnMgmt_DEBUG         
            printf("----------------3   soap error %d-----------\n", soap.error); 
            soap_print_fault(&soap, stderr); 
            #endif 
                                                                                                                                                                                                                                                                                     
            if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                                                                                                                                   
            else                                                                                                                                                                                                                                                                                                                                                
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
            }
            WriteLog(iRet); 
            return iRet;                                                                                                                                                                                                                                                                                                                                        
        } 
    }
    else
    {
        if(soap_ssl_client_context(&soap, SOAP_SSL_NO_AUTHENTICATION, NULL, NULL, NULL, NULL, NULL))                                                                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                                                                                                                 
            #ifdef ConnMgmt_DEBUG         
            printf("----------------3  soap error %d-----------\n", soap.error); 
            soap_print_fault(&soap, stderr); 
            #endif 
                                                                                                                                                                                                                                                                                     
            if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                                                                                                                                   
            else                                                                                                                                                                                                                                                                                                                                                
            {                                                                                                                                                                                                                                                                                                                                                   
                iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
            }    
            WriteLog(iRet); 		
            return iRet;                                                                                                                                                                                                                                                                                                                                        
        } 
    }  

    soap_call_ns1__UpdateResult(&soap, soap_endpoint, soap_action, deviceInfo.HardwareID, (int)updateResultKind, &UpdateResultResponse);                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                                                                        
    if (soap.error)                                                                                                                                                                                                                                                                                                                                     
    {                                                                                                                                                                                                                                                                                                                                                   
        #ifdef ConnMgmt_DEBUG                                                                                                                                                                                                                                                                                                                
        printf("----------------4  soap error %d-----------\n", soap.error);
        soap_print_fault(&soap, stderr);
        #endif         
                                                                                                                                                                                                                                                                          
        if (soap.error > 200)                                                                                                                                                                                                                                                                                                                               
        {                                                                                                                                                                                                                                                                                                                                                   
            iRet = soap.error + ConnMgmt_Http_Base;                                                                                                                                                                                                                                                                                                             
        }                                                                                                                                                                                                                                                                                                                                                   
        else                                                                                                                                                                                                                                                                                                                                                
        {                                                                                                                                                                                                                                                                                                                                                   
            iRet = soap.error + ConnMgmt_Soap_Base;                                                                                                                                                                                                                                                                                                             
        }
        WriteLog(iRet); 
        return iRet;                                                                                                                                                                                                                                                                                                                                        
    }
    iRet=0; 
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                  

/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Tell web service, client has received shared secret                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/// <returns>0: success; !0: failed</returns> 
int ConnMgmt_SendSharedSecretUpdateSuccess()                                                                                                                                                                                                                                                                                                        
{                                                                                                                                                                                                                                                                                                                                                   
    int iRet = 1;   
    iRet = SendUpdateResult((Protocol_UpdateResult) Protocol_UpdateResult_SharedSecret);                                                                                                                                                                                                                                                                
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                                                                                                                                                                                                                                                                                                   

/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Tell web service, client has received special cert                                                                                                                                                                                                                                                                                                          
/// </summary>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/// <returns>0: success; !0: failed</returns> 																																																																																					
int ConnMgmt_SendSpecialCertUpdateSuccess()                                                                                                                                                                                                                                                                                                         
{                                                                                                                                                                                                                                                                                                                                                   
    int iRet = 1;                                                                                                                                                                                                                                                                                                                                       
    iRet = SendUpdateResult((Protocol_UpdateResult) Protocol_UpdateResult_SpecialCert);                                                                                                                                                                                                                                                                 
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                                                                                                                                                                                                                                                                                                   

/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Get Current State                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="pCurrentState">the data will be saved to this struct</param>                                                                                                                                                                                                                                                                                 
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                                                                                     
/*int ConnMgmt_GetCurrentState(CurrentState * pCurrentState)                                                                                                                                                                                                                                                                                          
{                                                                                                                                                                                                                                                                                                                                                   
    if (pCurrentState == NULL) return ConnMgmt_CurrentStatePointIsNull;
    int iRet=1;        	
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}*/                                                                                                                                                                                                                                                                                                                                                   

/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Download cert form the web service, including shared secret, special cert, normal cert                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="pBootCert">the data will be saved to this struct</param>                                                                                                                                                                                                                                                                                 
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                                                                                     
int ConnMgmt_DownloadBootCert(BootCert * pBootCert)                                                                                                                                                                                                                                                                                                 
{                                                                                                                                                                                                                                                                                                                                                   
    if (pBootCert == NULL) return ConnMgmt_BooCertPointIsNull;
    int iRet=1; 
    iRet = DownloadCert((DownloadKind)DownloadKind_PullCert, pBootCert); 		
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                                                                                                                                                                                                                                                                                                   

/// <summary>                                                                                                                                                                                                                                                                                                                                       
/// Download cert form the web service, including shared secret, special cert                                                                                                                                                                                                                                                                                                            
/// </summary>                                                                                                                                                                                                                                                                                                                                      
/// <param name="pBootCert">the data will be saved to this struct</param>                                                                                                                                                                                                                                                                                 
/// <returns>0: success; !0: failed</returns>                                                                                                                                                                                                                                                                                                                                                     
int ConnMgmt_DownloadSpecialBootCert(BootCert * pBootCert)                                                                                                                                                                                                                                                                                          
{                                                                                                                                                                                                                                                                                                                                                   
    if (pBootCert == NULL) return ConnMgmt_BooCertPointIsNull;
    int iRet=1; 
    iRet = DownloadCert((DownloadKind)DownloadKind_PushCert, pBootCert);                                                                                                                                                                                                                                                                                 
    return iRet;                                                                                                                                                                                                                                                                                                                                        
}                                                                                                                                                                                                                                                                                                                                                   
