Compare commits

..

5 Commits

Author SHA1 Message Date
Shilpa Seshadri
bf342a6983 Clear auth token if fetch fails 2019-05-21 18:31:03 -07:00
Weston Schmidt
0910dfa11e Merge pull request #239 from gbuddappagari/boot_time_fix
Handle unknown and * partner_id in parodus
2018-09-10 09:55:06 -07:00
Gayathri
1b007fe3bb Handle unknown and * partner_id in parodus 2018-09-10 16:23:28 +05:30
Shilpa Seshadri
a252447494 Modify nopoll git tag as appropriate 2018-08-27 23:30:04 -07:00
Gayathri
7f4b6e3f9e Modified validation logic for boot-time
(cherry picked from commit 844a1d925a)

Conflicts:
	src/config.c
	src/config.h
2018-08-27 23:18:53 -07:00
79 changed files with 1278 additions and 12341 deletions

View File

@@ -13,7 +13,7 @@ addons:
notification_email: weston_schmidt@alumni.purdue.edu
build_command_prepend: "mkdir coverity_build && cd coverity_build && cmake .."
build_command: "make"
branch_pattern: ignore
branch_pattern: master
before_install:
- sudo pip install codecov
@@ -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

@@ -1,81 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
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
- Add pause/resume heartBeatTimer
- parodus event handler to listen to interface_down and interface_up event
## [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)
- Memory leak fixes
- Changed connection logic (connection.c) for retries, and added unit test
- Partner-id comparison made case insensitive
- Reverted from NNG to nanomag (v1.1.2)
- reverted temporary CMake reference to https://github.com/bill1600/seshat
- Added log for time difference of parodus connect time and boot time
- 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
- Added command line arguments for secure token read and acquire.
- DNS check for <device-id>.<URL> to allow custom device handling logic (like test boxes, refurbishing, etc).
- Add check for matching `partner-id` for incoming WRP messages based on command line argument passed.
- CRUD operations to local namespace is now supported.
- Via CRUD calls, the custom metadata tag values are now supported.
### Changed
- Configurable security flag and port.
- Default HTTP port to 80 and HTTPS port to 443.
- Updates to how `nopoll` is called have been implemented.
### Fixed
- 64 bit pointer fixes (#144, #145).
- Handle `403` error from talaria (#147).
- Several additional NULL pointer checks & recovery logic blocks added.
- A scenario where ping requests are not responded to was fixed.
### Security
- Added command line arguments for secure token read and acquire. Token presented to cloud for authentication verification.
## [1.0.0] - 2017-11-17
### Added
- Added the basic implementation.
## [0.0.1] - 2016-08-15
### Added
- 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

@@ -23,7 +23,6 @@ set(INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/_install)
set(PREFIX_DIR ${CMAKE_CURRENT_BINARY_DIR}/_prefix)
set(INCLUDE_DIR ${INSTALL_DIR}/include)
set(INCLUDE_UCRESOLV ${PREFIX_DIR}/ucresolv/src/ucresolv/include)
set(PATCHES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/patches)
set(LIBRARY_DIR ${INSTALL_DIR}/lib)
set(LIBRARY_DIR64 ${INSTALL_DIR}/lib64)
set(COMMON_LIBRARY_DIR ${INSTALL_DIR}/lib/${CMAKE_LIBRARY_ARCHITECTURE})
@@ -34,7 +33,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
@@ -73,7 +71,7 @@ if (NOT BUILD_YOCTO)
ExternalProject_Add(trower-base64
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/trower-base64
GIT_REPOSITORY https://github.com/Comcast/trower-base64.git
GIT_TAG "v1.1.1"
GIT_TAG "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libtrower-base64 STATIC SHARED IMPORTED)
@@ -85,7 +83,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 "18e83e32bfccd1f308b4df0fe0aa3565302903a4"
CONFIGURE_COMMAND COMMAND <SOURCE_DIR>/autogen.sh --prefix=${PREFIX}
--includedir=${INCLUDE_DIR}
--libdir=${LIBRARY_DIR}
@@ -101,7 +99,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 "096998834451219ee7813d8977f6a4027b0ccb43"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libnanomsg STATIC SHARED IMPORTED)
@@ -114,7 +112,7 @@ ExternalProject_Add(cJSON
#PREFIX ${PREFIX_DIR}/cJSON
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cJSON
GIT_REPOSITORY https://github.com/DaveGamble/cJSON.git
GIT_TAG "v1.7.8"
GIT_TAG "aafb64a1c549b7b927e339df6d35b1d5059dc235"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcJSON STATIC SHARED IMPORTED)
@@ -126,7 +124,7 @@ add_dependencies(libcJSON cJSON)
ExternalProject_Add(msgpack
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/msgpack
GIT_REPOSITORY https://github.com/msgpack/msgpack-c.git
GIT_TAG "cpp-3.1.1"
GIT_TAG "7a98138f27f27290e680bf8fbf1f8d1b089bf138"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
-DMSGPACK_ENABLE_CXX=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
@@ -135,24 +133,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 "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcimplog STATIC SHARED IMPORTED)
@@ -165,7 +151,7 @@ ExternalProject_Add(wrp-c
DEPENDS trower-base64 msgpack cimplog
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/wrp-c
GIT_REPOSITORY https://github.com/Comcast/wrp-c.git
GIT_TAG "1.0.1"
GIT_TAG "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
-DMSGPACK_ENABLE_CXX=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
@@ -177,6 +163,22 @@ ExternalProject_Add(wrp-c
add_library(libwrp-c STATIC SHARED IMPORTED)
add_dependencies(libwrp-c wrp-c)
# libparodus external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(libparodus
DEPENDS trower-base64 msgpack nanomsg wrp-c
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/libparodus
GIT_REPOSITORY https://github.com/Comcast/libparodus.git
GIT_TAG "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
-DMAIN_PROJ_BUILD=ON
-DMAIN_PROJ_LIB_PATH=${LIBRARY_DIR}
-DMAIN_PROJ_LIB64_PATH=${LIBRARY_DIR64}
-DMAIN_PROJ_COMMON_PATH=${COMMON_LIBRARY_DIR}
-DMAIN_PROJ_INCLUDE_PATH=${INCLUDE_DIR}
)
add_library(liblibparodus STATIC SHARED IMPORTED)
add_dependencies(liblibparodus libparodus)
if (ENABLE_SESHAT)
# libseshat external dependency
@@ -184,8 +186,7 @@ if (ENABLE_SESHAT)
ExternalProject_Add(libseshat
DEPENDS cJSON trower-base64 msgpack nanomsg wrp-c
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/libseshat
GIT_REPOSITORY https://github.com/Comcast/seshat.git
GIT_TAG "1.0.1"
GIT_REPOSITORY https://github.com/comcast/seshat.git
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
-DMAIN_PROJ_BUILD=ON
-DMAIN_PROJ_LIB_PATH=${LIBRARY_DIR}
@@ -204,8 +205,8 @@ 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 "master"
#GIT_TAG "abd4376ff56212d16f69e850a64f6e095857ca39"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcjwt STATIC SHARED IMPORTED)
@@ -217,7 +218,7 @@ if (FEATURE_DNS_QUERY)
ExternalProject_Add(ucresolv
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/ucresolv
GIT_REPOSITORY https://github.com/Comcast/libucresolv.git
GIT_TAG "1.0.0"
GIT_TAG "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libucresolv STATIC SHARED IMPORTED)
@@ -234,7 +235,7 @@ if (BUILD_TESTING)
ExternalProject_Add(cmocka
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cmocka
GIT_REPOSITORY https://github.com/elventear/cmocka.git
GIT_TAG "b71a3060699bc1a5b00e958be353772f42545ac2"
GIT_TAG "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libcmocka STATIC SHARED IMPORTED)

View File

@@ -1,16 +1,11 @@
# parodus
C implementation of the WebPA client coordinator
[![Build Status](https://travis-ci.org/Comcast/parodus.svg?branch=master)](https://travis-ci.org/Comcast/parodus)
[![codecov.io](http://codecov.io/github/Comcast/parodus/coverage.svg?branch=master)](http://codecov.io/github/Comcast/parodus?branch=master)
[![Coverity](https://img.shields.io/coverity/scan/11192.svg)](https://scan.coverity.com/projects/comcast-parodus)
[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/Comcast/parodus/blob/master/LICENSE)
[![GitHub release](https://img.shields.io/github/release/Comcast/parodus.svg)](CHANGELOG.md)
C implementation of the XMiDT client coordinator
XMiDT is a highly scalable, highly available, generic message routing system.
# Building and Testing Instructions
```
@@ -55,11 +50,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 webpa 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)
- /crud-config-file -Config json file to store objects during create, retrieve, update and delete (CRUD) operations -optional argument
- /token-acquisition-script -Script to create new auth token for establishing secure connection (absolute path where that script is present) -optional argument
# if ENABLE_SESHAT is enabled
@@ -75,12 +68,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 +75,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
# 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
# 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
```

View File

@@ -11,11 +11,10 @@
# 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.
set(SOURCES main.c mutex.c networking.c nopoll_helpers.c heartBeat.c nopoll_handlers.c
set(SOURCES main.c mutex.c networking.c nopoll_helpers.c nopoll_handlers.c
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)
upstream.c downstream.c thread_tasks.c partners_check.c token.c)
if (ENABLE_SESHAT)
set(SOURCES ${SOURCES} seshat_interface.c)
@@ -30,7 +29,6 @@ target_link_libraries (parodus
${CMAKE_THREAD_LIBS_INIT}
-lwrp-c
-lmsgpackc
-lcurl
-ltrower-base64
-lnopoll
-luuid

View File

@@ -25,10 +25,6 @@
#include "config.h"
#include "connection.h"
bool interface_down_event = false;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -129,52 +125,3 @@ char* getWebpaConveyHeader()
return NULL;
}
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *diff)
{
if ((stop->tv_nsec - start->tv_nsec) < 0) {
diff->tv_sec = stop->tv_sec - start->tv_sec - 1;
diff->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000UL;
} else {
diff->tv_sec = stop->tv_sec - start->tv_sec;
diff->tv_nsec = stop->tv_nsec - start->tv_nsec;
}
return;
}
/*------------------------------------------------------------------------------*/
/* For interface_down_event Flag */
/*------------------------------------------------------------------------------*/
// Get value of interface_down_event
bool get_interface_down_event()
{
bool tmp = false;
pthread_mutex_lock (&interface_down_mut);
tmp = interface_down_event;
pthread_mutex_unlock (&interface_down_mut);
return tmp;
}
// Reset value of interface_down_event to false
void reset_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = false;
pthread_mutex_unlock (&interface_down_mut);
}
// set value of interface_down_event to true
void set_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = true;
pthread_mutex_unlock (&interface_down_mut);
}

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
@@ -60,12 +59,6 @@ extern int numLoops;
#define FOREVER() numLoops--
#endif
// Return values for find_servers() in connection.c
#define FIND_SUCCESS 0
#define FIND_INVALID_DEFAULT -2
#define FIND_JWT_FAIL -1
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
@@ -84,57 +77,10 @@ typedef struct {
int rr_len;
} rr_rec_t;
//------------ Used in comnection.c -----------------
typedef struct {
int allow_insecure;
char *server_addr; // must be freed
unsigned int port;
} server_t;
typedef struct {
server_t defaults; // from command line
server_t jwt; // from jwt endpoint claim
server_t redirect; // from redirect response to
// nopoll_conn_wait_until_connection_ready
} server_list_t;
//---- Used in connection.c for expire timer
typedef struct {
int running;
struct timespec start_time;
struct timespec end_time;
} expire_timer_t;
//--- Used in connection.c for backoff delay timer
typedef struct {
int count;
int max_count;
int delay;
} backoff_timer_t;
//--- Used in connection.c for init_header_info
typedef struct {
char *conveyHeader; // Do not free
char *device_id; // Need to free
char *user_agent; // Need to free
} header_info_t;
// connection context which is defined in createNopollConnection
// and passed into functions keep_retrying_connect, connect_and_wait,
// wait_connection_ready, and nopoll_connect
typedef struct {
noPollCtx *nopoll_ctx;
server_list_t server_list;
server_t *current_server;
header_info_t header_info;
char *extra_headers; // need to be freed
expire_timer_t connect_timer;
} create_connection_ctx_t;
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
extern bool g_shutdown;
extern bool LastReasonStatus;
extern ParodusMsg *ParodusMsgQ;
int numLoops;
/*----------------------------------------------------------------------------*/
@@ -151,27 +97,6 @@ void parStrncpy(char *destStr, const char *srcStr, size_t destSize);
char* getWebpaConveyHeader();
void *CRUDHandlerTask();
void addCRUDmsgToQueue(wrp_msg_t *crudMsg);
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result);
/*------------------------------------------------------------------------------*/
/* For interface_down_event Flag */
/*------------------------------------------------------------------------------*/
// Get value of interface_down_event
bool get_interface_down_event();
// Reset value of interface_down_event to false
void reset_interface_down_event();
// Set value of interface_down_event to true
void set_interface_down_event();
#ifdef __cplusplus
}
#endif

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;
}
@@ -248,49 +224,3 @@ int deleteFromList(char* service_name)
ParodusError("Could not find the entry to delete from list\n");
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
*@msgSize : Total size of the msg to send to client
*/
int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize)
{
int bytes =0;
reg_list_item_t *temp = NULL;
temp = get_global_node();
//Checking for individual clients & Sending msg to registered client
while (NULL != temp)
{
ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
// Sending message to registered clients
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;
}
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,8 @@ 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

@@ -1,68 +0,0 @@
/**
* Copyright 2018 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 close_retry.c
*
* @description Functions required to manage connection close retry.
*
*/
#include "close_retry.h"
bool close_retry = false;
pthread_mutex_t close_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t close_con=PTHREAD_COND_INITIALIZER;
pthread_cond_t *get_global_close_retry_con(void)
{
return &close_con;
}
pthread_mutex_t *get_global_close_retry_mut(void)
{
return &close_mut;
}
// Get value of close_retry
bool get_close_retry()
{
bool tmp = false;
pthread_mutex_lock (&close_mut);
tmp = close_retry;
pthread_mutex_unlock (&close_mut);
return tmp;
}
// Reset value of close_retry to false
void reset_close_retry()
{
pthread_mutex_lock (&close_mut);
close_retry = false;
pthread_mutex_unlock (&close_mut);
}
// set value of close_retry to true
void set_close_retry()
{
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_cond_signal(&close_con);
pthread_mutex_unlock (&close_mut);
}

View File

@@ -1,53 +0,0 @@
/**
* Copyright 2018 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 close_retry.h
*
* @description Functions required to manage connection close retry.
*
*/
#ifndef _CLOSERETRY_H_
#define _CLOSERETRY_H_
#include <pthread.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// Get the condition variable
pthread_cond_t *get_global_close_retry_con();
// Get the mutex variable
pthread_mutex_t *get_global_close_retry_mut();
// Get value of close_retry
bool get_close_retry();
// Reset value of close_retry to false
void reset_close_retry();
// Set value of close_retry to true
void set_close_retry();
#ifdef __cplusplus
}
#endif
#endif

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 */
/*----------------------------------------------------------------------------*/
@@ -51,16 +51,7 @@ void set_parodus_cfg(ParodusCfg *cfg)
memcpy(&parodusCfg, cfg, sizeof(ParodusCfg));
}
void set_cloud_disconnect_reason(ParodusCfg *cfg, char *disconn_reason)
{
cfg->cloud_disconnect = strdup(disconn_reason);
}
void reset_cloud_disconnect_reason(ParodusCfg *cfg)
{
cfg->cloud_disconnect = NULL;
}
static void execute_token_script(char *token, char *name, size_t len, char *mac, char *serNum);
const char *get_tok (const char *src, int delim, char *result, int resultsize)
{
@@ -141,6 +132,31 @@ void read_key_from_file (const char *fname, char *buf, size_t buflen)
ParodusInfo ("%d bytes read\n", nbytes);
}
static 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)
@@ -185,7 +201,7 @@ int server_is_http (const char *full_url,
}
int parse_webpa_url__ (const char *full_url,
int parse_webpa_url(const char *full_url,
char *server_addr, int server_addr_buflen,
char *port_buf, int port_buflen)
{
@@ -194,9 +210,6 @@ int parse_webpa_url__ (const char *full_url,
char *end_port;
size_t server_len;
int http_match;
char *closeBracket = NULL;
char *openBracket = NULL;
char *checkPort = NULL;
ParodusInfo ("full url: %s\n", full_url);
http_match = server_is_http (full_url, &server_ptr);
@@ -209,40 +222,6 @@ int parse_webpa_url__ (const char *full_url,
// If there's a '/' on end, null it out
if ((server_len>0) && (server_addr[server_len-1] == '/'))
server_addr[server_len-1] = '\0';
openBracket = strchr(server_addr,'[');
if(openBracket != NULL){
//Remove [ from server address
char *remove = server_addr;
remove++;
parStrncpy (server_addr, remove, server_addr_buflen);
closeBracket = strchr(server_addr,']');
if(closeBracket != NULL){
//Remove ] by making it as null
*closeBracket = '\0';
closeBracket++;
checkPort = strchr(closeBracket,':');
if (NULL == checkPort) {
if (http_match)
parStrncpy (port_buf, "80", port_buflen);
else
parStrncpy (port_buf, "443", port_buflen);
} else {
checkPort++;
end_port = strchr (checkPort, '/');
if (NULL != end_port)
*end_port = '\0'; // terminate port with null
parStrncpy (port_buf, checkPort, port_buflen);
}
}else{
ParodusError("Invalid url %s\n", full_url);
return -1;
}
}else if (strchr(server_addr,']') != NULL ){
ParodusError("Invalid url %s\n", full_url);
return -1;
}else{
// Look for ':'
port_val = strchr (server_addr, ':');
@@ -251,11 +230,6 @@ int parse_webpa_url__ (const char *full_url,
parStrncpy (port_buf, "80", port_buflen);
else
parStrncpy (port_buf, "443", port_buflen);
end_port = strchr (server_addr, '/');
if (NULL != end_port) {
*end_port = '\0'; // terminate server address with null
}
} else {
*port_val = '\0'; // terminate server address with null
port_val++;
@@ -264,7 +238,6 @@ int parse_webpa_url__ (const char *full_url,
*end_port = '\0'; // terminate port with null
parStrncpy (port_buf, port_val, port_buflen);
}
}
ParodusInfo ("server %s, port %s, http_match %d\n",
server_addr, port_buf, http_match);
return http_match;
@@ -292,49 +265,6 @@ unsigned int parse_num_arg (const char *arg, const char *arg_name)
return result;
}
int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port)
{
int allow_insecure;
unsigned int port_val;
int buflen = strlen (full_url) + 1;
char *url_buf = NULL;
char port_buf[8];
#define ERROR__(msg) \
ParodusError (msg); \
if (NULL != url_buf) \
free (url_buf);
*server_addr = NULL;
url_buf = (char *) malloc (buflen);
if (NULL == url_buf) {
ERROR__ ("parse_webpa_url allocatio n failed.\n")
return -1;
}
allow_insecure = parse_webpa_url__ (full_url,
url_buf, buflen, port_buf, 8);
if (allow_insecure < 0) {
ERROR__ ("parse_webpa_url invalid url\n")
return -1;
}
port_val = parse_num_arg (port_buf, "server port");
if (port_val == (unsigned int) -1) {
ERROR__ ("Invalid port in server url")
return -1;
}
if ((port_val == 0) || (port_val > 65535)) {
ERROR__ ("port value out of range in server url")
return -1;
}
*server_addr = url_buf;
*port = port_val;
return allow_insecure;
#undef ERROR__
}
int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
{
static const struct option long_options[] = {
@@ -361,13 +291,9 @@ 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'},
{"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'},
{"token-acquisition-script", required_argument, 0, 'J'},
{0, 0, 0, 0}
};
int c;
@@ -382,19 +308,13 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
cfg->acquire_jwt = 0;
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 */
while (1)
{
/* 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",
long_options, &option_index);
/* Detect the end of the options. */
@@ -435,7 +355,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,41 +447,19 @@ 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 '?':
/* getopt_long already printed an error message. */
break;
@@ -605,6 +502,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)
@@ -635,13 +590,7 @@ 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);
}
void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg)
@@ -779,6 +728,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,41 +755,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);
}
else
{
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,18 +42,13 @@ 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"
#define WEBPA_BACKOFF_MAX "webpa-backoff-max"
#define PARTNER_ID "partner-id"
#define CERT_PATH "ssl-cert-path"
#define CLOUD_STATUS "cloud-status"
#define CLOUD_DISCONNECT "cloud-disconnect"
#define CLOUD_STATUS_ONLINE "online"
#define CLOUD_STATUS_OFFLINE "offline"
#define CLOUD_DISCONNECT_REASON "disconnection-reason"
#define BOOT_RETRY_WAIT "boot-time-retry-wait"
#define PROTOCOL_VALUE "PARODUS-2.0"
@@ -99,26 +94,18 @@ 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;
unsigned int boot_retry_wait;
unsigned int boot_retry_wait;
} ParodusCfg;
#define FLAGS_IPV6_ONLY (1 << 0)
#define FLAGS_IPV4_ONLY (1 << 1)
#define FLAGS_IPV6_IPV4 (FLAGS_IPV6_ONLY | FLAGS_IPV4_ONLY)
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg);
void createNewAuthToken(char *newToken, size_t len);
/**
* parse command line arguments and create config structure
@@ -132,26 +119,28 @@ 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 *);
char *get_token_application(void) ;
void set_cloud_disconnect_reason(ParodusCfg *cfg, char *disconn_reason);
void reset_cloud_disconnect_reason(ParodusCfg *cfg);
/**
* parse a webpa url. Extract the server address, the port
* and return whether it's secure or not
*
* @param full_url full url
* @param server_addr ptr to a server address ptr
* will be NULL if invalid,
* otherwise will need to be freed
* @param port ptr to port variable
* @param full_url full url
* @param server_addr buffer containing server address found in url
* @param server_addr_buflen len of the server addr buffer provided by caller
* @param port_buf buffer containing port value found in url
* @param port_buflen len of the port buffer provided by caller
* @return 1 if insecure connection is allowed, 0 if not,
* or -1 if error
*/
int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port);
int parse_webpa_url(const char *full_url,
char *server_addr, int server_addr_buflen,
char *port_buf, int port_buflen);
#ifdef __cplusplus
}
#endif

View File

@@ -33,37 +33,28 @@
#include "spin_thread.h"
#include "service_alive.h"
#include "seshat_interface.h"
#include "crud_interface.h"
#include "heartBeat.h"
#include "close_retry.h"
#include <curl/curl.h>
#ifdef FEATURE_DNS_QUERY
#include <ucresolv_log.h>
#endif
#include <time.h>
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define HEARTBEAT_RETRY_SEC 30 /* Heartbeat (ping/pong) timeout in seconds */
#define CLOUD_RECONNECT_TIME 5 /* Cloud disconnect max time in minutes */
/*----------------------------------------------------------------------------*/
/* 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;
bool close_retry = false;
bool LastReasonStatus = false;
volatile unsigned int heartBeatTimer = 0;
pthread_mutex_t close_mut=PTHREAD_MUTEX_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result);
/*----------------------------------------------------------------------------*/
/* External Functions */
@@ -71,13 +62,10 @@ void timespec_diff(struct timespec *start, struct timespec *stop,
void createSocketConnection(void (* initKeypress)())
{
int intTimer=0;
//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 +83,15 @@ 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)
{
ParodusError("Unrecovered error, terminating the process\n");
OnboardLog("Unrecovered error, terminating the process\n");
abort();
}
createNopollConnection(ctx);
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);
if (NULL != initKeypress)
{
@@ -121,103 +100,51 @@ void createSocketConnection(void (* initKeypress)())
seshat_registered = __registerWithSeshat();
clock_gettime(CLOCK_REALTIME, &start_svc_alive_timer);
do
{
struct timespec start, stop, diff;
int time_taken_ms;
clock_gettime(CLOCK_REALTIME, &start);
nopoll_loop_wait(ctx, 5000000);
clock_gettime(CLOCK_REALTIME, &stop);
intTimer = intTimer + 5;
timespec_diff(&start, &stop, &diff);
time_taken_ms = diff.tv_sec * 1000 + (diff.tv_nsec / 1000000);
// ParodusInfo("nopoll_loop_wait() time %d msec\n", time_taken_ms);
heartBeatTimer = get_heartBeatTimer();
if(heartBeatTimer >= webpa_ping_timeout_ms)
if(heartBeatTimer >= get_parodus_cfg()->webpa_ping_timeout)
{
ParodusInfo("heartBeatTimer %d webpa_ping_timeout_ms %d\n", heartBeatTimer, webpa_ping_timeout_ms);
if(!get_close_retry())
if(!close_retry)
{
ParodusError("ping wait time > %d . Terminating the connection with WebPA server and retrying\n", webpa_ping_timeout_ms / 1000);
ParodusError("ping wait time > %d. Terminating the connection with WebPA server and retrying\n", get_parodus_cfg()->webpa_ping_timeout);
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();
LastReasonStatus = true;
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
}
else
{
ParodusPrint("heartBeatHandler - close_retry set to %d, hence resetting the heartBeatTimer\n",get_close_retry());
{
ParodusPrint("heartBeatHandler - close_retry set to %d, hence resetting the heartBeatTimer\n",close_retry);
}
reset_heartBeatTimer();
heartBeatTimer = 0;
}
else {
increment_heartBeatTimer(time_taken_ms);
else if(intTimer >= 30)
{
ParodusPrint("heartBeatTimer %d\n",heartBeatTimer);
heartBeatTimer += HEARTBEAT_RETRY_SEC;
intTimer = 0;
}
if( false == seshat_registered ) {
seshat_registered = __registerWithSeshat();
}
if(get_close_retry())
if(close_retry)
{
ParodusInfo("close_retry is %d, hence closing the connection and retrying\n", get_close_retry());
ParodusInfo("close_retry is %d, hence closing the connection and retrying\n", close_retry);
close_and_unref_connection(get_global_conn());
set_global_conn(NULL);
get_parodus_cfg()->cloud_status = CLOUD_STATUS_OFFLINE;
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());
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(!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 ();
}
} while(!close_retry);
close_and_unref_connection(get_global_conn());
nopoll_ctx_unref(ctx);
nopoll_cleanup_library();
curl_global_cleanup();
}
void shutdownSocketConnection(void) {
g_shutdown = true;
}

View File

@@ -45,7 +45,6 @@ extern UpStreamMsg *UpStreamMsgQ;
* and creates the intial connection and manages the connection wait, close mechanisms.
*/
void createSocketConnection(void (* initKeypress)());
void shutdownSocketConnection(void);
#ifdef __cplusplus
}

View File

@@ -25,30 +25,24 @@
#include "time.h"
#include "token.h"
#include "config.h"
#include "auth_token.h"
#include "nopoll_helpers.h"
#include "mutex.h"
#include "spin_thread.h"
#include "ParodusInternal.h"
#include "heartBeat.h"
#include "close_retry.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define HTTP_CUSTOM_HEADER_COUNT 5
#define INITIAL_CJWT_RETRY -2
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
char deviceMAC[32]={'\0'};
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 noPollConn * nopoll_tls_common_conn (noPollCtx * ctx,char * serverAddr,char *serverPort,char * extra_headers);
static char* build_extra_headers( const char *auth, const char *device_id,
const char *user_agent, const char *convey );
@@ -75,557 +69,254 @@ void set_global_reconnect_reason(char *reason)
reconnect_reason = reason;
}
bool get_global_reconnect_status()
{
return LastReasonStatus;
}
void set_global_reconnect_status(bool status)
{
LastReasonStatus = status;
}
int get_cloud_disconnect_time()
{
return cloud_disconnect_max_time;
}
void set_cloud_disconnect_time(int disconnTime)
{
cloud_disconnect_max_time = disconnTime;
}
//--------------------------------------------------------------------
// createNopollConnection_logic:
// call stack:
// createNopollConnection
// find_servers
// keep_trying_connect // keep trying till success or need to requery dns
// connect_and_wait // tries both ipv6 and ipv4, if necessary
// nopoll_connect
// wait_connection_ready
//--------------------------------------------------------------------
#define FREE_PTR_VAR(ptr_var) \
if (NULL != ptr_var) { \
free(ptr_var); \
ptr_var = NULL; \
}
void set_server_null (server_t *server)
{
server->server_addr = NULL;
}
void set_server_list_null (server_list_t *server_list)
{
set_server_null (&server_list->defaults);
set_server_null (&server_list->jwt);
set_server_null (&server_list->redirect);
}
int server_is_null (server_t *server)
{
return (NULL == server->server_addr);
}
void free_server (server_t *server)
{
FREE_PTR_VAR (server->server_addr)
}
void free_server_list (server_list_t *server_list)
{
free_server (&server_list->redirect);
free_server (&server_list->jwt);
free_server (&server_list->defaults);
}
// If there's a redirect server, that's it,
// else if there's a jwt server that's it,
// else it's the default server
server_t *get_current_server (server_list_t *server_list)
{
if (!server_is_null (&server_list->redirect))
return &server_list->redirect;
if (!server_is_null (&server_list->jwt))
return &server_list->jwt;
return &server_list->defaults;
}
int parse_server_url (const char *full_url, server_t *server)
{
server->allow_insecure = parse_webpa_url (full_url,
&server->server_addr, &server->port);
return server->allow_insecure;
}
//--------------------------------------------------------------------
void init_expire_timer (expire_timer_t *timer)
{
timer->running = false;
}
int check_timer_expired (expire_timer_t *timer, long timeout_ms)
{
long time_diff_ms;
if (!timer->running) {
getCurrentTime(&timer->start_time);
timer->running = true;
ParodusInfo("First connect error occurred, initialized the connect error timer\n");
return false;
}
getCurrentTime(&timer->end_time);
time_diff_ms = timeValDiff (&timer->start_time, &timer->end_time);
ParodusPrint("checking timeout difference:%ld\n", time_diff_ms);
if(time_diff_ms >= timeout_ms)
return true;
return false;
}
//--------------------------------------------------------------------
void init_backoff_timer (backoff_timer_t *timer, int max_count)
{
timer->count = 1;
timer->max_count = max_count;
timer->delay = 1;
}
int update_backoff_delay (backoff_timer_t *timer)
{
if (timer->count < timer->max_count) {
timer->count += 1;
timer->delay = timer->delay + timer->delay + 1;
// 3,7,15,31 ..
}
return timer->delay;
}
static void backoff_delay (backoff_timer_t *timer)
{
update_backoff_delay (timer);
ParodusInfo("Waiting with backoffRetryTime %d seconds\n", timer->delay);
sleep (timer->delay);
}
//--------------------------------------------------------------------
void free_header_info (header_info_t *header_info)
{
FREE_PTR_VAR (header_info->user_agent)
FREE_PTR_VAR (header_info->device_id)
// Don't free header_info->conveyHeader, because it's static
header_info->conveyHeader = NULL;
}
void set_header_info_null (header_info_t *header_info)
{
header_info->conveyHeader = NULL;
header_info->user_agent = NULL;
header_info->device_id = NULL;
}
int init_header_info (header_info_t *header_info)
{
ParodusCfg *cfg = get_parodus_cfg();
size_t device_id_len;
#define CFG_PARAM(param) ((0 != strlen(cfg->param)) ? cfg->param : "unknown")
const char *user_agent_format = "%s (%s; %s/%s;)";
char *protocol = CFG_PARAM (webpa_protocol);
char *fw_name = CFG_PARAM (fw_name);
char *hw_model = CFG_PARAM (hw_model);
char *hw_manufacturer = CFG_PARAM (hw_manufacturer);
size_t user_agent_len = strlen(protocol) + strlen(fw_name) +
strlen(hw_model) + strlen(hw_manufacturer) + strlen(user_agent_format)
+ 1;
set_header_info_null (header_info);
header_info->user_agent = (char *) malloc (user_agent_len);
if (NULL == header_info->user_agent) {
ParodusError ("header user agent allocation failed.\n");
return -1;
}
snprintf(header_info->user_agent, user_agent_len, user_agent_format,
protocol, fw_name, hw_model, hw_manufacturer);
device_id_len = strlen (cfg->hw_mac) + 5;
header_info->device_id = (char *) malloc (device_id_len);
if (NULL == header_info->device_id) {
ParodusError ("header device id allocation failed.\n");
FREE_PTR_VAR (header_info->user_agent)
return -1;
}
snprintf(header_info->device_id, device_id_len, "mac:%s", cfg->hw_mac);
ParodusInfo("User-Agent: %s\n",header_info->user_agent);
header_info->conveyHeader = getWebpaConveyHeader(); // ptr to static variable returned
if (NULL == header_info->conveyHeader) {
ParodusError ("getWebpaConveyHeader error\n");
free_header_info (header_info);
return -1;
}
ParodusInfo("Device_id %s\n", header_info->device_id);
return 0;
#undef CFG_PARAM
}
char *build_extra_hdrs (header_info_t *header_info)
// result must be freed
{
char *auth_token = get_parodus_cfg()->webpa_auth_token;
return build_extra_headers( (0 < strlen(auth_token) ? auth_token : NULL),
header_info->device_id, header_info->user_agent, header_info->conveyHeader );
}
//--------------------------------------------------------------------
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)
{
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))
{
getAuthToken(cfg);
}
ctx->extra_headers = build_extra_hdrs (&ctx->header_info);
}
void free_connection_ctx (create_connection_ctx_t *ctx)
{
free_extra_headers (ctx);
free_header_info (&ctx->header_info);
free_server_list (&ctx->server_list);
}
//--------------------------------------------------------------------
// find_servers:
// get and parse default server
// if necessary, query dns and parse server from jwt
// populate server_list
// return values defined in ParodusInternal.h
int find_servers (server_list_t *server_list)
{
server_t *default_server = &server_list->defaults;
free_server_list (server_list);
// parse default server URL
if (parse_server_url (get_parodus_cfg()->webpa_url, default_server) < 0)
return FIND_INVALID_DEFAULT; // must have valid default url
ParodusInfo("default server_Address %s\n", default_server->server_addr);
ParodusInfo("default port %u\n", default_server->port);
#ifdef FEATURE_DNS_QUERY
if (get_parodus_cfg()->acquire_jwt) {
server_t *jwt_server = &server_list->jwt;
//query dns and validate JWT
jwt_server->allow_insecure = allow_insecure_conn(
&jwt_server->server_addr, &jwt_server->port);
if (jwt_server->allow_insecure < 0) {
return FIND_JWT_FAIL;
}
ParodusInfo("JWT ON: jwt_server_url stored as %s\n", jwt_server->server_addr);
}
#endif
return FIND_SUCCESS;
}
//--------------------------------------------------------------------
// connect to current server
int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
{
noPollCtx *nopoll_ctx = ctx->nopoll_ctx;
server_t *server = ctx->current_server;
noPollConn *connection;
noPollConnOpts * opts;
char *default_url = get_parodus_cfg()->webpa_path_url;
char port_buf[8];
sprintf (port_buf, "%u", server->port);
if (server->allow_insecure > 0) {
ParodusPrint("secure false\n");
opts = createConnOpts(ctx->extra_headers, false);
connection = nopoll_conn_new_opts (nopoll_ctx, opts,
server->server_addr, port_buf,
NULL, default_url,NULL,NULL);// WEBPA-787
} else {
ParodusPrint("secure true\n");
opts = createConnOpts(ctx->extra_headers, true);
if (is_ipv6) {
ParodusInfo("Connecting in Ipv6 mode\n");
connection = nopoll_conn_tls_new6 (nopoll_ctx, opts,
server->server_addr, port_buf,
NULL, default_url,NULL,NULL);
} else {
ParodusInfo("Connecting in Ipv4 mode\n");
connection = nopoll_conn_tls_new (nopoll_ctx, opts,
server->server_addr, port_buf,
NULL, default_url,NULL,NULL);
}
}
if ((NULL == connection) && (!is_ipv6)) {
if((checkHostIp(server->server_addr) == -2)) {
if (check_timer_expired (&ctx->connect_timer, 15*60*1000) && !get_interface_down_event()) {
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);
kill(getpid(),SIGTERM);
}
}
}
set_global_conn(connection);
return (NULL != connection);
}
//--------------------------------------------------------------------
// 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_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;
char *redirectURL = NULL;
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;
ParodusError("Received temporary redirection response message %s\n", redirectURL);
// Extract server Address and port from the redirectURL
if (strncmp (redirect_ptr, "Redirect:", 9) == 0)
redirect_ptr += 9;
free_server (&ctx->server_list.redirect);
if (parse_server_url (redirect_ptr, &ctx->server_list.redirect) < 0) {
ParodusError ("Redirect url error %s\n", redirectURL);
free (redirectURL);
return WAIT_FAIL;
}
free (redirectURL);
set_current_server (ctx); // set current server to redirect server
return WAIT_ACTION_RETRY;
}
FREE_NON_NULL_PTR (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("Client connection timeout\n");
ParodusError("RDK-10037 - WebPA Connection Lost\n");
return WAIT_FAIL;
}
//--------------------------------------------------------------------
// 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
int connect_and_wait (create_connection_ctx_t *ctx)
{
unsigned int force_flags = get_parodus_cfg()->flags;
int is_ipv6 = true;
int nopoll_connected;
int wait_rtn;
if( FLAGS_IPV4_ONLY == (FLAGS_IPV4_ONLY & force_flags) ) {
is_ipv6 = false;
}
// This loop will be executed at most twice:
// Once for ipv6 and once for ipv4
while (true) {
nopoll_connected = nopoll_connect (ctx, is_ipv6);
wait_rtn = WAIT_FAIL;
if (nopoll_connected) {
if(nopoll_conn_is_ok(get_global_conn())) {
ParodusPrint("Connected to Server but not yet ready\n");
wait_rtn = wait_connection_ready (ctx);
if (wait_rtn == WAIT_SUCCESS)
return CONN_WAIT_SUCCESS;
} else { // nopoll_conn not ok
ParodusError("Error connecting to server\n");
ParodusError("RDK-10037 - WebPA Connection Lost\n");
}
} // nopoll_connected
if (nopoll_connected) {
close_and_unref_connection(get_global_conn());
set_global_conn(NULL);
}
if (wait_rtn == WAIT_ACTION_RETRY)
return CONN_WAIT_ACTION_RETRY;
// try ipv4 if we need to
if ((0==force_flags) && (0==ctx->current_server->allow_insecure) && is_ipv6) {
is_ipv6 = false;
continue;
}
return CONN_WAIT_RETRY_DNS;
}
}
//--------------------------------------------------------------------
// Tries to connect until
// a) success, or
// b) need to requery dns
int keep_trying_to_connect (create_connection_ctx_t *ctx,
backoff_timer_t *backoff_timer)
{
int rtn;
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 ..
if (rtn == CONN_WAIT_RETRY_DNS)
return false; //find_server again
// else retry
}
}
//--------------------------------------------------------------------
/**
* @brief createNopollConnection interface to create WebSocket client connections.
*Loads the WebPA config file and creates the intial connection and manages the connection wait, close mechanisms.
*/
int createNopollConnection(noPollCtx *ctx)
{
create_connection_ctx_t conn_ctx;
int max_retry_count;
int query_dns_status;
struct timespec connect_time,*connectTimePtr;
connectTimePtr = &connect_time;
backoff_timer_t backoff_timer;
if(ctx == NULL) {
bool initial_retry = false;
int backoffRetryTime = 0;
int max_retry_sleep;
char port[8];
char server_Address[256];
char redirectURL[128]={'\0'};
int status=0;
int allow_insecure;
int connErr=0;
struct timespec connErr_start,connErr_end,*connErr_startPtr,*connErr_endPtr;
connErr_startPtr = &connErr_start;
connErr_endPtr = &connErr_end;
//Retry Backoff count shall start at c=2 & calculate 2^c - 1.
int c=2;
char *conveyHeader = NULL;
char device_id[32]={'\0'};
char user_agent[512]={'\0'};
char * extra_headers = NULL;
if(ctx == NULL) {
return nopoll_false;
}
}
ParodusPrint("BootTime In sec: %d\n", get_parodus_cfg()->boot_time);
ParodusInfo("Received reboot_reason as:%s\n", get_parodus_cfg()->hw_last_reboot_reason);
ParodusInfo("Received reconnect_reason as:%s\n", reconnect_reason);
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_server_list_null (&conn_ctx.server_list);
init_backoff_timer (&backoff_timer, max_retry_count);
while (!g_shutdown)
{
query_dns_status = find_servers (&conn_ctx.server_list);
if (query_dns_status == FIND_INVALID_DEFAULT)
return nopoll_false;
set_current_server (&conn_ctx);
if (keep_trying_to_connect (&conn_ctx, &backoff_timer))
break;
// retry dns query
// If close_retry is reset due to interface down event, stop retry
// and wait till close_retry is set again.
if(!get_close_retry() && get_interface_down_event()) {
pthread_mutex_lock(get_global_close_retry_mut());
pthread_cond_wait(get_global_close_retry_con(), get_global_close_retry_mut());
pthread_mutex_unlock (get_global_close_retry_mut());
//&conn_ctx.header_info->conveyHeader = getWebpaConveyHeader();
}
allow_insecure = parse_webpa_url (get_parodus_cfg()->webpa_url,
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
if (allow_insecure < 0)
return nopoll_false; // must have valid default url
#ifdef FEATURE_DNS_QUERY
if (get_parodus_cfg()->acquire_jwt) {
//query dns and validate JWT
int jwt_insecure = allow_insecure_conn(
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
if (jwt_insecure >= 0)
allow_insecure = jwt_insecure;
}
if(conn_ctx.current_server->allow_insecure <= 0)
#endif
ParodusInfo("server_Address %s\n",server_Address);
ParodusInfo("port %s\n", port);
max_retry_sleep = (int) get_parodus_cfg()->webpa_backoff_max;
ParodusPrint("max_retry_sleep is %d\n", max_retry_sleep );
snprintf(user_agent, sizeof(user_agent),"%s (%s; %s/%s;)",
((0 != strlen(get_parodus_cfg()->webpa_protocol)) ? get_parodus_cfg()->webpa_protocol : "unknown"),
((0 != strlen(get_parodus_cfg()->fw_name)) ? get_parodus_cfg()->fw_name : "unknown"),
((0 != strlen(get_parodus_cfg()->hw_model)) ? get_parodus_cfg()->hw_model : "unknown"),
((0 != strlen(get_parodus_cfg()->hw_manufacturer)) ? get_parodus_cfg()->hw_manufacturer : "unknown"));
ParodusInfo("User-Agent: %s\n",user_agent);
conveyHeader = getWebpaConveyHeader();
parStrncpy(deviceMAC, get_parodus_cfg()->hw_mac,sizeof(deviceMAC));
snprintf(device_id, sizeof(device_id), "mac:%s", deviceMAC);
ParodusInfo("Device_id %s\n",device_id);
extra_headers = build_extra_headers(
((0 < strlen(get_parodus_cfg()->webpa_auth_token)) ? get_parodus_cfg()->webpa_auth_token : NULL),
device_id, user_agent, conveyHeader );
do
{
//calculate backoffRetryTime and to perform exponential increment during retry
if(backoffRetryTime < max_retry_sleep)
{
backoffRetryTime = (int) pow(2, c) -1;
}
ParodusPrint("New backoffRetryTime value calculated as %d seconds\n", backoffRetryTime);
noPollConn *connection;
if(allow_insecure <= 0)
{
ParodusPrint("secure true\n");
connection = nopoll_tls_common_conn(ctx,server_Address, port, extra_headers);
}
else
{
ParodusPrint("secure false\n");
noPollConnOpts * opts;
opts = createConnOpts(extra_headers, false);
connection = nopoll_conn_new_opts (ctx, opts,server_Address,port,NULL,get_parodus_cfg()->webpa_path_url,NULL,NULL);// WEBPA-787
}
set_global_conn(connection);
if(get_global_conn() != NULL)
{
if(!nopoll_conn_is_ok(get_global_conn()))
{
ParodusError("Error connecting to server\n");
ParodusError("RDK-10037 - WebPA Connection Lost\n");
// Copy the server address from config to avoid retrying to the same failing talaria redirected node
allow_insecure = parse_webpa_url (get_parodus_cfg()->webpa_url,
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
close_and_unref_connection(get_global_conn());
set_global_conn(NULL);
initial_retry = true;
ParodusInfo("Waiting with backoffRetryTime %d seconds\n", backoffRetryTime);
sleep(backoffRetryTime);
continue;
}
else
{
ParodusPrint("Connected to Server but not yet ready\n");
initial_retry = false;
//reset backoffRetryTime back to the starting value, as next reason can be different
c = 2;
backoffRetryTime = (int) pow(2, c) -1;
}
if(!nopoll_conn_wait_until_connection_ready(get_global_conn(), 10, &status, redirectURL))
{
if(status == 307 || status == 302 || status == 303) // only when there is a http redirect
{
char *redirect_ptr = redirectURL;
ParodusError("Received temporary redirection response message %s\n", redirectURL);
// Extract server Address and port from the redirectURL
if (strncmp (redirect_ptr, "Redirect:", 9) == 0)
redirect_ptr += 9;
allow_insecure = parse_webpa_url (redirect_ptr,
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
if (allow_insecure < 0) {
ParodusError ("Invalid redirectURL\n");
allow_insecure = parse_webpa_url (get_parodus_cfg()->webpa_url,
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
} else
ParodusInfo("Trying to Connect to new Redirected server : %s with port : %s\n", server_Address, port);
//reset c=2 to start backoffRetryTime as retrying using new redirect server
c = 2;
}
else if(status == 403)
{
ParodusError("Received Unauthorized response with status: %d\n", status);
//Get new token and update auth header
if (strlen(get_parodus_cfg()->token_acquisition_script) >0) {
createNewAuthToken(get_parodus_cfg()->webpa_auth_token,sizeof(get_parodus_cfg()->webpa_auth_token));
}
extra_headers = build_extra_headers( (0 < strlen(get_parodus_cfg()->webpa_auth_token) ? get_parodus_cfg()->webpa_auth_token : NULL),
device_id, user_agent, conveyHeader );
//reset c=2 to start backoffRetryTime as retrying
c = 2;
}
else
{
ParodusError("Client connection timeout\n");
ParodusError("RDK-10037 - WebPA Connection Lost\n");
// Copy the server address and port from config to avoid retrying to the same failing talaria redirected node
allow_insecure = parse_webpa_url (get_parodus_cfg()->webpa_url,
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
ParodusInfo("Waiting with backoffRetryTime %d seconds\n", backoffRetryTime);
sleep(backoffRetryTime);
c++;
}
//reset httpStatus before next retry
ParodusPrint("reset httpStatus from server before next retry\n");
status = 0;
close_and_unref_connection(get_global_conn());
set_global_conn(NULL);
initial_retry = true;
}
else
{
initial_retry = false;
ParodusInfo("Connection is ready\n");
}
}
else
{
/* If the connect error is due to DNS resolving to 10.0.0.1 then start timer.
* Timeout after 15 minutes if the error repeats continuously and kill itself.
*/
if((checkHostIp(server_Address) == -2))
{
if(connErr == 0)
{
getCurrentTime(connErr_startPtr);
connErr = 1;
ParodusInfo("First connect error occurred, initialized the connect error timer\n");
}
else
{
getCurrentTime(connErr_endPtr);
ParodusPrint("checking timeout difference:%ld\n", timeValDiff(connErr_startPtr, connErr_endPtr));
if(timeValDiff(connErr_startPtr, connErr_endPtr) >= (15*60*1000))
{
ParodusError("WebPA unable to connect due to DNS resolving to 10.0.0.1 for over 15 minutes; crashing service.\n");
reconnect_reason = "Dns_Res_webpa_reconnect";
LastReasonStatus = true;
kill(getpid(),SIGTERM);
}
}
}
initial_retry = true;
ParodusInfo("Waiting with backoffRetryTime %d seconds\n", backoffRetryTime);
sleep(backoffRetryTime);
c++;
// Copy the server address and port from config to avoid retrying to the same failing talaria redirected node
allow_insecure = parse_webpa_url (get_parodus_cfg()->webpa_url,
server_Address, (int) sizeof(server_Address),
port, (int) sizeof(port));
}
}while(initial_retry);
if(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) {
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);
free_header_info (&conn_ctx.header_info);
free_server_list (&conn_ctx.server_list);
// Reset close_retry flag and heartbeatTimer once the connection retry is successful
ParodusPrint("createNopollConnection(): reset_close_retry\n");
reset_close_retry();
reset_heartBeatTimer();
set_global_reconnect_reason("webpa_process_starts");
set_global_reconnect_status(false);
ParodusPrint("createNopollConnection(): close_mut lock\n");
pthread_mutex_lock (&close_mut);
close_retry = false;
pthread_mutex_unlock (&close_mut);
ParodusPrint("createNopollConnection(): close_mut unlock\n");
heartBeatTimer = 0;
// Reset connErr flag on successful connection
connErr = 0;
reconnect_reason = "webpa_process_starts";
LastReasonStatus =false;
ParodusPrint("LastReasonStatus reset after successful connection\n");
setMessageHandlers();
return nopoll_true;
}
}
/* Build the extra headers string with any/all conditional logic in one place. */
static char* build_extra_headers( const char *auth, const char *device_id,
@@ -646,24 +337,44 @@ static char* build_extra_headers( const char *auth, const char *device_id,
(NULL != convey) ? convey : "" );
}
static noPollConn * nopoll_tls_common_conn (noPollCtx * ctx,char * serverAddr,char *serverPort,char * extra_headers)
{
unsigned int flags = 0;
noPollConnOpts * opts;
noPollConn *connection = NULL;
opts = createConnOpts(extra_headers, true);
flags = get_parodus_cfg()->flags;
if( FLAGS_IPV4_ONLY == (FLAGS_IPV4_ONLY & flags) ) {
ParodusInfo("Connecting in Ipv4 mode\n");
connection = nopoll_conn_tls_new (ctx, opts,serverAddr,serverPort,NULL,get_parodus_cfg()->webpa_path_url,NULL,NULL);
} else if( FLAGS_IPV6_ONLY == (FLAGS_IPV6_ONLY & flags) ) {
ParodusInfo("Connecting in Ipv6 mode\n");
connection = nopoll_conn_tls_new6 (ctx, opts,serverAddr,serverPort,NULL,get_parodus_cfg()->webpa_path_url,NULL,NULL);
} else {
ParodusInfo("Try connecting with Ipv6 mode\n");
connection = nopoll_conn_tls_new6 (ctx, opts,serverAddr,serverPort,NULL,get_parodus_cfg()->webpa_path_url,NULL,NULL);
if(connection == NULL)
{
ParodusInfo("Ipv6 connection failed. Try connecting with Ipv4 mode \n");
opts = createConnOpts(extra_headers, true);
connection = nopoll_conn_tls_new (ctx, opts,serverAddr,serverPort,NULL,get_parodus_cfg()->webpa_path_url,NULL,NULL);
}
}
return connection;
}
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);
@@ -684,38 +395,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

@@ -34,6 +34,9 @@ extern "C" {
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
extern bool close_retry;
extern volatile unsigned int heartBeatTimer;
extern pthread_mutex_t close_mut;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
@@ -52,18 +55,6 @@ void set_global_conn(noPollConn *);
char *get_global_reconnect_reason();
void set_global_reconnect_reason(char *reason);
bool get_global_reconnect_status();
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

@@ -1,187 +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 crud_interface.c
*
* @description This file is used to manage incoming and outgoing CRUD messages.
*
*/
#include "ParodusInternal.h"
#include "crud_tasks.h"
#include "crud_interface.h"
#include "upstream.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Internal variables */
/*----------------------------------------------------------------------------*/
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;
crudMessage = (CrudMsg *)malloc(sizeof(CrudMsg));
if(crudMessage && crudMsg!=NULL)
{
crudMessage->msg = crudMsg;
crudMessage->next = NULL;
ParodusPrint("Inside addCRUDmsgToQueue : mutex lock in producer \n");
pthread_mutex_lock(&crud_mut);
if(crudMsgQ ==NULL)
{
crudMsgQ = crudMessage;
ParodusPrint("Producer added message\n");
pthread_cond_signal(&crud_con);
pthread_mutex_unlock(&crud_mut);
ParodusPrint("Inside addCRUDmsgToQueue : mutex unlock in producer \n");
}
else
{
CrudMsg *temp = crudMsgQ;
while(temp->next)
{
temp = temp->next;
}
temp->next = crudMessage;
pthread_mutex_unlock(&crud_mut);
}
}
else
{
ParodusError("Memory allocation failed for CRUD\n");
}
}
void *CRUDHandlerTask()
{
int ret = 0;
ssize_t resp_size = 0;
void *resp_bytes;
wrp_msg_t *crud_response = NULL;
while(FOREVER())
{
pthread_mutex_lock(&crud_mut);
ParodusPrint("Mutex lock in CRUD consumer thread\n");
if(crudMsgQ !=NULL)
{
CrudMsg *message = crudMsgQ;
crudMsgQ = crudMsgQ->next;
pthread_mutex_unlock(&crud_mut);
ParodusPrint("Mutex unlock in CRUD consumer thread\n");
ret = processCrudRequest(message->msg, &crud_response);
wrp_free_struct(message->msg);
free(message);
message = NULL;
if(ret == 0)
{
ParodusInfo("CRUD processed successfully\n");
}
else
{
ParodusError("Failure in CRUD request processing !!\n");
}
ParodusPrint("msgpack encode to send to upstream\n");
resp_size = wrp_struct_to( crud_response, WRP_BYTES, &resp_bytes );
ParodusPrint("Encoded CRUD resp_size :%lu\n", resp_size);
ParodusPrint("Adding CRUD response to upstreamQ\n");
addCRUDresponseToUpstreamQ(resp_bytes, resp_size);
wrp_free_struct(crud_response);
}
else
{
if (g_shutdown) {
pthread_mutex_unlock (&crud_mut);
break;
}
pthread_cond_wait(&crud_con, &crud_mut);
pthread_mutex_unlock (&crud_mut);
}
}
return 0;
}
//CRUD Producer adds the response into common UpStreamQ
void addCRUDresponseToUpstreamQ(void *response_bytes, ssize_t response_size)
{
UpStreamMsg *response;
response = (UpStreamMsg *)malloc(sizeof(UpStreamMsg));
if(response)
{
response->msg =(void *)response_bytes;
response->len =(int)response_size;
response->next=NULL;
pthread_mutex_lock (get_global_nano_mut());
ParodusPrint("Mutex lock in CRUD response producer\n");
if(get_global_UpStreamMsgQ() == NULL)
{
set_global_UpStreamMsgQ(response);
ParodusPrint("Producer added CRUD response to UpStreamQ\n");
pthread_cond_signal(get_global_nano_con());
pthread_mutex_unlock (get_global_nano_mut());
ParodusPrint("mutex unlock in CRUD response producer\n");
}
else
{
ParodusPrint("Producer adding CRUD response to UpStreamQ\n");
UpStreamMsg *temp = get_global_UpStreamMsgQ();
while(temp->next)
{
temp = temp->next;
}
temp->next = response;
pthread_mutex_unlock (get_global_nano_mut());
}
}
else
{
ParodusError("failure in allocation for CRUD response\n");
}
}

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 crud_interface.h
*
* @description This header defines functions required to manage CRUD messages.
*
*/
#ifndef _CRUD_INTERFACE_H_
#define _CRUD_INTERFACE_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
typedef struct CrudMsg__
{
wrp_msg_t *msg;
struct CrudMsg__ *next;
} CrudMsg;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
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
}
#endif
#endif /* _CRUD_INTERFACE_H_ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +0,0 @@
/**
* Copyright 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 <wrp-c.h>
#include <stdlib.h>
int createObject( wrp_msg_t *reqMsg, wrp_msg_t **response );
int retrieveObject( wrp_msg_t *reqMsg, wrp_msg_t **response);
int updateObject( wrp_msg_t *reqMsg, wrp_msg_t **response);
int deleteObject(wrp_msg_t *reqMsg, wrp_msg_t **response);
int writeToJSON(char *data);
int readFromJSON(char **data);
int retrieveFromMemory(char *keyName, cJSON **jsonresponse);

View File

@@ -1,109 +0,0 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cJSON.h>
#include <wrp-c.h>
#include "crud_tasks.h"
#include "crud_internal.h"
int processCrudRequest( wrp_msg_t *reqMsg, wrp_msg_t **responseMsg)
{
wrp_msg_t *resp_msg = NULL;
int ret = -1;
resp_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg->msg_type = reqMsg->msg_type;
resp_msg->u.crud.transaction_uuid = strdup(reqMsg->u.crud.transaction_uuid);
resp_msg->u.crud.source = strdup(reqMsg->u.crud.dest);
resp_msg->u.crud.dest = strdup(reqMsg->u.crud.source);
switch( reqMsg->msg_type )
{
case WRP_MSG_TYPE__CREATE:
ParodusInfo( "CREATE request\n" );
ret = createObject( reqMsg, &resp_msg );
if(ret != 0)
{
ParodusError("Failed to create object in config JSON\n");
//WRP payload is NULL for failure cases
resp_msg ->u.crud.payload = NULL;
resp_msg ->u.crud.payload_size = 0;
*responseMsg = resp_msg;
return -1;
}
*responseMsg = resp_msg;
break;
case WRP_MSG_TYPE__RETREIVE:
ParodusInfo( "RETREIVE request\n" );
ret = retrieveObject( reqMsg, &resp_msg );
if(ret != 0)
{
ParodusError("Failed to retrieve object \n");
//WRP payload is NULL for failure cases
resp_msg ->u.crud.payload = NULL;
resp_msg ->u.crud.payload_size = 0;
*responseMsg = resp_msg;
return -1;
}
*responseMsg = resp_msg;
break;
case WRP_MSG_TYPE__UPDATE:
ParodusInfo( "UPDATE request\n" );
ret = updateObject( reqMsg, &resp_msg );
if(ret ==0)
{
//WRP payload is NULL for update requests
resp_msg ->u.crud.payload = NULL;
resp_msg ->u.crud.payload_size = 0;
}
else
{
ParodusError("Failed to update object \n");
*responseMsg = resp_msg;
return -1;
}
*responseMsg = resp_msg;
break;
case WRP_MSG_TYPE__DELETE:
ParodusInfo( "DELETE request\n" );
ret = deleteObject(reqMsg, &resp_msg );
if(ret == 0)
{
//WRP payload is NULL for delete requests
resp_msg ->u.crud.payload = NULL;
resp_msg ->u.crud.payload_size = 0;
}
else
{
ParodusError("Failed to delete object \n");
*responseMsg = resp_msg;
return -1;
}
*responseMsg = resp_msg;
break;
default:
ParodusInfo( "Unknown msgType for CRUD request\n" );
*responseMsg = resp_msg;
break;
}
return 0;
}

View File

@@ -1,31 +0,0 @@
/**
* Copyright 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 <wrp-c.h>
#include "ParodusInternal.h"
/**
* @brief processCrudRequest function to process CRUD operations.
*
* @note processCrudRequest function allocates memory for response,
* caller needs to free the response (resMsg) in both success and failure case.
* @param[in] decoded request in wrp_msg_t structure format
* @param[out] resulting wrp_msg_t structure as a response
* @return 0 in success case and -1 in error case
*/
int processCrudRequest(wrp_msg_t * reqMsg, wrp_msg_t **resMsg);

View File

@@ -26,11 +26,7 @@
#include "connection.h"
#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 +41,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;
@@ -98,35 +93,15 @@ void listenerOnMessage(void * msg, size_t msgSize)
cJSON_AddStringToObject(response, "message", "Invalid partner_id");
}
destVal = strdup(((WRP_MSG_TYPE__EVENT == msgType) ? message->u.event.dest :
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.dest : message->u.crud.dest)));
destVal = ((WRP_MSG_TYPE__EVENT == msgType) ? message->u.event.dest :
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.dest : message->u.crud.dest));
if( (destVal != NULL) && (ret >= 0) )
{
char *newDest = NULL;
char *tempDest = strtok(destVal , "/");
if(tempDest != NULL)
{
newDest = strtok(NULL , "/");
}
if(newDest != NULL)
{
parStrncpy(dest,newDest, sizeof(dest));
}
else
{
parStrncpy(dest,destVal, sizeof(dest));
}
strtok(destVal , "/");
parStrncpy(dest,strtok(NULL , "/"), sizeof(dest));
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();
//Checking for individual clients & Sending to each client
@@ -146,28 +121,8 @@ 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)
{
ParodusPrint("Received CRUD request : dest : %s\n", dest);
if ((message->u.crud.source == NULL) || (message->u.crud.transaction_uuid == NULL))
{
ParodusError("Invalid request\n");
response = cJSON_CreateObject();
cJSON_AddNumberToObject(response, "statusCode", 400);
cJSON_AddStringToObject(response, "message", "Invalid Request");
ret = -1;
}
else
{
createNewMsgForCRUD(message, &crudMessage);
addCRUDmsgToQueue(crudMessage);
}
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);
@@ -192,15 +147,8 @@ 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";
}
resp_msg ->u.crud.source = message->u.crud.dest;
resp_msg ->u.crud.dest = message->u.crud.source;
resp_msg ->u.crud.transaction_uuid = message->u.crud.transaction_uuid;
resp_msg ->u.crud.path = message->u.crud.path;
}
@@ -234,6 +182,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;
}
@@ -244,9 +194,6 @@ void listenerOnMessage(void * msg, size_t msgSize)
default:
break;
}
ParodusPrint("free for downstream decoded msg\n");
wrp_free_struct(message);
message = NULL;
}
else
{
@@ -254,116 +201,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

@@ -1,77 +0,0 @@
/**
* Copyright 2018 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 heartBeat.c
*
* @description This decribes functions required to manage heartBeatTimer.
*
*/
#include "heartBeat.h"
#include <stdbool.h>
volatile unsigned int heartBeatTimer = 0;
volatile bool paused = false;
pthread_mutex_t heartBeat_mut=PTHREAD_MUTEX_INITIALIZER;
// Get value of heartBeatTimer
unsigned int get_heartBeatTimer()
{
unsigned int tmp = 0;
pthread_mutex_lock (&heartBeat_mut);
tmp = heartBeatTimer;
pthread_mutex_unlock (&heartBeat_mut);
return tmp;
}
// Reset value of heartBeatTimer to 0
void reset_heartBeatTimer()
{
pthread_mutex_lock (&heartBeat_mut);
heartBeatTimer = 0;
pthread_mutex_unlock (&heartBeat_mut);
}
// Increment value of heartBeatTimer to desired value
void increment_heartBeatTimer(unsigned int inc_time_ms)
{
pthread_mutex_lock (&heartBeat_mut);
if (!paused)
heartBeatTimer += inc_time_ms;
pthread_mutex_unlock (&heartBeat_mut);
}
// Pause heartBeatTimer, i.e. stop incrementing
void pause_heartBeatTimer()
{
pthread_mutex_lock (&heartBeat_mut);
heartBeatTimer = 0;
paused = true;
pthread_mutex_unlock (&heartBeat_mut);
}
// Resume heartBeatTimer, i.e. resume incrementing
void resume_heartBeatTimer()
{
pthread_mutex_lock (&heartBeat_mut);
paused = false;
pthread_mutex_unlock (&heartBeat_mut);
}

View File

@@ -1,52 +0,0 @@
/**
* Copyright 2018 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 heartBeat.h
*
* @description This decribes functions required to manage heartBeatTimer.
*
*/
#ifndef _HEARBEAT_H_
#define _HEARBEAT_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
// Get value of heartBeatTimer
unsigned int get_heartBeatTimer();
// Reset value of heartBeatTimer to 0
void reset_heartBeatTimer();
// Increment value of heartBeatTimer to desired value
void increment_heartBeatTimer(unsigned int inc_time_ms);
// Pause heartBeatTimer, i.e. stop incrementing
void pause_heartBeatTimer();
// Resume heartBeatTimer, i.e. resume incrementing
void resume_heartBeatTimer();
#ifdef __cplusplus
}
#endif
#endif

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);
@@ -105,7 +103,7 @@ static void sig_handler(int sig)
{
signal(SIGINT, sig_handler); /* reset it to this function */
ParodusInfo("SIGINT received!\n");
shutdownSocketConnection();
exit(0);
}
else if ( sig == SIGUSR1 )
{
@@ -134,7 +132,7 @@ static void sig_handler(int sig)
else
{
ParodusInfo("Signal %d received!\n", sig);
shutdownSocketConnection();
exit(0);
}
}

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

