Compare commits

..

1 Commits

Author SHA1 Message Date
Shilpa Seshadri
b134a646e5 Clear auth token if fetch fails 2019-05-15 20:13:06 -07:00
52 changed files with 521 additions and 2172 deletions

View File

@@ -26,7 +26,7 @@ install:
script:
- mkdir build
- cd build
- cmake .. -DINTEGRATION_TESTING:BOOL=false -DDISABLE_VALGRIND:BOOL=false -DENABLE_SESHAT:BOOL=true -DFEATURE_DNS_QUERY:BOOL=true
- cmake .. -DINTEGRATION_TESTING:BOOL=false -DDISABLE_VALGRIND:BOOL=true -DENABLE_SESHAT:BOOL=true -DFEATURE_DNS_QUERY:BOOL=true
- make
- export ARGS="-V"
- make test

View File

@@ -5,17 +5,6 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
- Security: Added support to use auth token during initial connect to cloud
- Fix re-registration fails that lose a socket
- Fix mutex error in service alive
- Security: Mutual Authentication (mTLS or two way TLS)
- Rename command line options for MTLS cert and Key
- Update to use nanomsg v. 1.1.4
- requestNewAuthToken will clear the token if it fails.
- request auth token on every retry, not just after 403
- update to use nopoll v 1.0.2
## [1.0.2] - 2019-02-08
- Refactored connection.c and updated corresponding unit tests
- Additional `/cloud-status` and `/cloud-disconnect` fields.
- Switched from nanomsg (Release 1.1.2) to NNG (Release v1.0.1)
@@ -28,19 +17,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- added NULL check for device mac id in upstream retrieve message handling
- backoff retry to include find_servers in loop (connection.c)
- backoff max is max count not max delay
- used mutex protection to make client list and nn_sends thread safe
- put mutex lock into get_global_node
- change svc alive from a thread to a function called every 30 sec from main
- shut down tasks properly
- fix memory leaks
- Fixed memory leak in upstream event message flow
- Fixed crash in CRUD request processing
- Fixed issue on RETRIEVE respone processing
- Enabled valgrind
- Fixed main loop to keep calling svc_alive_task during a cloud disconnect and retry
- change svc alive back to a separate thread. Shut it down with pthread_cond_timedwait
- Refactored Upsteam RETRIEVE flow
- Fix re-registration to call nn_shutdown and nn_close, so we don't lose a socket.
## [1.0.1] - 2018-07-18
### Added
@@ -73,7 +49,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Initial creation
[Unreleased]: https://github.com/Comcast/parodus/compare/1.0.1...HEAD
[1.0.2]: https://github.com/Comcast/parodus/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/Comcast/parodus/compare/1.0.0...1.0.1
[1.0.0]: https://github.com/Comcast/parodus/compare/79fa7438de2b14ae64f869d52f5c127497bf9c3f...1.0.0

View File

@@ -34,7 +34,6 @@ include_directories(${INCLUDE_DIR}
${INCLUDE_DIR}/cjson
${INCLUDE_DIR}/nopoll
${INCLUDE_DIR}/msgpack
${INCLUDE_DIR}/curl
${INCLUDE_DIR}/trower-base64
${INCLUDE_DIR}/wrp-c
${INCLUDE_DIR}/libparodus
@@ -85,7 +84,7 @@ add_dependencies(libtrower-base64 trower-base64)
ExternalProject_Add(nopoll
PREFIX ${PREFIX_DIR}/nopoll
GIT_REPOSITORY https://github.com/Comcast/nopoll.git
GIT_TAG "1.0.2"
GIT_TAG "1.0.1"
CONFIGURE_COMMAND COMMAND <SOURCE_DIR>/autogen.sh --prefix=${PREFIX}
--includedir=${INCLUDE_DIR}
--libdir=${LIBRARY_DIR}
@@ -101,7 +100,7 @@ add_dependencies(libnopoll nopoll)
ExternalProject_Add(nanomsg
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/nanomsg
GIT_REPOSITORY https://github.com/nanomsg/nanomsg.git
GIT_TAG "1.1.4"
GIT_TAG "1.1.2"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libnanomsg STATIC SHARED IMPORTED)
@@ -135,24 +134,12 @@ add_library(libmsgpack STATIC SHARED IMPORTED)
add_dependencies(libmsgpack msgpack)
# curl external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(curl
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/curl
GIT_REPOSITORY https://github.com/curl/curl.git
GIT_TAG "curl-7_63_0"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcurl STATIC SHARED IMPORTED)
add_dependencies(libcurl curl)
# cimplog external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(cimplog
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cimplog
GIT_REPOSITORY https://github.com/Comcast/cimplog.git
GIT_TAG "1.0.2"
GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcimplog STATIC SHARED IMPORTED)
@@ -204,8 +191,7 @@ endif (ENABLE_SESHAT)
ExternalProject_Add(cjwt
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cjwt
GIT_REPOSITORY https://github.com/Comcast/cjwt.git
GIT_TAG "1b023c41bb2d6dbbf493c202ed81f06c84d5b51b"
#GIT_TAG "1.0.1"
GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcjwt STATIC SHARED IMPORTED)

View File

