static void net_ping(const char *host)
{
    SlPingStartCommand_t pingParams = {0};
    SlPingReport_t pingReport = {0};
    unsigned long ulIpAddr = 0;
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_PING_DONE);

    // Set the ping parameters
    pingParams.PingIntervalTime = 1000;
    pingParams.PingSize = 20;
    pingParams.PingRequestTimeout = 3000;
    pingParams.TotalNumberOfAttempts = 3;
    pingParams.Flags = 0;
    pingParams.Ip = g_ulGatewayIP;

    UART_PRINT("ping host: %s\r\n", host);

    sl_NetAppDnsGetHostByName((signed char*)host, strlen(host), &ulIpAddr, SL_AF_INET);
    UART_PRINT("host ip: 0x%08X\r\n", host);
    pingParams.Ip = ulIpAddr;
    sl_NetAppPingStart((SlPingStartCommand_t*)&pingParams, SL_AF_INET, (SlPingReport_t*)&pingReport, SimpleLinkPingReport);

    while (!IS_PING_DONE(g_ulStatus))
        _SlNonOsMainLoopTask();
}
int ConnectNetwork(Network* n, char* addr, int port)
{
	SlSockAddrIn_t sAddr;
	int addrSize;
	int retVal;
	unsigned long ipAddress;

	sl_NetAppDnsGetHostByName(addr, strlen(addr), &ipAddress, AF_INET);

	sAddr.sin_family = AF_INET;
	sAddr.sin_port = sl_Htons((unsigned short)port);
	sAddr.sin_addr.s_addr = sl_Htonl(ipAddress);

	addrSize = sizeof(SlSockAddrIn_t);

	n->my_socket = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
	if( n->my_socket < 0 ) {
		// error
		return -1;
	}

	retVal = sl_Connect(n->my_socket, ( SlSockAddr_t *)&sAddr, addrSize);
	if( retVal < 0 ) {
		// error
		sl_Close(n->my_socket);
	    return retVal;
	}

	SysTickIntRegister(SysTickIntHandler);
	SysTickPeriodSet(80000);
	SysTickEnable();

	return retVal;
}
int NetworkConnectTLS(Network *n, char* addr, int port, SlSockSecureFiles_t* certificates, unsigned char sec_method, unsigned int cipher, char server_verify)
{
    SlSockAddrIn_t sAddr;
    int addrSize;
    int retVal;
    unsigned long ipAddress;

    retVal = sl_NetAppDnsGetHostByName(addr, strlen(addr), &ipAddress, AF_INET);
    if (retVal < 0) {
        return -1;
    }

    sAddr.sin_family = AF_INET;
    sAddr.sin_port = sl_Htons((unsigned short)port);
    sAddr.sin_addr.s_addr = sl_Htonl(ipAddress);

    addrSize = sizeof(SlSockAddrIn_t);

    n->my_socket = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_SEC_SOCKET);
    if (n->my_socket < 0) {
        return -1;
    }

    SlSockSecureMethod method;
    method.secureMethod = sec_method;
    retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method));
    if (retVal < 0) {
        return retVal;
    }

    SlSockSecureMask mask;
    mask.secureMask = cipher;
    retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &mask, sizeof(mask));
    if (retVal < 0) {
        return retVal;
    }

    if (certificates != NULL) {
        retVal = sl_SetSockOpt(n->my_socket, SL_SOL_SOCKET, SL_SO_SECURE_FILES, certificates->secureFiles, sizeof(SlSockSecureFiles_t));
        if (retVal < 0)
        {
            return retVal;
        }
    }

    retVal = sl_Connect(n->my_socket, (SlSockAddr_t *)&sAddr, addrSize);
    if (retVal < 0) {
        if (server_verify || retVal != -453) {
            sl_Close(n->my_socket);
            return retVal;
        }
    }

    SysTickIntRegister(SysTickIntHandler);
    SysTickPeriodSet(80000);
    SysTickEnable();

    return retVal;
}
Exemple #4
0
//*****************************************************************************
//
//! getHostIP
//!
//! \brief  This function obtains the server IP address using a DNS lookup
//!
//! \param[in]  pcHostName        The server hostname
//! \param[out] pDestinationIP    This parameter is filled with host IP address.
//!
//! \return On success, +ve value is returned. On error, -ve value is returned
//!
//
//*****************************************************************************
long getHostIP(char* pcHostName, unsigned long * pDestinationIP)
{
    long lStatus = 0;

    lStatus = sl_NetAppDnsGetHostByName((signed char *) pcHostName,
                                            strlen(pcHostName),
                                            pDestinationIP, SL_AF_INET);
    return lStatus;
}
Exemple #5
0
STATIC int wlan_gethostbyname(const char *name, mp_uint_t len, uint8_t *out_ip, uint8_t family) {
    uint32_t ip;
    int result = sl_NetAppDnsGetHostByName((_i8 *)name, (_u16)len, (_u32*)&ip, (_u8)family);
    out_ip[0] = ip;
    out_ip[1] = ip >> 8;
    out_ip[2] = ip >> 16;
    out_ip[3] = ip >> 24;
    return result;
}
/*!
    \brief This function obtains the server IP address

    \param[in]      none

    \return         zero for success and -1 for error

    \warning
*/
static int32_t GetHostIP(void){
  int32_t status = -1;

  status = sl_NetAppDnsGetHostByName(appData.HostName,
                                       strlen(appData.HostName),
                                       &appData.DestinationIP, SL_AF_INET);
  if (status < 0){
    LCD_OutString("Unable to reach Host\n");
    return status;
  }
  return SUCCESS;
}
Exemple #7
0
//*****************************************************************************
//! \brief This function checks the internet connection by pinging 
//!     the external-host (HOST_NAME)
//!
//! \param  None
//!
//! \return  0 on success, negative error-code on error
//!
//*****************************************************************************
static long CheckInternetConnection()
{
    SlPingStartCommand_t pingParams = {0};
    SlPingReport_t pingReport = {0};

    unsigned long ulIpAddr = 0;
    long lRetVal = -1;

    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_PING_DONE);
    g_ulPingPacketsRecv = 0;

    // Set the ping parameters
    pingParams.PingIntervalTime = PING_INTERVAL;
    pingParams.PingSize = PING_PKT_SIZE;
    pingParams.PingRequestTimeout = PING_TIMEOUT;
    pingParams.TotalNumberOfAttempts = NO_OF_ATTEMPTS;
    pingParams.Flags = 0;
    pingParams.Ip = g_ulGatewayIP;

    // Get external host IP address
    lRetVal = sl_NetAppDnsGetHostByName((signed char*)HOST_NAME, sizeof(HOST_NAME),
                                                &ulIpAddr, SL_AF_INET);
    ASSERT_ON_ERROR(lRetVal);

    // Replace the ping address to match HOST_NAME's IP address
    pingParams.Ip = ulIpAddr;

    // Try to ping HOST_NAME
    lRetVal = sl_NetAppPingStart((SlPingStartCommand_t*)&pingParams, SL_AF_INET,
                            (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
    ASSERT_ON_ERROR(lRetVal);

    // Wait
    while(!IS_PING_DONE(g_ulStatus))
    { 
      // Wait for Ping Event 
#ifndef SL_PLATFORM_MULTI_THREADED
        _SlNonOsMainLoopTask(); 
#endif
    }

    if (0 == g_ulPingPacketsRecv)
    {
        // Problem with internet connection
        ASSERT_ON_ERROR(INTERNET_CONNECTION_FAILED);
    }

    // Internet connection is successful
    return SUCCESS;
}
struct hostent *gethostbyname(const char *name) {
  static _u32 ip;
  static struct hostent he;

  int err = sl_NetAppDnsGetHostByName((_i8 *) name, strlen(name), &ip, AF_INET);
  if (err != 0) return NULL;
  ip = htonl(ip);
  he.h_name = (char *) &ip;
  he.h_aliases = NULL;
  he.h_addrtype = AF_INET;
  he.h_length = 1;
  he.h_addr_list = &he.h_name;
  return &he;
}
/*
 * ::gethostbyname()
 */
struct hostent *gethostbyname(const char *name)
{
    static struct hostent he;
    static struct in_addr ia;
    static struct in_addr *ia_list[2];
    static char *alias_list[1];
    unsigned long ip;

    int result = sl_NetAppDnsGetHostByName((int8_t*)name, strlen(name), &ip,
                                           SL_AF_INET);

    if (result < 0)
    {
        switch (result)
        {
            default:
                h_errno = NO_RECOVERY;
                break;
            case SL_NET_APP_DNS_MALFORMED_PACKET:
            case SL_NET_APP_DNS_MISMATCHED_RESPONSE:
            case SL_POOL_IS_EMPTY:
                h_errno = TRY_AGAIN;
                break;
            case SL_NET_APP_DNS_QUERY_NO_RESPONSE:
            case SL_NET_APP_DNS_NO_SERVER:
            case SL_NET_APP_DNS_QUERY_FAILED:
                h_errno = HOST_NOT_FOUND;
                break;
        }
        return NULL;
    }

    alias_list[0] = NULL;

    ia.s_addr = ip;
    ia_list[0] = &ia;
    ia_list[1] = NULL;

    he.h_name = (char*)name;
    he.h_aliases = alias_list;
    he.h_addrtype = AF_INET;
    he.h_length = 4;
    he.h_addr_list = (char**)ia_list;

    return &he;
}
//*****************************************************************************
//
//! Network_IF_GetHostIP
//!
//! \brief  This function obtains the server IP address using a DNS lookup
//!
//! \param[in]  pcHostName        The server hostname
//! \param[out] pDestinationIP    This parameter is filled with host IP address.
//!
//! \return On success, +ve value is returned. On error, -ve value is returned
//!
//
//*****************************************************************************
long Network_IF_GetHostIP( char* pcHostName,unsigned long * pDestinationIP )
{
    long lStatus = 0;

    lStatus = sl_NetAppDnsGetHostByName((signed char *) pcHostName,
                                            strlen(pcHostName),
                                            pDestinationIP, SL_AF_INET);
    ASSERT_ON_ERROR(lStatus);

    UART_PRINT("Get Host IP succeeded.\n\rHost: %s IP: %d.%d.%d.%d \n\r\n\r",
                    pcHostName, SL_IPV4_BYTE(*pDestinationIP,3),
                    SL_IPV4_BYTE(*pDestinationIP,2),
                    SL_IPV4_BYTE(*pDestinationIP,1),
                    SL_IPV4_BYTE(*pDestinationIP,0));
    return lStatus;

}
Exemple #11
0
char* HTTP_Request(const char *hostName, uint16_t port, const char *method, const char *request, char *requestData1, char *requestData2) {
	SlSockAddrIn_t Addr; int32_t retVal; uint32_t ASize = 0;
	cleanup();
	strcpy(HostName, hostName);
	UARTprintf("\r\n\r\nUsing host: %s\r\n", HostName);
	retVal = sl_NetAppDnsGetHostByName(HostName, strlen(HostName),&DestinationIP, SL_AF_INET);
	if(retVal == 0){
		Addr.sin_family = SL_AF_INET;
		Addr.sin_port = sl_Htons(port);
		Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian 
		ASize = sizeof(SlSockAddrIn_t);
		SockID = -1;
		SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
		if( SockID >= 0 ){
			retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize);
		}
		if((SockID >= 0)&&(retVal >= 0)){
			uint32_t copyIndex = 0;
			strcpy(&SendBuff[copyIndex], method);  copyIndex += strlen(method);
			strcpy(&SendBuff[copyIndex], " ");     copyIndex += 1;
			strcpy(&SendBuff[copyIndex], request); copyIndex += strlen(request);
			if(requestData1) {
				strcpy(&SendBuff[copyIndex], requestData1);
				copyIndex += strlen(requestData1);
			}
			if(requestData2) {
				strcpy(&SendBuff[copyIndex], requestData2);
				copyIndex += strlen(requestData2);
			}
			strcpy(&SendBuff[copyIndex], REQ_1);   copyIndex += strlen(REQ_1);
			strcpy(&SendBuff[copyIndex], hostName); copyIndex += strlen(hostName);
			strcpy(&SendBuff[copyIndex], REQ_2);   copyIndex += strlen(REQ_2);
			SendBuff[copyIndex] = '\0';
			
			UARTprintf("Sending request: %s\r\n\r\n", SendBuff);
			sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET 
			sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response 
			sl_Close(SockID);
			
			return Recvbuff;
		}
	}
	return NULL;
}
Exemple #12
0
/*!
    \brief This function checks the internet connection by pinging
           the external-host (HOST_NAME)

    \param[in]  None

    \return     0 on success, negative error-code on error
*/
static _i32 checkInternetConnection()
{
    SlPingStartCommand_t pingParams = {0};
    SlPingReport_t pingReport = {0};

    _u32 ipAddr = 0;

    _i32 retVal = -1;

    CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
    g_PingPacketsRecv = 0;

    /* Set the ping parameters */
    pingParams.PingIntervalTime = PING_INTERVAL;
    pingParams.PingSize = PING_PKT_SIZE;
    pingParams.PingRequestTimeout = PING_TIMEOUT;
    pingParams.TotalNumberOfAttempts = NO_OF_ATTEMPTS;
    pingParams.Flags = 0;
    pingParams.Ip = g_GatewayIP;

    /* Check for Internet connection */
    retVal = sl_NetAppDnsGetHostByName((_i8 *)HOST_NAME, pal_Strlen(HOST_NAME), &ipAddr, SL_AF_INET);
    ASSERT_ON_ERROR(retVal);

    /* Replace the ping address to match HOST_NAME's IP address */
    pingParams.Ip = ipAddr;

    /* Try to ping HOST_NAME */
    retVal = sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
                                 (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
    ASSERT_ON_ERROR(retVal);

    /* Wait */
    while(!IS_PING_DONE(g_Status)) { _SlNonOsMainLoopTask(); }

    if (0 == g_PingPacketsRecv)
    {
        /* Problem with internet connection*/
        ASSERT_ON_ERROR(INTERNET_CONNECTION_FAILED);
    }

    /* Internet connection is successful */
    return SUCCESS;
}
Exemple #13
0
//--tested, working--//
int WiFiClass::hostByName(char* aHostname, IPAddress& aResult)
{
    if (!_initialized) {
        init();
    }
    //
    //Use the netapp api to resolve an IP for the requested hostname
    //
    unsigned long DestinationIP;
    int iRet = sl_NetAppDnsGetHostByName(aHostname, strlen(aHostname), &DestinationIP, SL_AF_INET);
    aResult = sl_Htonl(DestinationIP);
    
    if (iRet >= 0) {
        return 1;
    } else {
        return iRet;
    }
    
}
unsigned long GetServerIP(/*const char *hostName*/) {

	char *hostName = HOST_NAME;
	unsigned long destinationServerIP = 0;
	unsigned int retry = 0;
	int retVal = 0;

	do {
		retry++;
		retVal = sl_NetAppDnsGetHostByName(hostName, strlen(hostName), &destinationServerIP, SL_AF_INET);
		if (0 > retVal) {
			UART_PRINT("Getting IP for Host Name failed\r\n");
		}
		if (retry > (DNS_RETRY - 1)) {
			UART_PRINT("Couldn't get the IP of the host, Exiting application\r\n");
			return 0;
		}
	} while (retry < DNS_RETRY && 0 > retVal);
	return destinationServerIP;
}
//*****************************************************************************
//
//! Network_IF_GetHostIP
//!
//! \brief  This function obtains the server IP address using a DNS lookup
//!
//! \param  The server hostname
//!
//! \return IP address: Success or 0: Failure.
//!
//
//*****************************************************************************
unsigned long Network_IF_GetHostIP( char* pcHostName )
{
    int iStatus = 0;
    unsigned long ulDestinationIP;

    iStatus = sl_NetAppDnsGetHostByName(
                  pcHostName, strlen(pcHostName),
                  &ulDestinationIP, SL_AF_INET);
    if (iStatus == 0)
    {
        UART_PRINT("Get Host IP succeeded.\n\rHost: %s IP: %d.%d.%d.%d \n\r\n\r",
                   pcHostName, SL_IPV4_BYTE(ulDestinationIP,3),
                   SL_IPV4_BYTE(ulDestinationIP,2),
                   SL_IPV4_BYTE(ulDestinationIP,1),
                   SL_IPV4_BYTE(ulDestinationIP,0));
        return ulDestinationIP;
    }
    else
    {
        return 0;
    }
}
Exemple #16
0
ext_tcp_utils_function_return_state_t ext_tcp_utils_getaddrbyhost(kaa_dns_resolve_listener_t *resolve_listener
                                                                , const kaa_dns_resolve_info_t *resolve_props
                                                                , kaa_sockaddr_t *result
                                                                , kaa_socklen_t *result_size)
{
    (void)resolve_listener;
    KAA_RETURN_IF_NIL4(resolve_props, resolve_props->hostname, result, result_size, RET_STATE_VALUE_ERROR);
    if (*result_size < sizeof(struct sockaddr_in))
        return RET_STATE_BUFFER_NOT_ENOUGH;

    unsigned long out_ip = 0;
    int ai_family;
    int resolve_error = 0;
    struct sockaddr_in tmp_addr;

    ai_family = AF_INET;
    *result_size = sizeof(struct sockaddr_in);

    char hostname_str[resolve_props->hostname_length + 1];
    memcpy(hostname_str, resolve_props->hostname, resolve_props->hostname_length);
    hostname_str[resolve_props->hostname_length] = '\0';

    if (strcmp(hostname_str, "localhost"))
        resolve_error = sl_NetAppDnsGetHostByName((signed char*)hostname_str, resolve_props->hostname_length, &out_ip, ai_family);
    else
        out_ip = 0x7F000001;

    memset(&tmp_addr, 0, *result_size);
    tmp_addr.sin_family = ai_family;
    tmp_addr.sin_addr.s_addr = sl_Htonl((unsigned int)out_ip);
    tmp_addr.sin_port = sl_Htons((unsigned short)resolve_props->port);

    if (resolve_error || !out_ip)
        return RET_STATE_VALUE_ERROR;

    memcpy(result, (struct sockaddr*)&tmp_addr, *result_size);
    return RET_STATE_VALUE_READY;
}
Exemple #17
0
//*****************************************************************************
//
//! This function demonstrates how certificate can be used with SSL.
//! The procedure includes the following steps:
//! 1) connect to an open AP
//! 2) get the server name via a DNS request
//! 3) define all socket options and point to the CA certificate
//! 4) connect to the server via TCP
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  LED1 is turned solid in case of success
//!    LED2 is turned solid in case of failure
//!
//*****************************************************************************
static long ssl()
{
    SlSockAddrIn_t    Addr;
    int    iAddrSize;
    unsigned char    ucMethod = SL_SO_SEC_METHOD_SSLV3;
    unsigned int uiIP,uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA;
    long lRetVal = -1;
    int iSockID;

    GPIO_IF_LedConfigure(LED1|LED3);

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO); 

    lRetVal = InitializeAppVariables();
    ASSERT_ON_ERROR(lRetVal);

    //
    // Following function configure the device to default state by cleaning
    // the persistent settings stored in NVMEM (viz. connection profiles &
    // policies, power policy etc)
    //
    // Applications may choose to skip this step if the developer is sure
    // that the device is in its default state at start of applicaton
    //
    // Note that all profiles and persistent settings that were done on the
    // device will be lost
    //
    lRetVal = ConfigureSimpleLinkToDefaultState();
    if(lRetVal < 0)
    {
      if (DEVICE_NOT_IN_STATION_MODE == lRetVal)
          UART_PRINT("Failed to configure the device in its default state \n\r");

      return lRetVal;
    }

    UART_PRINT("Device is configured in default state \n\r");

    CLR_STATUS_BIT_ALL(g_ulStatus);

    ///
    // Assumption is that the device is configured in station mode already
    // and it is in its default state
    //
    lRetVal = sl_Start(0, 0, 0);
    if (lRetVal < 0 || ROLE_STA != lRetVal)
    {
        UART_PRINT("Failed to start the device \n\r");
        return lRetVal;
    }

    UART_PRINT("Device started as STATION \n\r");

    //
    //Connecting to WLAN AP
    //
    lRetVal = WlanConnect();
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to establish connection w/ an AP \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    UART_PRINT("Connection established w/ AP and IP is aquired \n\r");

    //Set time of the device for certificate verification.
    lRetVal = set_time();
    if(lRetVal < 0)
    {
        UART_PRINT("Unable to set time in the device");
        return lRetVal;
    }


    lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host),
                                    (unsigned long*)&uiIP, SL_AF_INET);

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't retrive the host name \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    Addr.sin_family = SL_AF_INET;
    Addr.sin_port = sl_Htons(GOOGLE_DST_PORT);
    Addr.sin_addr.s_addr = sl_Htonl(uiIP);
    iAddrSize = sizeof(SlSockAddrIn_t);
    //
    // opens a secure socket 
    //
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
    if( iSockID < 0 )
    {
        UART_PRINT("Device unable to create secure socket \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // configure the socket as SSLV3.0 
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\
                               sizeof(ucMethod));
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }
    //
    //configure the socket as RSA with RC4 128 SHA 
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\
                           sizeof(uiCipher));
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    //configure the socket with GOOGLE CA certificate - for server verification
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \
                           SL_SO_SECURE_FILES_CA_FILE_NAME, \
                           SL_SSL_CA_CERT_FILE_NAME, \
                           strlen(SL_SSL_CA_CERT_FILE_NAME));

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \
    						SO_SECURE_DOMAIN_NAME_VERIFICATION, \
							g_Host, strlen((const char *)g_Host));
    if( lRetVal < 0 )
    {
    	UART_PRINT("Device couldn't set socket options \n\r");
    	GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    	return lRetVal;
    }


    /* connect to the peer device - Google server */
    lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize);

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't connect to Google server \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    return SUCCESS;
}
Exemple #18
0
//*****************************************************************************
//
//! Function to connect to server and download the requested file
//!
//! \param  none
//!
//! \return Error-code or SUCCESS
//!
//*****************************************************************************
static long ServerFileDownload()
{
    long lRetVal = -1;
    struct sockaddr_in addr;
    HTTPCli_Struct cli;

    //
    // Following function configure the device to default state by cleaning
    // the persistent settings stored in NVMEM (viz. connection profiles &
    // policies, power policy etc)
    //
    // Applications may choose to skip this step if the developer is sure
    // that the device is in its desired state at start of applicaton
    //
    // Note that all profiles and persistent settings that were done on the
    // device will be lost
    //
    lRetVal = ConfigureSimpleLinkToDefaultState();
    if(lRetVal < 0)
    {
        if (DEVICE_NOT_IN_STATION_MODE == lRetVal)
        {
            UART_PRINT("Failed to configure the device in its default state, "
                            "Error-code: %d\n\r", DEVICE_NOT_IN_STATION_MODE);
        }

        LOOP_FOREVER();
    }

    UART_PRINT("Device is configured in default state \n\r");

    //
    // Assumption is that the device is configured in station mode already
    // and it is in its default state
    //
    lRetVal = sl_Start(0, 0, 0);
    if (lRetVal < 0 || ROLE_STA != lRetVal)
    {
        ASSERT_ON_ERROR(DEVICE_START_FAILED);
    }

    UART_PRINT("Device started as STATION \n\r");

    // Connecting to WLAN AP - Set with static parameters defined at the top
    // After this call we will be connected and have IP address
    lRetVal = WlanConnect();

    UART_PRINT("Connected to the AP: %s\r\n", SSID_NAME);

    lRetVal = sl_NetAppDnsGetHostByName((signed char *)HOST_NAME,
                                       strlen((const char *)HOST_NAME),
                                       &g_ulDestinationIP,SL_AF_INET);
    if(lRetVal < 0)
    {
        ASSERT_ON_ERROR(GET_HOST_IP_FAILED);
    }

    // Set up the input parameters for HTTP Connection
    addr.sin_family = AF_INET;
    addr.sin_port = htons(HOST_PORT);
    addr.sin_addr.s_addr = sl_Htonl(g_ulDestinationIP);
    
    // Testing HTTPCli open call: handle, address params only
    HTTPCli_construct(&cli);
    lRetVal = HTTPCli_connect(&cli, (struct sockaddr *)&addr, 0, NULL);
    if (lRetVal < 0)
    {
        UART_PRINT("Connection to server failed\n\r");
	    ASSERT_ON_ERROR(SERVER_CONNECTION_FAILED);
    }    
    else
    {
        UART_PRINT("Connection to server created successfully\r\n");
    }
    // Download the file, verify the file and replace the exiting file
    lRetVal = GetData(&cli);
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't download the file from the server\n\r");
    }
	
    HTTPCli_destruct(&cli);

    return SUCCESS;
}
Exemple #19
0
//*****************************************************************************
//
//! This function POST to Event Hub REST API using TLS
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  Error number on Failure
//
//*****************************************************************************
long PostEventHubSSL()
{
    SlSockAddrIn_t    Addr;
    int    iAddrSize;
    unsigned char ucMethod = SL_SO_SEC_METHOD_TLSV1; //SL_SO_SEC_METHOD_SSLv3_TLSV1_2; //SL_SO_SEC_METHOD_TLSV1_2; //SL_SO_SEC_METHOD_SSLV3;
    unsigned int uiIP;
    unsigned int uiCipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA;
    long lRetVal = -1;
    int iSSLSockID;
    char acSendBuff[512];
    char acRecvbuff[1460];
    //char* pcBufData;
    char* pcBufHeaders;

    //
    // Retrieve IP from Hostname
    //
    lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host), (unsigned long*)&uiIP, SL_AF_INET);
    if(lRetVal < 0)
    {
        CLI_Write("Could not retrive the IP Address for Azure Server.\n\r");
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    Addr.sin_family = SL_AF_INET;
    Addr.sin_port = sl_Htons(SSL_DST_PORT);
    Addr.sin_addr.s_addr = sl_Htonl(uiIP);
    iAddrSize = sizeof(SlSockAddrIn_t);

    //
    // Opens a secure socket
    //
    iSSLSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
    if( iSSLSockID < 0 )
    {
        CLI_Write("Unable to create secure socket.\n\r");
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // Configure the socket as TLS (SSLV3.0 does not work because of POODLE - http://en.wikipedia.org/wiki/POODLE)
    //
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod, sizeof(ucMethod));
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't set socket option (TLS).\n\r");
        sl_Close(iSSLSockID);
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // Configure the socket as RSA with RC4 128 SHA
    //
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher, sizeof(uiCipher));
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't set socket option (RSA).\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
    }

    //
    // Configure the socket with Azure CA certificate - for server verification
    //
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, SL_SSL_CA_CERT_FILE_NAME, strlen(SL_SSL_CA_CERT_FILE_NAME));
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't set socket option (CA Certificate).\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
    }

    //
    // Configure the recieve timeout
    //
    struct SlTimeval_t timeVal;
    timeVal.tv_sec = SERVER_RESPONSE_TIMEOUT;    // In Seconds
    timeVal.tv_usec = 0;     // Microseconds. 10000 microseconds resolution
    lRetVal = sl_SetSockOpt(iSSLSockID, SL_SOL_SOCKET, SL_SO_RCVTIMEO, (unsigned char*)&timeVal, sizeof(timeVal));
    if(lRetVal < 0)
    {
       CLI_Write("Couldn't set socket option (Receive Timeout).\n\r");
       sl_Close(iSSLSockID);
       return lRetVal;
    }

    //
    // Connect to the peer device - Azure server */
    //
    lRetVal = sl_Connect(iSSLSockID, ( SlSockAddr_t *)&Addr, iAddrSize);
    if(lRetVal < 0)
    {
        CLI_Write("Couldn't connect to Azure server.\n\r");
        sl_Close(iSSLSockID);
        //GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // Generate a random number for the temperture
    //
    srand((unsigned int)time(NULL));
    float a = 5.0;
    float fRandTemp = 25 - (((float)rand()/(float)(RAND_MAX)) * a);

    char  cTempChar[5];
    sprintf(cTempChar, "%.2f", fRandTemp);

    //
    // Creates the HTTP POST string.
    //
    int dataLength = strlen(DATA1) + 5 + strlen(DATA2);
    char cCLLength[4];

    pcBufHeaders = acSendBuff;
    strcpy(pcBufHeaders, POSTHEADER);
    pcBufHeaders += strlen(POSTHEADER);
    strcpy(pcBufHeaders, HOSTHEADER);
    pcBufHeaders += strlen(HOSTHEADER);
    strcpy(pcBufHeaders, AUTHHEADER);
    pcBufHeaders += strlen(AUTHHEADER);
    strcpy(pcBufHeaders, CHEADER);
    pcBufHeaders += strlen(CHEADER);
    strcpy(pcBufHeaders, CTHEADER);
    pcBufHeaders += strlen(CTHEADER);
    strcpy(pcBufHeaders, CLHEADER1);

    pcBufHeaders += strlen(CLHEADER1);
    sprintf(cCLLength, "%d", dataLength);

    strcpy(pcBufHeaders, cCLLength);
    pcBufHeaders += strlen(cCLLength);
    strcpy(pcBufHeaders, CLHEADER2);
    pcBufHeaders += strlen(CLHEADER2);

    strcpy(pcBufHeaders, DATA1);
    pcBufHeaders += strlen(DATA1);
    strcpy(pcBufHeaders , cTempChar);
    pcBufHeaders += strlen(cTempChar);
    strcpy(pcBufHeaders, DATA2);

    int testDataLength = strlen(pcBufHeaders);

    //
    // Send the packet to the server */
    //
    lRetVal = sl_Send(iSSLSockID, acSendBuff, strlen(acSendBuff), 0);
    if(lRetVal < 0)
    {
        CLI_Write("POST failed.\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
    }

    //
    // Receive response packet from the server */
    //
    lRetVal = sl_Recv(iSSLSockID, &acRecvbuff[0], sizeof(acRecvbuff), 0);
	if(lRetVal < 0)
	{
        CLI_Write("Received failed.\n\r");
        sl_Close(iSSLSockID);
        return lRetVal;
	}
	else
	{
		CLI_Write("HTTP POST Successful. Telemetry successfully logged\n\r");
	}

    sl_Close(iSSLSockID);

    return SUCCESS;
}
Exemple #20
0
int main(void){int32_t retVal;  SlSecParams_t secParams;
  char *pConfig = NULL; INT32 ASize = 0; SlSockAddrIn_t  Addr;
	ADC0_InitSWTriggerSeq3_Ch9();         // allow time to finish activating
  initClk();        // PLL 50 MHz
	Output_On();
	UART_Init();      // Send data to PC, 115200 bps
  Timer1_Init();
  LED_Init();       // initialize LaunchPad I/O 
  UARTprintf("Weather App\n");
  retVal = configureSimpleLinkToDefaultState(pConfig); // set policies
  if(retVal < 0)Crash(4000000);
  retVal = sl_Start(0, pConfig, 0);
  if((retVal < 0) || (ROLE_STA != retVal) ) Crash(8000000);
  secParams.Key = PASSKEY;
  secParams.KeyLen = strlen(PASSKEY);
  secParams.Type = SEC_TYPE; // OPEN, WPA, or WEP
  sl_WlanConnect(SSID_NAME, strlen(SSID_NAME), 0, &secParams, 0);
  while((0 == (g_Status&CONNECTED)) || (0 == (g_Status&IP_AQUIRED))){
    _SlNonOsMainLoopTask();
  }
  UARTprintf("Connected\n");
  while(1){
		int i = 0;
		while(i < 10){
			int sendc = 0;
			strcpy(HostName,"openweathermap.org");
			retVal = sl_NetAppDnsGetHostByName(HostName,
							 strlen(HostName),&DestinationIP, SL_AF_INET);
			if(retVal == 0){
				Addr.sin_family = SL_AF_INET;
				Addr.sin_port = sl_Htons(80);
				Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian 
				ASize = sizeof(SlSockAddrIn_t);
				SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
				if( SockID >= 0 ){
					retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize);
				}
				if((SockID >= 0)&&(retVal >= 0)){
					strcpy(SendBuff,REQUEST); 
					sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET 
					sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response 
					sl_Close(SockID);
					LED_GreenOn();
					UARTprintf("\r\n\r\n");
					UARTprintf(Recvbuff);  UARTprintf("\r\n");
				}
			}
			ST7735_OutUDec(sendc);
			ST7735_OutString("\n");
			i++;
		}
		
		//while(Board_Input()==0){}; // wait for touch
		LED_GreenOff();
		//Temp Part e
		getTemp(Recvbuff);
		ST7735_OutChar('T');
		ST7735_OutChar('e');
		ST7735_OutChar('m');
		ST7735_OutChar('p');
		ST7735_OutChar(' ');
		ST7735_OutChar('=');
		ST7735_OutChar(' ');
		for(int i = 0; i < 5; i++){
			ST7735_OutChar(myArray[i]);
		}
		ST7735_OutChar('\n');

		//ADC Part f
		ADC0_SAC_R = ADC_SAC_AVG_64X;    //enable 64 times average before obtaining result
    int voltage = ADC0_InSeq3();
		ST7735_OutString("Voltage~");
		ST7735_sDecOut3(voltage);
		
		char* voltageString;
		char voltageStringNum[5];
		sprintf(voltageStringNum, "%.1d.%.3d", voltage/1000, voltage%1000);
		//ST7735_OutString(voltageStringNum);
		
		char* sendString;
		char str1[173] = "GET /query?city=Austin%20Texas&id=Ty%20Winkler%20Jeremiah%20Bartlett&greet=Voltage%3D";
		strcat(str1, voltageStringNum);
		strcat(str1, "V&edxcode=8086 HTTP/1.1\r\nUser-Agent: Keil\r\nHost: embsysmooc.appspot.com\r\n\r\n");
		
		
		strcpy(HostName,"embsysmooc.appspot.com");
		retVal = sl_NetAppDnsGetHostByName(HostName,
						 strlen(HostName),&DestinationIP, SL_AF_INET);
		if(retVal == 0){
			Addr.sin_family = SL_AF_INET;
			Addr.sin_port = sl_Htons(80);
			Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);// IP to big endian 
			ASize = sizeof(SlSockAddrIn_t);
			SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
			if( SockID >= 0 ){
				retVal = sl_Connect(SockID, ( SlSockAddr_t *)&Addr, ASize);
			}
			if((SockID >= 0)&&(retVal >= 0)){
				strcpy(SendBuff, str1);
				count = 0;					
				sl_Send(SockID, SendBuff, strlen(SendBuff), 0);// Send the HTTP GET 
				sl_Recv(SockID, Recvbuff, MAX_RECV_BUFF_SIZE, 0);// Receive response 
				sl_Close(SockID);
				LED_GreenOn();
				UARTprintf("\r\n\r\n");
				//ST7735_OutString(Recvbuff);  
				UARTprintf("\r\n");
			}
		}
		while(1);
	}
}
//****************************************************************************
//****************************************************************************
//****************************************************************************
//****************************************************************************
//****************************************************************************
//
//!	\brief pings to the default gateway and ip address of domain "www.ti.com"
//!
//! This function pings to the default gateway to ensure the wlan cannection,
//! then check for the internet connection, if present then get the ip address
//! of Domain name "www.ti.com" and pings to it
//!
//!	\param  ulDefaultGateway is the default gateway for the ap to which the
//!         device is connected
//!
//!	\return -1 for unsuccessful LAN connection, -2 for problem with internet
//!         conection and 0 for succesful ping to the Domain name
//
//****************************************************************************
int PingTest(unsigned long ulDefaultGateway)
{
    int iStatus = 0;
    SlPingStartCommand_t PingParams;
    SlPingReport_t PingReport;
    unsigned long ulIpAddr;
	char *pinghostname = "www.sina.com.cn";
//	unsigned short pinghostname_len = strlen(pinghostname);
	
    // Set the ping parameters
	PingParams.PingIntervalTime = 100;
	PingParams.PingSize = 5;
	PingParams.PingRequestTimeout = 1000;
	PingParams.TotalNumberOfAttempts = 10;
	PingParams.Flags = 0;//?if flags parameter is set to 0, ping will report back once all requested pings are done 
	PingParams.Ip = SL_AF_INET;
    // Fill the GW IP address, which is our AP address
	//PingParams.Ip = ulDefaultGateway;
	PingParams.Ip =SL_IPV4_VAL(192,168,1,1);
    // Check for LAN connection 
    sl_NetAppPingStart((SlPingStartCommand_t*)&PingParams, SL_AF_INET,
                 (SlPingReport_t*)&PingReport, SimpleLinkPingReport);

	
    while (!g_uiPingDone)
	{
		//looping till ping is running
              Z_DelayS(1);
    
        UART_PRINT("i am waiting ping end now \n\r"); 
    
	}
	
    
    g_uiPingDone = 0;


	if(g_uiPingPacketsRecv)
	{

	UART_PRINT("We were able to ping now \n\r"); 
	
		g_uiPingPacketsRecv = 0;
		// We were able to ping the AP

		/* Check for Internet connection */
		/* Querying for ti.com IP address */
		iStatus = sl_NetAppDnsGetHostByName(pinghostname, strlen(pinghostname), &ulIpAddr, SL_AF_INET);
		if (iStatus < 0)
		{

		UART_PRINT("Problem with Internet connection \n\r"); 
		
			// LAN connection is successful
			// Problem with Internet connection
			return -2;
		}


		// Replace the ping address to match ti.com IP address
		PingParams.Ip = ulIpAddr;
                
                UART_PRINT(pinghostname); 

		UART_PRINT(" ip is :  "); 
		Z_IPDispaly(&ulIpAddr);
                
                return 0;  ///not to ping  www.ti.com

		// Try to ping www.ti.com
		sl_NetAppPingStart((SlPingStartCommand_t*)&PingParams, SL_AF_INET,
                     (SlPingReport_t*)&PingReport, SimpleLinkPingReport);

		while (!g_uiPingDone)
		{
			//looping till ping is running
		}
        
        if (g_uiPingPacketsRecv)
		{
			// LAN connection is successful
			// Internet connection is successful
			g_uiPingPacketsRecv = 0;
			return 0;
		}
		else
		{
			// LAN connection is successful
			// Problem with Internet connection
			return -2;
		}
                

    }
	else
	{
		// Problem with LAN connection
		UART_PRINT(" Problem with LAN connection \n\r"); 
		return -1;
	}
}
/*
 * ::getaddrinfo
 */