@@ -24,8 +24,6 @@
#include "ParodusInternal.h"
#include "nopoll_handlers.h"
#include "connection.h"
#include "heartBeat.h"
#include "close_retry.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -38,7 +36,6 @@
pthread_mutex_t g_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond=PTHREAD_COND_INITIALIZER;
ParodusMsg *ParodusMsgQ = NULL;
noPollMsg * previous_msg = NULL;
/*----------------------------------------------------------------------------*/
/* External Functions */
@@ -57,43 +54,18 @@ void listenerOnMessage_queue(noPollCtx * ctx, noPollConn * conn, noPollMsg * msg
UNUSED(ctx);
UNUSED(conn);
UNUSED(user_data);
noPollMsg * aux;
if (nopoll_msg_is_fragment (msg))
{
ParodusInfo("Found fragment, FIN = %d \n", nopoll_msg_is_final (msg));
aux = previous_msg;
previous_msg = nopoll_msg_join (previous_msg, msg);
nopoll_msg_unref (aux);
if (! nopoll_msg_is_final (msg)) {
ParodusInfo ("Found fragment that is not final..\n");
return;
}
ParodusInfo("Found final fragment *** \n");
}
ParodusMsg *message;
message = (ParodusMsg *)malloc(sizeof(ParodusMsg));
if(message)
{
if(previous_msg)
{
message->msg = previous_msg;
message->payload = (void *)nopoll_msg_get_payload (previous_msg);
message->len = nopoll_msg_get_payload_size (previous_msg);
message->next = NULL;
}
else
{
message->msg = msg;
message->payload = (void *)nopoll_msg_get_payload (msg);
message->len = nopoll_msg_get_payload_size (msg);
message->next = NULL;
message->msg = msg;
message->payload = (void *)nopoll_msg_get_payload (msg);
message->len = nopoll_msg_get_payload_size (msg);
message->next = NULL;
nopoll_msg_ref(msg);
}
pthread_mutex_lock (&g_mutex);
ParodusPrint("mutex lock in producer thread\n");
@@ -122,7 +94,6 @@ void listenerOnMessage_queue(noPollCtx * ctx, noPollConn * conn, noPollMsg * msg
//Memory allocation failed
ParodusError("Memory allocation is failed\n");
}
previous_msg = NULL;
ParodusPrint("*****Returned from listenerOnMessage_queue*****\n");
}
@@ -138,7 +109,6 @@ void listenerOnPingMessage (noPollCtx * ctx, noPollConn * conn, noPollMsg * msg,
{
UNUSED(ctx);
UNUSED(user_data);
UNUSED(conn);
noPollPtr payload = NULL;
payload = (noPollPtr ) nopoll_msg_get_payload(msg);
@@ -148,7 +118,9 @@ void listenerOnPingMessage (noPollCtx * ctx, noPollConn * conn, noPollMsg * msg,
ParodusInfo("Ping received with payload %s, opcode %d\n",(char *)payload, nopoll_msg_opcode(msg));
if (nopoll_msg_opcode(msg) == NOPOLL_PING_FRAME)
{
reset_heartBeatTimer();
nopoll_conn_send_frame (conn, nopoll_true, nopoll_true, NOPOLL_PONG_FRAME, strlen(payload), payload, 0);
heartBeatTimer = 0;
ParodusPrint("Sent Pong frame and reset HeartBeat Timer\n");
}
}
}
@@ -157,35 +129,24 @@ void listenerOnCloseMessage (noPollCtx * ctx, noPollConn * conn, noPollPtr user_
{
UNUSED(ctx);
UNUSED(conn);
UNUSED(user_data);
int closeStatus;
char * defaultReason = "SSL_Socket_Close";
ParodusPrint("listenerOnCloseMessage(): mutex lock in producer thread\n");
closeStatus = nopoll_conn_get_close_status (conn);
if( closeStatus == 1006 && !get_global_reconnect_status())
if((user_data != NULL) && (strstr(user_data, "SSL_Socket_Close") != NULL) && !LastReasonStatus)
{
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);
ParodusInfo("Reconnect detected, setting Reconnect reason as Server close\n");
set_global_reconnect_reason("Server_closed_connection");
LastReasonStatus = true;
}
else if(!get_global_reconnect_status())
else if ((user_data == NULL) && !LastReasonStatus)
{
ParodusInfo("Reconnect detected, setting Reconnect reason as Unknown\n");
OnboardLog("Reconnect detected, setting Reconnect reason as Unknown\n");
set_global_reconnect_reason("Unknown");
}
if(!get_interface_down_event())
{
ParodusInfo("Setting the close and retry connection\n");
set_close_retry();
}
else
ParodusInfo("Not Setting the close and retry connection as interface is down\n");
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
ParodusPrint("listenerOnCloseMessage(): mutex unlock in producer thread\n");
}

View File

@@ -36,6 +36,9 @@ extern "C" {
extern pthread_mutex_t g_mutex;
extern pthread_cond_t g_cond;
extern pthread_mutex_t close_mut;
extern volatile unsigned int heartBeatTimer;
extern bool close_retry;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */

View File

@@ -25,7 +25,6 @@
#include "connection.h"
#include "nopoll_helpers.h"
#include "nopoll_handlers.h"
#include "time.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -34,10 +33,6 @@
#define MAX_SEND_SIZE (60 * 1024)
#define FLUSH_WAIT_TIME (2000000LL)
struct timespec connStuck_start,connStuck_end;
struct timespec *connStuck_startPtr = &connStuck_start;
struct timespec *connStuck_endPtr = &connStuck_end;
/*----------------------------------------------------------------------------*/
/* External functions */
/*----------------------------------------------------------------------------*/
@@ -54,11 +49,8 @@ void setMessageHandlers()
void sendMessage(noPollConn *conn, void *msg, size_t len)
{
int bytesWritten = 0;
static int connErr=0;
long timeDiff = 0;
ParodusInfo("sendMessage length %zu\n", len);
if(nopoll_conn_is_ok(conn) && nopoll_conn_is_ready(conn))
{
//bytesWritten = nopoll_conn_send_binary(conn, msg, len);
@@ -68,40 +60,10 @@ void sendMessage(noPollConn *conn, void *msg, size_t len)
{
ParodusError("Failed to send bytes %zu, bytes written were=%d (errno=%d, %s)..\n", len, bytesWritten, errno, strerror(errno));
}
connErr = 0;
}
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(get_interface_down_event())
{
ParodusError("Unable to connect to server since interface is down\n");
}
else
{
if (connErr == 0)
{
getCurrentTime(connStuck_startPtr);
ParodusInfo("Conn got stuck, initialized the first timer\n");
connErr = 1;
}
else
{
getCurrentTime(connStuck_endPtr);
timeDiff = timeValDiff(connStuck_startPtr, connStuck_endPtr);
ParodusPrint("checking timeout difference:%ld\n", timeDiff);
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);
}
}
}
ParodusError("Failed to send msg upstream as connection is not OK\n");
}
}
@@ -159,7 +121,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