@@ -55,9 +55,9 @@ make test
- /force-ipv6 -Forcefully connect parodus to ipv6 address (optional argument)
- /client-cert-path -MTLS client cert location to request auth token for establishing secure connection [absolute path where client cert is present] (optional argument)
- /token-read-script -Script to get auth token for establishing secure connection (absolute path where that script is present) -optional argument
- /token-server-url -complete server url with API path to request new auth token for establishing secure connection (optional argument)
- /token-acquisition-script -Script to create new auth token for establishing secure connection (absolute path where that script is present) -optional argument
- /crud-config-file -Config json file to store objects during create, retrieve, update and delete (CRUD) operations -optional argument
@@ -75,12 +75,6 @@ make test
- /jwt-public-key-file -JWT token validation key
# if ENABLE_MUTUAL_AUTH is enabled
- /mtls-client-cert-path - Provide the client cert for establishing a mutual auth secure websocket connection
- /mtls-client-key-path - Provide the client cert key for establishing a mutual auth secure websocket connection
```
# Sample parodus start commands:
@@ -88,17 +82,17 @@ make test
```
# Seshat & FEATURE_DNS_QUERY Enabled
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=https://somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --acquire-jwt=1 --dns-txt-url=somebody.net --jwt-public-key-file=webpa-rs256.pem --jwt-algo=RS256 --seshat-url=tcp://127.0.0.1:7777 --client-cert-path=/tmp/clientcert.mch --token-server-url=https://somebody.net:8080/token --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --acquire-jwt=1 --dns-txt-url=somebody.net --jwt-public-key-file=webpa-rs256.pem --jwt-algo=RS256 --seshat-url=tcp://127.0.0.1:7777 --token-read-script=/usr/ccsp/parodus/parodus_token1.sh --token-acquisition-script=/usr/ccsp/parodus/parodus_token2.sh --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
# Seshat is not enabled
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=https://somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --acquire-jwt=1 --dns-txt-url=somebody.net --jwt-public-key-file=webpa-rs256.pem --jwt-algo=RS256 --client-cert-path=/tmp/clientcert.mch --token-server-url=https://somebody.net:8080/token --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --acquire-jwt=1 --dns-txt-url=somebody.net --jwt-public-key-file=webpa-rs256.pem --jwt-algo=RS256 --token-read-script=/usr/ccsp/parodus/parodus_token1.sh --token-acquisition-script=/usr/ccsp/parodus/parodus_token2.sh --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
# When both Seshat & FEATURE_DNS_QUERY not Enabled
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=https://somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --client-cert-path=/tmp/clientcert.mch --token-server-url=https://somebody.net:8080/token --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --token-read-script=/usr/ccsp/parodus/parodus_token1.sh --token-acquisition-script=/usr/ccsp/parodus/parodus_token2.sh --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
```

View File

@@ -15,7 +15,7 @@ set(SOURCES main.c mutex.c networking.c nopoll_helpers.c heartBeat.c nopoll_hand
ParodusInternal.c string_helpers.c time.c config.c conn_interface.c
connection.c spin_thread.c client_list.c service_alive.c
upstream.c downstream.c thread_tasks.c partners_check.c token.c
crud_interface.c crud_tasks.c crud_internal.c close_retry.c auth_token.c)
crud_interface.c crud_tasks.c crud_internal.c close_retry.c)
if (ENABLE_SESHAT)
set(SOURCES ${SOURCES} seshat_interface.c)
@@ -30,7 +30,6 @@ target_link_libraries (parodus
${CMAKE_THREAD_LIBS_INIT}
-lwrp-c
-lmsgpackc
-lcurl
-ltrower-base64
-lnopoll
-luuid

View File

@@ -50,8 +50,7 @@
/* Macros */
/*----------------------------------------------------------------------------*/
#define UNUSED(x) (void )(x)
#define NANO_SOCKET_SEND_TIMEOUT_MS 2000
#define NANO_SOCKET_RCV_TIMEOUT_MS 500
#define NANOMSG_SOCKET_TIMEOUT_MSEC 2000
#ifndef TEST
#define FOREVER() 1
@@ -134,7 +133,6 @@ typedef struct {
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
extern bool g_shutdown;
extern ParodusMsg *ParodusMsgQ;
int numLoops;
/*----------------------------------------------------------------------------*/

View File

@@ -1,302 +0,0 @@
/**
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file auth_token.c
*
* @description This file is to fetch authorization token during parodus cloud connection.
*
*/
#include <stdio.h>
#include <fcntl.h>
#include "config.h"
#include "auth_token.h"
#include "ParodusInternal.h"
#include <cjwt/cjwt.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <uuid/uuid.h>
#define MAX_BUF_SIZE 128
#define CURL_TIMEOUT_SEC 25L
#define MAX_CURL_RETRY_COUNT 3
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
void createCurlheader(char *mac_header, char *serial_header, char *uuid_header, char *transaction_uuid, struct curl_slist *list, struct curl_slist **header_list);
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
/*
* @brief Initialize curl object with required options. create newToken using libcurl.
* @param[out] newToken auth token string obtained from JWT curl response
* @param[in] len total token size
* @param[in] r_count Number of curl retries on ipv4 and ipv6 mode during failure
* @return returns 0 if success, otherwise failed to fetch auth token and will be retried.
*/
int requestNewAuthToken(char *newToken, size_t len, int r_count)
{
CURL *curl;
CURLcode res;
CURLcode time_res;
struct curl_slist *list = NULL;
struct curl_slist *headers_list = NULL;
char *mac_header = NULL;
char *serial_header = NULL;
char *uuid_header = NULL;
char *transaction_uuid = NULL;
double total;
long response_code;
struct token_data data;
data.size = 0;
data.data = newToken;
curl = curl_easy_init();
if(curl)
{
data.data[0] = '\0';
createCurlheader(mac_header, serial_header, uuid_header, transaction_uuid, list, &headers_list);
curl_easy_setopt(curl, CURLOPT_URL, get_parodus_cfg()->token_server_url);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT_SEC);
if(get_parodus_cfg()->webpa_interface_used !=NULL && strlen(get_parodus_cfg()->webpa_interface_used) >0)
{
curl_easy_setopt(curl, CURLOPT_INTERFACE, get_parodus_cfg()->webpa_interface_used);
}
/* set callback for writing received data */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_fn);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers_list);
/* setting curl resolve option as default mode.
If any failure, retry with v4 first and then v6 mode. */
if(r_count == 1)
{
ParodusInfo("curl Ip resolve option set as V4 mode\n");
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
}
else if(r_count == 2)
{
ParodusInfo("curl Ip resolve option set as V6 mode\n");
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
}
else
{
ParodusInfo("curl Ip resolve option set as default mode\n");
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
}
/* set the cert for client authentication */
curl_easy_setopt(curl, CURLOPT_SSLCERT, get_parodus_cfg()->client_cert_path);
curl_easy_setopt(curl, CURLOPT_CAINFO, get_parodus_cfg()->cert_path);
/* disconnect if it is failed to validate server's cert */
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
ParodusInfo("themis curl response %d http_code %d\n", res, response_code);
time_res = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total);
if(time_res == 0)
{
ParodusInfo("curl response Time: %.1f seconds\n", total);
}
curl_slist_free_all(headers_list);
if(res != 0)
{
ParodusError("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
data.size = 0;
memset (data.data, 0, len);
return -1;
}
else
{
if(response_code == 200)
{
ParodusInfo("cURL success\n");
}
}
curl_easy_cleanup(curl);
}
else
{
ParodusError("curl init failure\n");
data.size = 0;
memset (data.data, 0, len);
return -1;
}
return 0;
}
/*
* @brief Fetches authorization token and update to parodus config.
This will do curl retry in case of any failure till it reaches max curl retry count.
* @param[in] cfg Global parodus config structure to update webpa_auth_token
*/
void getAuthToken(ParodusCfg *cfg)
{
int status = -1;
int retry_count = 0;
memset (cfg->webpa_auth_token, 0, sizeof(cfg->webpa_auth_token));
if( cfg->hw_mac != NULL && strlen(cfg->hw_mac) !=0 )
{
if( cfg->client_cert_path !=NULL && strlen(cfg->client_cert_path) !=0 )
{
while(1)
{
//Fetch new auth token using libcurl
status = requestNewAuthToken(cfg->webpa_auth_token, sizeof(cfg->webpa_auth_token), retry_count);
if(status == 0)
{
ParodusInfo("cfg->webpa_auth_token created successfully\n");
break;
}
else
{
ParodusError("Failed to create new token\n");
retry_count++;
ParodusError("Curl execution is failed, retry attempt: %d\n", retry_count);
}
if(retry_count == MAX_CURL_RETRY_COUNT)
{
ParodusError("Curl retry is reached to max %d attempts, proceeding without token\n", retry_count);
break;
}
}
}
else
{
ParodusError("client_cert_path is NULL, failed to fetch auth token\n");
}
}
else
{
ParodusError("hw_mac is NULL, failed to fetch auth token\n");
}
}
/* @brief callback function for writing libcurl received data
* @param[in] buffer curl delivered data which need to be saved.
* @param[in] size size is always 1
* @param[in] nmemb size of delivered data
* @param[out] data curl response data saved.
*/
size_t write_callback_fn(void *buffer, size_t size, size_t nmemb, struct token_data *data)
{
ParodusCfg *cfg;
size_t max_data_size = sizeof (cfg->webpa_auth_token);
size_t index = data->size;
size_t n = (size * nmemb);
data->size += n;
if (data->size >= max_data_size) {
ParodusError("Auth token data overruns buffer\n");
data->size = 0;
return 0;
}
memcpy((data->data + index), buffer, n);
data->data[data->size] = '\0';
return n;
}
/* @brief function to generate random uuid.
*/
char* generate_trans_uuid()
{
char *transID = NULL;
uuid_t transaction_Id;
char *trans_id = NULL;
trans_id = (char *)malloc(37);
uuid_generate_random(transaction_Id);
uuid_unparse(transaction_Id, trans_id);
if(trans_id !=NULL)
{
transID = trans_id;
}
return transID;
}
/* @brief function to create curl header contains mac, serial number and uuid.
* @param[in] mac_header mac address header key value pair
* @param[in] serial_header serial number key value pair
* @param[in] uuid_header transaction uuid key value pair
* @param[in] list temp curl header list
* @param[out] header_list output curl header list
*/
void createCurlheader(char *mac_header, char *serial_header, char *uuid_header, char *transaction_uuid, struct curl_slist *list, struct curl_slist **header_list)
{
mac_header = (char *) malloc(sizeof(char)*MAX_BUF_SIZE);
if(mac_header !=NULL)
{
snprintf(mac_header, MAX_BUF_SIZE, "X-Midt-Mac-Address: %s", get_parodus_cfg()->hw_mac);
ParodusPrint("mac_header formed %s\n", mac_header);
list = curl_slist_append(list, mac_header);
free(mac_header);
mac_header = NULL;
}
serial_header = (char *) malloc(sizeof(char)*MAX_BUF_SIZE);
if(serial_header !=NULL)
{
snprintf(serial_header, MAX_BUF_SIZE, "X-Midt-Serial-Number: %s", get_parodus_cfg()->hw_serial_number);
ParodusPrint("serial_header formed %s\n", serial_header);
list = curl_slist_append(list, serial_header);
free(serial_header);
serial_header = NULL;
}
transaction_uuid = generate_trans_uuid();
if(transaction_uuid !=NULL)
{
uuid_header = (char *) malloc(sizeof(char)*MAX_BUF_SIZE);
if(uuid_header !=NULL)
{
snprintf(uuid_header, MAX_BUF_SIZE, "X-Midt-Uuid: %s", transaction_uuid);
ParodusInfo("uuid_header formed %s\n", uuid_header);
list = curl_slist_append(list, uuid_header);
free(transaction_uuid);
transaction_uuid = NULL;
free(uuid_header);
uuid_header = NULL;
}
}
else
{
ParodusError("Failed to generate transaction_uuid\n");
}
*header_list = list;
}

View File

@@ -1,57 +0,0 @@
/**
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file auth_token.h
*
* @description This file is to fetch authorization token during parodus cloud connection.
*
*/
#ifndef _AUTH_TOKEN_H_
#define _AUTH_TOKEN_H_
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
struct token_data {
size_t size;
char* data;
};
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
int requestNewAuthToken(char *newToken, size_t len, int r_count);
void getAuthToken(ParodusCfg *cfg);
size_t write_callback_fn(void *buffer, size_t size, size_t nmemb, struct token_data *data);
char* generate_trans_uuid();
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -30,7 +30,6 @@
/*----------------------------------------------------------------------------*/
static int numOfClients = 0;
static reg_list_item_t * g_head = NULL;
pthread_mutex_t client_mut=PTHREAD_MUTEX_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* External functions */
@@ -38,16 +37,9 @@ pthread_mutex_t client_mut=PTHREAD_MUTEX_INITIALIZER;
reg_list_item_t * get_global_node(void)
{
pthread_mutex_lock (&client_mut);
return g_head;
}
void release_global_node (void)
{
pthread_mutex_unlock (&client_mut);
}
int get_numOfClients()
{
return numOfClients;
@@ -60,12 +52,11 @@ int addToList( wrp_msg_t **msg)
int rc = -1;
int sock;
int retStatus = -1;
sock = nn_socket( AF_SP, NN_PUSH );
ParodusPrint("sock created for adding entries to list: %d\n", sock);
if(sock >= 0)
{
int t = NANO_SOCKET_SEND_TIMEOUT_MS;
int t = NANOMSG_SOCKET_TIMEOUT_MSEC;
rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_SNDTIMEO, &t, sizeof(t));
if(rc < 0)
{
@@ -76,11 +67,7 @@ int addToList( wrp_msg_t **msg)
if(rc < 0)
{
ParodusError ("Unable to connect socket (errno=%d, %s)\n",errno, strerror(errno));
if (nn_close (sock) < 0)
{
ParodusError ("nn_close socket=%d (err=%d, %s)\n",
sock, errno, strerror(errno));
}
nn_close (sock);
}
else
@@ -91,7 +78,6 @@ int addToList( wrp_msg_t **msg)
{
memset( new_node, 0, sizeof( reg_list_item_t ) );
new_node->sock = sock;
new_node->endpoint = rc;
ParodusPrint("new_node->sock is %d\n", new_node->sock);
@@ -224,21 +210,11 @@ int deleteFromList(char* service_name)
}
ParodusPrint("Deleting the node\n");
if(nn_shutdown(curr_node->sock, curr_node->endpoint) < 0)
{
ParodusError ("nn_shutdown socket=%d endpt=%d, err=%d\n",
curr_node->sock, curr_node->endpoint, errno);
}
if (nn_close (curr_node->sock) < 0)
{
ParodusError ("nn_close socket=%d err=%d\n",
curr_node->sock, errno);
}
free( curr_node );
curr_node = NULL;
ParodusInfo("Deleted successfully and returning..\n");
numOfClients =numOfClients - 1;
ParodusPrint("numOfClients after delete is %d\n", numOfClients);
ParodusPrint("numOfClients after delte is %d\n", numOfClients);
return 0;
}
@@ -249,22 +225,6 @@ int deleteFromList(char* service_name)
return -1;
}
void deleteAllClients (void)
{
reg_list_item_t *next_node = NULL;
while (NULL != g_head)
{
next_node = g_head->next;
free (g_head);
g_head = next_node;
}
if (numOfClients > 0) {
ParodusInfo ("Deleted %d clients\n", numOfClients);
numOfClients = 0;
}
}
/*
*@dest : Client destination to send message
*@Msg: Msg to send it to client (No free done here), user responsibilites to free the msg
@@ -283,7 +243,6 @@ int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize)
if( strcmp(dest, temp->service_name) == 0)
{
bytes = nn_send(temp->sock, *Msg, msgSize, 0);
release_global_node ();
ParodusInfo("sent downstream message to reg_client '%s'\n", temp->url);
ParodusPrint("downstream bytes sent:%d\n", bytes);
return 1;
@@ -291,6 +250,5 @@ int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize)
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
release_global_node ();
return 0;
}

View File

@@ -30,7 +30,6 @@
typedef struct reg_list_item
{
int sock;
int endpoint;
char service_name[32];
char url[100];
struct reg_list_item *next;
@@ -51,11 +50,9 @@ int sendAuthStatus(reg_list_item_t *new_node);
int deleteFromList(char* service_name);
int get_numOfClients();
void deleteAllClients (void);
int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize);
reg_list_item_t * get_global_node(void);
void release_global_node (void);
#ifdef __cplusplus
}

View File

@@ -26,9 +26,8 @@
#include "config.h"
#include "ParodusInternal.h"
#include <cjwt/cjwt.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <uuid/uuid.h>
#define MAX_BUF_SIZE 128
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
@@ -37,6 +36,7 @@
static ParodusCfg parodusCfg;
static unsigned int rsa_algorithms =
(1<<alg_rs256) | (1<<alg_rs384) | (1<<alg_rs512);
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -141,6 +141,31 @@ void read_key_from_file (const char *fname, char *buf, size_t buflen)
ParodusInfo ("%d bytes read\n", nbytes);
}
void execute_token_script(char *token, char *name, size_t len, char *mac, char *serNum)
{
FILE* out = NULL, *file = NULL;
char command[MAX_BUF_SIZE] = {'\0'};
if(strlen(name)>0)
{
file = fopen(name, "r");
if(file)
{
snprintf(command,sizeof(command),"%s %s %s",name,serNum,mac);
out = popen(command, "r");
if(out)
{
fgets(token, len, out);
pclose(out);
}
fclose(file);
}
else
{
ParodusError ("File %s open error\n", name);
}
}
}
// strips ':' characters
// verifies that there exactly 12 characters
int parse_mac_address (char *target, const char *arg)
@@ -361,13 +386,10 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
{"ssl-cert-path", required_argument, 0, 'c'},
{"force-ipv4", no_argument, 0, '4'},
{"force-ipv6", no_argument, 0, '6'},
{"token-read-script", required_argument, 0, 'T'},
{"boot-time-retry-wait", required_argument, 0, 'w'},
{"client-cert-path", required_argument, 0, 'P'},
{"token-server-url", required_argument, 0, 'U'},
{"token-acquisition-script", required_argument, 0, 'J'},
{"crud-config-file", required_argument, 0, 'C'},
{"connection-health-file", required_argument, 0, 'S'},
{"mtls-client-key-path", required_argument, 0, 'K'},
{"mtls-client-cert-path", required_argument, 0,'M'},
{0, 0, 0, 0}
};
int c;
@@ -383,9 +405,6 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
cfg->jwt_algo = 0;
parStrncpy (cfg->jwt_key, "", sizeof(cfg->jwt_key));
cfg->crud_config_file = NULL;
cfg->connection_health_file = NULL;
cfg->client_cert_path = NULL;
cfg->token_server_url = NULL;
cfg->cloud_status = NULL;
cfg->cloud_disconnect = NULL;
optind = 1; /* We need this if parseCommandLine is called again */
@@ -394,7 +413,7 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "m:s:f:d:r:n:b:u:t:o:i:l:p:e:D:j:a:k:c:T:w:J:46:C:S:K:M",
c = getopt_long (argc, argv, "m:s:f:d:r:n:b:u:t:o:i:l:p:e:D:j:a:k:c:T:w:J:46:C",
long_options, &option_index);
/* Detect the end of the options. */
@@ -435,7 +454,6 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
case 'r':
parStrncpy(cfg->hw_last_reboot_reason, optarg,sizeof(cfg->hw_last_reboot_reason));
ParodusInfo("hw_last_reboot_reason is %s\n",cfg->hw_last_reboot_reason);
OnboardLog("Last reboot reason is %s\n",cfg->hw_last_reboot_reason);
break;
case 'n':
@@ -528,40 +546,23 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
cfg->flags |= FLAGS_IPV6_ONLY;
break;
case 'J':
parStrncpy(cfg->token_acquisition_script, optarg,sizeof(cfg->token_acquisition_script));
break;
case 'T':
parStrncpy(cfg->token_read_script, optarg,sizeof(cfg->token_read_script));
break;
case 'w':
cfg->boot_retry_wait = parse_num_arg (optarg, "boot-time-retry-wait");
ParodusInfo("boot_retry_wait is %d\n",cfg->boot_retry_wait);
break;
case 'S':
cfg->connection_health_file = strdup(optarg);
ParodusInfo("connection_health_file is %s\n", cfg->connection_health_file);
break;
case 'C':
cfg->crud_config_file = strdup(optarg);
ParodusInfo("crud_config_file is %s\n", cfg->crud_config_file);
break;
case 'P':
cfg->client_cert_path = strdup(optarg);
ParodusInfo("client_cert_path is %s\n", cfg->client_cert_path);
break;
case 'U':
cfg->token_server_url = strdup(optarg);
ParodusInfo("token_server_url is %s\n", cfg->token_server_url);
break;
case 'K':
cfg->mtls_client_key_path = strdup(optarg);
ParodusInfo("mtls_client_key_path is %s\n", cfg->mtls_client_key_path);
break;
case 'M':
cfg->mtls_client_cert_path = strdup(optarg);
ParodusInfo("mtls_client_cert_path is %s\n", cfg->mtls_client_cert_path);
break;
case 'C':
cfg->crud_config_file = strdup(optarg);
ParodusInfo("crud_config_file is %s\n", cfg->crud_config_file);
break;
case '?':
/* getopt_long already printed an error message. */
@@ -605,6 +606,64 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
return 0;
}
/*
* call parodus create/acquisition script to create new auth token, if success then calls
* execute_token_script func with args as parodus read script.
*/
void createNewAuthToken(char *newToken, size_t len)
{
//Call create script
char output[12] = {'\0'};
memset (newToken, 0, len);
execute_token_script(output,get_parodus_cfg()->token_acquisition_script,sizeof(output),get_parodus_cfg()->hw_mac,get_parodus_cfg()->hw_serial_number);
if (strlen(output)>0 && strcmp(output,"SUCCESS")==0)
{
//Call read script
execute_token_script(newToken,get_parodus_cfg()->token_read_script,len,get_parodus_cfg()->hw_mac,get_parodus_cfg()->hw_serial_number);
}
else
{
ParodusError("Failed to create new token\n");
}
}
/*
* Fetches authorization token from the output of read script. If read script returns "ERROR"
* it will call createNewAuthToken to create and read new token
*/
void getAuthToken(ParodusCfg *cfg)
{
//local var to update cfg->webpa_auth_token only in success case
char output[4069] = {'\0'} ;
memset (cfg->webpa_auth_token, 0, sizeof(cfg->webpa_auth_token));
if( strlen(cfg->token_read_script) !=0 && strlen(cfg->token_acquisition_script) !=0)
{
execute_token_script(output,cfg->token_read_script,sizeof(output),cfg->hw_mac,cfg->hw_serial_number);
if ((strlen(output) == 0))
{
ParodusError("Unable to get auth token\n");
}
else if(strcmp(output,"ERROR")==0)
{
ParodusInfo("Failed to read token from %s. Proceeding to create new token.\n",cfg->token_read_script);
//Call create/acquisition script
createNewAuthToken(cfg->webpa_auth_token, sizeof(cfg->webpa_auth_token));
}
else
{
ParodusInfo("update cfg->webpa_auth_token in success case\n");
parStrncpy(cfg->webpa_auth_token, output, sizeof(cfg->webpa_auth_token));
}
}
else
{
ParodusInfo("Both read and write file are NULL \n");
}
}
void setDefaultValuesToCfg(ParodusCfg *cfg)
{
if(cfg == NULL)
@@ -636,9 +695,6 @@ void setDefaultValuesToCfg(ParodusCfg *cfg)
parStrncpy(cfg->webpa_uuid, "1234567-345456546",sizeof(cfg->webpa_uuid));
ParodusPrint("cfg->webpa_uuid is :%s\n", cfg->webpa_uuid);
cfg->crud_config_file = NULL;
cfg->connection_health_file = NULL;
cfg->client_cert_path = NULL;
cfg->token_server_url = NULL;
cfg->cloud_status = CLOUD_STATUS_OFFLINE;
ParodusInfo("Default cloud_status is %s\n", cfg->cloud_status);
@@ -779,6 +835,24 @@ void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg)
ParodusPrint("cert_path is NULL. set to empty\n");
}
if(strlen(config->token_acquisition_script )!=0)
{
parStrncpy(cfg->token_acquisition_script, config->token_acquisition_script,sizeof(cfg->token_acquisition_script));
}
else
{
ParodusPrint("token_acquisition_script is NULL. read from tmp file\n");
}
if(strlen(config->token_read_script )!=0)
{
parStrncpy(cfg->token_read_script, config->token_read_script,sizeof(cfg->token_read_script));
}
else
{
ParodusPrint("token_read_script is NULL. read from tmp file\n");
}
cfg->boot_time = config->boot_time;
cfg->webpa_ping_timeout = config->webpa_ping_timeout;
cfg->webpa_backoff_max = config->webpa_backoff_max;
@@ -788,15 +862,6 @@ void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg)
parStrncpy(cfg->webpa_uuid, "1234567-345456546",sizeof(cfg->webpa_uuid));
ParodusPrint("cfg->webpa_uuid is :%s\n", cfg->webpa_uuid);
if(config->connection_health_file != NULL)
{
cfg->connection_health_file = strdup(config->connection_health_file);
}
else
{
ParodusPrint("connection_health_file is NULL. set to empty\n");
}
if(config->crud_config_file != NULL)
{
cfg->crud_config_file = strdup(config->crud_config_file);
@@ -805,24 +870,6 @@ void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg)
{
ParodusPrint("crud_config_file is NULL. set to empty\n");
}
if(config->client_cert_path != NULL)
{
cfg->client_cert_path = strdup(config->client_cert_path);
}
else
{
ParodusPrint("client_cert_path is NULL. set to empty\n");
}
if(config->token_server_url != NULL)
{
cfg->token_server_url = strdup(config->token_server_url);
}
else
{
ParodusPrint("token_server_url is NULL. set to empty\n");
}
}

View File

@@ -42,7 +42,7 @@ extern "C" {
#define BOOT_TIME "boot-time"
#define LAST_RECONNECT_REASON "webpa-last-reconnect-reason"
#define WEBPA_PROTOCOL "webpa-protocol"
#define WEBPA_INTERFACE "webpa-interface-used"
#define WEBPA_INTERFACE "webpa-inteface-used"
#define WEBPA_UUID "webpa-uuid"
#define WEBPA_URL "webpa-url"
#define WEBPA_PING_TIMEOUT "webpa-ping-timeout"
@@ -99,11 +99,6 @@ typedef struct
char webpa_auth_token[4096];
char token_acquisition_script[64];
char token_read_script[64];
char *client_cert_path;
char *token_server_url;
char *connection_health_file;
char *mtls_client_key_path;
char *mtls_client_cert_path;
char *crud_config_file;
char *cloud_status;
char *cloud_disconnect;
@@ -119,6 +114,7 @@ typedef struct
/*----------------------------------------------------------------------------*/
void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg);
void createNewAuthToken(char *newToken, size_t len);
/**
* parse command line arguments and create config structure
@@ -132,6 +128,7 @@ void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg);
int parseCommandLine(int argc,char **argv,ParodusCfg * cfg);
void setDefaultValuesToCfg(ParodusCfg *cfg);
void getAuthToken(ParodusCfg *cfg);
// Accessor for the global config structure.
ParodusCfg *get_parodus_cfg(void);
void set_parodus_cfg(ParodusCfg *);
@@ -152,6 +149,7 @@ void reset_cloud_disconnect_reason(ParodusCfg *cfg);
*/
int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port);
#ifdef __cplusplus
}
#endif

View File

@@ -36,7 +36,6 @@
#include "crud_interface.h"
#include "heartBeat.h"
#include "close_retry.h"
#include <curl/curl.h>
#ifdef FEATURE_DNS_QUERY
#include <ucresolv_log.h>
#endif
@@ -53,18 +52,12 @@
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool g_shutdown = false;
pthread_t upstream_tid;
pthread_t upstream_msg_tid;
pthread_t downstream_tid;
pthread_t svc_alive_tid;
pthread_t crud_tid;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result);
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -74,10 +67,8 @@ void createSocketConnection(void (* initKeypress)())
//ParodusCfg *tmpCfg = (ParodusCfg*)config_in;
noPollCtx *ctx;
bool seshat_registered = false;
int create_conn_rtn = 0;
unsigned int webpa_ping_timeout_ms = 1000 * get_parodus_cfg()->webpa_ping_timeout;
unsigned int heartBeatTimer = 0;
struct timespec start_svc_alive_timer;
//loadParodusCfg(tmpCfg,get_parodus_cfg());
#ifdef FEATURE_DNS_QUERY
@@ -95,24 +86,20 @@ void createSocketConnection(void (* initKeypress)())
nopoll_log_set_handler (ctx, __report_log, NULL);
#endif
start_conn_in_progress ();
create_conn_rtn = createNopollConnection(ctx);
stop_conn_in_progress ();
if(!create_conn_rtn)
if(!createNopollConnection(ctx))
{
ParodusError("Unrecovered error, terminating the process\n");
OnboardLog("Unrecovered error, terminating the process\n");
abort();
}
packMetaData();
UpStreamMsgQ = NULL;
StartThread(handle_upstream, &upstream_tid);
StartThread(processUpstreamMessage, &upstream_msg_tid);
StartThread(handle_upstream);
StartThread(processUpstreamMessage);
ParodusMsgQ = NULL;
StartThread(messageHandlerTask, &downstream_tid);
StartThread(serviceAliveTask, &svc_alive_tid);
StartThread(CRUDHandlerTask, &crud_tid);
StartThread(messageHandlerTask);
StartThread(serviceAliveTask);
StartThread(CRUDHandlerTask);
if (NULL != initKeypress)
{
@@ -121,8 +108,6 @@ void createSocketConnection(void (* initKeypress)())
seshat_registered = __registerWithSeshat();
clock_gettime(CLOCK_REALTIME, &start_svc_alive_timer);
do
{
struct timespec start, stop, diff;
@@ -145,7 +130,6 @@ void createSocketConnection(void (* initKeypress)())
{
ParodusError("ping wait time > %d . Terminating the connection with WebPA server and retrying\n", webpa_ping_timeout_ms / 1000);
ParodusInfo("Reconnect detected, setting Ping_Miss reason for Reconnect\n");
OnboardLog("Reconnect detected, setting Ping_Miss reason for Reconnect\n");
set_global_reconnect_reason("Ping_Miss");
set_global_reconnect_status(true);
set_close_retry();
@@ -174,47 +158,22 @@ void createSocketConnection(void (* initKeypress)())
ParodusInfo("cloud_status set as %s after connection close\n", get_parodus_cfg()->cloud_status);
if(get_parodus_cfg()->cloud_disconnect !=NULL)
{
ParodusPrint("get_parodus_cfg()->cloud_disconnect is %s\n", get_parodus_cfg()->cloud_disconnect);
set_cloud_disconnect_time(CLOUD_RECONNECT_TIME);
ParodusInfo("Waiting for %d minutes for reconnecting .. \n", get_cloud_disconnect_time());
ParodusPrint("get_parodus_cfg()->cloud_disconnect is %s\n", get_parodus_cfg()->cloud_disconnect);
set_cloud_disconnect_time(CLOUD_RECONNECT_TIME);
ParodusInfo("Waiting for %d minutes for reconnecting .. \n", get_cloud_disconnect_time());
sleep (get_cloud_disconnect_time() * 60);
ParodusInfo("cloud-disconnect reason reset after %d minutes\n", get_cloud_disconnect_time());
free(get_parodus_cfg()->cloud_disconnect);
reset_cloud_disconnect_reason(get_parodus_cfg());
sleep( get_cloud_disconnect_time() * 60 );
ParodusInfo("cloud-disconnect reason reset after %d minutes\n", get_cloud_disconnect_time());
free(get_parodus_cfg()->cloud_disconnect);
reset_cloud_disconnect_reason(get_parodus_cfg());
}
start_conn_in_progress ();
createNopollConnection(ctx);
stop_conn_in_progress ();
}
} while(!get_close_retry() && !g_shutdown);
pthread_mutex_lock (get_global_svc_mut());
pthread_cond_signal (get_global_svc_con());
pthread_mutex_unlock (get_global_svc_mut());
pthread_mutex_lock (get_global_crud_mut());
pthread_cond_signal (get_global_crud_con());
pthread_mutex_unlock (get_global_crud_mut());
pthread_mutex_lock (&g_mutex);
pthread_cond_signal (&g_cond);
pthread_mutex_unlock (&g_mutex);
pthread_mutex_lock (get_global_nano_mut ());
pthread_cond_signal (get_global_nano_con());
pthread_mutex_unlock (get_global_nano_mut());
ParodusInfo ("joining threads\n");
JoinThread (svc_alive_tid);
JoinThread (upstream_tid);
JoinThread (downstream_tid);
JoinThread (upstream_msg_tid);
JoinThread (crud_tid);
deleteAllClients ();
close_and_unref_connection(get_global_conn());
nopoll_ctx_unref(ctx);
nopoll_cleanup_library();
curl_global_cleanup();
}
void shutdownSocketConnection(void) {

View File

@@ -25,7 +25,6 @@
#include "time.h"
#include "token.h"
#include "config.h"
#include "auth_token.h"
#include "nopoll_helpers.h"
#include "mutex.h"
#include "spin_thread.h"
@@ -47,7 +46,6 @@ static char *reconnect_reason = "webpa_process_starts";
static int cloud_disconnect_max_time = 5;
static noPollConn *g_conn = NULL;
static bool LastReasonStatus = false;
static int init = 1;
static noPollConnOpts * createConnOpts (char * extra_headers, bool secure);
static char* build_extra_headers( const char *auth, const char *device_id,
const char *user_agent, const char *convey );
@@ -296,25 +294,22 @@ void set_current_server (create_connection_ctx_t *ctx)
ctx->current_server = get_current_server (&ctx->server_list);
}
void free_extra_headers (create_connection_ctx_t *ctx)
void set_extra_headers (create_connection_ctx_t *ctx, int reauthorize)
{
FREE_PTR_VAR (ctx->extra_headers)
}
void set_extra_headers (create_connection_ctx_t *ctx)
{
ParodusCfg * cfg = get_parodus_cfg();
free_extra_headers (ctx);
if ((strlen(cfg->webpa_auth_token) == 0) &&
(cfg->client_cert_path != NULL) && (strlen(cfg->client_cert_path) > 0))
if (reauthorize && (strlen(get_parodus_cfg()->token_acquisition_script) >0))
{
getAuthToken(cfg);
createNewAuthToken(get_parodus_cfg()->webpa_auth_token,
sizeof(get_parodus_cfg()->webpa_auth_token));
}
ctx->extra_headers = build_extra_hdrs (&ctx->header_info);
}
void free_extra_headers (create_connection_ctx_t *ctx)
{
FREE_PTR_VAR (ctx->extra_headers)
}
void free_connection_ctx (create_connection_ctx_t *ctx)
{
free_extra_headers (ctx);
@@ -389,12 +384,10 @@ int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
NULL, default_url,NULL,NULL);
}
}
if ((NULL == connection) && (!is_ipv6)) {
if (NULL == connection) {
if((checkHostIp(server->server_addr) == -2)) {
if (check_timer_expired (&ctx->connect_timer, 15*60*1000)) {
ParodusError("WebPA unable to connect due to DNS resolving to 10.0.0.1 for over 15 minutes; crashing service.\n");
OnboardLog("WebPA unable to connect due to DNS resolving to 10.0.0.1 for over 15 minutes; crashing service.\n");
OnboardLog("Reconnect detected, setting Dns_Res_webpa_reconnect reason for Reconnect\n");
set_global_reconnect_reason("Dns_Res_webpa_reconnect");
set_global_reconnect_status(true);
@@ -410,11 +403,9 @@ int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
//--------------------------------------------------------------------
// Return codes for wait_connection_ready
#define WAIT_SUCCESS 0
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define WAIT_FAIL 2
#define FREE_NON_NULL_PTR(ptr) if (NULL != ptr) free(ptr)
int wait_connection_ready (create_connection_ctx_t *ctx)
{
int wait_status;
@@ -422,10 +413,7 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
if(nopoll_conn_wait_for_status_until_connection_ready(get_global_conn(), 10,
&wait_status, &redirectURL))
{
FREE_NON_NULL_PTR (redirectURL);
return WAIT_SUCCESS;
}
if(wait_status == 307 || wait_status == 302 || wait_status == 303) // only when there is a http redirect
{
char *redirect_ptr = redirectURL;
@@ -443,15 +431,15 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
set_current_server (ctx); // set current server to redirect server
return WAIT_ACTION_RETRY;
}
FREE_NON_NULL_PTR (redirectURL);
if (NULL != redirectURL) {
free (redirectURL);
}
if(wait_status == 403)
{
ParodusCfg *cfg = get_parodus_cfg();
/* clear auth token in cfg so that we will refetch auth token */
memset (cfg->webpa_auth_token, 0, sizeof(cfg->webpa_auth_token));
ParodusError("Received Unauthorized response with status: %d\n", wait_status);
OnboardLog("Received Unauthorized response with status: %d\n", wait_status);
return WAIT_ACTION_RETRY;
ParodusError("Received Unauthorized response with status: %d\n", wait_status);
free_extra_headers (ctx);
set_extra_headers (ctx, true);
return WAIT_ACTION_RETRY;
}
ParodusError("Client connection timeout\n");
ParodusError("RDK-10037 - WebPA Connection Lost\n");
@@ -461,9 +449,9 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
//--------------------------------------------------------------------
// Return codes for connect_and_wait
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define CONN_WAIT_RETRY_DNS 2
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define CONN_WAIT_RETRY_DNS 2
int connect_and_wait (create_connection_ctx_t *ctx)
{
@@ -522,12 +510,9 @@ int keep_trying_to_connect (create_connection_ctx_t *ctx,
while (true)
{
set_extra_headers (ctx);
rtn = connect_and_wait (ctx);
if (rtn == CONN_WAIT_SUCCESS)
return true;
if (rtn == CONN_WAIT_ACTION_RETRY) // if redirected or build_headers
continue;
backoff_delay (backoff_timer); // 3,7,15,31 ..
@@ -563,15 +548,15 @@ int createNopollConnection(noPollCtx *ctx)
max_retry_count = (int) get_parodus_cfg()->webpa_backoff_max;
ParodusPrint("max_retry_count is %d\n", max_retry_count );
memset (&conn_ctx, 0, sizeof(create_connection_ctx_t));
conn_ctx.nopoll_ctx = ctx;
init_expire_timer (&conn_ctx.connect_timer);
init_header_info (&conn_ctx.header_info);
set_extra_headers (&conn_ctx, false);
set_server_list_null (&conn_ctx.server_list);
init_backoff_timer (&backoff_timer, max_retry_count);
while (!g_shutdown)
while (true)
{
query_dns_status = find_servers (&conn_ctx.server_list);
if (query_dns_status == FIND_INVALID_DEFAULT)
@@ -585,21 +570,18 @@ int createNopollConnection(noPollCtx *ctx)
if(conn_ctx.current_server->allow_insecure <= 0)
{
ParodusInfo("Connected to server over SSL\n");
OnboardLog("Connected to server over SSL\n");
}
else
{
ParodusInfo("Connected to server\n");
OnboardLog("Connected to server\n");
}
get_parodus_cfg()->cloud_status = CLOUD_STATUS_ONLINE;
ParodusInfo("cloud_status set as %s after successful connection\n", get_parodus_cfg()->cloud_status);
if((get_parodus_cfg()->boot_time != 0) && init) {
if(get_parodus_cfg()->boot_time != 0) {
getCurrentTime(connectTimePtr);
ParodusInfo("connect_time-diff-boot_time=%d\n", connectTimePtr->tv_sec - get_parodus_cfg()->boot_time);
init = 0; //set init to 0 so that this is logged only during process start up and not during reconnect
}
free_extra_headers (&conn_ctx);
@@ -641,20 +623,13 @@ static char* build_extra_headers( const char *auth, const char *device_id,
static noPollConnOpts * createConnOpts (char * extra_headers, bool secure)
{
noPollConnOpts * opts;
char * mtls_client_cert_path = NULL;
char * mtls_client_key_path = NULL;
opts = nopoll_conn_opts_new ();
if(secure)
{
if(strlen(get_parodus_cfg()->cert_path) > 0)
{
if( ( get_parodus_cfg()->mtls_client_cert_path !=NULL && strlen(get_parodus_cfg()->mtls_client_cert_path) > 0) && (get_parodus_cfg()->mtls_client_key_path !=NULL && strlen(get_parodus_cfg()->mtls_client_key_path) > 0) )
{
mtls_client_cert_path = get_parodus_cfg()->mtls_client_cert_path;
mtls_client_key_path = get_parodus_cfg()->mtls_client_key_path;
}
nopoll_conn_opts_set_ssl_certs(opts, mtls_client_cert_path, mtls_client_key_path, NULL, get_parodus_cfg()->cert_path);
nopoll_conn_opts_set_ssl_certs(opts, NULL, NULL, NULL, get_parodus_cfg()->cert_path);
}
nopoll_conn_opts_ssl_peer_verify (opts, nopoll_true);
nopoll_conn_opts_set_ssl_protocol (opts, NOPOLL_METHOD_TLSV1_2);
@@ -675,38 +650,3 @@ void close_and_unref_connection(noPollConn *conn)
}
}
void write_conn_in_prog_file (const char *msg)
{
int fd;
FILE *fp;
unsigned long timestamp;
ParodusCfg *cfg = get_parodus_cfg();
if (NULL == cfg->connection_health_file)
return;
fd = open (cfg->connection_health_file, O_CREAT | O_WRONLY | O_SYNC, 0666);
if (fd < 0) {
ParodusError ("Error(1) %d opening file %s\n", errno, cfg->connection_health_file);
return;
}
ftruncate (fd, 0);
fp = fdopen (fd, "w");
if (fp == NULL) {
ParodusError ("Error(2) %d opening file %s\n", errno, cfg->connection_health_file);
return;
}
timestamp = (unsigned long) time(NULL);
fprintf (fp, "{%s=%lu}\n", msg, timestamp);
fclose (fp);
}
void start_conn_in_progress (void)
{
write_conn_in_prog_file ("START");
}
void stop_conn_in_progress (void)
{
write_conn_in_prog_file ("STOP");
}

View File

@@ -57,13 +57,6 @@ void set_global_reconnect_status(bool status);
int get_cloud_disconnect_time();
void set_cloud_disconnect_time(int disconnTime);
/**
* @brief Interface to self heal connection in progress getting stuck
*/
void start_conn_in_progress (void);
void stop_conn_in_progress (void);
#ifdef __cplusplus
}
#endif

View File

@@ -44,16 +44,6 @@ CrudMsg *crudMsgQ = NULL;
/* External functions */
/*----------------------------------------------------------------------------*/
pthread_cond_t *get_global_crud_con(void)
{
return &crud_con;
}
pthread_mutex_t *get_global_crud_mut(void)
{
return &crud_mut;
}
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
CrudMsg * crudMessage;
@@ -132,10 +122,6 @@ void *CRUDHandlerTask()
}
else
{
if (g_shutdown) {
pthread_mutex_unlock (&crud_mut);
break;
}
pthread_cond_wait(&crud_con, &crud_mut);
pthread_mutex_unlock (&crud_mut);
}

View File

@@ -24,8 +24,6 @@
#ifndef _CRUD_INTERFACE_H_
#define _CRUD_INTERFACE_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
@@ -45,8 +43,6 @@ typedef struct CrudMsg__
/*----------------------------------------------------------------------------*/
void addCRUDresponseToUpstreamQ(void *response_bytes, ssize_t response_size);
pthread_cond_t *get_global_crud_con(void);
pthread_mutex_t *get_global_crud_mut(void);
#ifdef __cplusplus
}

View File

@@ -1346,7 +1346,6 @@ static int ConnDisconnectFromCloud(char *disconn_reason)
if(!close_retry)
{
ParodusInfo("Reconnect detected, setting reason %s for Reconnect\n", disconn_reason);
OnboardLog("Reconnect detected, setting reason %s for Reconnect\n", disconn_reason);
set_global_reconnect_reason(disconn_reason);
set_global_reconnect_status(true);
set_close_retry();

View File

@@ -27,10 +27,7 @@
#include "partners_check.h"
#include "ParodusInternal.h"
#include "crud_interface.h"
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
static void createNewMsgForCRUD(wrp_msg_t *message, wrp_msg_t **crudMessage );
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -45,7 +42,6 @@ void listenerOnMessage(void * msg, size_t msgSize)
{
int rv =0;
wrp_msg_t *message;
wrp_msg_t *crudMessage= NULL;
char* destVal = NULL;
char dest[32] = {'\0'};
int msgType;
@@ -79,6 +75,7 @@ void listenerOnMessage(void * msg, size_t msgSize)
case WRP_MSG_TYPE__AUTH:
{
ParodusInfo("Authorization Status received with Status code :%d\n", message->u.auth.status);
wrp_free_struct(message);
break;
}
@@ -121,13 +118,9 @@ void listenerOnMessage(void * msg, size_t msgSize)
ParodusInfo("Received downstream dest as :%s and transaction_uuid :%s\n", dest,
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.transaction_uuid :
((WRP_MSG_TYPE__EVENT == msgType) ? "NA" : message->u.crud.transaction_uuid)));
OnboardLog("%s\n",
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.transaction_uuid :
((WRP_MSG_TYPE__EVENT == msgType) ? "NA" : message->u.crud.transaction_uuid)));
free(destVal);
temp = get_global_node();
temp = get_global_node();
//Checking for individual clients & Sending to each client
while (NULL != temp)
@@ -146,11 +139,10 @@ void listenerOnMessage(void * msg, size_t msgSize)
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
release_global_node ();
/* check Downstream dest for CRUD requests */
if(destFlag ==0 && strcmp("parodus", dest)==0)
{
/* check Downstream dest for CRUD requests */
if(destFlag ==0 && strcmp("parodus", dest)==0)
{
ParodusPrint("Received CRUD request : dest : %s\n", dest);
if ((message->u.crud.source == NULL) || (message->u.crud.transaction_uuid == NULL))
{
@@ -162,12 +154,11 @@ void listenerOnMessage(void * msg, size_t msgSize)
}
else
{
createNewMsgForCRUD(message, &crudMessage);
addCRUDmsgToQueue(crudMessage);
addCRUDmsgToQueue(message);
}
destFlag =1;
}
//if any unknown dest received sending error response to server
}
//if any unknown dest received sending error response to server
if(destFlag ==0)
{
ParodusError("Unknown dest:%s\n", dest);
@@ -193,14 +184,14 @@ void listenerOnMessage(void * msg, size_t msgSize)
else
{
resp_msg ->u.crud.source = message->u.crud.dest;
if(message->u.crud.source !=NULL)
{
resp_msg ->u.crud.dest = message->u.crud.source;
}
else
{
resp_msg ->u.crud.dest = "unknown";
}
if(message->u.crud.source !=NULL)
{
resp_msg ->u.crud.dest = message->u.crud.source;
}
else
{
resp_msg ->u.crud.dest = "unknown";
}
resp_msg ->u.crud.transaction_uuid = message->u.crud.transaction_uuid;
resp_msg ->u.crud.path = message->u.crud.path;
}
@@ -234,6 +225,8 @@ void listenerOnMessage(void * msg, size_t msgSize)
resp_bytes = NULL;
}
free(resp_msg);
ParodusPrint("free for downstream decoded msg\n");
wrp_free_struct(message);
}
break;
}
@@ -242,11 +235,9 @@ void listenerOnMessage(void * msg, size_t msgSize)
case WRP_MSG_TYPE__SVC_ALIVE:
case WRP_MSG_TYPE__UNKNOWN:
default:
wrp_free_struct(message);
break;
}
ParodusPrint("free for downstream decoded msg\n");
wrp_free_struct(message);
message = NULL;
}
else
{
@@ -254,116 +245,3 @@ void listenerOnMessage(void * msg, size_t msgSize)
}
}
}
/*----------------------------------------------------------------------------*/
/* Internal Functions */
/*----------------------------------------------------------------------------*/
/**
* @brief createNewMsgForCRUD function to create new message for processing CRUD requests
*
* @param[in] message The message received from server
* @param[out] crudMessage New message for processing CRUD requests
*/
static void createNewMsgForCRUD(wrp_msg_t *message, wrp_msg_t **crudMessage )
{
wrp_msg_t *msg;
msg = ( wrp_msg_t * ) malloc( sizeof( wrp_msg_t ) );
size_t i;
if(msg != NULL)
{
memset( msg, 0, sizeof( wrp_msg_t ) );
msg->msg_type = message->msg_type;
if(message->u.crud.source != NULL)
{
ParodusPrint("message->u.crud.source = %s\n",message->u.crud.source);
msg->u.crud.source = strdup(message->u.crud.source);
}
if(message->u.crud.dest!= NULL)
{
ParodusPrint("message->u.crud.dest = %s\n",message->u.crud.dest);
msg->u.crud.dest = strdup(message->u.crud.dest);
}
if(message->u.crud.transaction_uuid != NULL)
{
ParodusPrint("message->u.crud.transaction_uuid = %s\n",message->u.crud.transaction_uuid);
msg->u.crud.transaction_uuid = strdup(message->u.crud.transaction_uuid);
}
if(message->u.crud.partner_ids!= NULL && message->u.crud.partner_ids->count >0)
{
msg->u.crud.partner_ids = ( partners_t * ) malloc( sizeof( partners_t ) +
sizeof( char * ) * message->u.crud.partner_ids->count );
if(msg->u.crud.partner_ids != NULL)
{
msg->u.crud.partner_ids->count = message->u.crud.partner_ids->count;
for(i = 0; i<message->u.crud.partner_ids->count; i++)
{
ParodusPrint("message->u.crud.partner_ids->partner_ids[%d] = %s\n",i,message->u.crud.partner_ids->partner_ids[i]);
msg->u.crud.partner_ids->partner_ids[i] = strdup(message->u.crud.partner_ids->partner_ids[i]);
}
}
}
if(message->u.crud.headers!= NULL && message->u.crud.headers->count >0)
{
msg->u.crud.headers = ( headers_t * ) malloc( sizeof( headers_t ) +
sizeof( char * ) * message->u.crud.headers->count );
if(msg->u.crud.headers != NULL)
{
msg->u.crud.headers->count = message->u.crud.headers->count;
for(i = 0; i<message->u.crud.headers->count; i++)
{
ParodusPrint("message->u.crud.headers->headers[%d] = %s\n",i,message->u.crud.headers->headers[i]);
msg->u.crud.headers->headers[i] = strdup(message->u.crud.headers->headers[i]);
}
}
}
if(message->u.crud.metadata != NULL && message->u.crud.metadata->count > 0)
{
msg->u.crud.metadata = (data_t *) malloc( sizeof( data_t ) );
if(msg->u.crud.metadata != NULL)
{
memset( msg->u.crud.metadata, 0, sizeof( data_t ) );
msg->u.crud.metadata->count = message->u.crud.metadata->count;
msg->u.crud.metadata->data_items = ( struct data* )malloc( sizeof( struct data ) * ( message->u.crud.metadata->count ) );
for(i=0; i<message->u.crud.metadata->count; i++)
{
if(message->u.crud.metadata->data_items[i].name != NULL)
{
ParodusPrint("message->u.crud.metadata->data_items[%d].name : %s\n",i,message->u.crud.metadata->data_items[i].name);
msg->u.crud.metadata->data_items[i].name = strdup(message->u.crud.metadata->data_items[i].name);
}
if(message->u.crud.metadata->data_items[i].value != NULL)
{
ParodusPrint("message->u.crud.metadata->data_items[%d].value : %s\n",i,message->u.crud.metadata->data_items[i].value);
msg->u.crud.metadata->data_items[i].value = strdup(message->u.crud.metadata->data_items[i].value);
}
}
}
}
msg->u.crud.include_spans = message->u.crud.include_spans;
if(message->u.crud.content_type != NULL)
{
ParodusPrint("message->u.crud.content_type : %s\n",message->u.crud.content_type);
msg->u.crud.content_type = strdup(message->u.crud.content_type);
}
msg->u.crud.spans.spans = NULL; /* not supported */
msg->u.crud.spans.count = 0; /* not supported */
msg->u.crud.status = message->u.crud.status;
msg->u.crud.rdr = message->u.crud.rdr;
if(message->u.crud.payload != NULL)
{
ParodusPrint("message->u.crud.payload = %s\n", (char *)message->u.crud.payload);
msg->u.crud.payload = strdup((char *)message->u.crud.payload);
}
msg->u.crud.payload_size = message->u.crud.payload_size;
if(message->u.crud.path != NULL)
{
ParodusPrint("message->u.crud.path = %s\n", message->u.crud.path);
msg->u.crud.path = strdup(message->u.crud.path);
}
*crudMessage = msg;
}
}

View File

@@ -18,10 +18,8 @@
#include <string.h>
#include "stdlib.h"
#include "config.h"
#include "auth_token.h"
#include "conn_interface.h"
#include "parodus_log.h"
#include <curl/curl.h>
#ifdef INCLUDE_BREAKPAD
#include "breakpad_wrapper.h"
#else
@@ -82,7 +80,7 @@ int main( int argc, char **argv)
if (0 != parseCommandLine(argc,argv,cfg)) {
abort();
}
curl_global_init(CURL_GLOBAL_DEFAULT);
getAuthToken(cfg);
createSocketConnection( NULL);

View File

@@ -70,7 +70,6 @@ int checkHostIp(char * serverIP)
if (retVal != 0)
{
ParodusError("getaddrinfo: %s\n", gai_strerror(retVal));
OnboardLog("getaddrinfo: %s\n", gai_strerror(retVal));
}
else
{

View File

@@ -167,14 +167,12 @@ void listenerOnCloseMessage (noPollCtx * ctx, noPollConn * conn, noPollPtr user_
if( closeStatus == 1006 && !get_global_reconnect_status())
{
ParodusInfo("Reconnect detected, setting default Reconnect reason %s\n",defaultReason);
OnboardLog("Reconnect detected, setting default Reconnect reason %s\n",defaultReason);
set_global_reconnect_reason(defaultReason);
set_global_reconnect_status(true);
}
else if(!get_global_reconnect_status())
{
ParodusInfo("Reconnect detected, setting Reconnect reason as Unknown\n");
OnboardLog("Reconnect detected, setting Reconnect reason as Unknown\n");
set_global_reconnect_reason("Unknown");
}

View File

@@ -73,7 +73,6 @@ void sendMessage(noPollConn *conn, void *msg, size_t len)
else
{
ParodusError("Failed to send msg upstream as connection is not OK\n");
OnboardLog("Failed to send msg upstream as connection is not OK\n");
if (connErr == 0)
{
getCurrentTime(connStuck_startPtr);
@@ -89,7 +88,6 @@ void sendMessage(noPollConn *conn, void *msg, size_t len)
if( timeDiff >= (10*60*1000))
{
ParodusError("conn got stuck for over 10 minutes; crashing service.\n");
OnboardLog("conn got stuck for over 10 minutes; crashing service.\n");
kill(getpid(),SIGTERM);
}
@@ -151,7 +149,6 @@ void __report_log (noPollCtx * ctx, noPollDebugLevel level, const char * log_msg
if (level == NOPOLL_LEVEL_CRITICAL)
{
ParodusError("%s\n", log_msg );
OnboardLog("%s\n", log_msg );
}
return;
}

View File

@@ -33,9 +33,3 @@
#define ParodusError(...) cimplog_error(LOGGING_MODULE, __VA_ARGS__)
#define ParodusInfo(...) cimplog_info(LOGGING_MODULE, __VA_ARGS__)
#define ParodusPrint(...) cimplog_debug(LOGGING_MODULE, __VA_ARGS__)
#ifdef FEATURE_SUPPORT_ONBOARD_LOGGING
#define OnboardLog(...) onboarding_log(LOGGING_MODULE, __VA_ARGS__)
#else
#define OnboardLog(...)
#endif

View File

@@ -178,7 +178,6 @@ int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
if(matchFlag != 1)
{
ParodusError("Invalid partner_id %s\n",temp);
OnboardLog("Invalid partner_id %s\n",temp);
if(partnersList != NULL)
{
for(j=0; j<partnersList->count; j++)

View File

@@ -31,41 +31,9 @@
/*----------------------------------------------------------------------------*/
#define KEEPALIVE_INTERVAL_SEC 30
pthread_mutex_t svc_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t svc_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Utiliy Functions */
/*----------------------------------------------------------------------------*/
static int wait__ (unsigned int secs)
{
int shutdown_flag;
struct timespec svc_alive_timer;
clock_gettime(CLOCK_REALTIME, &svc_alive_timer);
svc_alive_timer.tv_sec += secs;
pthread_mutex_lock(&svc_mut);
pthread_cond_timedwait (&svc_con, &svc_mut, &svc_alive_timer);
shutdown_flag = g_shutdown;
pthread_mutex_unlock (&svc_mut);
return shutdown_flag;
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
pthread_cond_t *get_global_svc_con(void)
{
return &svc_con;
}
pthread_mutex_t *get_global_svc_mut(void)
{
return &svc_mut;
}
/*
* @brief To handle registered services to indicate that the service is still alive.
*/
@@ -90,10 +58,10 @@ void *serviceAliveTask()
while(1)
{
ParodusPrint("serviceAliveTask: numOfClients registered is %d\n", get_numOfClients());
temp = get_global_node();
if(get_numOfClients() > 0)
{
//sending svc msg to all the clients every 30s
temp = get_global_node();
size = (size_t) nbytes;
while(NULL != temp)
{
@@ -114,9 +82,8 @@ void *serviceAliveTask()
byte = 0;
if(ret == 0)
{
release_global_node ();
ParodusPrint("Deletion from list is success, doing resync with head\n");
temp= get_global_node();
ParodusInfo("Deletion from list is success, doing resync with head\n");
ret = -1;
}
else
@@ -124,20 +91,15 @@ void *serviceAliveTask()
temp= temp->next;
}
}
release_global_node ();
ParodusPrint("Waiting for 30s to send keep alive msg \n");
if (wait__ (KEEPALIVE_INTERVAL_SEC))
break;
sleep(KEEPALIVE_INTERVAL_SEC);
}
else
{
release_global_node ();
ParodusInfo("No clients are registered, waiting ..\n");
if (wait__ (50))
break;
sleep(50);
}
}
free (svc_bytes);
}
return 0;
}

View File

@@ -24,8 +24,6 @@
#ifndef _SERVICE_ALIVE_H_
#define _SERVICE_ALIVE_H_
#include <pthread.h>
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
@@ -35,8 +33,7 @@ extern "C" {
#endif
void *serviceAliveTask();
pthread_cond_t *get_global_svc_con(void);
pthread_mutex_t *get_global_svc_mut(void);
#ifdef __cplusplus
}

View File

@@ -23,6 +23,7 @@
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "spin_thread.h"
#include "parodus_log.h"
@@ -30,12 +31,12 @@
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
void StartThread(void *(*start_routine) (void *), pthread_t *threadId)
void StartThread(void *(*start_routine) (void *))
{
int err = 0;
pthread_t __threadId;
pthread_t threadId;
err = pthread_create(&__threadId, NULL, start_routine, NULL);
err = pthread_create(&threadId, NULL, start_routine, NULL);
if (err != 0)
{
ParodusError("Error creating thread :[%s]\n", strerror(err));
@@ -43,13 +44,8 @@ void StartThread(void *(*start_routine) (void *), pthread_t *threadId)
}
else
{
*threadId = __threadId;
ParodusPrint("Thread created Successfully %lu\n", (unsigned long) __threadId);
ParodusPrint("Thread created Successfully %lu\n", (unsigned long) threadId);
}
}
void JoinThread (pthread_t threadId)
{
pthread_join (threadId, NULL);
}

View File

@@ -24,8 +24,6 @@
#ifndef _SPIN_THREAD_H_
#define _SPIN_THREAD_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
@@ -34,8 +32,8 @@ extern "C" {
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void StartThread(void *(*start_routine) (void *), pthread_t *threadId);
void JoinThread (pthread_t threadId);
void StartThread(void *(*start_routine) (void *));
#ifdef __cplusplus
}

View File

@@ -43,10 +43,6 @@ void *messageHandlerTask()
}
else
{
if (g_shutdown) {
pthread_mutex_unlock (&g_mutex);
break;
}
ParodusPrint("Before pthread cond wait in consumer thread\n");
pthread_cond_wait(&g_cond, &g_mutex);
pthread_mutex_unlock (&g_mutex);

View File

@@ -139,7 +139,6 @@ int analyze_jwt (const cjwt_t *jwt, char **url_buf, unsigned int *port)
show_times (exp_time, cur_time);
if (exp_time < cur_time) {
ParodusError ("JWT has expired\n");
OnboardLog ("JWT has expired\n");
return TOKEN_ERR_JWT_EXPIRED;
}
}
@@ -147,7 +146,6 @@ int analyze_jwt (const cjwt_t *jwt, char **url_buf, unsigned int *port)
url_buf, port);
if (http_match < 0) {
ParodusError ("Invalid endpoint claim in JWT\n");
OnboardLog("Invalid endpoint claim in JWT\n");
return TOKEN_ERR_BAD_ENDPOINT;
}
ParodusInfo ("JWT is_http strncmp: %d\n", http_match);
@@ -529,9 +527,7 @@ int allow_insecure_conn(char **server_addr, unsigned int *port)
}
if (insecure >= 0) {
char *claim_str = cJSON_Print (jwt->private_claims);
ParodusInfo ("JWT claims: %s\n", claim_str);
free (claim_str);
ParodusInfo ("JWT claims: %s\n", cJSON_Print (jwt->private_claims));
}
cjwt_destroy(&jwt);

View File

@@ -34,7 +34,7 @@
/* Macros */
/*----------------------------------------------------------------------------*/
#define METADATA_COUNT 12
#define PARODUS_SERVICE_NAME "parodus"
#define CLOUD_STATUS_FORMAT "parodus/cloud-status"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
@@ -129,12 +129,6 @@ void *handle_upstream()
sock = nn_socket( AF_SP, NN_PULL );
if(sock >= 0)
{
int t = NANO_SOCKET_RCV_TIMEOUT_MS;
int rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
if (rc < 0)
{
ParodusError ("Unable to set socket receive timeout (errno=%d, %s)\n",errno, strerror(errno));
}
ParodusPrint("Nanomsg bind with get_parodus_cfg()->local_url %s\n", get_parodus_cfg()->local_url);
bind = nn_bind(sock, get_parodus_cfg()->local_url);
if(bind < 0)
@@ -143,18 +137,11 @@ void *handle_upstream()
}
else
{
ParodusInfo("nanomsg server gone into the listening mode...\n");
while( FOREVER() )
{
buf = NULL;
ParodusInfo("nanomsg server gone into the listening mode...\n");
bytes = nn_recv (sock, &buf, NN_MSG, 0);
if (g_shutdown)
break;
if (bytes < 0) {
if ((errno != EAGAIN) && (errno != ETIMEDOUT))
ParodusInfo ("Error (%d) receiving message from nanomsg client\n", errno);
continue;
}
ParodusInfo ("Upstream message received from nanomsg client\n");
message = (UpStreamMsg *)malloc(sizeof(UpStreamMsg));
@@ -190,16 +177,6 @@ void *handle_upstream()
ParodusError("failure in allocation for message\n");
}
}
if(nn_shutdown(sock, bind) < 0)
{
ParodusError ("nn_shutdown bind socket=%d endpt=%d, err=%d\n",
sock, bind, errno);
}
if (nn_close (sock) < 0)
{
ParodusError ("nn_close bind socket=%d err=%d\n",
sock, errno);
}
}
}
else
@@ -220,10 +197,11 @@ void *processUpstreamMessage()
reg_list_item_t *temp = NULL;
int matchFlag = 0;
int status = -1;
char *device_id = NULL;
size_t device_id_len = 0;
size_t parodus_len;
int ret = -1;
char *serviceName = NULL;
char *macId = NULL;
char *destService, *destApplication =NULL;
char *sourceService, *sourceApplication =NULL;
int sendStatus =-1;
while(FOREVER())
{
@@ -244,40 +222,34 @@ void *processUpstreamMessage()
if(rv > 0)
{
msgType = msg->msg_type;
if(msgType == WRP_MSG_TYPE__SVC_REGISTRATION)
if(msgType == 9)
{
ParodusInfo("\n Nanomsg client Registration for Upstream\n");
//Extract serviceName and url & store it in a linked list for reg_clients
temp = get_global_node();
if(get_numOfClients() !=0)
{
matchFlag = 0;
ParodusPrint("matchFlag reset to %d\n", matchFlag);
temp = get_global_node();
while(temp!=NULL)
{
if(strcmp(temp->service_name, msg->u.reg.service_name)==0)
{
ParodusInfo("match found, client is already registered\n");
parStrncpy(temp->url,msg->u.reg.url, sizeof(temp->url));
if(nn_shutdown(temp->sock, temp->endpoint) < 0)
if(nn_shutdown(temp->sock, 0) < 0)
{
ParodusError ("nn_shutdown socket=%d endpt=%d, err=%d\n",
temp->sock, temp->endpoint, errno);
}
if (nn_close (temp->sock) < 0)
{
ParodusError ("nn_close socket=%d err=%d\n",
temp->sock, errno);
ParodusError ("Failed to shutdown\n");
}
temp->sock = nn_socket(AF_SP,NN_PUSH );
if(temp->sock >= 0)
{
int t = NANO_SOCKET_SEND_TIMEOUT_MS;
int t = NANOMSG_SOCKET_TIMEOUT_MSEC;
rc = nn_setsockopt(temp->sock, NN_SOL_SOCKET, NN_SNDTIMEO, &t, sizeof(t));
if(rc < 0)
{
ParodusError ("Unable to set socket send timeout (errno=%d, %s)\n",errno, strerror(errno));
ParodusError ("Unable to set socket timeout (errno=%d, %s)\n",errno, strerror(errno));
}
rc = nn_connect(temp->sock, msg->u.reg.url);
if(rc < 0)
@@ -286,8 +258,7 @@ void *processUpstreamMessage()
}
else
{
temp->endpoint = rc;
ParodusInfo("Client registered before. Sending ack on socket %d\n", temp->sock);
ParodusInfo("Client registered before. Sending acknowledgement \n");
status =sendAuthStatus(temp);
if(status == 0)
@@ -318,13 +289,11 @@ void *processUpstreamMessage()
ParodusPrint("sent auth status to reg client\n");
}
}
release_global_node ();
}
else if(msgType == WRP_MSG_TYPE__EVENT)
{
ParodusInfo(" Received upstream event data: dest '%s'\n", msg->u.event.dest);
partners_t *partnersList = NULL;
int j = 0;
int ret = validate_partner_id(msg, &partnersList);
if(ret == 1)
@@ -353,18 +322,6 @@ void *processUpstreamMessage()
{
sendUpstreamMsgToServer(&message->msg, message->len);
}
if(partnersList != NULL)
{
for(j=0; j<(int)partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
{
free(partnersList->partner_ids[j]);
}
}
free(partnersList);
}
partnersList = NULL;
}
else
{
@@ -377,48 +334,90 @@ void *processUpstreamMessage()
else
{
ParodusInfo(" Received upstream data with MsgType: %d dest: '%s' transaction_uuid: %s status: %d\n",msgType, msg->u.crud.dest, msg->u.crud.transaction_uuid, msg->u.crud.status );
if(WRP_MSG_TYPE__RETREIVE == msgType)
if(WRP_MSG_TYPE__RETREIVE == msgType && msg->u.crud.dest !=NULL && msg->u.crud.source != NULL)
{
ret = getDeviceId(&device_id, &device_id_len);
if(ret == 0)
macId = wrp_get_msg_element(WRP_ID_ELEMENT__ID, msg, DEST);
destService = wrp_get_msg_element(WRP_ID_ELEMENT__SERVICE, msg, DEST);
destApplication = wrp_get_msg_element(WRP_ID_ELEMENT__APPLICATION, msg, DEST);
sourceService = wrp_get_msg_element(WRP_ID_ELEMENT__SERVICE, msg, SOURCE);
sourceApplication = wrp_get_msg_element(WRP_ID_ELEMENT__APPLICATION, msg, SOURCE);
/* Handle cloud-status retrieve request here
Expecting dest format as mac:xxxxxxxxxxxx/parodus/cloud-status
Parse dest field and check destService is "parodus" and destApplication is "cloud-status"
*/
if(macId != NULL)
{
if(destService != NULL && destApplication != NULL && strcmp(destService,"parodus")== 0 && strcmp(destApplication,"cloud-status")== 0)
{
ParodusPrint("device_id %s device_id_len %lu\n", device_id, device_id_len);
/* Match dest based on device_id. Check dest start with: "mac:112233445xxx" ? */
if( 0 == strncasecmp(device_id, msg->u.crud.dest, device_id_len-1) )
retrieve_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(retrieve_msg, 0, sizeof(wrp_msg_t));
retrieve_msg->msg_type = msg->msg_type;
retrieve_msg->u.crud.transaction_uuid = strdup(msg->u.crud.transaction_uuid);
retrieve_msg->u.crud.source = strdup(msg->u.crud.source);
retrieve_msg->u.crud.dest = strdup(msg->u.crud.dest);
addCRUDmsgToQueue(retrieve_msg);
}
else if(sourceService != NULL && sourceApplication != NULL && strcmp(sourceService,"parodus")== 0 && strcmp(sourceApplication,"cloud-status")== 0 && strncmp(msg->u.crud.dest,"mac:", 4)==0)
{
/* Handle cloud-status retrieve response here to send it to registered client
Expecting src format as mac:xxxxxxxxxxxx/parodus/cloud-status and dest as mac:
Parse src field and check sourceService is "parodus" and sourceApplication is "cloud-status"
*/
serviceName = wrp_get_msg_element(WRP_ID_ELEMENT__SERVICE, msg, DEST);
if ( serviceName != NULL)
{
/* For this device. */
parodus_len = strlen( PARODUS_SERVICE_NAME );
if( 0 == strncmp(PARODUS_SERVICE_NAME, &msg->u.crud.dest[device_id_len], parodus_len-1) )
//Send Client cloud-status response back to registered client
ParodusInfo("Sending cloud-status response to %s client\n",serviceName);
sendStatus=sendMsgtoRegisteredClients(serviceName,(const char **)&message->msg,message->len);
if(sendStatus ==1)
{
/* For Parodus CRUD queue. */
ParodusInfo("Create RetrieveMsg and add to parodus CRUD queue\n");
createUpstreamRetrieveMsg(msg, &retrieve_msg);
addCRUDmsgToQueue(retrieve_msg);
ParodusInfo("Send upstreamMsg successfully to registered client %s\n", serviceName);
}
else
{
/* For nanomsg clients. */
getServiceNameAndSendResponse(msg, &message->msg, message->len);
ParodusError("Failed to send upstreamMsg to registered client %s\n", serviceName);
}
free(serviceName);
serviceName = NULL;
}
else
{
/* Not for this device. Send upstream */
ParodusInfo("sendUpstreamMsgToServer \n");
sendUpstreamMsgToServer(&message->msg, message->len);
}
if(device_id != NULL)
{
free(device_id);
device_id = NULL;
ParodusError("serviceName is NULL,not sending cloud-status response to client\n");
}
}
else
{
ParodusError("Failed to get device_id\n");
ParodusInfo("sendUpstreamMsgToServer \n");
sendUpstreamMsgToServer(&message->msg, message->len);
}
} else if (WRP_MSG_TYPE__SVC_ALIVE != msgType) {
/* Don't reply to service alive message */
}
else
{
ParodusError("MAC is null, not handling retrieve wrp message \n");
}
if(sourceService !=NULL)
{
free(sourceService);
sourceService = NULL;
}
if(sourceApplication !=NULL)
{
free(sourceApplication);
sourceApplication = NULL;
}
if(destService !=NULL)
{
free(destService);
destService = NULL;
}
if(destApplication !=NULL)
{
free(destApplication);
destApplication = NULL;
}
}
else
{
sendUpstreamMsgToServer(&message->msg, message->len);
}
}
@@ -451,10 +450,6 @@ void *processUpstreamMessage()
}
else
{
if (g_shutdown) {
pthread_mutex_unlock (&nano_mut);
break;
}
ParodusPrint("Before pthread cond wait in consumer thread\n");
pthread_cond_wait(&nano_con, &nano_mut);
pthread_mutex_unlock (&nano_mut);
@@ -464,107 +459,6 @@ void *processUpstreamMessage()
return NULL;
}
/**
* @brief getDeviceId function to create deviceId in the format "mac:112233445xxx"
*
* @param[out] device_id in the format "mac:112233445xxx"
* @param[out] total size of device_id
*/
int getDeviceId(char **device_id, size_t *device_id_len)
{
char *deviceID = NULL;
size_t len;
if((get_parodus_cfg()->hw_mac !=NULL) && (strlen(get_parodus_cfg()->hw_mac)!=0))
{
len = strlen(get_parodus_cfg()->hw_mac) + 5;
deviceID = (char *) malloc(sizeof(char)*64);
if(deviceID != NULL)
{
snprintf(deviceID, len, "mac:%s", get_parodus_cfg()->hw_mac);
*device_id = deviceID;
*device_id_len = len;
}
else
{
ParodusError("device_id allocation failed\n");
return -1;
}
}
else
{
ParodusError("device mac is NULL\n");
return -1;
}
return 0;
}
/**
* @brief createUpstreamRetrieveMsg function to create new message for processing Retrieve requests
*
* @param[in] message The upstream message received from cloud or internal clients
* @param[out] retrieve_msg New message for processing Retrieve requests
*/
void createUpstreamRetrieveMsg(wrp_msg_t *message, wrp_msg_t **retrieve_msg)
{
wrp_msg_t *msg;
msg = ( wrp_msg_t * ) malloc( sizeof( wrp_msg_t ) );
if(msg != NULL)
{
memset(msg, 0, sizeof(wrp_msg_t));
msg->msg_type = message->msg_type;
if(message->u.crud.transaction_uuid != NULL)
{
msg->u.crud.transaction_uuid = strdup(message->u.crud.transaction_uuid);
}
if(message->u.crud.source !=NULL)
{
msg->u.crud.source = strdup(message->u.crud.source);
}
if(message->u.crud.dest != NULL)
{
msg->u.crud.dest = strdup(message->u.crud.dest);
}
*retrieve_msg = msg;
}
}
/**
* @brief getServiceNameAndSendResponse function to fetch client service name and to send msg to it.
*
* @param[in] msg The decoded message to fetch client service name from its dest field
* @param[in] msg_bytes The encoded upstream msg to be sent to client
* @param[in] msg_size Total size of the msg to send to client
*/
void getServiceNameAndSendResponse(wrp_msg_t *msg, void **msg_bytes, size_t msg_size)
{
char *serviceName = NULL;
int sendStatus =-1;
serviceName = wrp_get_msg_element(WRP_ID_ELEMENT__SERVICE, msg, DEST);
if ( serviceName != NULL)
{
sendStatus=sendMsgtoRegisteredClients(serviceName,(const char **)msg_bytes, msg_size);
if(sendStatus ==1)
{
ParodusInfo("Send upstreamMsg successfully to registered client %s\n", serviceName);
}
else
{
ParodusError("Failed to send upstreamMsg to registered client %s\n", serviceName);
}
free(serviceName);
serviceName = NULL;
}
else
{
ParodusError("serviceName is NULL,not sending retrieve response to client\n");
}
}
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
{
void *appendData;
@@ -589,7 +483,6 @@ void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
else
{
ParodusInfo("close_retry is %d, unable to send response as connection retry is in progress\n", close_retry);
OnboardLog("close_retry is %d, unable to send response as connection retry is in progress\n", close_retry);
}
free(appendData);
appendData =NULL;

View File

@@ -47,10 +47,8 @@ typedef struct UpStreamMsg__
void packMetaData();
void *handle_upstream();
void *processUpstreamMessage();
int getDeviceId(char **device_id, size_t *device_id_len);
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size);
void getServiceNameAndSendResponse(wrp_msg_t *msg, void **msg_bytes, size_t msg_size);
void createUpstreamRetrieveMsg(wrp_msg_t *message, wrp_msg_t **retrieve_msg);
void set_global_UpStreamMsgQ(UpStreamMsg * UpStreamQ);
UpStreamMsg * get_global_UpStreamMsgQ(void);
pthread_cond_t *get_global_nano_con(void);

View File

@@ -120,10 +120,10 @@ target_link_libraries (test_nopoll_handlers_fragment -lnopoll -lcunit -lcimplog
add_test(NAME test_connection COMMAND ${MEMORY_CHECK} ./test_connection)
set (CONN_SRC ../src/connection.c
../src/string_helpers.c ../src/mutex.c ../src/time.c
../src/config.c ../src/auth_token.c ../src/spin_thread.c ../src/heartBeat.c ../src/close_retry.c)
../src/config.c ../src/spin_thread.c ../src/heartBeat.c ../src/close_retry.c)
#set(CONN_SRC ../src/connection.c ${PARODUS_COMMON_SRC})
add_executable(test_connection test_connection.c ${CONN_SRC})
target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -luuid)
target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_connection - function createNopollConnection
@@ -141,7 +141,7 @@ target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -l
add_test(NAME test_client_list COMMAND ${MEMORY_CHECK} ./test_client_list)
#add_executable(test_client_list test_client_list.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/downstream.c ../src/connection.c ../src/nopoll_handlers.c ../src/ParodusInternal.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS})
set(CLIST_SRC test_client_list.c ../src/client_list.c ../src/auth_token.c
set(CLIST_SRC test_client_list.c ../src/client_list.c
../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c
../src/downstream.c ../src/connection.c ../src/nopoll_handlers.c ../src/heartBeat.c ../src/close_retry.c
../src/ParodusInternal.c ../src/thread_tasks.c ../src/conn_interface.c
@@ -155,7 +155,7 @@ endif (ENABLE_SESHAT)
add_executable(test_client_list ${CLIST_SRC})
#target_link_libraries (test_client_list ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS})
target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS} -lcurl -luuid)
target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS})
#-------------------------------------------------------------------------------
# test_service_alive
@@ -163,7 +163,7 @@ target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS} -lcurl -luuid)
add_test(NAME test_service_alive COMMAND ${MEMORY_CHECK} ./test_service_alive)
#add_executable(test_service_alive test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS})
set(SVA_SRC test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/auth_token.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ../src/heartBeat.c ../src/close_retry.c ${PARODUS_COMMON_SRC})
set(SVA_SRC test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ../src/heartBeat.c ../src/close_retry.c ${PARODUS_COMMON_SRC})
if (ENABLE_SESHAT)
set(SVA_SRC ${SVA_SRC} ../src/seshat_interface.c)
else()
@@ -172,36 +172,16 @@ endif (ENABLE_SESHAT)
add_executable(test_service_alive ${SVA_SRC})
#target_link_libraries (test_service_alive ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS})
target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS} -lcurl -luuid)
target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS})
#-------------------------------------------------------------------------------
# test_config
#-------------------------------------------------------------------------------
add_test(NAME test_config COMMAND ${MEMORY_CHECK} ./test_config)
add_executable(test_config test_config.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
add_executable(test_config test_config.c ../src/config.c ../src/string_helpers.c)
target_link_libraries (test_config -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_auth_token
#-------------------------------------------------------------------------------
add_test(NAME test_auth_token COMMAND ${MEMORY_CHECK} ./test_auth_token)
add_executable(test_auth_token test_auth_token.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_auth_token -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_auth_token_more
#-------------------------------------------------------------------------------
add_test(NAME test_auth_token_more COMMAND ${MEMORY_CHECK} ./test_auth_token_more)
add_executable(test_auth_token_more test_auth_token_more.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_auth_token_more -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm
)
#-------------------------------------------------------------------------------
@@ -223,7 +203,7 @@ target_link_libraries (test_crud_tasks -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
add_test(NAME test_crud_internal COMMAND ${MEMORY_CHECK} ./test_crud_internal)
add_executable(test_crud_internal test_crud_internal.c ../src/config.c ../src/close_retry.c ../src/string_helpers.c ../src/crud_internal.c )
target_link_libraries (test_crud_internal -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid)
target_link_libraries (test_crud_internal -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_upstream
@@ -235,17 +215,6 @@ target_link_libraries (test_upstream -lcmocka gcov -lcunit -lcimplog
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
#-------------------------------------------------------------------------------
# test_upstream_sock
#-------------------------------------------------------------------------------
add_test(NAME test_upstream_sock COMMAND ${MEMORY_CHECK} ./test_upstream_sock)
add_executable(test_upstream_sock test_upstream_sock.c ../src/upstream.c
../src/client_list.c ../src/close_retry.c ../src/string_helpers.c)
target_link_libraries (test_upstream_sock -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll -lnanomsg
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
#-------------------------------------------------------------------------------
# test_downstream
#-------------------------------------------------------------------------------
@@ -290,14 +259,14 @@ else()
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_conn_interface ${CONIFC_SRC})
target_link_libraries (test_conn_interface -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid )
target_link_libraries (test_conn_interface -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_ParodusInternal
#-------------------------------------------------------------------------------
add_test(NAME test_ParodusInternal COMMAND ${MEMORY_CHECK} ./test_ParodusInternal)
add_executable(test_ParodusInternal test_ParodusInternal.c ../src/ParodusInternal.c ../src/config.c ../src/string_helpers.c)
target_link_libraries (test_ParodusInternal -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid)
target_link_libraries (test_ParodusInternal -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_partners_check
@@ -316,7 +285,7 @@ set(TOKEN_SRC ../src/conn_interface.c ../src/config.c
../src/nopoll_handlers.c ../src/nopoll_helpers.c
../src/partners_check.c ../src/ParodusInternal.c
../src/upstream.c ../src/downstream.c
../src/networking.c ../src/auth_token.c
../src/networking.c
../src/thread_tasks.c ../src/time.c
../src/string_helpers.c ../src/mutex.c
../src/token.c ../src/heartBeat.c
@@ -337,7 +306,7 @@ endif (FEATURE_DNS_QUERY)
add_executable(test_token ${TOKEN_SRC} )
#target_link_libraries (test_token ${PARODUS_COMMON_LIBS} ${PARODUS_JWT_LIBS} -lcmocka )
target_link_libraries (test_token ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -luuid)
target_link_libraries (test_token ${PARODUS_COMMON_LIBS} -lcmocka )
#-------------------------------------------------------------------------------
# test_seshat_interface - registerWithSeshat

View File

@@ -1,334 +0,0 @@
/**
* Copyright 2010-2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <malloc.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <CUnit/Basic.h>
#include "../src/config.h"
#include "../src/auth_token.h"
#include "../src/ParodusInternal.h"
extern int requestNewAuthToken(char *newToken, size_t len, int r_count);
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
typedef void CURL;
typedef enum {
CURLINFO_RESPONSE_CODE = 2,
CURLINFO_TOTAL_TIME
} CURLINFO;
struct token_data test_data;
int curl_easy_perform(CURL *curl)
{
UNUSED(curl);
char *msg = "response";
int rtn;
function_called();
rtn = (int) mock();
if (0 == rtn)
write_callback_fn (msg, 1, strlen(msg), &test_data);
return rtn;
}
int curl_easy_getinfo(CURL *curl, CURLINFO CURLINFO_RESPONSE_CODE, long response_code)
{
UNUSED(curl);
UNUSED(CURLINFO_RESPONSE_CODE);
UNUSED(response_code);
function_called();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void getAuthToken_Null()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
cfg.client_cert_path = NULL;
getAuthToken(&cfg);
set_parodus_cfg(&cfg);
assert( cfg.client_cert_path == NULL);
assert_int_equal (0, (int) cfg.webpa_auth_token[0]);
}
void getAuthToken_MacNull()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
cfg.client_cert_path = NULL;
getAuthToken(&cfg);
set_parodus_cfg(&cfg);
assert( cfg.client_cert_path == NULL);
assert_int_equal (0, (int) cfg.webpa_auth_token[0]);
}
#if 0
void test_requestNewAuthToken_init_fail ()
{
char token[32];
ParodusCfg cfg;
int output = -1;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, -1);
expect_function_calls (curl_easy_getinfo, 1);
requestNewAuthToken (token, sizeof(token), 2);
assert_int_equal (output, -1);
free(cfg.token_server_url);
}
#endif
void test_requestNewAuthToken_failure ()
{
char token[32];
ParodusCfg cfg;
int output = -1;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
test_data.size = 0;
test_data.data = token;
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, -1);
expect_function_calls (curl_easy_getinfo, 1);
requestNewAuthToken (token, sizeof(token), 2);
assert_int_equal (output, -1);
assert_int_equal (0, (int) token[0]);
free(cfg.token_server_url);
}
void test_requestNewAuthToken ()
{
char token[1024];
ParodusCfg cfg;
int output = -1;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
test_data.size = 0;
test_data.data = token;
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
output = requestNewAuthToken (token, sizeof(token), 1);
assert_int_equal (output, 0);
assert_string_equal (token, "response");
free(cfg.token_server_url);
}
void test_getAuthToken ()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
cfg.client_cert_path = strdup("testcert");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
/* To test curl failure case and retry on v4 mode */
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
/* To test curl failure case and retry on v6 mode */
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
/* To test curl success case */
test_data.size = 0;
test_data.data = cfg.webpa_auth_token;
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
getAuthToken(&cfg);
assert_string_equal (cfg.webpa_auth_token, "response");
free(cfg.client_cert_path);
free(cfg.token_server_url);
}
void test_getAuthTokenFailure ()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
cfg.client_cert_path = strdup("testcert");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_perform, -1);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
getAuthToken(&cfg);
assert_string_equal( cfg.webpa_auth_token, "");
free(cfg.client_cert_path);
free(cfg.token_server_url);
}
void test_write_callback_fn ()
{
ParodusCfg *cfg;
size_t max_data_size = sizeof (cfg->webpa_auth_token);
char *buffer1 = "response1";
size_t buf1len = strlen(buffer1);
char *buffer2 = "R2";
size_t buf2len = strlen(buffer2);
char buffer3[max_data_size];
int out_len=0;
struct token_data data;
data.size = 0;
data.data = (char *) malloc(max_data_size);
data.data[0] = '\0';
out_len = write_callback_fn(buffer1, 1, buf1len, &data);
assert_string_equal(data.data, buffer1);
assert_int_equal (out_len, buf1len);
assert_int_equal (data.size, buf1len);
out_len = write_callback_fn(buffer2, 1, buf2len, &data);
assert_string_equal(data.data, "response1R2");
assert_int_equal (out_len, buf2len);
assert_int_equal (data.size, buf1len+buf2len);
memset (buffer3, 'x', max_data_size);
out_len = write_callback_fn(buffer3, 1, max_data_size, &data);
assert_int_equal (out_len, 0);
assert_int_equal (data.size, 0);
free(data.data);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_write_callback_fn),
cmocka_unit_test(test_requestNewAuthToken),
// cmocka_unit_test(test_requestNewAuthToken_init_fail),
cmocka_unit_test(test_requestNewAuthToken_failure),
cmocka_unit_test(getAuthToken_Null),
cmocka_unit_test(getAuthToken_MacNull),
cmocka_unit_test(test_getAuthToken),
cmocka_unit_test(test_getAuthTokenFailure),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -1,109 +0,0 @@
/**
* Copyright 2010-2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <malloc.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <CUnit/Basic.h>
#include "../src/config.h"
#include "../src/auth_token.h"
#include "../src/ParodusInternal.h"
extern int requestNewAuthToken(char *newToken, size_t len, int r_count);
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
typedef void CURL;
typedef enum {
CURLINFO_RESPONSE_CODE = 2,
CURLINFO_TOTAL_TIME
} CURLINFO;
struct token_data test_data;
CURL *curl_easy_init ()
{
function_called();
return (CURL *) mock();
}
int curl_easy_perform(CURL *curl)
{
UNUSED(curl);
char *msg = "response";
int rtn;
function_called();
rtn = (int) mock();
if (0 == rtn)
write_callback_fn (msg, 1, strlen(msg), &test_data);
return rtn;
}
int curl_easy_getinfo(CURL *curl, CURLINFO CURLINFO_RESPONSE_CODE, long response_code)
{
UNUSED(curl);
UNUSED(CURLINFO_RESPONSE_CODE);
UNUSED(response_code);
function_called();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_requestNewAuthToken_init_fail ()
{
char token[32];
ParodusCfg cfg;
int output = -1;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
will_return (curl_easy_init, NULL);
expect_function_calls (curl_easy_init, 1);
requestNewAuthToken (token, sizeof(token), 2);
assert_int_equal (output, -1);
assert_int_equal (0, (int) token[0]);
free(cfg.token_server_url);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_requestNewAuthToken_init_fail)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -26,9 +26,6 @@
#define TEST_CLIENT1_URL "tcp://127.0.0.1:6677"
#define TEST_CLIENT2_URL "tcp://127.0.0.1:6655"
pthread_t test_tid;
pthread_t test_tid2;
static void *client_rcv_task();
static void *client2_rcv_task();
@@ -61,7 +58,7 @@ void test_client_addtolist()
ParodusPrint("decoded service_name:%s\n", message->u.reg.service_name);
ParodusPrint("decoded dest:%s\n", message->u.reg.url);
StartThread(client_rcv_task, &test_tid);
StartThread(client_rcv_task);
status = addToList(&message);
ParodusPrint("addToList status is %d\n", status);
@@ -76,7 +73,7 @@ void test_client_addtolist()
CU_ASSERT_STRING_EQUAL( temp->service_name, message->u.reg.service_name );
CU_ASSERT_STRING_EQUAL( temp->url, message->u.reg.url );
}
release_global_node ();
wrp_free_struct(message);
free(bytes);
ParodusInfo("test_client_addtolist done..\n");
@@ -192,7 +189,7 @@ void test_addtolist_multiple_clients()
ParodusPrint("decoded service_name:%s\n", message->u.reg.service_name);
ParodusPrint("decoded dest:%s\n", message->u.reg.url);
StartThread(client2_rcv_task, &test_tid2);
StartThread(client2_rcv_task);
status = addToList(&message);
ParodusPrint("addToList status is %d\n", status);
@@ -209,7 +206,7 @@ void test_addtolist_multiple_clients()
CU_ASSERT_STRING_EQUAL( temp->url, message->u.reg.url );
}
release_global_node ();
wrp_free_struct(message);
free(bytes);
ParodusInfo("test_addtolist_multiple_clients done..\n");

View File

@@ -25,7 +25,6 @@
#include <CUnit/Basic.h>
#include "../src/config.h"
#include "../src/auth_token.h"
#include "../src/ParodusInternal.h"
extern int parse_mac_address (char *target, const char *arg);
@@ -38,6 +37,8 @@ extern int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port);
extern unsigned int get_algo_mask (const char *algo_str);
extern unsigned int parse_num_arg (const char *arg, const char *arg_name);
extern void execute_token_script(char *token, char *name, size_t len, char *mac, char *serNum);
extern void createNewAuthToken(char *newToken, size_t len);
/*----------------------------------------------------------------------------*/
/* Mocks */
@@ -52,7 +53,6 @@ void create_token_script(char *fname)
sprintf(command, "chmod +x %s",fname);
system(command);
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -184,10 +184,9 @@ void test_parseCommandLine()
#endif
"--force-ipv4",
"--force-ipv6",
"--boot-time-retry-wait=10",
"--token-read-script=/tmp/token.sh",
"--token-acquisition-script=/tmp/token.sh",
"--ssl-cert-path=/etc/ssl/certs/ca-certificates.crt",
"--client-cert-path=testcert",
"--token-server-url=https://dev.comcast.net/token",
#ifdef FEATURE_DNS_QUERY
"--acquire-jwt=1",
"--dns-txt-url=mydns.mycom.net",
@@ -215,7 +214,6 @@ void test_parseCommandLine()
assert_string_equal( parodusCfg.hw_last_reboot_reason, "unknown");
assert_string_equal( parodusCfg.fw_name, "TG1682_DEV_master_2016000000sdy");
assert_int_equal( (int) parodusCfg.webpa_ping_timeout,180);
assert_int_equal( (int) parodusCfg.boot_retry_wait,10);
assert_string_equal( parodusCfg.webpa_interface_used, "br0");
assert_string_equal( parodusCfg.webpa_url, "http://127.0.0.1");
assert_int_equal( (int) parodusCfg.webpa_backoff_max,0);
@@ -226,20 +224,18 @@ void test_parseCommandLine()
assert_string_equal( parodusCfg.seshat_url, "ipc://127.0.0.1:7777");
#endif
assert_int_equal( (int) parodusCfg.flags, FLAGS_IPV6_ONLY|FLAGS_IPV4_ONLY);
set_parodus_cfg(&parodusCfg);
sprintf(expectedToken,"secure-token-%s-%s",parodusCfg.hw_serial_number,parodusCfg.hw_mac);
getAuthToken(&parodusCfg);
set_parodus_cfg(&parodusCfg);
assert_string_equal( get_parodus_cfg()->webpa_auth_token,expectedToken);
assert_string_equal( parodusCfg.cert_path,"/etc/ssl/certs/ca-certificates.crt");
assert_string_equal( parodusCfg.client_cert_path,"testcert");
assert_string_equal( parodusCfg.token_server_url,"https://dev.comcast.net/token");
#ifdef FEATURE_DNS_QUERY
assert_int_equal( (int) parodusCfg.acquire_jwt, 1);
assert_string_equal(parodusCfg.dns_txt_url, "mydns.mycom.net");
assert_int_equal( (int) parodusCfg.jwt_algo, 1024);
assert_string_equal ( get_parodus_cfg()->jwt_key, jwt_key);
#endif
assert_int_equal( (int) parodusCfg.boot_retry_wait, 10);
assert_string_equal(parodusCfg.crud_config_file, "parodus_cfg.json");
}
@@ -321,13 +317,13 @@ void test_loadParodusCfg()
Cfg->jwt_algo = 1025;
parStrncpy(Cfg->jwt_key, "AGdyuwyhwl2ow2ydsoioiygkshwdthuwd",sizeof(Cfg->jwt_key));
#endif
parStrncpy(Cfg->token_acquisition_script , "/tmp/token.sh", sizeof(Cfg->token_acquisition_script));
parStrncpy(Cfg->token_read_script , "/tmp/token.sh", sizeof(Cfg->token_read_script));
parStrncpy(Cfg->cert_path, "/etc/ssl.crt",sizeof(Cfg->cert_path));
#ifdef ENABLE_SESHAT
parStrncpy(Cfg->seshat_url, "ipc://tmp/seshat_service.url", sizeof(Cfg->seshat_url));
#endif
Cfg->crud_config_file = strdup("parodus_cfg.json");
Cfg->client_cert_path = strdup("testcert");
Cfg->token_server_url = strdup("https://dev.comcast.net/token");
memset(&tmpcfg,0,sizeof(ParodusCfg));
loadParodusCfg(Cfg,&tmpcfg);
@@ -338,14 +334,14 @@ void test_loadParodusCfg()
assert_string_equal( tmpcfg.local_url, "tcp://10.0.0.1:6000");
assert_string_equal( tmpcfg.partner_id, "shaw");
assert_string_equal( tmpcfg.webpa_protocol, protocol);
assert_string_equal(tmpcfg.client_cert_path, "testcert");
assert_string_equal(tmpcfg.token_server_url, "https://dev.comcast.net/token");
#ifdef FEATURE_DNS_QUERY
assert_int_equal( (int) tmpcfg.acquire_jwt, 1);
assert_string_equal(tmpcfg.dns_txt_url, "mydns");
assert_int_equal( (int) tmpcfg.jwt_algo, 1025);
assert_string_equal(tmpcfg.jwt_key, "AGdyuwyhwl2ow2ydsoioiygkshwdthuwd");
#endif
assert_string_equal( tmpcfg.token_acquisition_script,"/tmp/token.sh");
assert_string_equal( tmpcfg.token_read_script,"/tmp/token.sh");
assert_string_equal(tmpcfg.cert_path, "/etc/ssl.crt");
#ifdef ENABLE_SESHAT
assert_string_equal(tmpcfg.seshat_url, "ipc://tmp/seshat_service.url");
@@ -557,6 +553,47 @@ void test_get_algo_mask ()
#endif
}
void test_execute_token_script()
{
char *cmd1 = "../../tests/return_ser_mac.bsh";
char *cmd2 = "nosuch";
char token[32];
memset (token, '\0', sizeof(token));
execute_token_script (token, cmd1, sizeof(token), "mac123", "ser456");
assert_string_equal (token, "SER_MAC ser456 mac123");
memset (token, '\0', sizeof(token));
execute_token_script (token, cmd2, sizeof(token), "mac123", "ser456");
assert_string_equal (token, "");
}
void test_new_auth_token ()
{
char token[64];
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
parStrncpy (cfg.token_acquisition_script, "../../tests/return_success.bsh",
sizeof(cfg.token_acquisition_script));
parStrncpy (cfg.token_read_script, "../../tests/return_ser_mac.bsh",
sizeof(cfg.token_read_script));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
createNewAuthToken (token, sizeof(token));
assert_string_equal (token, "SER_MAC Fer23u948590 123567892366");
memset (token, 0, sizeof(token));
parStrncpy (cfg.token_acquisition_script, "../../tests/return_failure.bsh",
sizeof(cfg.token_acquisition_script));
set_parodus_cfg(&cfg);
createNewAuthToken (token, sizeof(token));
assert_string_equal (token, "");
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -581,6 +618,8 @@ int main(void)
//cmocka_unit_test(test_parodusGitVersion),
cmocka_unit_test(test_setDefaultValuesToCfg),
cmocka_unit_test(err_setDefaultValuesToCfg),
cmocka_unit_test(test_execute_token_script),
cmocka_unit_test(test_new_auth_token)
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -35,12 +35,8 @@
/*----------------------------------------------------------------------------*/
UpStreamMsg *UpStreamMsgQ;
ParodusMsg *ParodusMsgQ;
pthread_mutex_t g_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t nano_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t nano_con=PTHREAD_COND_INITIALIZER;
pthread_mutex_t svc_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t svc_con=PTHREAD_COND_INITIALIZER;
pthread_mutex_t nano_mut;
pthread_cond_t nano_con;
/*----------------------------------------------------------------------------*/
@@ -74,15 +70,6 @@ noPollMutexUnlock mutex_unlock
UNUSED(mutex_create); UNUSED(mutex_destroy); UNUSED(mutex_lock); UNUSED(mutex_unlock);
function_called();
}
void start_conn_in_progress (void)
{
}
void stop_conn_in_progress (void)
{
}
void packMetaData()
{
function_called();
@@ -116,9 +103,9 @@ void *messageHandlerTask()
return NULL;
}
int serviceAliveTask()
void *serviceAliveTask()
{
return 0;
return NULL;
}
int nopoll_loop_wait(noPollCtx * ctx,long timeout)
@@ -169,18 +156,12 @@ void set_global_conn(noPollConn *conn)
function_called();
}
void StartThread(void *(*start_routine) (void *), pthread_t *threadId)
void StartThread(void *(*start_routine) (void *))
{
UNUSED(start_routine);
UNUSED(threadId);
function_called();
}
void JoinThread (pthread_t threadId)
{
UNUSED(threadId);
}
noPollCtx* nopoll_ctx_new(void)
{
function_called();
@@ -211,16 +192,6 @@ pthread_mutex_t *get_global_nano_mut(void)
return &nano_mut;
}
pthread_cond_t *get_global_svc_con(void)
{
return &svc_con;
}
pthread_mutex_t *get_global_svc_mut(void)
{
return &svc_mut;
}
/*
* Mock func to calculate time diff between start and stop time
* This timespec_diff retuns 1 sec as diff time
@@ -234,10 +205,6 @@ void timespec_diff(struct timespec *start, struct timespec *stop,
diff->tv_nsec = 1000;
}
void deleteAllClients (void)
{
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/

View File

@@ -63,7 +63,6 @@ bool LastReasonStatus;
pthread_mutex_t close_mut;
// Mock values
bool g_shutdown = false;
char *mock_server_addr;
unsigned int mock_port;
int mock_wait_status;
@@ -117,8 +116,6 @@ nopoll_bool nopoll_conn_wait_for_status_until_connection_ready (noPollConn * co
int timeout, int *status, char ** message)
{
UNUSED(conn); UNUSED(timeout);
*message = NULL;
if (mock_wait_status >= 1000) {
*status = mock_wait_status / 1000;
mock_wait_status = mock_wait_status % 1000;
@@ -377,21 +374,13 @@ void test_set_current_server()
assert_ptr_equal (&ctx.server_list.defaults, ctx.current_server);
}
void init_cfg_header_info (ParodusCfg *cfg)
{
parStrncpy(cfg->hw_mac , "123567892366", sizeof(cfg->hw_mac));
parStrncpy(cfg->hw_model, "TG1682", sizeof(cfg->hw_model));
parStrncpy(cfg->hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg->hw_manufacturer));
parStrncpy(cfg->fw_name , "2.364s2", sizeof(cfg->fw_name));
parStrncpy(cfg->webpa_protocol , "WebPA-1.6", sizeof(cfg->webpa_protocol));
}
void test_set_extra_headers ()
{
int rtn;
create_connection_ctx_t ctx;
ParodusCfg cfg;
const char *expected_extra_headers =
"\r\nAuthorization: Bearer SER_MAC Fer23u948590 123567892366"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
@@ -400,10 +389,16 @@ void test_set_extra_headers ()
memset(&cfg,0,sizeof(cfg));
memset (&ctx, 0, sizeof(ctx));
cfg.client_cert_path = strdup("testcert");
parStrncpy (cfg.token_acquisition_script, "../../tests/return_success.bsh",
sizeof(cfg.token_acquisition_script));
parStrncpy (cfg.token_read_script, "../../tests/return_ser_mac.bsh",
sizeof(cfg.token_read_script));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
init_cfg_header_info (&cfg);
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
set_parodus_cfg(&cfg);
rtn = init_header_info (&ctx.header_info);
@@ -414,9 +409,9 @@ void test_set_extra_headers ()
assert_string_equal (ctx.header_info.conveyHeader, "WebPA-1.6 (TG1682)");
set_extra_headers (&ctx, true);
assert_string_equal (get_parodus_cfg()->webpa_auth_token,
"SER_MAC Fer23u948590 123567892366");
assert_string_equal (ctx.extra_headers, expected_extra_headers);
if(cfg.client_cert_path !=NULL) {
free(cfg.client_cert_path); }
free (ctx.extra_headers);
free_header_info (&ctx.header_info);
@@ -520,58 +515,34 @@ void test_nopoll_connect ()
test_server.allow_insecure = 1;
will_return (nopoll_conn_new_opts, NULL);
expect_function_call (nopoll_conn_new_opts);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
test_server.allow_insecure = 0;
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, false), 0);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, -2);
//expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, -2);
expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, false), 0);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, -2);
//expect_function_call (checkHostIp);
//ctx.connect_timer.start_time.tv_sec -= (15*60);
//will_return(kill, 1);
//expect_function_call(kill);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, -2);
expect_function_call (checkHostIp);
ctx.connect_timer.start_time.tv_sec -= (15*60);
will_return(kill, 1);
expect_function_call(kill);
assert_int_equal (nopoll_connect (&ctx, false), 0);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
init_expire_timer (&ctx.connect_timer);
@@ -585,12 +556,19 @@ void test_nopoll_connect ()
// Return codes for wait_connection_ready
#define WAIT_SUCCESS 0
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define WAIT_FAIL 2
void test_wait_connection_ready ()
{
create_connection_ctx_t ctx;
ParodusCfg Cfg;
const char *expected_extra_headers =
"\r\nAuthorization: Bearer Auth---"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
"\r\nX-WebPA-Convey: WebPA-1.6 (TG1682)";
memset(&ctx,0,sizeof(ctx));
set_server_list_null (&ctx.server_list);
@@ -605,7 +583,7 @@ void test_wait_connection_ready ()
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_FAIL);
mock_wait_status = 503;
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
@@ -640,18 +618,30 @@ void test_wait_connection_ready ()
free_server (&ctx.server_list.redirect);
mock_wait_status = 403;
memset(&Cfg, 0, sizeof(ParodusCfg));
parStrncpy (Cfg.webpa_auth_token, "Auth---", sizeof (Cfg.webpa_auth_token));
parStrncpy(Cfg.hw_model, "TG1682", sizeof(Cfg.hw_model));
parStrncpy(Cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(Cfg.hw_manufacturer));
parStrncpy(Cfg.hw_mac , "123567892366", sizeof(Cfg.hw_mac));
parStrncpy(Cfg.fw_name , "2.364s2", sizeof(Cfg.fw_name));
parStrncpy(Cfg.webpa_protocol , "WebPA-1.6", sizeof(Cfg.webpa_protocol));
set_parodus_cfg(&Cfg);
init_header_info (&ctx.header_info);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_ACTION_RETRY);
assert_string_equal (ctx.extra_headers, expected_extra_headers);
free_extra_headers (&ctx);
free_header_info (&ctx.header_info);
}
// Return codes for connect_and_wait
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define CONN_WAIT_RETRY_DNS 2
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define CONN_WAIT_RETRY_DNS 2
void test_connect_and_wait ()
{
@@ -724,8 +714,8 @@ void test_connect_and_wait ()
test_server.allow_insecure = 0;
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_RETRY_DNS);
Cfg.flags = 0;
@@ -733,8 +723,8 @@ void test_connect_and_wait ()
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
@@ -803,16 +793,22 @@ void test_keep_trying ()
server_t test_server;
backoff_timer_t backoff_timer;
ParodusCfg Cfg;
char *test_extra_headers =
"\r\nAuthorization: Bearer SER_MAC Fer23u948590 123567892366"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
"\r\nX-WebPA-Convey: WebPA-1.6 (TG1682)";
memset(&Cfg, 0, sizeof(ParodusCfg));
parStrncpy (Cfg.webpa_url, "http://mydns.mycom.net:8080", sizeof(Cfg.webpa_url));
init_cfg_header_info (&Cfg);
mock_wait_status = 0;
memset(&ctx,0,sizeof(ctx));
ctx.nopoll_ctx = &test_nopoll_ctx;
ctx.current_server = &test_server;
ctx.extra_headers = test_extra_headers;
test_server.allow_insecure = 1;
test_server.server_addr = "mydns.mycom.net";

View File

@@ -35,11 +35,9 @@
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool g_shutdown = false;
extern CrudMsg *crudMsgQ;
int numLoops = 1;
wrp_msg_t *temp = NULL;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/

View File

@@ -165,7 +165,7 @@ void test_retrieveFromMemory()
assert_int_equal (ret, 0);
ret = retrieveFromMemory("webpa-protocol", &jsonresponse );
assert_int_equal (ret, 0);
ret = retrieveFromMemory("webpa-interface-used", &jsonresponse );
ret = retrieveFromMemory("webpa-inteface-used", &jsonresponse );
assert_int_equal (ret, 0);
ret = retrieveFromMemory("webpa-backoff-max", &jsonresponse );
assert_int_equal (ret, 0);
@@ -200,7 +200,7 @@ void test_retrieveFromMemoryFailure()
assert_int_equal (ret, -1);
ret = retrieveFromMemory("webpa-protocol", &jsonresponse );
assert_int_equal (ret, -1);
ret = retrieveFromMemory("webpa-interface-used", &jsonresponse );
ret = retrieveFromMemory("webpa-inteface-used", &jsonresponse );
assert_int_equal (ret, -1);
ret = retrieveFromMemory("webpa-backoff-max", &jsonresponse );
assert_int_equal (ret, 0);

View File

@@ -61,10 +61,6 @@ reg_list_item_t * get_global_node(void)
return mock_ptr_type(reg_list_item_t *);
}
void release_global_node (void)
{
}
ssize_t wrp_to_struct( const void *bytes, const size_t length,
const enum wrp_format fmt, wrp_msg_t **msg )
{
@@ -72,7 +68,7 @@ ssize_t wrp_to_struct( const void *bytes, const size_t length,
function_called();
*msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
memset(*msg, 0, sizeof(wrp_msg_t));
(*msg)->msg_type = WRP_MSG_TYPE__REQ;
(*msg)->msg_type = WRP_MSG_TYPE__REQ;
(*msg)->u.req.dest = (char *) malloc(sizeof(char) *100);
(*msg)->u.req.partner_ids = (partners_t *) malloc(sizeof(partners_t));
(*msg)->u.req.partner_ids->count = 1;
@@ -83,10 +79,8 @@ ssize_t wrp_to_struct( const void *bytes, const size_t length,
{
(*msg)->msg_type = WRP_MSG_TYPE__CREATE;
parStrncpy((*msg)->u.crud.dest,"mac:1122334455/parodus", 100);
(*msg)->u.crud.source = (char *) malloc(sizeof(char) *40);
parStrncpy ((*msg)->u.crud.source, "tag-update", 40);
(*msg)->u.crud.transaction_uuid = (char *) malloc(sizeof(char) *40);
parStrncpy ((*msg)->u.crud.transaction_uuid, "1234", 40);
(*msg)->u.crud.source = "tag-update";
(*msg)->u.crud.transaction_uuid = "1234";
}
return (ssize_t) mock();
}

View File

@@ -244,10 +244,6 @@ reg_list_item_t *get_global_node(void)
return NULL;
}
void release_global_node (void)
{
}
void wrp_free_struct( wrp_msg_t *msg )
{
if( WRP_MSG_TYPE__EVENT == tests[i].s.msg_type ) {

View File

@@ -33,18 +33,6 @@ static void *keep_alive_thread();
static void add_client();
int sock1;
pthread_t threadId;
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;
pthread_cond_t *get_global_crud_con(void)
{
return &crud_con;
}
pthread_mutex_t *get_global_crud_mut(void)
{
return &crud_mut;
}
/*----------------------------------------------------------------------------*/
/* Tests */
@@ -60,14 +48,12 @@ void *CRUDHandlerTask()
{
return NULL;
}
static void add_client()
{
const wrp_msg_t reg = { .msg_type = WRP_MSG_TYPE__SVC_REGISTRATION,
.u.reg.service_name = "service_client",
.u.reg.url = TEST_SERVICE_URL};
pthread_t test_tid;
void *bytes;
int size =0;
int rv;
@@ -85,7 +71,7 @@ static void add_client()
ParodusPrint("decoded service_name:%s\n", message->u.reg.service_name);
ParodusPrint("decoded dest:%s\n", message->u.reg.url);
StartThread(client_rcv_task, &test_tid);
StartThread(client_rcv_task);
status = addToList(&message);
ParodusPrint("addToList status is %d\n", status);
@@ -148,10 +134,7 @@ static void *keep_alive_thread()
//ParodusPrint("keep_alive threadId is %d\n", threadId);
sleep(2);
ParodusPrint("Starting serviceAliveTask..\n");
while (true) {
serviceAliveTask();
sleep (30);
}
serviceAliveTask();
return 0;
}

View File

@@ -23,8 +23,6 @@
#include "../src/ParodusInternal.h"
#include "../src/spin_thread.h"
pthread_t test_tid;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -56,7 +54,7 @@ void *_routine(void *v)
void test_StartThread_error()
{
StartThread(&_routine, &test_tid);
StartThread(&_routine);
}
void add_suites( CU_pSuite *suite )

View File

@@ -23,8 +23,6 @@
#include "../src/ParodusInternal.h"
#include "../src/spin_thread.h"
pthread_t test_tid;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -46,7 +44,7 @@ void *_routine(void *v)
void test_StartThread_success()
{
StartThread(&_routine, &test_tid);
StartThread(&_routine);
}
void add_suites( CU_pSuite *suite )

View File

@@ -30,7 +30,6 @@
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool g_shutdown = false;
ParodusMsg *ParodusMsgQ;
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;

View File

@@ -158,19 +158,6 @@ extern void read_key_from_file (const char *fname, char *buf, size_t buflen);
extern const char *get_tok (const char *src, int delim, char *result, int resultsize);
extern unsigned int get_algo_mask (const char *algo_str);
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;
pthread_cond_t *get_global_crud_con(void)
{
return &crud_con;
}
pthread_mutex_t *get_global_crud_mut(void)
{
return &crud_mut;
}
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;

View File

@@ -23,7 +23,7 @@
#include <cmocka.h>
#include <assert.h>
#include <wrp-c.h>
#include <pthread.h>
#include "../src/token.h"
@@ -31,20 +31,6 @@
/* Mocks */
/*----------------------------------------------------------------------------*/
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;
pthread_cond_t *get_global_crud_con(void)
{
return &crud_con;
}
pthread_mutex_t *get_global_crud_mut(void)
{
return &crud_mut;
}
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;

View File

@@ -38,12 +38,10 @@
/*----------------------------------------------------------------------------*/
static noPollConn *conn;
static char *reconnect_reason = "webpa_process_starts";
bool g_shutdown = false;
static ParodusCfg parodusCfg;
extern size_t metaPackSize;
extern UpStreamMsg *UpStreamMsgQ;
int numLoops = 1;
int deviceIDNull =0;
wrp_msg_t *temp = NULL;
extern pthread_mutex_t nano_mut;
extern pthread_cond_t nano_con;
@@ -68,10 +66,6 @@ reg_list_item_t * get_global_node(void)
return mock_ptr_type(reg_list_item_t *);
}
void release_global_node (void)
{
}
int get_numOfClients()
{
function_called();
@@ -98,21 +92,8 @@ void sendMessage(noPollConn *conn, void *msg, size_t len)
function_called();
}
void set_parodus_cfg(ParodusCfg *cfg)
{
memcpy(&parodusCfg, cfg, sizeof(ParodusCfg));
}
ParodusCfg *get_parodus_cfg(void)
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
parStrncpy(cfg.hw_mac , "14cfe2142xxx", sizeof(cfg.hw_mac));
if(deviceIDNull)
{
parStrncpy(cfg.hw_mac , "", sizeof(cfg.hw_mac));
}
set_parodus_cfg(&cfg);
return &parodusCfg;
}
@@ -215,13 +196,6 @@ int nn_shutdown (int s, int how)
return (int)mock();
}
int nn_close (int s)
{
UNUSED(s);
function_called();
return (int)mock();
}
int nn_setsockopt (int s, int level, int option, const void *optval, size_t optvallen)
{
UNUSED(s); UNUSED(level); UNUSED(option); UNUSED(optval); UNUSED(optvallen);
@@ -267,16 +241,10 @@ void test_handleUpstreamNull()
UpStreamMsgQ = NULL;
will_return(nn_socket, 1);
expect_function_call(nn_socket);
will_return(nn_setsockopt, 0);
expect_function_call(nn_setsockopt);
will_return(nn_bind, 1);
expect_function_call(nn_bind);
will_return(nn_recv, 12);
expect_function_call(nn_recv);
will_return(nn_shutdown, 0);
expect_function_call(nn_shutdown);
will_return(nn_close, 0);
expect_function_call(nn_close);
handle_upstream();
}
@@ -292,16 +260,10 @@ void test_handle_upstream()
UpStreamMsgQ->next->next = NULL;
will_return(nn_socket, 1);
expect_function_call(nn_socket);
will_return(nn_setsockopt, 0);
expect_function_call(nn_setsockopt);
will_return(nn_bind, 1);
expect_function_call(nn_bind);
will_return(nn_recv, 12);
expect_function_call(nn_recv);
will_return(nn_shutdown, 0);
expect_function_call(nn_shutdown);
will_return(nn_close, 0);
expect_function_call(nn_close);
handle_upstream();
free(UpStreamMsgQ->next);
free(UpStreamMsgQ);
@@ -311,8 +273,6 @@ void err_handleUpstreamBindFailure()
{
will_return(nn_socket, 1);
expect_function_call(nn_socket);
will_return(nn_setsockopt, 0);
expect_function_call(nn_setsockopt);
will_return(nn_bind, -1);
expect_function_call(nn_bind);
handle_upstream();
@@ -454,18 +414,15 @@ void test_processUpstreamMessageRegMsg()
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(get_global_node, (intptr_t)head);
expect_function_call(get_global_node);
will_return(get_numOfClients, 1);
expect_function_call(get_numOfClients);
will_return(get_global_node, (intptr_t)head);
expect_function_call(get_global_node);
will_return(nn_shutdown, 1);
expect_function_call(nn_shutdown);
will_return(nn_close, 0);
expect_function_call(nn_close);
will_return(nn_socket, 1);
expect_function_call(nn_socket);
@@ -516,9 +473,6 @@ void test_processUpstreamMessageRegMsgNoClients()
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(get_global_node, (intptr_t)head);
expect_function_call(get_global_node);
will_return(get_numOfClients, 0);
expect_function_call(get_numOfClients);
@@ -616,27 +570,21 @@ void err_processUpstreamMessageRegMsg()
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(get_global_node, (intptr_t)head);
expect_function_call(get_global_node);
will_return(get_numOfClients, 1);
expect_function_call(get_numOfClients);
will_return(get_global_node, (intptr_t)head);
expect_function_call(get_global_node);
will_return(nn_shutdown, -1);
expect_function_call(nn_shutdown);
will_return(nn_close, 0);
expect_function_call(nn_close);
will_return(nn_socket, -1);
expect_function_call(nn_socket);
will_return(nn_shutdown, 1);
expect_function_call(nn_shutdown);
will_return(nn_close, 0);
expect_function_call(nn_close);
will_return(nn_socket, 1);
expect_function_call(nn_socket);
@@ -778,16 +726,16 @@ void test_processUpstreamMsg_cloud_status()
void test_processUpstreamMsg_sendToClient()
{
numLoops = 2;
metaPackSize = 20;
numLoops = 2;
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = strdup("First Message");
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next= NULL;
UpStreamMsgQ->next = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->next->msg = strdup("Second Message");
UpStreamMsgQ->next->len = 15;
UpStreamMsgQ->next->next = NULL;
UpStreamMsgQ->next->msg = strdup("Second Message");
UpStreamMsgQ->next->len = 15;
UpStreamMsgQ->next->next = NULL;
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
@@ -810,66 +758,86 @@ void test_processUpstreamMsg_sendToClient()
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
}
void test_processUpstreamMsg_serviceNameNULL()
void test_processUpstreamMessageNullCheck()
{
numLoops = 1;
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = strdup("First Message");
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next= NULL;
UpStreamMsgQ->next = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->next->msg = strdup("Second Message");
UpStreamMsgQ->next->len = 15;
UpStreamMsgQ->next->next = NULL;
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
temp->msg_type = 6;
temp->u.crud.dest = strdup("mac:14cfe2142xxx/");
temp->u.crud.source = strdup("mac:14cfe2142xxx/parodus/cloud-status");
temp->u.crud.transaction_uuid = strdup("123");
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
numLoops = 1;
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = strdup("First Message");
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next= NULL;
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
temp->msg_type = WRP_MSG_TYPE__RETREIVE;
temp->u.crud.dest = strdup("mac:14cfe2142xxx/parodus/cloud-status");
temp->u.crud.source = strdup("mac:14cfe2142xxx/config");
temp->u.crud.transaction_uuid = strdup("123");
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
expect_function_call(addCRUDmsgToQueue);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
}
void err_processUpstreamMsg_deviceID()
void err_processUpstreamMessageNullCheck()
{
numLoops = 1;
metaPackSize = 20;
deviceIDNull = 1;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = "First Message";
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next= NULL;
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
temp->msg_type = 6;
temp->u.crud.dest = "mac:14cfe2142xxx/parodus/cloud-status";
temp->u.crud.source = "mac:14cfe2142xxx/config";
temp->u.crud.transaction_uuid = "123";
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
numLoops = 1;
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = strdup("First Message");
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next= NULL;
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
temp->msg_type = WRP_MSG_TYPE__RETREIVE;
temp->u.crud.dest = strdup("mac:/parodus/cloud-status");
temp->u.crud.source = strdup("mac:14cfe2142xxx/config");
temp->u.crud.transaction_uuid = strdup("123");
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
}
void err_processUpstreamMessageWithoutMac()
{
numLoops = 1;
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = strdup("First Message");
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next= NULL;
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
temp->msg_type = WRP_MSG_TYPE__RETREIVE;
temp->u.crud.dest = strdup("/parodus/cloud-status");
temp->u.crud.source = strdup("mac:14cfe2142xxx/config");
temp->u.crud.transaction_uuid = strdup("123");
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -902,8 +870,9 @@ int main(void)
cmocka_unit_test(test_processUpstreamMsgCrud_nnfree),
cmocka_unit_test(test_processUpstreamMsg_cloud_status),
cmocka_unit_test(test_processUpstreamMsg_sendToClient),
cmocka_unit_test(test_processUpstreamMsg_serviceNameNULL),
cmocka_unit_test(err_processUpstreamMsg_deviceID)
cmocka_unit_test(test_processUpstreamMessageNullCheck),
cmocka_unit_test(err_processUpstreamMessageNullCheck),
cmocka_unit_test(err_processUpstreamMessageWithoutMac),
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -1,249 +0,0 @@
/**
* Copyright 2010-2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <malloc.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
#include <wrp-c.h>
#include <nanomsg/nn.h>
#include "../src/upstream.h"
#include "../src/config.h"
#include "../src/client_list.h"
#include "../src/ParodusInternal.h"
#include "../src/partners_check.h"
#include "../src/close_retry.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
#define GOOD_CLIENT_URL "tcp://127.0.0.1:6667"
static noPollConn *conn;
static char *reconnect_reason = "webpa_process_starts";
bool g_shutdown = false;
static ParodusCfg parodusCfg;
extern size_t metaPackSize;
extern UpStreamMsg *UpStreamMsgQ;
int numLoops = 1;
int deviceIDNull =0;
wrp_msg_t *reg_msg = NULL;
extern pthread_mutex_t nano_mut;
extern pthread_cond_t nano_con;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
reg_list_item_t *get_reg_list()
{
reg_list_item_t *item = get_global_node();
release_global_node();
return item;
}
noPollConn *get_global_conn()
{
return conn;
}
char *get_global_reconnect_reason()
{
return reconnect_reason;
}
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;
function_called();
return;
}
void sendMessage(noPollConn *conn, void *msg, size_t len)
{
(void) conn; (void) msg; (void) len;
function_called();
}
void set_parodus_cfg(ParodusCfg *cfg)
{
memcpy(&parodusCfg, cfg, sizeof(ParodusCfg));
}
ParodusCfg *get_parodus_cfg(void)
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
parStrncpy(cfg.hw_mac , "14cfe2142xxx", sizeof(cfg.hw_mac));
if(deviceIDNull)
{
parStrncpy(cfg.hw_mac , "", sizeof(cfg.hw_mac));
}
set_parodus_cfg(&cfg);
return &parodusCfg;
}
/*-------------------------------------------
int nn_connect (int s, const char *addr)
{
(void) s; (void) addr;
printf ("nn_connect, socket %d\n", s);
return 1;
}
---------------------------------------------*/
ssize_t wrp_pack_metadata( const data_t *packData, void **data )
{
(void) packData; (void) data;
function_called();
return (ssize_t)mock();
}
size_t appendEncodedData( void **appendData, void *encodedBuffer, size_t encodedSize, void *metadataPack, size_t metadataSize )
{
(void) encodedBuffer; (void) encodedSize; (void) metadataPack; (void) metadataSize;
function_called();
char *data = (char *) malloc (sizeof(char) * 100);
parStrncpy(data, "AAAAAAAAYYYYIGkYTUYFJH", 100);
*appendData = data;
return (size_t)mock();
}
int nn_send (int s, const void *buf, size_t len, int flags)
{
UNUSED(s); UNUSED(buf); UNUSED(len); UNUSED(flags);
function_called();
return (int)mock();
}
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)
{
UNUSED(cond); UNUSED(mutex);
function_called();
return (int)mock();
}
ssize_t wrp_to_struct( const void *bytes, const size_t length, const enum wrp_format fmt, wrp_msg_t **msg )
{
UNUSED(bytes); UNUSED(length); UNUSED(fmt);
function_called();
*msg = reg_msg;
return (ssize_t)mock();
}
void wrp_free_struct( wrp_msg_t *msg )
{
UNUSED(msg);
function_called();
}
int nn_freemsg (void *msg)
{
UNUSED(msg);
function_called();
return (int)mock();
}
int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
UNUSED(msg); UNUSED(partnerIds);
function_called();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_message()
{
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = "First Message";
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next = NULL;
numLoops = 1;
reg_msg = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(reg_msg,0,sizeof(wrp_msg_t));
reg_msg->msg_type = WRP_MSG_TYPE__SVC_REGISTRATION;
reg_msg->u.reg.service_name = "config";
reg_msg->u.reg.url = GOOD_CLIENT_URL;
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(nn_send, 1);
expect_function_call(nn_send);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(reg_msg);
free(UpStreamMsgQ);
}
void test_processUpstreamMessage()
{
int last_sock = -1;
reg_list_item_t * reg_item = get_reg_list ();
assert_null (reg_item);
test_message();
reg_item = get_reg_list ();
assert_non_null (reg_item);
if (NULL == reg_item)
return;
last_sock = reg_item->sock;
test_message ();
assert_int_equal (get_numOfClients(), 1);
if (get_numOfClients() != 1)
return;
reg_item = get_reg_list ();
assert_int_equal (last_sock, reg_item->sock);
if (last_sock != reg_item->sock)
return;
test_message ();
assert_int_equal (get_numOfClients(), 1);
if (get_numOfClients() != 1)
return;
reg_item = get_reg_list ();
assert_int_equal (last_sock, reg_item->sock);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_processUpstreamMessage)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}