int getaddrinfo(const char *nodename, const char *servname,
                const struct addrinfo *hints,
                struct addrinfo **res)
{
    unsigned long ip_addr;
    uint8_t domain;

    *res = malloc(sizeof(struct addrinfo));
    if (*res == NULL)
    {
        return EAI_MEMORY;
    }
    memset(*res, 0, sizeof(struct addrinfo));

    (*res)->ai_addr = malloc(sizeof(struct sockaddr));
    if ((*res)->ai_addr == NULL)
    {
        free(*res);
        return EAI_MEMORY;
    }
    memset((*res)->ai_addr, 0, sizeof(struct addrinfo));

    switch (hints->ai_family)
    {
        case AF_INET:
            domain = SL_AF_INET;
            break;
        case AF_INET6:
            domain = SL_AF_INET6;
            break;
        case AF_PACKET:
            domain = SL_AF_PACKET;
            break;
        default:
            errno = EAFNOSUPPORT;
            free((*res)->ai_addr);
            free(*res);
            return -1;
    }

    int result = sl_NetAppDnsGetHostByName((int8_t*)nodename, strlen(nodename),
                                           &ip_addr, domain);

    if (result != 0)
    {
        free((*res)->ai_addr);
        free(*res);
        switch (result)
        {
            default:
            case SL_POOL_IS_EMPTY:
                return EAI_AGAIN;
            case SL_NET_APP_DNS_QUERY_NO_RESPONSE:
            case SL_NET_APP_DNS_NO_SERVER:
            case SL_NET_APP_DNS_QUERY_FAILED:
            case SL_NET_APP_DNS_MALFORMED_PACKET:
            case SL_NET_APP_DNS_MISMATCHED_RESPONSE:
                return EAI_FAIL;
        }
    }