@@ -93,18 +93,13 @@ int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
for(j = 0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j]) {
ParodusPrint("partnersList->partner_ids[%lu] = %s\n",j, partnersList->partner_ids[j]);
ParodusPrint("msg->u.event.partner_ids->partner_ids[%lu] = %s\n",i, msg->u.event.partner_ids->partner_ids[i]);
if(strcasecmp(partnersList->partner_ids[j], msg->u.event.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
else
ParodusError("partner Id in partnersList is NULL but count is not 0");
ParodusPrint("partnersList->partner_ids[%lu] = %s\n",j, partnersList->partner_ids[j]);
if(strcmp(partnersList->partner_ids[j], msg->u.event.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
/* Commandline input partner_ids matched with partner_ids from request */
if(matchFlag == 1)
@@ -158,19 +153,13 @@ int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
for(j = 0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
{
ParodusPrint("partnersList->partner_ids[%lu] = %s\n",j, partnersList->partner_ids[j]);
ParodusPrint("msg->u.req.partner_ids->partner_ids[%lu] = %s\n",i, msg->u.req.partner_ids->partner_ids[i]);
if(strcasecmp(partnersList->partner_ids[j], msg->u.req.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
else
ParodusError("partner Id in partnersList is NULL but count is not 0");
ParodusPrint("partnersList->partner_ids[%lu] = %s\n",j, partnersList->partner_ids[j]);
if(strcmp(partnersList->partner_ids[j], msg->u.req.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
}
@@ -178,12 +167,11 @@ 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++)
{
if(NULL != partnersList->partner_ids[j])
if(partnersList->partner_ids[j] != NULL)
{
free(partnersList->partner_ids[j]);
}
@@ -203,7 +191,7 @@ int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
for(j=0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
if(partnersList->partner_ids[j] != NULL)
{
free(partnersList->partner_ids[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

@@ -111,7 +111,8 @@ static void show_times (time_t exp_time, time_t cur_time)
}
// returns 1 if insecure, 0 if secure, < 0 if error
int analyze_jwt (const cjwt_t *jwt, char **url_buf, unsigned int *port)
int analyze_jwt (const cjwt_t *jwt, char *url_buf, int url_buflen,
char *port_buf, int port_buflen)
{
cJSON *claims = jwt->private_claims;
cJSON *endpoint = NULL;
@@ -139,15 +140,13 @@ 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;
}
}
http_match = parse_webpa_url (endpoint->valuestring,
url_buf, port);
url_buf, url_buflen, port_buf, port_buflen);
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);
@@ -186,7 +185,7 @@ int nquery(const char* dns_txt_record_id, u_char *nsbuf)
ParodusError ("nquery: nsbuf is NULL\n");
return (-1);
}
statp.options = RES_DEBUG;
statp.options |= RES_DEBUG;
if (__res_ninit(&statp) < 0) {
ParodusError ("res_ninit error: can't initialize statp.\n");
return (-1);
@@ -234,10 +233,11 @@ static bool is_digit (char c)
// strip quotes and newlines from rr rec
const char *strip_rr_data (const char *rr_ptr, int *rrlen)
{
int len = *rrlen;
int len;
const char *optr = rr_ptr;
char c;
len = strlen (optr);
if (len > 0) {
c = optr[0];
if (!is_digit(c)) {
@@ -338,7 +338,6 @@ int get_rr_seq_table (ns_msg *msg_handle, int num_rr_recs, rr_rec_t *seq_table)
continue;
++num_txt_recs;
rr_ptr = (const char *)ns_rr_rdata(rr);
rrlen = ns_rr_rdlen(rr);
ParodusPrint ("Found rr rec type %d: %s\n", ns_t_txt, rr_ptr);
rr_ptr = strip_rr_data (rr_ptr, &rrlen);
seq_pos = find_seq_num (rr_ptr, rrlen);
@@ -430,10 +429,8 @@ int query_dns(const char* dns_txt_record_id,char *jwt_ans)
ParodusError ("Unable to allocate nsbuf in query_dns\n");
return TOKEN_ERR_MEMORY_FAIL;
}
l = nquery(dns_txt_record_id,nsbuf);
if (l < 0) {
ParodusError("nquery returns error: l value is %d\n", l);
free (nsbuf);
return l;
}
@@ -475,7 +472,8 @@ static void get_dns_txt_record_id (char *buf)
}
#endif
int allow_insecure_conn(char **server_addr, unsigned int *port)
int allow_insecure_conn(char *url_buf, int url_buflen,
char *port_buf, int port_buflen)
{
#ifdef FEATURE_DNS_QUERY
int insecure=0, ret = -1;
@@ -493,18 +491,15 @@ int allow_insecure_conn(char **server_addr, unsigned int *port)
get_dns_txt_record_id (dns_txt_record_id);
ret = query_dns(dns_txt_record_id, jwt_token);
ParodusPrint("query_dns returns %d\n", ret);
if(ret){
ParodusError("Failed in DNS query\n");
if (ret == TOKEN_ERR_MEMORY_FAIL){
if (ret == TOKEN_ERR_MEMORY_FAIL) {
insecure = ret;
}
else{
} else {
insecure = TOKEN_ERR_QUERY_DNS_FAIL;
}
goto end;
}
//Decoding the jwt token
key = get_parodus_cfg()->jwt_key;
ret = cjwt_decode( jwt_token, 0, &jwt, ( const uint8_t * )key,strlen(key) );
@@ -523,15 +518,13 @@ int allow_insecure_conn(char **server_addr, unsigned int *port)
//validate algo from --jwt_algo
if( validate_algo(jwt) ) {
insecure = analyze_jwt (jwt, server_addr, port);
insecure = analyze_jwt (jwt, url_buf, url_buflen, port_buf, port_buflen);
} else {
insecure = TOKEN_ERR_ALGO_NOT_ALLOWED;
}
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);
@@ -539,8 +532,10 @@ end:
if (NULL != jwt_token)
free (jwt_token);
#else
(void) server_addr;
(void) port;
(void) url_buf;
(void) url_buflen;
(void) port_buf;
(void) port_buflen;
int insecure = TOKEN_NO_DNS_QUERY;
#endif
ParodusPrint ("Allow Insecure %d\n", insecure);

View File

@@ -78,13 +78,15 @@ Yes Yes http True Default
* query the dns server, obtain a jwt, determine if insecure
* connections can be allowed.
*
* @param server_addr ptr to buffer ptr containing endpoint value found in JWT
* will be NULL if invalid, otherwise needs to be freed
* @param port ptr to variable receiving the port number
* @param url_buf buffer containing endpoint value found in JWT
* @param url_buflen len of the url buffer provided by caller
* @param port_buf buffer containing port value found in JWT
* @param port_buflen len of the port buffer provided by caller
* @return 1 if insecure connection is allowed, 0 if not,
* or one of the error codes given above.
*/
int allow_insecure_conn (char **server_addr, unsigned int *port);
int allow_insecure_conn(char *url_buf, int url_buflen,
char *port_buf, int port_buflen);
#endif

View File

@@ -28,13 +28,12 @@
#include "connection.h"
#include "client_list.h"
#include "nopoll_helpers.h"
#include "close_retry.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define METADATA_COUNT 12
#define PARODUS_SERVICE_NAME "parodus"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
@@ -49,26 +48,6 @@ pthread_mutex_t nano_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t nano_con=PTHREAD_COND_INITIALIZER;
UpStreamMsg * get_global_UpStreamMsgQ(void)
{
return UpStreamMsgQ;
}
void set_global_UpStreamMsgQ(UpStreamMsg * UpStreamQ)
{
UpStreamMsgQ = UpStreamQ;
}
pthread_cond_t *get_global_nano_con(void)
{
return &nano_con;
}
pthread_mutex_t *get_global_nano_mut(void)
{
return &nano_mut;
}
/*----------------------------------------------------------------------------*/
/* Internal Functions */
/*----------------------------------------------------------------------------*/
@@ -129,12 +108,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 +116,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 +156,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
@@ -215,15 +171,11 @@ void *processUpstreamMessage()
{
int rv=-1, rc = -1;
int msgType;
wrp_msg_t *msg,*retrieve_msg = NULL;
wrp_msg_t *msg;
void *bytes;
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;
while(FOREVER())
{
@@ -244,40 +196,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 +232,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 +263,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,108 +296,37 @@ 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
{
//Sending to server for msgTypes 3, 5, 6, 7, 8.
if( WRP_MSG_TYPE__REQ == msgType )
{
ParodusInfo(" Received upstream data with MsgType: %d dest: '%s' transaction_uuid: %s\n", msgType, msg->u.req.dest, msg->u.req.transaction_uuid );
sendUpstreamMsgToServer(&message->msg, message->len);
}
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)
{
ret = getDeviceId(&device_id, &device_id_len);
if(ret == 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) )
{
/* 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) )
{
/* For Parodus CRUD queue. */
ParodusInfo("Create RetrieveMsg and add to parodus CRUD queue\n");
createUpstreamRetrieveMsg(msg, &retrieve_msg);
addCRUDmsgToQueue(retrieve_msg);
}
else
{
/* For nanomsg clients. */
getServiceNameAndSendResponse(msg, &message->msg, message->len);
}
}
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;
}
}
else
{
ParodusError("Failed to get device_id\n");
}
} else if (WRP_MSG_TYPE__SVC_ALIVE != msgType) {
/* Don't reply to service alive message */
sendUpstreamMsgToServer(&message->msg, message->len);
}
}
}
}
//Sending to server for msgTypes 3, 5, 6, 7, 8.
if( WRP_MSG_TYPE__REQ == msgType ) {
ParodusInfo(" Received upstream data with MsgType: %d dest: '%s' transaction_uuid: %s\n",
msgType, msg->u.req.dest, msg->u.req.transaction_uuid );
} 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 );
}
sendUpstreamMsgToServer(&message->msg, message->len);
}
}
else
{
ParodusError("Error in msgpack decoding for upstream\n");
}
ParodusPrint("Free for upstream decoded msg\n");
wrp_free_struct(msg);
msg = NULL;
//nn_freemsg should not be done for parodus/tags/ CRUD requests as it is not received through nanomsg.
if ((msg && (msg->u.crud.source !=NULL) && wrp_does_service_match("parodus", msg->u.crud.source) == 0))
{
free(message->msg);
}
else
{
if(nn_freemsg (message->msg) < 0)
{
ParodusError ("Failed to free msg\n");
}
}
ParodusPrint("Free for upstream decoded msg\n");
if (msg) {
wrp_free_struct(msg);
if(nn_freemsg (message->msg) < 0)
{
ParodusError ("Failed to free msg\n");
}
msg = NULL;
free(message);
message = NULL;
free(message);
message = NULL;
}
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,112 +336,11 @@ 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;
size_t encodedSize;
bool close_retry = false;
//appending response with metadata
if(metaPackSize > 0)
{
@@ -578,19 +349,8 @@ void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
ParodusPrint("encodedSize after appending :%zu\n", encodedSize);
ParodusInfo("Sending response to server\n");
close_retry = get_close_retry();
/* send response when connection retry is not in progress. Also during cloud_disconnect UPDATE request. Here, close_retry becomes 1 hence check is added to send disconnect response to server. */
//TODO: Upstream and downstream messages in queue should be handled and queue should be empty before parodus forcefully disconnect from cloud.
if(!close_retry || (get_parodus_cfg()->cloud_disconnect !=NULL))
{
sendMessage(get_global_conn(),appendData, encodedSize);
}
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);
}
sendMessage(get_global_conn(),appendData, encodedSize);
free(appendData);
appendData =NULL;
}

View File

@@ -24,12 +24,10 @@
#ifndef _UPSTREAM_H_
#define _UPSTREAM_H_
#include <pthread.h>
#include <wrp-c.h>
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
@@ -47,14 +45,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);
pthread_mutex_t *get_global_nano_mut(void);
#ifdef __cplusplus
}

View File

@@ -18,7 +18,7 @@ set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -W -g -fprofile-arcs -ftest-cove
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage -O0")
set (PARODUS_COMMON_SRC ../src/string_helpers.c ../src/mutex.c ../src/time.c ../src/config.c ../src/spin_thread.c ../src/token.c)
set (PARODUS_COMMON_LIBS gcov -lcunit -lcimplog -lwrp-c
-luuid -lmsgpackc -lnopoll -lnanomsg -lpthread
-luuid -lpthread -lmsgpackc -lnopoll -lnanomsg
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
@@ -36,20 +36,6 @@ endif ()
link_directories ( ${LIBRARY_DIR} )
#-------------------------------------------------------------------------------
# test_heartBeatTimer
#-------------------------------------------------------------------------------
add_test(NAME test_heartBeatTimer COMMAND ${MEMORY_CHECK} ./test_heartBeatTimer)
add_executable(test_heartBeatTimer test_heartBeatTimer.c ../src/heartBeat.c)
target_link_libraries (test_heartBeatTimer ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_close_retry
#-------------------------------------------------------------------------------
add_test(NAME test_close_retry COMMAND ${MEMORY_CHECK} ./test_close_retry)
add_executable(test_close_retry test_close_retry.c ../src/close_retry.c)
target_link_libraries (test_close_retry ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_mutex
#-------------------------------------------------------------------------------
@@ -71,6 +57,26 @@ add_test(NAME test_nopoll_helpers COMMAND ${MEMORY_CHECK} ./test_nopoll_helpers)
add_executable(test_nopoll_helpers test_nopoll_helpers.c ../src/nopoll_helpers.c)
target_link_libraries (test_nopoll_helpers -Wl,--no-as-needed -lrt -lcmocka -lcimplog -lnopoll)
#-------------------------------------------------------------------------------
# libpd_test
#-------------------------------------------------------------------------------
add_executable (libpd_test libpd_test.c ../src/string_helpers.c)
target_link_libraries (libpd_test
cunit
-llibparodus
-lwrp-c
-luuid
-lmsgpackc
-ltrower-base64
-lnanomsg
-lcimplog
-lm
-lpthread
-lrt)
if (ENABLE_SESHAT)
target_link_libraries (libpd_test -llibseshat)
endif (ENABLE_SESHAT)
#-------------------------------------------------------------------------------
# test_time
#-------------------------------------------------------------------------------
@@ -103,37 +109,29 @@ target_link_libraries (test_string_helpers ${PARODUS_COMMON_LIBS} )
# test_nopoll_handlers
#-------------------------------------------------------------------------------
add_test(NAME test_nopoll_handlers COMMAND ${MEMORY_CHECK} ./test_nopoll_handlers)
add_executable(test_nopoll_handlers test_nopoll_handlers.c ../src/nopoll_handlers.c ../src/heartBeat.c ../src/close_retry.c)
add_executable(test_nopoll_handlers test_nopoll_handlers.c ../src/nopoll_handlers.c)
target_link_libraries (test_nopoll_handlers -lnopoll -lcunit -lcimplog -Wl,--no-as-needed -lrt -lpthread -lm)
#-------------------------------------------------------------------------------
# test_nopoll_handlers_fragment
#-------------------------------------------------------------------------------
add_test(NAME test_nopoll_handlers_fragment COMMAND ${MEMORY_CHECK} ./test_nopoll_handlers_fragment)
add_executable(test_nopoll_handlers_fragment test_nopoll_handlers_fragment.c ../src/nopoll_handlers.c ../src/heartBeat.c ../src/close_retry.c)
target_link_libraries (test_nopoll_handlers_fragment -lnopoll -lcunit -lcimplog -Wl,--no-as-needed -lrt -lpthread -lm -lcmocka)
#-------------------------------------------------------------------------------
# test_connection
#-------------------------------------------------------------------------------
#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)
#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)
add_test(NAME test_connection COMMAND ${MEMORY_CHECK} ./test_connection)
#add_executable(test_connection test_connection.c ../src/connection.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka)
set(SOURCES test_connection.c ../src/connection.c ${PARODUS_COMMON_SRC})
add_executable(test_connection ${SOURCES})
#target_link_libraries (test_connection ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} -lcmocka)
target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_connection - function createNopollConnection
#-------------------------------------------------------------------------------
#add_test(NAME test_createConnection COMMAND ${MEMORY_CHECK} ./test_createConnection)
add_test(NAME test_createConnection COMMAND ${MEMORY_CHECK} ./test_createConnection)
#add_executable(test_createConnection test_createConnection.c ../src/connection.c ../src/string_helpers.c ../src/config.c)
#target_link_libraries (test_createConnection ${PARODUS_COMMON_LIBS} -lcmocka)
#add_executable(test_createConnection test_createConnection.c ../src/connection.c ../src/string_helpers.c ../src/config.c ../src/heartBeat.c)
add_executable(test_createConnection test_createConnection.c ../src/connection.c ../src/string_helpers.c ../src/config.c)
#target_link_libraries (test_createConnection ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} -lcmocka )
#target_link_libraries (test_createConnection ${PARODUS_COMMON_LIBS} -lcmocka )
target_link_libraries (test_createConnection ${PARODUS_COMMON_LIBS} -lcmocka )
#-------------------------------------------------------------------------------
# test_client_list
@@ -141,21 +139,21 @@ target_link_libraries (test_nopoll_handlers_fragment -lnopoll -lcunit -lcimplog
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(SOURCES 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/downstream.c ../src/connection.c ../src/nopoll_handlers.c
../src/ParodusInternal.c ../src/thread_tasks.c ../src/conn_interface.c
../src/partners_check.c ../src/crud_interface.c ../src/crud_tasks.c ../src/crud_internal.c ${PARODUS_COMMON_SRC})
../src/partners_check.c ${PARODUS_COMMON_SRC})
if (ENABLE_SESHAT)
set(CLIST_SRC ${CLIST_SRC} ../src/seshat_interface.c)
set(SOURCES ${SOURCES} ../src/seshat_interface.c)
else()
set(CLIST_SRC ${CLIST_SRC} ../src/seshat_interface_stub.c)
set(SOURCES ${SOURCES} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_client_list ${CLIST_SRC})
add_executable(test_client_list ${SOURCES})
#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,98 +161,40 @@ 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(SOURCES 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})
if (ENABLE_SESHAT)
set(SVA_SRC ${SVA_SRC} ../src/seshat_interface.c)
set(SOURCES ${SOURCES} ../src/seshat_interface.c)
else()
set(SVA_SRC ${SVA_SRC} ../src/seshat_interface_stub.c)
set(SOURCES ${SOURCES} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_service_alive ${SVA_SRC})
add_executable(test_service_alive ${SOURCES})
#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
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm
)
#-------------------------------------------------------------------------------
# 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
)
#-------------------------------------------------------------------------------
# test_crud_interface
#-------------------------------------------------------------------------------
add_test(NAME test_crud_interface COMMAND ${MEMORY_CHECK} ./test_crud_interface)
add_executable(test_crud_interface test_crud_interface.c ../src/crud_interface.c ../src/ParodusInternal.c)
target_link_libraries (test_crud_interface -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_crud_tasks
#-------------------------------------------------------------------------------
add_test(NAME test_crud_tasks COMMAND ${MEMORY_CHECK} ./test_crud_tasks)
add_executable(test_crud_tasks test_crud_tasks.c ../src/crud_tasks.c )
target_link_libraries (test_crud_tasks -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_crud_internal
#-------------------------------------------------------------------------------
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)
#-------------------------------------------------------------------------------
# test_upstream
#-------------------------------------------------------------------------------
add_test(NAME test_upstream COMMAND ${MEMORY_CHECK} ./test_upstream)
add_executable(test_upstream test_upstream.c ../src/upstream.c ../src/close_retry.c ../src/string_helpers.c)
target_link_libraries (test_upstream -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll
-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)
add_executable(test_upstream test_upstream.c ../src/upstream.c ../src/string_helpers.c)
target_link_libraries (test_upstream -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_downstream
#-------------------------------------------------------------------------------
add_test(NAME test_downstream COMMAND ${MEMORY_CHECK} ./test_downstream)
add_executable(test_downstream test_downstream.c ../src/downstream.c ../src/string_helpers.c)
target_link_libraries (test_downstream -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
target_link_libraries (test_downstream -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_downstream_more
@@ -274,30 +214,21 @@ target_link_libraries (test_thread_tasks -lcmocka ${PARODUS_COMMON_LIBS} )
# test_conn_interface
#-------------------------------------------------------------------------------
add_test(NAME test_conn_interface COMMAND ${MEMORY_CHECK} ./test_conn_interface)
set(CONIFC_SRC test_conn_interface.c
../src/crud_interface.c ../src/crud_tasks.c ../src/crud_internal.c
../src/conn_interface.c
../src/config.c
../src/token.c
../src/string_helpers.c
../src/mutex.c
../src/heartBeat.c
../src/close_retry.c
)
set(SOURCES test_conn_interface.c ../src/conn_interface.c ../src/config.c ../src/string_helpers.c ../src/mutex.c)
if (ENABLE_SESHAT)
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface.c)
set(SOURCES ${SOURCES} ../src/seshat_interface.c)
else()
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface_stub.c)
set(SOURCES ${SOURCES} ../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 )
add_executable(test_conn_interface ${SOURCES})
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
@@ -310,45 +241,20 @@ target_link_libraries (test_partners_check -lcmocka ${PARODUS_COMMON_LIBS} -lwrp
# test_token - token.c tests
#-------------------------------------------------------------------------------
add_test(NAME test_token COMMAND ${MEMORY_CHECK} ./test_token)
set(TOKEN_SRC ../src/conn_interface.c ../src/config.c
../src/connection.c ../src/spin_thread.c
../src/service_alive.c ../src/client_list.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/thread_tasks.c ../src/time.c
../src/string_helpers.c ../src/mutex.c
../src/token.c ../src/heartBeat.c
../src/close_retry.c
)
if (ENABLE_SESHAT)
set(TOKEN_SRC ${TOKEN_SRC} ../src/seshat_interface.c)
else()
set(TOKEN_SRC ${TOKEN_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
if (FEATURE_DNS_QUERY)
set(TOKEN_SRC test_token.c ${TOKEN_SRC})
else()
set(TOKEN_SRC test_token_stub.c ${TOKEN_SRC})
endif (FEATURE_DNS_QUERY)
add_executable(test_token ${TOKEN_SRC} )
add_executable(test_token ${SOURCES} )
#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
#-------------------------------------------------------------------------------
add_test(NAME test_seshat_interface COMMAND ${MEMORY_CHECK} ./test_seshat_interface)
if (ENABLE_SESHAT)
set(SESHIFC_SRC test_seshat_interface.c ../src/seshat_interface.c ../src/string_helpers.c)
set(SOURCES test_seshat_interface.c ../src/seshat_interface.c ../src/string_helpers.c)
else()
set(SESHIFC_SRC test_seshat_interface_stub.c ../src/seshat_interface_stub.c)
set(SOURCES test_seshat_interface_stub.c ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_seshat_interface ${SESHIFC_SRC})
add_executable(test_seshat_interface ${SOURCES})
target_link_libraries (test_seshat_interface -lcmocka ${PARODUS_COMMON_LIBS} -lwrp-c)
if (INTEGRATION_TESTING)
@@ -356,28 +262,28 @@ if (INTEGRATION_TESTING)
# simple_connection test
#-------------------------------------------------------------------------------
add_test(NAME simple_connection COMMAND ${MEMORY_CHECK} ./simple_connection)
set(SIMCON_SRC simple_connection.c ${PARODUS_COMMON_SRC} ../src/upstream.c ../src/conn_interface.c
set(SOURCES simple_connection.c ${PARODUS_COMMON_SRC} ../src/upstream.c ../src/conn_interface.c
../src/thread_tasks.c ../src/downstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/connection.c ../src/ParodusInternal.c ../src/client_list.c ../src/partners_check.c ../src/service_alive.c)
if (ENABLE_SESHAT)
set(SIMCON_SRC ${SIMCON_SRC} ../src/seshat_interface.c)
set(SOURCES ${SOURCES} ../src/seshat_interface.c)
else()
set(SIMCON_SRC ${SIMCON_SRC} ../src/seshat_interface_stub.c)
set(SOURCES ${SOURCES} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(simple_connection ${SIMCON_SRC})
add_executable(simple_connection ${SOURCES})
target_link_libraries (simple_connection ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# simple test
#-------------------------------------------------------------------------------
add_test(NAME simple COMMAND ${MEMORY_CHECK} ./simple)
set(SIMPLE_SRC simple.c ../src/upstream.c ../src/conn_interface.c ../src/downstream.c ../src/thread_tasks.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/string_helpers.c ../src/mutex.c ../src/time.c
set(SOURCES simple.c ../src/upstream.c ../src/conn_interface.c ../src/downstream.c ../src/thread_tasks.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/string_helpers.c ../src/mutex.c ../src/time.c
../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/spin_thread.c ../src/client_list.c ../src/partners_check.c ../src/service_alive.c)
if (ENABLE_SESHAT)
set(SIMPLE_SRC ${SIMPLE_SRC} ../src/seshat_interface.c)
set(SOURCES ${SOURCES} ../src/seshat_interface.c)
else()
set(SIMPLE_SRC ${SIMPLE_SRC} ../src/seshat_interface_stub.c)
set(SOURCES ${SOURCES} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(simple ${SIMPLE_SRC})
add_executable(simple ${SOURCES})
target_link_libraries (simple ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} gcov -lnopoll )
target_link_libraries (simple ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} gcov -lnopoll -lnanomsg )
endif (INTEGRATION_TESTING)

View File

@@ -1,28 +0,0 @@
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDsLxH6GZFxU64v
GL9CNz3hLSoCb7TckabgbVp6PIRy9cKEwfqnQ/2ohqrdolMA6Peru2+DgBs1iJ3u
JNSc+8XFphUj0Jm2gVumVfclSZTEkM4xI4D3ABXn0Pj6/Ps5Skx9pXk3KI988ksB
secD+FNqBPgmKWG0Gp+JSrPEwAtA4ZBP/4vtCGxEFzRCSOSBkTh27n1f08M4PjsY
+vMvyTVF67y4Zb3nWJHpa1yOBlHid0xI138KPEBl+9Vai1AwRWbhlq52I9+IVjCo
N7Ui9KbRgfd21SJFLh3hDw6xSrNqtcU+mvv5GuLAxHF5tCcGpAgKvKhvjQU4v+fh
lGW77zkVAgMBAAECggEBAI8DoZsTyGIbDaovDgEGek3Tj1CSW64D9EyJavQBmSIT
don0+9Y08XAOu4AhPqmaZ/5xLQEvnUo5Q4hkfOnh+svH2Z0qPymoAtshytmlSJQO
KwzONtVaE+mfPGSes3DpcI/UlyWzRc+e15RbKUvaHohgIfLZs/Pe+yOjPF+y+h16
Tpvklvk9GuS5/njOm0N8iRZw0+mKMLjwKCf0Q9WpF5OXW7hYccG9aTpmiUDnpixP
nMyEdZMhmfFDLl+t6Txj3KhNX8jixDmfkuiPuoADWZuYk3GjS499nb3Y5Tmm8TLq
jf0St48y1bObNnkceSqODnUK2hUZzzWcgTLwIC1E0DECgYEA+QoVuCA5i3eAiyE7
PUsKpT0qVH/rWVWl0HYykUI7MSv0KJH7uPS+m2GzScxpCZoA4wtu6iK5IePNf645
yJAleglx+1vuBGCWQrr206gOPWrkthfVHd+pDCr/fnIG+RdNr9SgwUx1youpovQ4
x64RQuEyBXENt+xx2+fFI28GxEcCgYEA8skAisNqPgREewZ+hM2OkhIyU7GaKWgt
HfjPYHHYWVO/sSfOdcyzcCUZJkseBhIVEmIeiXM4NCO0spmieHa6bo8oLr1nPMtm
J4UkyVRPtO99V5mIBYOS3cWAEwEt7lWZ+4JiIyEBO/tMVjIrB8YkOE4LqV40Vvpu
XGJbtw3JEcMCgYEA15xnmXYs3Bamb85hn3tsyArgry/g7wM7//OVbDXPUY8gYE+j
hEpBC/3WX7pd5jYzNl8btBJD/pdfv39z/7Ts/W9YA6tfsuJ8tWFxeWYyjfIR+aVA
mhCeJy7C7RKD/vyyAd0xIKm2AZpRUAfpcNe/kguuZw+uNOK84QsUnsztKtkCgYAE
KBDMT2AoQ6ZwfMH5wBMqyQj3idjb0J7FHpdeTVSo4tgrTkUomyKPTvNJRovzCqg1
slxXehOCQQI89Ihli5LRhb3oXvG/hrPvBUaF892ReXAp6cT8Yy5GgbUZnjGNHQYP
2kGX3F7LChhaeW1nKqtAE4X7llNLEeqFxmFPlvrURQKBgA0c5s3WPeX5OfSRsLaF
iXaQNQ88QORNJ4hp/L7/o3ZNy7elH/R3GM1fs8Yf711CDxy4qI7icRYyrkl0P/Py
WyRbNnvw0JMa5xkzRgKlnvspfEfve7gzcZhE9yEw173MIyyoxIn43G9aGNSN3QIR
51ZlCYyuIAgR7p+9lKvM74HR
-----END PRIVATE KEY-----

403
tests/libpd_test.c Normal file
View File

@@ -0,0 +1,403 @@
/**
* 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 <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <CUnit/Basic.h>
#include <stdbool.h>
#include <libparodus.h>
#include <pthread.h>
#include "../src/ParodusInternal.h"
#define SEND_EVENT_MSGS 1
//#define TCP_URL(ip) "tcp://" ip
#define GOOD_CLIENT_URL "tcp://127.0.0.1:6667"
//#define PARODUS_URL "ipc:///tmp/parodus_server.ipc"
#define GOOD_PARODUS_URL "tcp://127.0.0.1:6666"
//#define CLIENT_URL "ipc:///tmp/parodus_client.ipc"
static void initEndKeypressHandler();
static void *endKeypressHandlerTask();
static pthread_t endKeypressThreadId;
static const char *service_name = "iot";
//static const char *service_name = "config";
static bool no_mock_send_only_test = false;
static libpd_instance_t test_instance;
// libparodus functions to be tested
extern int flush_wrp_queue (uint32_t delay_ms);
extern int connect_receiver (const char *rcv_url);
extern int connect_sender (const char *send_url);
extern void shutdown_socket (int *sock);
extern bool is_auth_received (void);
extern int libparodus_receive__ (wrp_msg_t **msg, uint32_t ms);
// libparodus_log functions to be tested
extern int get_valid_file_num (const char *file_name, const char *date);
extern int get_last_file_num_in_dir (const char *date, const char *log_dir);
extern const char *wrp_queue_name;
extern const char *parodus_url;
extern const char *client_url;
extern volatile int keep_alive_count;
extern volatile int reconnect_count;
void show_src_dest_payload (char *src, char *dest, void *payload, size_t payload_size)
{
size_t i;
char *payload_str = (char *) payload;
printf (" SOURCE: %s\n", src);
printf (" DEST : %s\n", dest);
printf (" PAYLOAD: ");
for (i=0; i<payload_size; i++)
putchar (payload_str[i]);
putchar ('\n');
}
void show_wrp_req_msg (struct wrp_req_msg *msg)
{
show_src_dest_payload (msg->source, msg->dest, msg->payload, msg->payload_size);
}
void show_wrp_event_msg (struct wrp_event_msg *msg)
{
show_src_dest_payload (msg->source, msg->dest, msg->payload, msg->payload_size);
}
void show_wrp_msg (wrp_msg_t *wrp_msg)
{
printf ("Received WRP Msg type %d\n", wrp_msg->msg_type);
if (wrp_msg->msg_type == WRP_MSG_TYPE__REQ) {
show_wrp_req_msg (&wrp_msg->u.req);
return;
}
if (wrp_msg->msg_type == WRP_MSG_TYPE__EVENT) {
show_wrp_event_msg (&wrp_msg->u.event);
return;
}
return;
}
void send_reply (wrp_msg_t *wrp_msg)
{
size_t i;
size_t payload_size = wrp_msg->u.req.payload_size;
char *payload = (char *) wrp_msg->u.req.payload;
char *temp;
// swap source and dest
temp = wrp_msg->u.req.source;
wrp_msg->u.req.source = wrp_msg->u.req.dest;
wrp_msg->u.req.dest = temp;
// Alter the payload
for (i=0; i<payload_size; i++)
payload[i] = tolower (payload[i]);
libparodus_send (test_instance, wrp_msg);
}
char *new_str (const char *str)
{
char *buf = malloc (strlen(str) + 1);
if (NULL == buf)
return NULL;
parStrncpy(buf, str, (strlen(str)+1));
return buf;
}
void insert_number_into_buf (char *buf, unsigned num)
{
char *pos = strrchr (buf, '#');
if (NULL == pos)
return;
while (true) {
*pos = (num%10) + '0';
num /= 10;
if (pos <= buf)
break;
pos--;
if (*pos != '#')
break;
}
}
int send_event_msg (const char *src, const char *dest,
const char *payload, unsigned event_num)
{
int rtn = 0;
char *payload_buf;
wrp_msg_t *new_msg;
#ifndef SEND_EVENT_MSGS
return 0;
#endif
new_msg = malloc (sizeof (wrp_msg_t));
if (NULL == new_msg)
return -1;
printf ("Making event msg\n");
new_msg->msg_type = WRP_MSG_TYPE__EVENT;
new_msg->u.event.source = new_str (src);
new_msg->u.event.dest = new_str (dest);
new_msg->u.event.headers = NULL;
new_msg->u.event.metadata = NULL;
payload_buf = new_str (payload);
insert_number_into_buf (payload_buf, event_num);
new_msg->u.event.payload = (void*) payload_buf;
new_msg->u.event.payload_size = strlen (payload) + 1;
printf ("Sending event msg %u\n", event_num);
rtn = libparodus_send (test_instance, new_msg);
//printf ("Freeing event msg\n");
wrp_free_struct (new_msg);
//printf ("Freed event msg\n");
return rtn;
}
int send_event_msgs (unsigned *msg_num, unsigned *event_num, int count)
{
int i;
unsigned msg_num_mod;
#ifndef SEND_EVENT_MSGS
return 0;
#endif
if (NULL != msg_num) {
(*msg_num)++;
msg_num_mod = (*msg_num) % 3;
if (msg_num_mod != 0)
return 0;
}
for (i=0; i<count; i++) {
(*event_num)++;
if (send_event_msg ("---LIBPARODUS---", "---ParodusService---",
"---EventMessagePayload####", *event_num) != 0)
return -1;
}
return 0;
}
int get_msg_num (const char *msg)
{
int num = -1;
bool found_pound = false;
int i;
char c;
for (i=0; (c=msg[i]) != 0; i++)
{
if (!found_pound) {
if (c == '#')
found_pound = true;
continue;
}
if ((c>='0') && (c<='9')) {
if (num == -1)
num = c - '0';
else
num = 10*num + (c - '0');
}
}
return num;
}
static int flush_queue_count = 0;
void qfree (void * msg)
{
flush_queue_count++;
free (msg);
}
void delay_ms(unsigned int secs, unsigned int msecs)
{
struct timespec ts;
ts.tv_sec = (time_t) secs;
ts.tv_nsec = (long) msecs * 1000000L;
nanosleep (&ts, NULL);
}
void dbg_log_err (const char *fmt, ...)
{
char errbuf[100];
va_list arg_ptr;
va_start(arg_ptr, fmt);
vprintf(fmt, arg_ptr);
va_end(arg_ptr);
printf ("LIBPD_TEST: %s\n", strerror_r (errno, errbuf, 100));
}
void wait_auth_received (void)
{
if (!is_auth_received ()) {
printf ("Waiting for auth received\n");
sleep(1);
}
if (!is_auth_received ()) {
printf ("Waiting for auth received\n");
sleep(1);
}
CU_ASSERT (is_auth_received ());
}
void test_send_only (void)
{
unsigned event_num = 0;
libpd_cfg_t cfg = {.service_name = service_name,
.receive = false, .keepalive_timeout_secs = 0};
CU_ASSERT (libparodus_init (&test_instance, &cfg) == 0);
CU_ASSERT (send_event_msgs (NULL, &event_num, 10) == 0);
CU_ASSERT (libparodus_shutdown (&test_instance) == 0);
}
void test_1(void)
{
unsigned msgs_received_count = 0;
int rtn;
wrp_msg_t *wrp_msg;
unsigned event_num = 0;
unsigned msg_num = 0;
libpd_cfg_t cfg = {.service_name = service_name,
.receive = true, .keepalive_timeout_secs = 0};
if (no_mock_send_only_test) {
test_send_only ();
return;
}
cfg.parodus_url = GOOD_PARODUS_URL;
cfg.client_url = GOOD_CLIENT_URL;
CU_ASSERT (libparodus_init (&test_instance, &cfg) == 0);
printf ("LIBPD_TEST: libparodus_init successful\n");
initEndKeypressHandler ();
wait_auth_received ();
printf ("LIBPD_TEST: starting msg receive loop\n");
while (true) {
rtn = libparodus_receive (test_instance, &wrp_msg, 2000);
if (rtn == 1) {
printf ("LIBPD_TEST: Timed out waiting for msg\n");
if (msgs_received_count > 0)
if (send_event_msgs (&msg_num, &event_num, 5) != 0)
break;
continue;
}
if (rtn != 0)
break;
show_wrp_msg (wrp_msg);
msgs_received_count++;
if (wrp_msg->msg_type == WRP_MSG_TYPE__REQ)
send_reply (wrp_msg);
wrp_free_struct (wrp_msg);
if (send_event_msgs (&msg_num, &event_num, 5) != 0)
break;
}
printf ("Messages received %u\n", msgs_received_count);
CU_ASSERT (libparodus_shutdown (&test_instance) == 0);
}
/*
* @brief To initiate end keypress handler
*/
static void initEndKeypressHandler()
{
int err = 0;
err = pthread_create(&endKeypressThreadId, NULL, endKeypressHandlerTask, NULL);
if (err != 0)
{
libpd_log (LEVEL_ERROR, "Error creating End Keypress Handler thread\n");
}
else
{
printf ("End Keypress handler Thread created successfully\n");
printf ("\n--->> Press <Enter> to shutdown the test. ---\n");
}
}
/*
* @brief To handle End Keypress
*/
static void *endKeypressHandlerTask()
{
char inbuf[10];
memset(inbuf, 0, 10);
while (true) {
fgets (inbuf, 10, stdin);
if ((inbuf[0] != '\n') && (inbuf[0] != '\0')) {
printf ("endKeyPressHandler exiting\n");
break;
}
}
libparodus_close_receiver (test_instance);
return NULL;
}
void add_suites( CU_pSuite *suite )
{
*suite = CU_add_suite( "libparodus tests", NULL, NULL );
CU_add_test( *suite, "Test 1", test_1 );
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( int argc, char **argv __attribute__((unused)) )
{
unsigned rv = 1;
CU_pSuite suite = NULL;
if (argc > 1) {
const char *arg = argv[1];
if ((arg[0] == 's') || (arg[0] == 'S'))
no_mock_send_only_test = true;
}
if( CUE_SUCCESS == CU_initialize_registry() ) {
add_suites( &suite );
if( NULL != suite ) {
CU_basic_set_mode( CU_BRM_VERBOSE );
CU_basic_run_tests();
printf( "\n" );
CU_basic_show_failures( CU_get_failure_list() );
printf( "\n\n" );
rv = CU_get_number_of_tests_failed();
}
CU_cleanup_registry();
}
if( 0 != rv ) {
return 1;
}
return 0;
}

View File

@@ -1,9 +0,0 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7C8R+hmRcVOuLxi/Qjc9
4S0qAm+03JGm4G1aejyEcvXChMH6p0P9qIaq3aJTAOj3q7tvg4AbNYid7iTUnPvF
xaYVI9CZtoFbplX3JUmUxJDOMSOA9wAV59D4+vz7OUpMfaV5NyiPfPJLAbHnA/hT
agT4JilhtBqfiUqzxMALQOGQT/+L7QhsRBc0QkjkgZE4du59X9PDOD47GPrzL8k1
Reu8uGW951iR6WtcjgZR4ndMSNd/CjxAZfvVWotQMEVm4ZaudiPfiFYwqDe1IvSm
0YH3dtUiRS4d4Q8OsUqzarXFPpr7+RriwMRxebQnBqQICryob40FOL/n4ZRlu+85
FQIDAQAB
-----END PUBLIC KEY-----

View File

@@ -1 +0,0 @@
echo -n FAILURE

View File

@@ -1 +0,0 @@
echo -n SER_MAC $1 $2

View File

@@ -1 +0,0 @@
echo -n SUCCESS

View File

@@ -95,38 +95,6 @@ void err_getWebpaConveyHeader()
getWebpaConveyHeader();
}
/*
* Test function to verify timespec_diff function
* Verifys when the time diff is positive ie stop time > start time
*/
void test_timespec_diff()
{
struct timespec start, stop, diff;
int time_taken_ms;
clock_gettime(CLOCK_REALTIME, &start);
sleep(1);
clock_gettime(CLOCK_REALTIME, &stop);
timespec_diff(&start, &stop, &diff);
time_taken_ms = diff.tv_sec * 1000 + (diff.tv_nsec / 1000000);
assert_true(time_taken_ms >= 0);
}
/*
* Test function to verify timespec_diff function
* Verifys when the time diff is negative ie stop time < start time
*/
void test_timespec_diff1()
{
struct timespec start, stop, diff;
int time_taken_ms;
clock_gettime(CLOCK_REALTIME, &start);
sleep(1);
clock_gettime(CLOCK_REALTIME, &stop);
timespec_diff(&stop, &start, &diff);
time_taken_ms = diff.tv_sec * 1000 + (diff.tv_nsec / 1000000);
assert_true(time_taken_ms <= 0);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -135,8 +103,6 @@ int main(void)
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_getWebpaConveyHeader),
cmocka_unit_test(err_getWebpaConveyHeader),
cmocka_unit_test(test_timespec_diff),
cmocka_unit_test(test_timespec_diff1),
};
return cmocka_run_group_tests(tests, NULL, NULL);

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

@@ -1,93 +0,0 @@
/**
* Copyright 2018 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 <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <pthread.h>
#include "../src/close_retry.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_close_retry() {
/* get close_retry initial value */
bool close_retry =false;
close_retry = get_close_retry();
ParodusInfo("close_retry initial value is: %d\n", close_retry);
assert_int_equal(close_retry, 0);
/* set close_retry value and check whether its returning modified value or not*/
set_close_retry();
close_retry = get_close_retry();
ParodusInfo("close_retry modified to: %d\n", close_retry);
assert_int_equal(close_retry,1);
/* reset close_retry */
reset_close_retry();
close_retry = get_close_retry();
ParodusInfo("close_retry reset to: %d\n", close_retry);
assert_int_equal(close_retry,0);
}
void *test_mutex_set_close_retry() {
set_close_retry();
return NULL;
}
void *test_mutex_reset_close_retry() {
reset_close_retry();
return NULL;
}
void test_mutex_close_retry() {
bool close_retry;
pthread_t thread[3];
pthread_create(&thread[0], NULL, test_mutex_set_close_retry, NULL);
pthread_create(&thread[1], NULL, test_mutex_set_close_retry, NULL);
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
/* After execution of threads check the value of close_retry */
close_retry = get_close_retry();
ParodusInfo("Threads execution is completed, close_retry is: %d\n", close_retry);
assert_int_equal(close_retry, 1);
pthread_create(&thread[2], NULL, test_mutex_reset_close_retry, NULL);
pthread_join(thread[2], NULL);
close_retry = get_close_retry();
ParodusInfo("close_retry reset to: %d\n", close_retry);
assert_int_equal(close_retry, 0);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_close_retry),
cmocka_unit_test(test_mutex_close_retry)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -25,17 +25,14 @@
#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);
extern int server_is_http (const char *full_url,
const char **server_ptr);
extern int parse_webpa_url__(const char *full_url,
extern int parse_webpa_url(const char *full_url,
char *server_addr, int server_addr_buflen,
char *port_buf, int port_buflen);
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);
@@ -52,7 +49,6 @@ void create_token_script(char *fname)
sprintf(command, "chmod +x %s",fname);
system(command);
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -73,7 +69,7 @@ void test_setParodusConfig()
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
parStrncpy(cfg.webpa_uuid , "1234567-345456546", sizeof(cfg.webpa_uuid));
parStrncpy(cfg.partner_id , "mycom", sizeof(cfg.partner_id));
parStrncpy(cfg.partner_id , "comcast", sizeof(cfg.partner_id));
#ifdef ENABLE_SESHAT
parStrncpy(cfg.seshat_url, "ipc://tmp/seshat_service.url", sizeof(cfg.seshat_url));
#endif
@@ -86,10 +82,10 @@ void test_setParodusConfig()
parStrncpy(cfg.dns_txt_url, "test",sizeof(cfg.dns_txt_url));
cfg.jwt_algo = 1025;
parStrncpy(cfg.jwt_key, "key.txt",sizeof(cfg.jwt_key));
#endif
cfg.crud_config_file = strdup("parodus_cfg.json");
set_parodus_cfg(&cfg);
ParodusCfg *temp = get_parodus_cfg();
#endif
set_parodus_cfg(&cfg);
ParodusCfg *temp = get_parodus_cfg();
assert_string_equal(cfg.hw_model, temp->hw_model);
assert_string_equal(cfg.hw_serial_number, temp->hw_serial_number);
@@ -115,7 +111,6 @@ void test_setParodusConfig()
assert_int_equal( (int) cfg.jwt_algo, (int) temp->jwt_algo);
assert_string_equal(cfg.jwt_key, temp->jwt_key);
#endif
assert_string_equal(cfg.crud_config_file, temp->crud_config_file);
}
void test_getParodusConfig()
@@ -184,17 +179,15 @@ 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",
"--dns-txt-url=fabric.comcast.net",
"--jwt-public-key-file=../../tests/jwt_key.tst",
"--jwt-algo=RS256",
#endif
"--crud-config-file=parodus_cfg.json",
NULL
};
int argc = (sizeof (command) / sizeof (char *)) - 1;
@@ -215,7 +208,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,21 +218,19 @@ 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_string_equal(parodusCfg.dns_txt_url, "fabric.comcast.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");
}
void test_parseCommandLineNull()
@@ -282,7 +272,7 @@ void err_parseCommandLine()
#ifdef FEATURE_DNS_QUERY
command[5] = "--webpa-url=https://127.0.0.1";
command[3] = "--acquire-jwt=1";
command[4] = "--dns-txt-url=mydns.mycom.net";
command[4] = "--dns-txt-url=fabric.comcast.net";
// missing algo
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
command[4] = "--jwt-algo=none:RS256";
@@ -317,17 +307,16 @@ void test_loadParodusCfg()
parStrncpy(Cfg->partner_id , "shaw", sizeof(Cfg->partner_id));
#ifdef FEATURE_DNS_QUERY
Cfg->acquire_jwt = 1;
parStrncpy(Cfg->dns_txt_url, "mydns",sizeof(Cfg->dns_txt_url));
parStrncpy(Cfg->dns_txt_url, "fabric",sizeof(Cfg->dns_txt_url));
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,19 +327,18 @@ 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_string_equal(tmpcfg.dns_txt_url, "fabric");
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");
#endif
assert_string_equal(tmpcfg.crud_config_file, "parodus_cfg.json");
free(Cfg);
}
@@ -371,7 +359,7 @@ void test_loadParodusCfgNull()
assert_string_equal( temp.webpa_path_url, WEBPA_PATH_URL);
assert_string_equal( temp.webpa_uuid,"1234567-345456546");
assert_string_equal( temp.local_url, PARODUS_UPSTREAM);
assert_null(temp.crud_config_file);
free(cfg);
}
@@ -421,7 +409,6 @@ void test_setDefaultValuesToCfg()
assert_int_equal((int)cfg->flags, 0);
assert_string_equal(cfg->webpa_path_url, WEBPA_PATH_URL);
assert_string_equal(cfg->webpa_uuid, "1234567-345456546");
assert_string_equal(cfg->cloud_status, CLOUD_STATUS_OFFLINE);
}
void err_setDefaultValuesToCfg()
@@ -462,89 +449,31 @@ void test_server_is_http ()
}
void test_parse_webpa_url__ ()
void test_parse_webpa_url ()
{
char addr_buf[80];
char port_buf[8];
assert_int_equal (parse_webpa_url__ ("mydns.mycom.net:8080",
assert_int_equal (parse_webpa_url ("fabric.webpa.comcast.net:8080",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("https://mydns.mycom.net:8080",
assert_int_equal (parse_webpa_url ("https://fabric.webpa.comcast.net:8080",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (addr_buf, "fabric.webpa.comcast.net");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("https://mydns.mycom.net/",
assert_int_equal (parse_webpa_url ("https://fabric.webpa.comcast.net/",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (addr_buf, "fabric.webpa.comcast.net");
assert_string_equal (port_buf, "443");
assert_int_equal (parse_webpa_url__ ("https://mydns.mycom.net/api/v2/",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (port_buf, "443");
assert_int_equal (parse_webpa_url__ ("http://mydns.mycom.net:8080",
assert_int_equal (parse_webpa_url ("http://fabric.webpa.comcast.net:8080",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (addr_buf, "fabric.webpa.comcast.net");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("http://mydns.mycom.net",
assert_int_equal (parse_webpa_url ("http://fabric.webpa.comcast.net",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (addr_buf, "fabric.webpa.comcast.net");
assert_string_equal (port_buf, "80");
assert_int_equal (parse_webpa_url__ ("https://[2001:558:fc18:2:f816:3eff:fe7f:6efa]:8080",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("https://[2001:558:fc18:2:f816:3eff:fe7f:6efa]",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "443");
assert_int_equal (parse_webpa_url__ ("http://[2001:558:fc18:2:f816:3eff:fe7f:6efa]:8080",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("http://[2001:558:fc18:2:f816:3eff:fe7f:6efa]",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "80");
assert_int_equal (parse_webpa_url__ ("http://2001:558:fc18:2:f816:3eff:fe7f:6efa]",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("http://[2001:558:fc18:2:f816:3eff:fe7f:6efa",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("[2001:558:fc18:2:f816:3eff:fe7f:6efa",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("https://[2001:558:fc18:2:f816:3eff:fe7f:6efa]:8080/api/v2/",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "8080");
}
void test_parse_webpa_url ()
{
char *addr;
unsigned int port;
assert_int_equal (parse_webpa_url ("mydns.mycom.net:8080",
&addr, &port), -1);
assert_int_equal (parse_webpa_url ("https://mydns.mycom.net:8080",
&addr, &port), 0);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 8080);
free (addr);
assert_int_equal (parse_webpa_url ("https://mydns.mycom.net/",
&addr, &port), 0);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 443);
free (addr);
assert_int_equal (parse_webpa_url ("http://mydns.mycom.net:8080",
&addr, &port), 1);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 8080);
free (addr);
assert_int_equal (parse_webpa_url ("http://mydns.mycom.net",
&addr, &port), 1);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 80);
free(addr);
}
void test_get_algo_mask ()
{
assert_true (get_algo_mask ("RS256:RS512") == 5120);
@@ -557,6 +486,7 @@ void test_get_algo_mask ()
#endif
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -573,12 +503,11 @@ int main(void)
cmocka_unit_test(test_parse_mac_address),
cmocka_unit_test(test_get_algo_mask),
cmocka_unit_test(test_server_is_http),
cmocka_unit_test(test_parse_webpa_url__),
cmocka_unit_test(test_parse_webpa_url),
cmocka_unit_test(test_parseCommandLine),
cmocka_unit_test(test_parseCommandLineNull),
cmocka_unit_test(err_parseCommandLine),
//cmocka_unit_test(test_parodusGitVersion),
cmocka_unit_test(test_parodusGitVersion),
cmocka_unit_test(test_setDefaultValuesToCfg),
cmocka_unit_test(err_setDefaultValuesToCfg),
};

View File

@@ -27,22 +27,15 @@
#include "../src/conn_interface.h"
#include "../src/connection.h"
#include "../src/config.h"
#include "../src/heartBeat.h"
#include "../src/close_retry.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
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;
extern bool close_retry;
extern pthread_mutex_t close_mut;
extern volatile unsigned int heartBeatTimer;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -74,32 +67,12 @@ 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();
}
int get_cloud_disconnect_time(void)
{
function_called();
return (int) (intptr_t)mock();
}
void set_cloud_disconnect_time(int Time)
{
UNUSED(Time);
function_called();
}
void *handle_upstream()
{
@@ -116,9 +89,9 @@ void *messageHandlerTask()
return NULL;
}
int serviceAliveTask()
void *serviceAliveTask()
{
return 0;
return NULL;
}
int nopoll_loop_wait(noPollCtx * ctx,long timeout)
@@ -134,12 +107,6 @@ void set_global_reconnect_reason(char *reason)
function_called();
}
void set_global_reconnect_status(bool status)
{
(void)status;
function_called();
}
void close_and_unref_connection(noPollConn *conn)
{
UNUSED(conn);
@@ -169,18 +136,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();
@@ -190,54 +151,6 @@ void initKeypress()
{
function_called();
}
UpStreamMsg * get_global_UpStreamMsgQ(void)
{
return UpStreamMsgQ;
}
void set_global_UpStreamMsgQ(UpStreamMsg * UpStreamQ)
{
UpStreamMsgQ = UpStreamQ;
}
pthread_cond_t *get_global_nano_con(void)
{
return &nano_con;
}
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
*/
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *diff)
{
UNUSED(start);
UNUSED(stop);
diff->tv_sec = 1;
diff->tv_nsec = 1000;
}
void deleteAllClients (void)
{
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -247,7 +160,10 @@ void test_createSocketConnection()
noPollCtx *ctx;
ParodusCfg cfg;
memset(&cfg,0,sizeof(ParodusCfg));
reset_close_retry();
pthread_mutex_lock (&close_mut);
close_retry = false;
pthread_mutex_unlock (&close_mut);
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)&ctx);
@@ -257,14 +173,13 @@ void test_createSocketConnection()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 5);
expect_function_calls(StartThread, 4);
expect_function_call(initKeypress);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
expect_function_call(set_global_reconnect_reason);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(set_global_reconnect_status);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(set_global_conn);
@@ -283,7 +198,9 @@ void test_createSocketConnection1()
noPollCtx *ctx;
ParodusCfg cfg;
memset(&cfg,0, sizeof(ParodusCfg));
set_close_retry();
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)&ctx);
@@ -293,7 +210,7 @@ void test_createSocketConnection1()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 5);
expect_function_calls(StartThread, 4);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
@@ -309,11 +226,10 @@ void test_createSocketConnection1()
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(NULL);
assert_string_equal(get_parodus_cfg()->cloud_status, CLOUD_STATUS_OFFLINE);
}
void test_PingMissIntervalTime()
void test_createSocketConnection2()
{
noPollCtx *ctx;
ParodusCfg cfg;
@@ -329,11 +245,12 @@ void test_PingMissIntervalTime()
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
parStrncpy(cfg.webpa_uuid , "1234567-345456546", sizeof(cfg.webpa_uuid));
//Max ping timeout is 6 sec
cfg.webpa_ping_timeout = 6;
cfg.webpa_ping_timeout = 1;
set_parodus_cfg(&cfg);
reset_close_retry();
pthread_mutex_lock (&close_mut);
close_retry = false;
pthread_mutex_unlock (&close_mut);
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)&ctx);
@@ -343,8 +260,7 @@ void test_PingMissIntervalTime()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 5);
//Increment ping interval time to 1 sec for each nopoll_loop_wait call
expect_function_calls(StartThread, 4);
will_return(nopoll_loop_wait, 1);
will_return(nopoll_loop_wait, 1);
will_return(nopoll_loop_wait, 1);
@@ -353,10 +269,9 @@ void test_PingMissIntervalTime()
will_return(nopoll_loop_wait, 1);
will_return(nopoll_loop_wait, 1);
expect_function_calls(nopoll_loop_wait, 7);
//Expecting Ping miss after 6 sec
expect_function_call(set_global_reconnect_reason);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(set_global_reconnect_status);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(set_global_conn);
@@ -368,13 +283,14 @@ void test_PingMissIntervalTime()
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(NULL);
}
void err_createSocketConnection()
{
set_close_retry();
reset_heartBeatTimer();
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
heartBeatTimer = 0;
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)NULL);
@@ -384,7 +300,7 @@ void err_createSocketConnection()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 5);
expect_function_calls(StartThread, 4);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
@@ -402,53 +318,6 @@ void err_createSocketConnection()
createSocketConnection(NULL);
}
void test_createSocketConnection_cloud_disconn()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(ParodusCfg));
cfg.cloud_disconnect = strdup("XPC");
set_parodus_cfg(&cfg);
set_close_retry();
reset_heartBeatTimer();
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)NULL);
expect_function_call(nopoll_ctx_new);
expect_function_call(nopoll_log_set_handler);
will_return(createNopollConnection, nopoll_true);
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 5);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(set_global_conn);
expect_function_call(set_cloud_disconnect_time);
will_return(get_cloud_disconnect_time, 0);
expect_function_call(get_cloud_disconnect_time);
will_return(get_cloud_disconnect_time, 0);
expect_function_call(get_cloud_disconnect_time);
will_return(get_cloud_disconnect_time, 0);
expect_function_call(get_cloud_disconnect_time);
will_return(createNopollConnection, nopoll_true);
expect_function_call(createNopollConnection);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(NULL);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -458,9 +327,8 @@ int main(void)
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_createSocketConnection),
cmocka_unit_test(test_createSocketConnection1),
cmocka_unit_test(test_PingMissIntervalTime),
cmocka_unit_test(test_createSocketConnection2),
cmocka_unit_test(err_createSocketConnection),
cmocka_unit_test(test_createSocketConnection_cloud_disconn)
};
return cmocka_run_group_tests(tests, NULL, NULL);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,397 +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 <string.h>
#include <unistd.h>
#include <wrp-c.h>
#include "../src/crud_interface.h"
#include "../src/config.h"
#include "../src/client_list.h"
#include "../src/ParodusInternal.h"
#include "../src/partners_check.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool g_shutdown = false;
extern CrudMsg *crudMsgQ;
int numLoops = 1;
wrp_msg_t *temp = NULL;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
char * get_global_UpStreamMsgQ(void)
{
function_called();
return (char *)mock();
}
int set_global_UpStreamMsgQ(void)
{
function_called();
return (int)mock();
}
int get_global_nano_con(void)
{
function_called();
return (int)mock();
}
int get_global_nano_mut(void)
{
function_called();
return (int)mock();
}
char *get_global_reconnect_reason()
{
function_called();
return (char *)(intptr_t)mock();
}
ParodusCfg *get_parodus_cfg(void)
{
function_called();
return (ParodusCfg*) (intptr_t)mock();
}
int pthread_mutex_lock(pthread_mutex_t *restrict mutex)
{
UNUSED(mutex);
function_called();
return (int)mock();
}
int pthread_mutex_unlock(pthread_mutex_t *restrict mutex)
{
UNUSED(mutex);
function_called();
return (int)mock();
}
int pthread_cond_signal(pthread_cond_t *restrict cond)
{
UNUSED(cond);
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();
}
int processCrudRequest(wrp_msg_t *reqMsg, wrp_msg_t **responseMsg )
{
UNUSED(reqMsg);
wrp_msg_t *resp_msg = NULL;
resp_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg->msg_type = 5;
resp_msg->u.crud.transaction_uuid = strdup("1234");
resp_msg->u.crud.source = strdup("tag-update");
resp_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
*responseMsg = resp_msg;
function_called();
return (int)mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_addCRUDmsgToQueue()
{
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
crudMsgQ = (CrudMsg *)malloc(sizeof(CrudMsg));
crudMsgQ->msg = crud_msg;
crudMsgQ->next = (CrudMsg *) malloc(sizeof(CrudMsg));
crudMsgQ->next->msg = crud_msg;
crudMsgQ->next->next = NULL;
addCRUDmsgToQueue(crud_msg);
free(crudMsgQ->next);
free(crudMsgQ);
crudMsgQ = NULL;
wrp_free_struct(crud_msg);
}
void test_addCRUDmsgToQueueNULL()
{
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
addCRUDmsgToQueue(crud_msg);
free(crudMsgQ->next);
free(crudMsgQ);
crudMsgQ = NULL;
wrp_free_struct(crud_msg);
}
void err_CRUDHandlerTask()
{
numLoops = 1;
crudMsgQ = NULL;
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_cond_wait, 0);
expect_function_call(pthread_cond_wait);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
CRUDHandlerTask();
}
void test_CRUDHandlerTask()
{
numLoops = 1;
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
crudMsgQ = (CrudMsg *)malloc(sizeof(CrudMsg));
crudMsgQ->msg = crud_msg;
crudMsgQ->next = NULL;
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
will_return(processCrudRequest, 0);
expect_function_call(processCrudRequest);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(get_global_UpStreamMsgQ, NULL);
expect_function_call(get_global_UpStreamMsgQ);
will_return(set_global_UpStreamMsgQ, 0);
expect_function_call(set_global_UpStreamMsgQ);
will_return(get_global_nano_con, 0);
expect_function_call(get_global_nano_con);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
CRUDHandlerTask();
free(crudMsgQ);
}
void test_CRUDHandlerTaskFailure()
{
numLoops = 1;
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
crudMsgQ = (CrudMsg *)malloc(sizeof(CrudMsg));
crudMsgQ->msg = crud_msg;
crudMsgQ->next = NULL;
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
will_return(processCrudRequest, -1);
expect_function_call(processCrudRequest);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(get_global_UpStreamMsgQ, 0);
expect_function_call(get_global_UpStreamMsgQ);
will_return(set_global_UpStreamMsgQ, 0);
expect_function_call(set_global_UpStreamMsgQ);
will_return(get_global_nano_con, 0);
expect_function_call(get_global_nano_con);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
CRUDHandlerTask();
free(crudMsgQ);
}
void test_addCRUDresponseToUpstreamQ()
{
numLoops = 1;
ssize_t resp_size = 0;
void *resp_bytes;
wrp_msg_t *resp_msg = NULL;
resp_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg->msg_type = 5;
resp_msg->u.crud.transaction_uuid = strdup("1234");
resp_msg->u.crud.source = strdup("tag-update");
resp_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
resp_size = wrp_struct_to( resp_msg, WRP_BYTES, &resp_bytes );
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(get_global_UpStreamMsgQ, 0);
expect_function_call(get_global_UpStreamMsgQ);
will_return(set_global_UpStreamMsgQ, 0);
expect_function_call(set_global_UpStreamMsgQ);
will_return(get_global_nano_con, 0);
expect_function_call(get_global_nano_con);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
addCRUDresponseToUpstreamQ(resp_bytes, resp_size);
wrp_free_struct(resp_msg);
}
void test_addCRUDmsgToQueueAllocation()
{
addCRUDmsgToQueue(NULL);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_addCRUDmsgToQueueNULL),
cmocka_unit_test(test_addCRUDmsgToQueue),
cmocka_unit_test(test_addCRUDmsgToQueueAllocation),
cmocka_unit_test(err_CRUDHandlerTask),
cmocka_unit_test(test_CRUDHandlerTask),
cmocka_unit_test(test_CRUDHandlerTaskFailure),
cmocka_unit_test(test_addCRUDresponseToUpstreamQ)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,283 +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 <string.h>
#include <unistd.h>
#include <wrp-c.h>
#include "../src/crud_tasks.h"
#include "../src/config.h"
#include "../src/client_list.h"
#include "../src/ParodusInternal.h"
#include "../src/partners_check.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
wrp_msg_t *response = NULL;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
cJSON * cJSON_Parse(const char *payload)
{
UNUSED(payload);
function_called();
return (cJSON *) mock();
}
int createObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
int retrieveObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
int updateObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
int deleteObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_processCrudRequestCreate()
{
int ret = -1;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 5;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(createObject, 0);
expect_function_call(createObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestCreateFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 5;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(createObject, -1);
expect_function_call(createObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestRetrieve()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 6;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(retrieveObject, 0);
expect_function_call(retrieveObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestRetrieveFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 6;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(retrieveObject, -1);
expect_function_call(retrieveObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestUpdate()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 7;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(updateObject, 0);
expect_function_call(updateObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestUpdateFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 7;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(updateObject, -1);
expect_function_call(updateObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestDelete()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 8;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(deleteObject, 0);
expect_function_call(deleteObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestDeleteFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 8;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(deleteObject, -1);
expect_function_call(deleteObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 3;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_processCrudRequestCreate),
cmocka_unit_test(test_processCrudRequestCreateFailure),
cmocka_unit_test(test_processCrudRequestRetrieve),
cmocka_unit_test(test_processCrudRequestRetrieveFailure),
cmocka_unit_test(test_processCrudRequestUpdate),
cmocka_unit_test(test_processCrudRequestUpdateFailure),
cmocka_unit_test(test_processCrudRequestDelete),
cmocka_unit_test(test_processCrudRequestDeleteFailure),
cmocka_unit_test(test_processCrudRequestFailure),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -21,7 +21,6 @@
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <wrp-c.h>
#include "../src/downstream.h"
#include "../src/ParodusInternal.h"
@@ -33,16 +32,9 @@
ParodusMsg *ParodusMsgQ;
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
int crud_test = 0;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
UNUSED(crudMsg) ;
function_called();
}
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
{
UNUSED(resp_bytes); UNUSED(resp_size);
@@ -61,10 +53,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,22 +60,13 @@ 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)->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;
(*msg)->u.req.partner_ids->partner_ids[0] = (char *) malloc(sizeof(char) *64);
parStrncpy((*msg)->u.req.dest,"mac:1122334455/iot", 100);
parStrncpy((*msg)->u.req.partner_ids->partner_ids[0],"comcast", 64);
if(crud_test)
{
(*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)->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;
(*msg)->u.req.partner_ids->partner_ids[0] = (char *) malloc(sizeof(char) *64);
parStrncpy((*msg)->u.req.dest,"mac:1122334455/iot", 100);
parStrncpy((*msg)->u.req.partner_ids->partner_ids[0],"comcast", 64);
return (ssize_t) mock();
}
@@ -210,23 +189,6 @@ void err_listenerOnMessageAllNull()
listenerOnMessage(NULL, 0);
}
void test_listenerOnMessageCRUD()
{
crud_test = 1;
will_return(wrp_to_struct, 2);
expect_function_calls(wrp_to_struct, 1);
will_return(get_numOfClients, 0);
expect_function_call(get_numOfClients);
will_return(validate_partner_id, 0);
expect_function_call(validate_partner_id);
will_return(get_global_node, (intptr_t)NULL);
expect_function_call(get_global_node);
expect_function_call(addCRUDmsgToQueue);
listenerOnMessage("Hello", 6);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -240,7 +202,6 @@ int main(void)
cmocka_unit_test(err_listenerOnMessageServiceUnavailable),
cmocka_unit_test(err_listenerOnMessageInvalidPartnerId),
cmocka_unit_test(err_listenerOnMessageAllNull),
cmocka_unit_test(test_listenerOnMessageCRUD),
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -58,7 +58,7 @@ static test_t tests[] = {
.r.msg_type = WRP_MSG_TYPE__CREATE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client1/iot",
.r.u.crud.source = "fake-client1",
.r.u.crud.dest = "fake-server1",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
@@ -88,7 +88,7 @@ static test_t tests[] = {
.r.msg_type = WRP_MSG_TYPE__RETREIVE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client2/iot",
.r.u.crud.source = "fake-client2",
.r.u.crud.dest = "fake-server2",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
@@ -118,7 +118,7 @@ static test_t tests[] = {
.r.msg_type = WRP_MSG_TYPE__UPDATE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client3/iot",
.r.u.crud.source = "fake-client3",
.r.u.crud.dest = "fake-server3",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
@@ -148,7 +148,7 @@ static test_t tests[] = {
.r.msg_type = WRP_MSG_TYPE__DELETE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client4/iot",
.r.u.crud.source = "fake-client4",
.r.u.crud.dest = "fake-server4",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
@@ -180,12 +180,6 @@ static uint8_t i;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;
return;
}
int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
(void) msg; (void) partnerIds;
@@ -244,10 +238,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

@@ -1,94 +0,0 @@
/**
* Copyright 2018 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 <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <pthread.h>
#include "../src/heartBeat.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_heartBeatTimer() {
/* get heartBeat timer's initial value */
unsigned int heartBeatTimer =5;
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer initial vaule is: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 0);
/* increment heartbeat timer value and check whether its returning modified value or not*/
unsigned int inc_time_ms =5;
increment_heartBeatTimer(inc_time_ms);
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer incremented to: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer,5);
/* reset heartBeat timer to 0 */
reset_heartBeatTimer();
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer reset to: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer,0);
}
void *test_mutexIncrementTimer() {
unsigned int inc_time_ms =5;
increment_heartBeatTimer(inc_time_ms);
return NULL;
}
void *test_mutexResetTimer() {
reset_heartBeatTimer();
return NULL;
}
void test_mutexHeartBeatTimer() {
unsigned int heartBeatTimer;
pthread_t thread[3];
pthread_create(&thread[0], NULL, test_mutexIncrementTimer, NULL);
pthread_create(&thread[1], NULL, test_mutexIncrementTimer, NULL);
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
/* After execution of both the threads check the value of timer */
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("Threads execution is completed, heartBeatTimer is: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 10);
pthread_create(&thread[2], NULL, test_mutexResetTimer, NULL);
pthread_join(thread[2], NULL);
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer reset to: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 0);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_heartBeatTimer),
cmocka_unit_test(test_mutexHeartBeatTimer),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -44,7 +44,7 @@
/*----------------------------------------------------------------------------*/
void test_checkHostIp()
{
CU_ASSERT_EQUAL(0, checkHostIp("www.python.org"))
CU_ASSERT_EQUAL(0, checkHostIp("fabric.webpa.comcast.net"))
}
void add_suites( CU_pSuite *suite )

View File

@@ -21,7 +21,6 @@
#include <nopoll_private.h>
#include <pthread.h>
#include "../src/ParodusInternal.h"
#include "../src/nopoll_handlers.h"
#include "../src/parodus_log.h"
@@ -30,7 +29,6 @@
/*----------------------------------------------------------------------------*/
volatile unsigned int heartBeatTimer;
bool LastReasonStatus;
int closeReason = 0;
pthread_mutex_t close_mut;
bool close_retry;
/*----------------------------------------------------------------------------*/
@@ -42,21 +40,6 @@ void set_global_reconnect_reason(char *reason)
(void) reason;
}
bool get_global_reconnect_status()
{
return LastReasonStatus;
}
bool get_interface_down_event()
{
return false;
}
void set_global_reconnect_status(bool status)
{
(void) status ;
}
const unsigned char *nopoll_msg_get_payload(noPollMsg *msg)
{
if( NULL != msg ) {
@@ -76,27 +59,12 @@ noPollOpCode nopoll_msg_opcode (noPollMsg * msg)
return NOPOLL_UNKNOWN_OP_CODE;
}
nopoll_bool nopoll_msg_is_fragment(noPollMsg *msg)
{
(void) msg;
return nopoll_false;
}
int nopoll_msg_get_payload_size(noPollMsg *msg)
{
(void) msg;
return 1;
}
int nopoll_conn_get_close_status (noPollConn * conn)
{
(void) conn;
if(closeReason)
return 1006;
else
return 0;
}
int nopoll_conn_send_frame (noPollConn * conn, nopoll_bool fin, nopoll_bool masked,
noPollOpCode op_code, long length, noPollPtr content, long sleep_in_header)
@@ -148,16 +116,16 @@ void *a1(void *in)
char str[] = "SSL_Socket_Close";
(void) in;
set_global_reconnect_status(false);
LastReasonStatus = false;
listenerOnCloseMessage(NULL, NULL, NULL);
set_global_reconnect_status(false);
LastReasonStatus = false;
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
set_global_reconnect_status(true);
LastReasonStatus = true;
listenerOnCloseMessage(NULL, NULL, NULL);
closeReason = 1;
set_global_reconnect_status(true);
LastReasonStatus = true;
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
pthread_exit(0);

View File

@@ -1,143 +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 <stdarg.h>
#include <stdbool.h>
#include <CUnit/Basic.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
#include <nopoll_private.h>
#include <pthread.h>
#include "../src/nopoll_handlers.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
volatile unsigned int heartBeatTimer;
bool LastReasonStatus;
pthread_mutex_t close_mut;
bool close_retry;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void set_global_reconnect_reason(char *reason)
{
(void) reason;
}
bool get_global_reconnect_status()
{
return LastReasonStatus;
}
bool get_interface_down_event()
{
return false;
}
void set_global_reconnect_status(bool status)
{
(void) status ;
}
nopoll_bool nopoll_msg_is_fragment(noPollMsg *msg)
{
(void)msg;
function_called();
return (nopoll_bool) mock();
}
nopoll_bool nopoll_msg_is_final(noPollMsg *msg)
{
(void)msg;
function_called();
return (nopoll_bool) mock();
}
const unsigned char *nopoll_msg_get_payload(noPollMsg *msg)
{
(void)msg;
function_called();
return (const unsigned char *) mock();
}
int nopoll_msg_get_payload_size(noPollMsg *msg)
{
(void) msg;
function_called ();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_listenerOnMessage_queue_fragment()
{
noPollMsg *msg, *msg1;
msg = nopoll_msg_new ();
//1st Fragment
msg->payload_size = strlen("hello");
msg->payload = nopoll_new (char, msg->payload_size + 1);
will_return(nopoll_msg_is_fragment, nopoll_true);
expect_function_call(nopoll_msg_is_fragment);
will_return(nopoll_msg_is_final, nopoll_false);
will_return(nopoll_msg_is_final, nopoll_false);
expect_function_calls(nopoll_msg_is_final, 2);
listenerOnMessage_queue(NULL, NULL, msg, NULL);
//2nd fragment/final message
msg1 = nopoll_msg_new ();
msg1->payload_size = strlen("world");
msg1->payload = nopoll_new (char, msg->payload_size + 1);
will_return(nopoll_msg_is_fragment, nopoll_true);
expect_function_call(nopoll_msg_is_fragment);
will_return(nopoll_msg_is_final, nopoll_true);
will_return(nopoll_msg_is_final, nopoll_true);
expect_function_calls(nopoll_msg_is_final, 2);
will_return(nopoll_msg_get_payload, (intptr_t)"helloworld");
expect_function_call(nopoll_msg_get_payload);
will_return(nopoll_msg_get_payload_size, 10);
expect_function_call(nopoll_msg_get_payload_size);
listenerOnMessage_queue(NULL, NULL, msg1, NULL);
//release the message
nopoll_msg_unref(msg);
nopoll_msg_unref(msg1);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( void )
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_listenerOnMessage_queue_fragment),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -16,7 +16,6 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
@@ -97,31 +96,6 @@ void listenerOnCloseMessage (noPollCtx * ctx, noPollConn * conn, noPollPtr user_
UNUSED(ctx); UNUSED(conn); UNUSED(user_data);
}
void getCurrentTime(struct timespec *timer)
{
(void) timer;
function_called();
}
long timeValDiff(struct timespec *starttime, struct timespec *finishtime)
{
(void) starttime; (void) finishtime;
function_called();
return (long) mock();
}
int kill(pid_t pid, int sig)
{
UNUSED(pid); UNUSED(sig);
function_called();
return (int) mock();
}
bool get_interface_down_event()
{
return false;
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -228,69 +202,6 @@ void test_sendMessage()
sendMessage(conn, "Hello Parodus!", len);
}
void connStuck_sendMessage()
{
int len = strlen("Hello Parodus!");
/* Initialize the timer when connection gets stuck */
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)NULL);
will_return(nopoll_conn_is_ok, nopoll_false);
expect_function_call(nopoll_conn_is_ok);
expect_function_call(getCurrentTime);
sendMessage(NULL, "Hello Parodus!", len);
/* When connection recovers within 10 mins, it should be able to re-connect */
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)NULL);
will_return(nopoll_conn_is_ok, nopoll_false);
expect_function_call(nopoll_conn_is_ok);
expect_function_call(getCurrentTime);
will_return(timeValDiff, 5*60*1000);
expect_function_call(timeValDiff);
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)conn);
will_return(nopoll_conn_is_ok, nopoll_true);
expect_function_call(nopoll_conn_is_ok);
expect_value(nopoll_conn_is_ready, (intptr_t)conn, (intptr_t)conn);
will_return(nopoll_conn_is_ready, nopoll_true);
expect_function_call(nopoll_conn_is_ready);
expect_value(__nopoll_conn_send_common, (intptr_t)conn, (intptr_t)conn);
expect_value(__nopoll_conn_send_common, length, len);
will_return(__nopoll_conn_send_common, len);
expect_function_calls(__nopoll_conn_send_common, 1);
sendMessage(conn, "Hello Parodus!", len);
/* When timer exceeds more than 10 mins kill the process */
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)NULL);
will_return(nopoll_conn_is_ok, nopoll_false);
expect_function_call(nopoll_conn_is_ok);
sendMessage(NULL, "Hello Parodus!", len);
expect_function_call(getCurrentTime);
sendMessage(NULL, "Hello Parodus!", len);
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)NULL);
will_return(nopoll_conn_is_ok, nopoll_false);
expect_function_call(nopoll_conn_is_ok);
expect_function_call(getCurrentTime);
will_return(timeValDiff, 10*60*1000);
expect_function_call(timeValDiff);
will_return(kill, 1);
expect_function_call(kill);
sendMessage(NULL, "Hello Parodus!", len);
}
void err_sendMessage()
{
int len = strlen("Hello Parodus!");
@@ -323,9 +234,7 @@ void err_sendMessageConnNull()
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)NULL);
will_return(nopoll_conn_is_ok, nopoll_false);
expect_function_call(nopoll_conn_is_ok);
expect_function_call(getCurrentTime);
sendMessage(NULL, "Hello Parodus!", len);
}
@@ -349,7 +258,6 @@ int main(void)
cmocka_unit_test(err_sendResponseFlushWrites),
cmocka_unit_test(err_sendResponseConnNull),
cmocka_unit_test(test_sendMessage),
cmocka_unit_test(connStuck_sendMessage),
cmocka_unit_test(err_sendMessage),
cmocka_unit_test(err_sendMessageConnNull),
cmocka_unit_test(test_reportLog),