    switch (hints->ai_family)
    {
        case AF_INET:
        {
            struct sockaddr_in *addr_in = (struct sockaddr_in*)(*res)->ai_addr;
            (*res)->ai_flags = 0;
            (*res)->ai_family = hints->ai_family;
            (*res)->ai_socktype = hints->ai_socktype;
            (*res)->ai_protocol = hints->ai_protocol;
            (*res)->ai_addrlen = sizeof(struct sockaddr_in);
            addr_in->sin_family = hints->ai_family;
            addr_in->sin_port = htons((uint16_t)strtol(servname, NULL, 0));
            addr_in->sin_addr.s_addr = htonl(ip_addr);
            break;
        }
        case AF_INET6:
        case AF_PACKET:
        default:
            errno = EAFNOSUPPORT;
            free((*res)->ai_addr);
            free(*res);
            return -1;
    }

    return 0;
}
Exemple #23
0
int main(int argc, char** argv)
{
    SlSockAddrIn_t      Addr = {0};

    _u32  cipher = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA;
    _u32  googleIP = 0;
    _u8   method = SL_SO_SEC_METHOD_SSLV3;

    _i32   AddrSize = -1;
    _i32   g_SockID = -1;
    _i32   retVal = -1;

    retVal = initializeAppVariables();
    ASSERT_ON_ERROR(retVal);

    /* Stop WDT and initialize the system-clock of the MCU
       These functions needs to be implemented in PAL */
    stopWDT();
    initClk();

    /* Configure command line interface */
    CLI_Configure();

    displayBanner();

    /*
     * Following function configures the device to default state by cleaning
     * the persistent settings stored in NVMEM (viz. connection profiles &
     * policies, power policy etc)
     *
     * Applications may choose to skip this step if the developer is sure
     * that the device is in its default state at start of application
     *
     * Note that all profiles and persistent settings that were done on the
     * device will be lost
     */
    retVal = configureSimpleLinkToDefaultState();
    if(retVal < 0)
    {
        if (DEVICE_NOT_IN_STATION_MODE == retVal)
        {
            CLI_Write(" Failed to configure the device in its default state \n\r");
        }

        LOOP_FOREVER();
    }

    CLI_Write(" Device is configured in default state \n\r");

    /*
     * Assumption is that the device is configured in station mode already
     * and it is in its default state
     */
    /* Initializing the CC3100 device */
    retVal = sl_Start(0, 0, 0);
    if ((retVal < 0) ||
            (ROLE_STA != retVal) )
    {
        CLI_Write(" Failed to start the device \n\r");
        LOOP_FOREVER();
    }

    CLI_Write(" Device started as STATION \n\r");

    /* Connecting to WLAN AP - Set with static parameters defined at the top
       After this call we will be connected and have IP address */
    retVal = establishConnectionWithAP();
    if(retVal < 0)
    {
        CLI_Write(" Failed to establish connection w/ an AP \n\r");
        LOOP_FOREVER();
    }

    CLI_Write(" Connection established w/ AP and IP is acquired \n\r");

    /* Update the CC3100 time */
    retVal = SetTime();
    if (retVal < 0)
    {
        CLI_Write(" Failed to set the device time \n\r");
        LOOP_FOREVER();
    }

    CLI_Write(" Establishing secure connection w/ google server \n\r");

    /* get the server name via a DNS request */
    retVal = sl_NetAppDnsGetHostByName(g_Google, pal_Strlen(g_Google),
                                       &googleIP, SL_AF_INET);
    if( retVal < 0 )
    {
        CLI_Write(" Failed to get the IP address \n\r");
        LOOP_FOREVER();
    }

    Addr.sin_family = SL_AF_INET;
    Addr.sin_port = sl_Htons(GOOGLE_DST_PORT);
    Addr.sin_addr.s_addr = sl_Htonl(googleIP);

    AddrSize = sizeof(SlSockAddrIn_t);

    /* opens a secure socket */
    g_SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
    if( g_SockID < 0 )
    {
        CLI_Write(" Failed to open socket \n\r");
        LOOP_FOREVER();
    }

    /* configure the socket as SSLV3.0 */
    retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECMETHOD,
                           &method, sizeof(method));
    if( retVal < 0 )
    {
        CLI_Write(" Failed to configure the socket \n\r");
        LOOP_FOREVER();
    }

    /* configure the socket as RSA with RC4 128 SHA */
    retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK,
                           &cipher, sizeof(cipher));
    if( retVal < 0 )
    {
        CLI_Write(" Failed to configure the socket \n\r");
        LOOP_FOREVER();
    }

    /* configure the socket with GOOGLE CA certificate-for server verification*/
    retVal = sl_SetSockOpt(g_SockID, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
                           SL_SSL_CA_CERT, pal_Strlen(SL_SSL_CA_CERT));
    if( retVal < 0 )
    {
        CLI_Write(" Failed to configure the socket \n\r");
        LOOP_FOREVER();
    }

    /* connect to the peer device - GMail server */
    retVal = sl_Connect(g_SockID, ( SlSockAddr_t *)&Addr, AddrSize);
    if (retVal < 0 )
    {
        CLI_Write(" Failed to connect w/ google server \n\r");
        LOOP_FOREVER();
    }

    CLI_Write(" Connection w/ google server established successfully \n\r");


    /* Stop the CC3100 device */
    retVal = sl_Stop(SL_STOP_TIMEOUT);
    if(retVal < 0)
        LOOP_FOREVER();

    return 0;
}
Exemple #24
0
//*****************************************************************************
//
//! This function demonstrates how certificate can be used with SSL.
//! The procedure includes the following steps:
//! 1) connect to an open AP
//! 2) get the server name via a DNS request
//! 3) define all socket options and point to the CA certificate
//! 4) connect to the server via TCP
//!
//! \param None
//!
//! \return  0 on success else error code
//! \return  LED1 is turned solid in case of success
//!    LED2 is turned solid in case of failure
//!
//*****************************************************************************
static int tls_connect()
{
    SlSockAddrIn_t    Addr;
    int    iAddrSize;
    unsigned char    ucMethod = SL_SO_SEC_METHOD_TLSV1_2;
    unsigned int uiIP,uiCipher = SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA;
    long lRetVal = -1;
    int iSockID;

    lRetVal = sl_NetAppDnsGetHostByName(g_Host, strlen((const char *)g_Host),
                                    (unsigned long*)&uiIP, SL_AF_INET);

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't retrive the host name \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    Addr.sin_family = SL_AF_INET;
    Addr.sin_port = sl_Htons(GOOGLE_DST_PORT);
    Addr.sin_addr.s_addr = sl_Htonl(uiIP);
    iAddrSize = sizeof(SlSockAddrIn_t);
    //
    // opens a secure socket 
    //
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
    if( iSockID < 0 )
    {
        UART_PRINT("Device unable to create secure socket \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    // configure the socket as TLS1.2
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, &ucMethod,\
                               sizeof(ucMethod));
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }
    //
    //configure the socket as ECDHE RSA WITH AES256 CBC SHA
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_SECURE_MASK, &uiCipher,\
                           sizeof(uiCipher));
    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //
    //configure the socket with CA certificate - for server verification
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \
                           SL_SO_SECURE_FILES_CA_FILE_NAME, \
						   SL_SSL_CA_CERT, \
                           strlen(SL_SSL_CA_CERT));

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //configure the socket with Client Certificate - for server verification
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \
    			SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, \
									SL_SSL_CLIENT, \
                           strlen(SL_SSL_CLIENT));

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }

    //configure the socket with Private Key - for server verification
    //
    lRetVal = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, \
    		SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, \
			SL_SSL_PRIVATE, \
                           strlen(SL_SSL_PRIVATE));

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't set socket options \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }


    /* connect to the peer device - Google server */
    lRetVal = sl_Connect(iSockID, ( SlSockAddr_t *)&Addr, iAddrSize);

    if(lRetVal < 0)
    {
        UART_PRINT("Device couldn't connect to AWS server \n\r");
        GPIO_IF_LedOn(MCU_RED_LED_GPIO);
        return lRetVal;
    }
    else{
    	UART_PRINT("Device has connected to the website:");
    	UART_PRINT(SERVER_NAME);
    	UART_PRINT("\n\r");
    }

    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    return iSockID;
}