View File

@@ -60,25 +60,6 @@ void test_validate_partner_id_for_req()
free(msg);
}
void test_validate_partner_id_for_req_case_insensitive()
{
static partners_t partner_ids = {2,{"Shaw","Comcast"}};
wrp_msg_t *msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
memset(msg, 0, sizeof(wrp_msg_t));
msg->msg_type = WRP_MSG_TYPE__REQ;
msg->u.req.partner_ids = &partner_ids;
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
parStrncpy(cfg.partner_id, "comcast", sizeof(cfg.partner_id));
will_return(get_parodus_cfg, (intptr_t)&cfg);
expect_function_call(get_parodus_cfg);
int ret = validate_partner_id(msg, NULL);
assert_int_equal(ret, 1);
free(msg);
}
void test_validate_partner_id_for_req_listNULL()
{
wrp_msg_t *msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
@@ -153,28 +134,6 @@ void test_validate_partner_id_for_event()
free(msg);
}
void test_validate_partner_id_for_event_case_insensitive()
{
static partners_t partner_ids = {1,{"Comcast"}};
wrp_msg_t *msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
memset(msg, 0, sizeof(wrp_msg_t));
msg->msg_type = WRP_MSG_TYPE__EVENT;
msg->u.event.partner_ids = &partner_ids;
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
parStrncpy(cfg.partner_id, "*,comcast", sizeof(cfg.partner_id));
will_return(get_parodus_cfg, (intptr_t)&cfg);
expect_function_call(get_parodus_cfg);
partners_t *list = NULL;
int ret = validate_partner_id(msg, &list);
assert_int_equal(ret, 1);
free(list);
free(msg);
}
void test_validate_partner_id_for_event_listNULL()
{
wrp_msg_t *msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
@@ -259,12 +218,10 @@ int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_validate_partner_id_for_req),
cmocka_unit_test(test_validate_partner_id_for_req_case_insensitive),
cmocka_unit_test(test_validate_partner_id_for_req_listNULL),
cmocka_unit_test(test_validate_partner_id_for_req_withoutId),
cmocka_unit_test(err_validate_partner_id_for_req),
cmocka_unit_test(test_validate_partner_id_for_event),
cmocka_unit_test(test_validate_partner_id_for_event_case_insensitive),
cmocka_unit_test(test_validate_partner_id_for_event_listNULL),
cmocka_unit_test(test_validate_partner_id_for_event_withoutId),
cmocka_unit_test(err_validate_partner_id_for_event),

View File

@@ -33,33 +33,11 @@ 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 */
/*----------------------------------------------------------------------------*/
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;
return;
}
void *CRUDHandlerTask()
{
return NULL;
}
static void add_client()
{
@@ -67,7 +45,6 @@ static void add_client()
.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 +62,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);
@@ -137,21 +114,13 @@ static void *client_rcv_task()
return 0;
}
static void handler(int signum)
{
UNUSED(signum);
pthread_exit(NULL);
}
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;
}
@@ -175,10 +144,9 @@ void test_keep_alive()
}
else
{
ParodusPrint("Thread created Successfully %p\n", threadId);
ParodusPrint("Thread created Successfully %d\n", (int ) threadId);
}
sleep(3);
signal(SIGUSR1, handler);
while( 1 )
{
@@ -188,9 +156,9 @@ void test_keep_alive()
if(byte >0)
{
ParodusInfo("Received keep alive msg!!! : %s \n", (char * )buf);
pthread_kill(threadId, SIGUSR1);
kill(threadId, SIGKILL);
ParodusInfo("keep_alive_thread with tid %p is stopped\n", threadId);
ParodusInfo("keep_alive_thread with tid %d is stopped\n", threadId);
break;
}
else
@@ -219,6 +187,7 @@ void add_suites( CU_pSuite *suite )
ParodusInfo("--------Start of Test Cases Execution ---------\n");
*suite = CU_add_suite( "tests", NULL, NULL );
CU_add_test( *suite, "Test 1", test_keep_alive );
}
/*----------------------------------------------------------------------------*/

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

@@ -24,7 +24,6 @@
#include <cmocka.h>
#include <assert.h>
#include <cjwt/cjwt.h>
#include <wrp-c.h>
#include "../src/token.h"
#include "../src/ParodusInternal.h"
@@ -39,11 +38,11 @@ time_t exp_time_bad = 1463955372; // 5/22/2016
const char *payload_good = "{" \
"\"iss\": \"SHA256:jdcRysFunWUAT852huQoIM9GN6k2s5c7iTMTMgujPAk\"," \
"\"endpoint\": \"https://mydns.mycom.net:8080/\"}";
"\"endpoint\": \"https://fabric.webpa.comcast.net:8080/\"}";
const char *payload_insec = "{" \
"\"iss\": \"SHA256:jdcRysFunWUAT852huQoIM9GN6k2s5c7iTMTMgujPAk\"," \
"\"endpoint\": \"http://mydns.mycom.net:8080/\"}";
"\"endpoint\": \"http://fabric.webpa.comcast.net:8080/\"}";
// missing endpoint
const char *payload_no_end = "{" \
@@ -53,89 +52,69 @@ const char *txt_record_id = "aabbccddeeff.test.webpa.comcast.net";
#define MAX_RR_RECS 10
/*
expiration = 2147483647 #1/18/2038
endpoint = "https://mydns.mycom.net:8080/"
dns_rec_claims = {
'iss': u'SHA256:jdcRysFunWUAT852huQoIM9GN6k2s5c7iTMTMgujPAk',
'endpoint': endpoint,
'exp': expiration
}
*/
const char *dns_recs_test =
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"01:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1\"\n"
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"01:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
const char *dns_recs_extra =
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"01:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"01:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm\"\n"
"\n" // non-txt record type
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
char *rr_recs_test[] = {
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1",
"EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX",
"iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ"
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm",
"X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-",
"ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA"
};
char *dns_jwt_test =
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1"
"EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX"
"iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ"
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm"
"X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-"
"ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA"
;
/*
expiration = 2147483647 #1/18/2038
endpoint = "https://mydns.mycom.net:8080/"
dns_rec2_claims = {
'endpoint': endpoint
}
*/
// no exp in it
const char *dns_recs2_test =
"\"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbmRwb2ludCI6Imh0dHBzOi8vbXlkbnMubXljb20ubmV0OjgwODAvIn0.YkudDhp7Ifr6wTsCfrYUUeRf1CMKannC6Bx994OrcBVwqNQ1G5uBXEgsslUnbqV_7FTGPp1Vs058qncmIXtEYxVlHt-mn1UEm6hyC_QGi9FfMHYBS7QHwcCIs467XUFMZayQ3upzZNXObhzJNF0-RR72S61cjSGqf1z5KgyBtoANtW6xCdWB5VV6CqCxlmJNj6d4N8vKiUvN346-UgB_H4AuaXCNdXJ2NP2DxRec-oNTCjhNzRn-6MaB-UwW_gD9CYfQ0vrw2Nv8dO1Sk5Ku94cdIfvUEft-kyqPGKmK8soIggjvmvW0JEPYwrWYY9Ry5SQf80-dLOPXCQSQ3Rzy7Q\""
const char *dns_recs_fabric =
"\"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbmRwb2ludCI6Imh0dHBzOi8vZmFicmljLndlYnBhLmNvbWNhc3QubmV0OjgwODAvIn0.24cvUmCGYqqXuSsgC7nNnle2JH-uy6Jwp5BKXADhXpc\""
;
// no exp in it
char *rr_recs2_test[] = {
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbmRwb2ludCI6Imh0dHBzOi8vbXlkbnMubXljb20ubmV0OjgwODAvIn0.YkudDhp7Ifr6wTsCfrYUUeRf1CMKannC6Bx994OrcBVwqNQ1G5uBXEgsslUnbqV_7FTGPp1Vs058qncmIXtEYxVlHt-mn1UEm6hyC_QGi9FfMHYBS7QHwcCIs467XUFMZayQ3upzZNXObhzJNF0-RR72S61cjSGqf1z5KgyBtoANtW6xCdWB5VV6CqCxlmJNj6d4N8vKiUvN346-UgB_H4AuaXCNdXJ2NP2DxRec-oNTCjhNzRn-6MaB-UwW_gD9CYfQ0vrw2Nv8dO1Sk5Ku94cdIfvUEft-kyqPGKmK8soIggjvmvW0JEPYwrWYY9Ry5SQf80-dLOPXCQSQ3Rzy7Q"
char *rr_recs_fabric[] = {
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbmRwb2ludCI6Imh0dHBzOi8vZmFicmljLndlYnBhLmNvbWNhc3QubmV0OjgwODAvIn0.24cvUmCGYqqXuSsgC7nNnle2JH-uy6Jwp5BKXADhXpc"
};
const char *dns_recs_err1 = // missing seq
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1\"\n"
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
const char *dns_recs_err2 = // invalid seq
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"0:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1\"\n"
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"0:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
const char *dns_recs_err3 = // invalid seq too high
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"99:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1\"\n"
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"99:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
const char *dns_recs_err4 = // duplicate seq number
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"01:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTSEEyNTY6amRjUnlzRnVuV1VBVDg1Mmh1UW9JTTlHTjZrMnM1YzdpVE1UTWd1alBBayIsImVuZHBvaW50IjoiaHR0cHM6Ly9teWRucy5teWNvbS5uZXQ6ODA4MC8iLCJleHAiOjIxNDc0ODM2NDd9.VjG2PzPws2J707PiEaUGOTXD9NWnrGyfAUvvfyXFw-Px3gx5wg1\"\n"
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\"01:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTQ3NjQ3OTksImlzcyI6IlNIQTI1NjpqZGNSeXNGdW5XVUFUODUyaHVRb0lNOUdONmsyczVjN2lUTVRNZ3VqUEFrIiwiZW5kcG9pbnQiOiJodHRwczovL2ZhYnJpYy53ZWJwYS5jb21jYXN0Lm5ldDo4MDgwLyJ9.ahYvcvZxKfKt-enfMZOT9JwCr7eGECv2fUYEDbVdm\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
const char *dns_recs_err5 = // missing rec 1
"\"03:iJmBr4pGROCCbRlbL3GpGDcSFJcaqBQFOriTRk0xKQ\"\n"
"\"03:ji81f9B4vnaENEZJgPzYiYdVLvbkgg9rbI7RVcEjutIszb7XZA\"\n"
"\n" // non-txt record type
"\"02:EXGyJQXrxMYuepAiFPT0sWxvydHvZKxcx7S5MCmlOhRpWZRrzgFceNWMwFcRPAPxovOoc4aYvx2DqGMdckmAD1q3y3Gjjw1qyxd4503jmrXKfjrdW3eFZD_Q454iRVf4c0CMWA5tl0ElOlX9u_HC3G_dPiKGUBU5PpWONgHpg2-ewrQcUe4-J4hBQmqZmRSB9n-6zB1XD80cDQO7aHeJ9aysJS1vgmwaSuT9y6PhPsp05NUC0TDzZVJUX\"\n"
"\"02:X1Jq1iPnD8MqkSOyHUQ8a17DOFQSmv8C3ZTKkjtFHEUR8l-KYhaA8bmU7Fzo8m0f4Ub411p4r4VE3KOdv8TWbKgKKIElONJmimpCDvHaUG6SZTaGB_proHyw5Vy5RzK4EAUc0C36hPBF6pIQfl5DgT1I66MHDcklMx2af2_F26Wv4rRX3pU_Q6fvustJhRTBcCJa7S6NZrm_Ca9rkRk5v2dyXkzrrB0_PCIoHITom8DPF8N56EDGzLyY25-\"\n"
;
cjwt_t jwt1; // secure, payload good
@@ -144,7 +123,7 @@ cjwt_t jwt3; // insecure
cjwt_t jwt4; // missing endpoint
// internal functions in token.c to be tested
extern int analyze_jwt (const cjwt_t *jwt, char **url_buf, unsigned int *port);
extern int analyze_jwt (const cjwt_t *jwt);
extern bool validate_algo(const cjwt_t *jwt);
extern int nquery(const char* dns_txt_record_id,u_char *nsbuf);
extern bool valid_b64_char (char c);
@@ -158,30 +137,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;
return;
}
void *CRUDHandlerTask()
{
return NULL;
}
int setup_test_jwts (void)
{
memset (&jwt1, 0, sizeof(cjwt_t));
@@ -227,8 +182,8 @@ static int get_dns_text (const char *dns_rec_id, u_char *nsbuf, int bufsize)
rec = dns_recs_test;
else if (strstr (dns_rec_id, ".extra.") != NULL)
rec = dns_recs_extra;
else if (strstr (dns_rec_id, ".test2.") != NULL)
rec = dns_recs2_test;
else if (strstr (dns_rec_id, ".fabric.") != NULL)
rec = dns_recs_fabric;
else if (strstr (dns_rec_id, ".err1.") != NULL)
rec = dns_recs_err1;
else if (strstr (dns_rec_id, ".err2.") != NULL)
@@ -249,9 +204,6 @@ static int get_dns_text (const char *dns_rec_id, u_char *nsbuf, int bufsize)
/* Mocks */
/*----------------------------------------------------------------------------*/
// These mocks assume that the pieces of a dns txt record end with '\n';
int ns_initparse(const u_char *nsbuf, int l, ns_msg *msg_handle)
{
UNUSED(l);
@@ -296,14 +248,12 @@ int ns_parserr(ns_msg *msg_handle, ns_sect sect, int rec, ns_rr *rr)
ptr += (l+1);
}
l = strlen(ptr);
if (l == 0) {
if (strlen (ptr) == 0) {
rr->type = ns_t_key;
} else {
rr->type = ns_t_txt;
}
rr->rdata = (u_char *) ptr;
rr->rdlength = l;
return 0;
}
@@ -332,34 +282,26 @@ void __res_nclose (res_state statp)
function_called ();
}
// Analyzes a jwt structure
void test_analyze_jwt ()
{
unsigned int port;
char *server_Address;
int ret = setup_test_jwts ();
assert_int_equal (ret, 0);
ret = analyze_jwt (&jwt1, &server_Address, &port);
ret = analyze_jwt (&jwt1);
assert_int_equal (ret, 0);
assert_string_equal (server_Address, "mydns.mycom.net");
assert_int_equal (port, 8080);
free (server_Address);
ret = analyze_jwt (&jwt2, &server_Address, &port);
ret = analyze_jwt (&jwt2);
assert_int_equal (ret, TOKEN_ERR_JWT_EXPIRED);
ret = analyze_jwt (&jwt3, &server_Address, &port);
ret = analyze_jwt (&jwt3);
assert_int_equal (ret, 1);
assert_string_equal (server_Address, "mydns.mycom.net");
assert_int_equal (port, 8080);
free (server_Address);
ret = analyze_jwt (&jwt4, &server_Address, &port);
ret = analyze_jwt (&jwt4);
assert_int_equal (ret, TOKEN_ERR_INVALID_JWT_CONTENT);
}
void test_validate_algo ()
{
bool ret;
ParodusCfg cfg;
cfg.jwt_algo = 1025;
parStrncpy (cfg.jwt_algo, "none:RS256", sizeof(cfg.jwt_algo));
set_parodus_cfg (&cfg);
jwt1.header.alg = alg_rs256;
ret = validate_algo (&jwt1);
@@ -411,14 +353,12 @@ void test_strip_rrdata ()
const char *result;
int rlen;
rlen = strlen (s1);
result = strip_rr_data (s1, &rlen);
assert_int_equal (rlen, s1len);
if (rlen == s1len) {
assert_int_equal (strncmp (result, ss1, rlen), 0);
}
rlen = strlen (s2);
result = strip_rr_data (s2, &rlen);
assert_int_equal (rlen, s1len);
if (rlen == s1len) {
@@ -504,7 +444,7 @@ void test_get_rr_seq_table()
assert_int_equal (ret, 0);
}
ret = get_dns_text (".test2.", nsbuf, 4096);
ret = get_dns_text (".fabric.", nsbuf, 4096);
assert_int_equal (ret, 0);
ns_initparse (nsbuf, 4096, &msg_handle);
assert_int_equal (msg_handle._counts[ns_s_an], 1);
@@ -512,9 +452,9 @@ void test_get_rr_seq_table()
assert_int_equal (num_txt_recs, 1);
assert_ptr_not_equal (seq_table[0].rr_ptr, NULL);
if (NULL != seq_table[0].rr_ptr) {
int len = strlen (rr_recs2_test[0]);
int len = strlen (rr_recs_fabric[0]);
assert_int_equal (len, seq_table[0].rr_len);
ret = strncmp (seq_table[0].rr_ptr, rr_recs2_test[0], len);
ret = strncmp (seq_table[0].rr_ptr, rr_recs_fabric[0], len);
assert_int_equal (ret, 0);
}
@@ -626,57 +566,53 @@ void test_query_dns ()
void test_allow_insecure_conn ()
{
int insecure;
char *server_addr;
unsigned int port;
ParodusCfg *cfg = get_parodus_cfg();
parStrncpy (cfg->hw_mac, "aabbccddeeff", sizeof(cfg->hw_mac));
parStrncpy (cfg->dns_txt_url, "test.mydns.mycom.net", sizeof(cfg->dns_txt_url));
cfg->jwt_algo = 1025;
parStrncpy (cfg->dns_txt_url, "test", sizeof(cfg->dns_txt_url));
parStrncpy (cfg->jwt_algo, "none:RS256", sizeof(cfg->jwt_algo));
read_key_from_file ("../../tests/pubkey4.pem", cfg->jwt_key, 4096);
read_key_from_file ("../../tests/webpa-rs256.pem", cfg->jwt_key, 4096);
will_return (__res_ninit, 0);
expect_function_call (__res_ninit);
expect_function_call (__res_nclose);
insecure = allow_insecure_conn (&server_addr, &port);
free (server_addr);
insecure = allow_insecure_conn ();
assert_int_equal (insecure, 0);
parStrncpy (cfg->hw_mac, "aabbccddeeff", sizeof(cfg->hw_mac));
parStrncpy (cfg->dns_txt_url, "err5.mydns.mycom.net", sizeof(cfg->dns_txt_url));
parStrncpy (cfg->dns_txt_url, "err5", sizeof(cfg->dns_txt_url));
will_return (__res_ninit, 0);
expect_function_call (__res_ninit);
expect_function_call (__res_nclose);
insecure = allow_insecure_conn (&server_addr, &port);
insecure = allow_insecure_conn ();
assert_int_equal (insecure, TOKEN_ERR_QUERY_DNS_FAIL);
parStrncpy (cfg->hw_mac, "aabbccddeeff", sizeof(cfg->hw_mac));
parStrncpy (cfg->dns_txt_url, "test.mydns.mycom.net", sizeof(cfg->dns_txt_url));
cfg->jwt_algo = 1024;
parStrncpy (cfg->dns_txt_url, "test", sizeof(cfg->dns_txt_url));
parStrncpy (cfg->jwt_algo, "none:RS256", sizeof(cfg->jwt_algo));
parStrncpy (cfg->jwt_key, "xxxxxxxxxx", sizeof(cfg->jwt_key));
will_return (__res_ninit, 0);
expect_function_call (__res_ninit);
expect_function_call (__res_nclose);
insecure = allow_insecure_conn (&server_addr, &port);
insecure = allow_insecure_conn ();
assert_int_equal (insecure, TOKEN_ERR_JWT_DECODE_FAIL);
parStrncpy (cfg->hw_mac, "aabbccddeeff", sizeof(cfg->hw_mac));
parStrncpy (cfg->dns_txt_url, "test.mydns.mycom.net", sizeof(cfg->dns_txt_url));
cfg->jwt_algo = 4097;
read_key_from_file ("../../tests/pubkey4.pem", cfg->jwt_key, 4096);
parStrncpy (cfg->dns_txt_url, "test", sizeof(cfg->dns_txt_url));
parStrncpy (cfg->jwt_algo, "none:RS512", sizeof(cfg->jwt_algo));
read_key_from_file ("../../tests/webpa-rs256.pem", cfg->jwt_key, 4096);
will_return (__res_ninit, 0);
expect_function_call (__res_ninit);
expect_function_call (__res_nclose);
insecure = allow_insecure_conn (&server_addr, &port);
insecure = allow_insecure_conn ();
assert_int_equal (insecure, TOKEN_ERR_ALGO_NOT_ALLOWED);
}
@@ -708,11 +644,11 @@ void test_get_algo_mask ()
{
unsigned mask;
mask = get_algo_mask ("rs256");
assert_int_equal ((int) mask, 1024);
mask = get_algo_mask ("none");
assert_int_equal ((int) mask, 1);
mask = get_algo_mask ("rs512:rs256");
assert_int_equal ((int) mask, 5120);
mask = get_algo_mask ("none:rs256");
assert_int_equal ((int) mask, 1025);
}
/*----------------------------------------------------------------------------*/
@@ -732,7 +668,7 @@ int main(void)
cmocka_unit_test(test_get_rr_seq_table),
cmocka_unit_test(test_assemble_jwt_from_dns),
cmocka_unit_test(test_query_dns),
cmocka_unit_test(test_allow_insecure_conn),
//cmocka_unit_test(test_allow_insecure_conn),
cmocka_unit_test(test_get_tok),
cmocka_unit_test(test_get_algo_mask),
};

View File

@@ -22,8 +22,7 @@
#include <setjmp.h>
#include <cmocka.h>
#include <assert.h>
#include <wrp-c.h>
#include <pthread.h>
#include "../src/token.h"
@@ -31,38 +30,11 @@
/* 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;
return;
}
void *CRUDHandlerTask()
{
return NULL;
}
void test_allow_insecure_conn ()
{
int insecure;
char *server_Address = NULL;
unsigned int port;
insecure = allow_insecure_conn (&server_Address, &port);
assert_int_equal (insecure, TOKEN_NO_DNS_QUERY);
insecure = allow_insecure_conn ();
assert_int_equal (insecure, 1);
}
/*----------------------------------------------------------------------------*/

View File

@@ -31,23 +31,17 @@
#include "../src/client_list.h"
#include "../src/ParodusInternal.h"
#include "../src/partners_check.h"
#include "../src/close_retry.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
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;
static int crud_test = 0;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -68,51 +62,19 @@ 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();
return (int)mock();
}
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;
function_called();
return;
}
int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize)
{
UNUSED(dest); UNUSED(Msg); UNUSED(msgSize);
function_called();
return (int)mock();
}
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;
}
@@ -179,19 +141,7 @@ ssize_t wrp_to_struct( const void *bytes, const size_t length, const enum wrp_fo
{
UNUSED(bytes); UNUSED(length); UNUSED(fmt);
function_called();
if(crud_test)
{
wrp_msg_t *resp_msg = NULL;
resp_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg->msg_type = 5;
resp_msg->u.crud.source = strdup("mac:14xxx/tags");
*msg = resp_msg;
}
else
{
*msg = temp;
}
*msg = temp;
return (ssize_t)mock();
}
@@ -215,13 +165,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 +210,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 +229,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 +242,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();
@@ -351,42 +280,10 @@ void test_processUpstreamMessage()
expect_function_call(appendEncodedData);
expect_function_call(sendMessage);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ->next);
free(UpStreamMsgQ);
}
void test_processUpstreamReqMessage()
{
numLoops = 1;
metaPackSize = 20;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = "First Message";
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->next->msg = "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 = 3;
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(appendEncodedData, 100);
expect_function_call(appendEncodedData);
expect_function_call(sendMessage);
will_return(nn_freemsg, 0);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
@@ -420,9 +317,10 @@ void test_processUpstreamMessageInvalidPartner()
expect_function_call(appendEncodedData);
expect_function_call(sendMessage);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ->next);
@@ -454,18 +352,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);
@@ -480,9 +375,10 @@ void test_processUpstreamMessageRegMsg()
will_return(get_numOfClients, 1);
expect_function_call(get_numOfClients);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
processUpstreamMessage();
free(temp);
@@ -516,17 +412,15 @@ 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);
will_return(addToList, 0);
expect_function_call(addToList);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
processUpstreamMessage();
free(temp);
@@ -555,11 +449,12 @@ void err_processUpstreamMessageDecodeErr()
temp = (wrp_msg_t *) malloc(sizeof(wrp_msg_t));
memset(temp,0,sizeof(wrp_msg_t));
temp->msg_type = 3;
will_return(wrp_to_struct, -1);
expect_function_call(wrp_to_struct);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
@@ -580,9 +475,10 @@ void err_processUpstreamMessageMetapackFailure()
will_return(wrp_to_struct, 15);
expect_function_call(wrp_to_struct);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
@@ -616,27 +512,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);
@@ -648,9 +538,10 @@ void err_processUpstreamMessageRegMsg()
will_return(addToList, -1);
expect_function_call(addToList);
will_return(nn_freemsg, 0);
expect_function_call(nn_freemsg);
expect_function_call(wrp_free_struct);
will_return(nn_freemsg,1);
expect_function_call(nn_freemsg);
processUpstreamMessage();
free(temp);
@@ -677,199 +568,12 @@ void test_sendUpstreamMsgToServer()
free(bytes);
}
void test_sendUpstreamMsg_close_retry()
{
set_close_retry();
void *bytes = NULL;
wrp_msg_t msg;
memset(&msg, 0, sizeof(wrp_msg_t));
msg.msg_type = WRP_MSG_TYPE__EVENT;
wrp_struct_to( &msg, WRP_BYTES, &bytes );
metaPackSize = 10;
will_return(appendEncodedData, 100);
expect_function_call(appendEncodedData);
sendUpstreamMsgToServer(&bytes, 110);
free(bytes);
}
void err_sendUpstreamMsgToServer()
{
metaPackSize = 0;
sendUpstreamMsgToServer(NULL, 110);
}
void test_get_global_UpStreamMsgQ()
{
assert_ptr_equal(UpStreamMsgQ, get_global_UpStreamMsgQ());
}
void test_set_global_UpStreamMsgQ()
{
static UpStreamMsg *UpStreamQ;
UpStreamQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamQ->msg = "First Message";
UpStreamQ->len = 13;
UpStreamQ->next = NULL;
set_global_UpStreamMsgQ(UpStreamQ);
assert_string_equal(UpStreamQ->msg, (char *)get_global_UpStreamMsgQ()->msg);
assert_int_equal(UpStreamQ->len, get_global_UpStreamMsgQ()->len);
free(UpStreamQ->next);
free(UpStreamQ);
}
void test_get_global_nano_con()
{
assert_ptr_equal(&nano_con, get_global_nano_con());
}
void test_get_global_nano_mut()
{
assert_ptr_equal(&nano_mut, get_global_nano_mut());
}
void test_processUpstreamMsgCrud_nnfree()
{
numLoops = 1;
crud_test = 1;
metaPackSize = 0;
UpStreamMsgQ = (UpStreamMsg *) malloc(sizeof(UpStreamMsg));
UpStreamMsgQ->msg = "First Message";
UpStreamMsgQ->len = 13;
UpStreamMsgQ->next = NULL;
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(UpStreamMsgQ);
crud_test = 0;
}
void test_processUpstreamMsg_cloud_status()
{
numLoops = 1;
metaPackSize = 20;
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);
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 test_processUpstreamMsg_sendToClient()
{
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;
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/config");
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);
will_return(sendMsgtoRegisteredClients, 1);
expect_function_call(sendMsgtoRegisteredClients);
expect_function_call(wrp_free_struct);
will_return(wrp_to_struct, 12);
expect_function_call(wrp_to_struct);
will_return(sendMsgtoRegisteredClients, 0);
expect_function_call(sendMsgtoRegisteredClients);
expect_function_call(wrp_free_struct);
processUpstreamMessage();
free(temp);
free(UpStreamMsgQ);
UpStreamMsgQ = NULL;
}
void test_processUpstreamMsg_serviceNameNULL()
{
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;
}
void err_processUpstreamMsg_deviceID()
{
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);
UpStreamMsgQ = NULL;
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -884,7 +588,6 @@ int main(void)
cmocka_unit_test(err_handleUpstreamBindFailure),
cmocka_unit_test(err_handleUpstreamSockFailure),
cmocka_unit_test(test_processUpstreamMessage),
cmocka_unit_test(test_processUpstreamReqMessage),
cmocka_unit_test(test_processUpstreamMessageInvalidPartner),
cmocka_unit_test(test_processUpstreamMessageRegMsg),
cmocka_unit_test(test_processUpstreamMessageRegMsgNoClients),
@@ -893,17 +596,7 @@ int main(void)
cmocka_unit_test(err_processUpstreamMessageMetapackFailure),
cmocka_unit_test(err_processUpstreamMessageRegMsg),
cmocka_unit_test(test_sendUpstreamMsgToServer),
cmocka_unit_test(test_sendUpstreamMsg_close_retry),
cmocka_unit_test(err_sendUpstreamMsgToServer),
cmocka_unit_test(test_get_global_UpStreamMsgQ),
cmocka_unit_test(test_set_global_UpStreamMsgQ),
cmocka_unit_test(test_get_global_nano_con),
cmocka_unit_test(test_get_global_nano_mut),
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)
};
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);
}