Compare commits

..

147 Commits
1.0.3 ... main

Author SHA1 Message Date
schmidtw
e3815115af Use newer codecove action. 2024-07-11 23:45:08 -07:00
Weston Schmidt
6dcabbcf5f Use the workflow from the upstream parodus repo. 2023-12-01 09:31:00 -08:00
Weston Schmidt
6782ae7868 Fix the path. 2023-11-28 00:51:34 -08:00
Weston Schmidt
e274b572dd Try the sonarcloud installer 2023-11-28 00:48:06 -08:00
Weston Schmidt
4107159696 Update push.yml 2023-11-28 00:14:03 -08:00
Weston Schmidt
94531a3faa Update push.yml 2023-11-28 00:10:22 -08:00
Weston Schmidt
373acb170a Update push.yml 2023-11-28 00:07:02 -08:00
Weston Schmidt
262a23e00e Update push.yml 2023-09-11 23:49:09 -07:00
Weston Schmidt
193706c21c Release 1.1.5 2021-06-02 18:46:53 -07:00
Weston Schmidt
dee98922a6 Update the readme links. 2021-06-02 18:28:37 -07:00
Weston Schmidt
b9fa918c15 Merge pull request #362 from xmidt-org/update-ci
Update the CI pipeline.
2021-06-02 18:25:04 -07:00
Weston Schmidt
a278a7017d Update the CI pipeline. 2021-06-02 18:17:54 -07:00
Weston Schmidt
69cf210a34 Merge pull request #359 from xmidt-org/whitesource/configure
Configure WhiteSource Bolt for GitHub
2021-06-02 18:06:27 -07:00
Weston Schmidt
77b587aa9d Merge pull request #361 from xmidt-org/proposed-add-auth-headers
Add additional headers to auth request
2021-06-02 16:44:07 -07:00
Weston Schmidt
441ecf702f Add additional headers to auth request
This adds the set of headers from the convey header into the auth
request in a way that doesn't require a change to Themis.
2021-06-02 00:57:51 -07:00
sadhyama
bdc2733d8e Merge pull request #360 from sadhyama/reb_reason
To increase reboot reason size
2021-02-03 19:35:33 +05:30
Sadhyama Vengilat
1f24671c0f To increase reboot reason size 2021-02-03 16:51:18 +05:30
whitesource-bolt-for-github[bot]
3de4ec59c1 Add .whitesource configuration file 2020-12-07 17:30:48 +00:00
sadhyama
a01ad8f15c Merge pull request #357 from sadhyama/part_id
Add partnerID header in auth token request
2020-11-16 14:42:18 +05:30
Sadhyama Vengilat
1d2e51e31e Add partnerID header in auth token request 2020-11-10 15:51:35 +05:30
Weston Schmidt
9e808acf7d Use the old default branch name for now. 2020-09-18 13:40:50 -07:00
Weston Schmidt
19f2fe1419 Merge pull request #356 from xmidt-org/add-sonar
Add sonar, travis and friends.
2020-09-15 18:55:34 -07:00
Weston Schmidt
b99c06a67b Disable the clang build for now. 2020-09-15 18:45:42 -07:00
Weston Schmidt
f57ebc1cd7 Disable string_helpers test for now since it fails... 2020-09-15 18:31:08 -07:00
Weston Schmidt
1df770a91b Remove the spin thread test due to what appear to be issues with travis-ci. 2020-09-15 18:23:09 -07:00
Weston Schmidt
a582bb3252 Fix several compilation errors (multiple definitions of global variables, remove overlapping strncpy() strings which cause latent bugs) to allow for code coverage to work. 2020-09-15 18:04:41 -07:00
Weston Schmidt
42dd20263b Ignore a test generated file. 2020-09-15 18:03:05 -07:00
Weston Schmidt
ac100c0f4e Disable valgrind for now to get updated builds working. 2020-09-15 12:06:22 -07:00
Weston Schmidt
290289f2f1 Remove the duplicate cmake line. 2020-09-15 12:00:00 -07:00
Weston Schmidt
8e9b98b697 Disable coverity since it makes the build always fail. 2020-09-15 11:52:04 -07:00
Weston Schmidt
b148d40c53 Disable valgrind for now to get updated builds working. 2020-09-15 11:51:18 -07:00
Weston Schmidt
dc6486f200 Add sonar, travis and friends. 2020-09-15 11:32:52 -07:00
shilpa24balaji
ad2d43b4f6 Merge pull request #354 from sadhyama/aker_blob
Webconfig communication to aker via parodus
2020-08-07 16:37:29 +05:30
Sadhyama Vengilat
54cfdd9c52 Support Retrieve with dest as mac:xxxxxxxxxxxx/parodus/service-status/service 2020-07-27 18:30:15 +05:30
Sadhyama Vengilat
19056ddfec Webconfig communication to aker via parodus 2020-07-17 01:11:35 +05:30
shilpa24balaji
1d85742497 Merge pull request #351 from krish-1/master
Code changes to drop root privilege
2020-04-01 20:57:12 -07:00
kjothi774
e29dd26d2b To drop root privilege for parodus process 2020-04-02 03:37:44 +00:00
kjothi774
5aae91763a To drop root privilege for parodus process 2020-04-02 03:03:12 +00:00
shilpa24balaji
9afa49140a Merge pull request #349 from bill1600/siglog
fix shutdown close msg to agree with splunk log
2020-03-27 18:25:40 -07:00
Bill Williams
4305dc8eef fix shutdown close msg to agree with splunk log 2020-03-26 09:30:26 -07:00
shilpa24balaji
f44fc2c8d9 Merge pull request #346 from bill1600/sigterm2
Parodus shutdown with SIGTERM to read close_reason file
2020-03-05 12:37:55 -08:00
Weston Schmidt
16543800d2 Merge pull request #344 from bill1600/jitter2
Jitter2
2020-03-03 11:04:18 -08:00
Bill Williams
bcb4840a41 update with requested changes 2020-02-27 16:54:51 -08:00
Bill Williams
b173828777 merge master 2020-02-13 10:50:21 -08:00
Bill Williams
2df8cdfeb5 change jitter calculation 2020-02-12 09:42:15 -08:00
shilpa24balaji
eba1309169 Merge pull request #342 from bill1600/cloudstat
check cloud status for sendMessage
2020-02-06 16:21:48 -08:00
Bill Williams
70c1c64550 fix/add unit tests for backoff delay 2020-02-04 13:41:27 -08:00
Bill Williams
e825c19ef3 use jitter in backoff delay 2020-02-04 10:22:17 -08:00
Bill Williams
95170d95c7 add unit test for cloud status offline 2020-02-03 13:13:31 -08:00
Bill Williams
33142a6ce7 add mock_event_handler for testing 2020-01-30 15:33:45 -08:00
Bill Williams
7b3ee1dd5a remove nopoll_conn_is_ok from sendMessage 2020-01-16 14:25:01 -08:00
Bill Williams
f2308e2966 remove nopoll_conn_is_ready test from sendMessage 2020-01-16 12:49:11 -08:00
Bill Williams
9c55157da7 fix test_nopoll_helpers 2020-01-15 13:41:57 -08:00
Bill Williams
1c254e28fe check cloud status for sendMessage 2020-01-15 12:06:09 -08:00
shilpa24balaji
8955787640 Merge pull request #340 from xmidt-org/revert-339-nopoll_timeout
Revert "To add Nopoll default connect timeout value"
2020-01-09 11:40:38 -08:00
shilpa24balaji
b633938bc7 Revert "To add Nopoll default connect timeout value" 2020-01-09 11:33:13 -08:00
shilpa24balaji
b0aeaf1fb2 Merge pull request #339 from guruchandru/nopoll_timeout
To add Nopoll default connect timeout value
2020-01-03 10:48:14 -08:00
Guru Chandru
ea726e0c10 To add Nopoll default connect timeout value 2020-01-03 14:14:51 +05:30
shilpa24balaji
cbdf5d2be9 Merge pull request #337 from bill1600/norequery
remerged noretrydns and two_times
2019-12-27 13:40:52 -08:00
shilpa24balaji
3d369cafb2 Merge pull request #338 from sadhyama/master
Unit tests for non 200 auth token response codes
2019-12-26 17:05:02 -08:00
Sadhyama Vengilat
c0dbdb5028 Unit tests for non 200 auth token response codes 2019-12-26 18:20:44 +05:30
shilpa24balaji
12a7765f98 Update event_handler.h 2019-12-25 22:09:05 -08:00
shilpa24balaji
88c87917a4 Update event_handler.c 2019-12-25 22:08:35 -08:00
shilpa24balaji
0905387d49 Free redirect server url during reconnect 2019-12-23 17:35:52 -08:00
Bill Williams
a8167fa417 change health file update interval to 240s 2019-12-20 14:30:01 -08:00
Bill Williams
6ab601e758 retrigger travis tests 2019-12-19 13:33:59 -08:00
Bill Williams
45536eb4e1 remerged noretrydns and two_times 2019-12-19 11:12:59 -08:00
shilpa24balaji
8208d3bfd0 Merge pull request #335 from sadhyama/auth_token
Fix Report failure on non-200 response code from auth token server
2019-12-17 12:35:04 -08:00
shilpa24balaji
4fc60b6b3c Merge pull request #330 from bill1600/idownunit
add unit tests for interface down
2019-12-17 12:33:51 -08:00
Sadhyama Vengilat
990d9df7e2 Fix Report failure on non-200 response code from auth token server 2019-12-12 21:17:02 +05:30
Weston Schmidt
fe52d9a55e Update README.md 2019-12-06 12:54:30 -08:00
shilpa24balaji
9cfc734c51 Merge pull request #331 from rajnishdey/errMsgUpdate
Change Info log level from error log level for "received temporary re…
2019-11-18 10:51:06 -08:00
Rajnish
153add9bec Change Info log level from error log level for "received temporary redirection response". 2019-11-18 11:28:43 -05:00
Bill Williams
8b553f8a29 add unit tests for interface down 2019-11-17 16:45:33 -08:00
shilpa24balaji
7679fdaf4a Merge pull request #327 from bill1600/ifcdown
update backoff delay and interface down logic
2019-11-15 12:27:41 -08:00
Bill Williams
1c09a80493 fix condition test in wait_while_interface_down 2019-11-14 15:31:28 -08:00
Bill Williams
bfad8ed44b fix deadlock in wait_while_interface_down 2019-11-14 10:56:47 -08:00
Bill Williams
17c7faff50 update backoff delay error logging 2019-11-12 15:12:53 -08:00
Bill Williams
01120da9ac backoff delay updates 2019-11-12 14:37:10 -08:00
shilpa24balaji
c7c6fb4926 Merge pull request #328 from bill1600/nosig9
Nosig9
2019-11-12 10:30:59 -08:00
Bill Williams
f4b2c252ae update changelog for nosig9 2019-11-12 10:18:40 -08:00
Bill Williams
8794ce2092 dont try to install handler for signal 9 2019-11-12 10:17:01 -08:00
Bill Williams
a61e97633b update backoff delay for interface down 2019-11-11 13:24:07 -08:00
shilpa24balaji
4d3d6ec99d Merge pull request #326 from bill1600/bkpshut
update parodus shutdown
2019-11-06 10:42:54 -08:00
shilpa24balaji
e6ac264e47 Update CHANGELOG.md 2019-11-06 10:31:53 -08:00
Bill Williams
70c9975ae9 remove leftover local test 2019-11-05 14:21:37 -08:00
Bill Williams
11a2b6f123 restore test_interface_down_retry 2019-11-04 15:29:43 -08:00
Bill Williams
81d8f59bbd fix so that parodus can be killed if it connection fail loop 2019-11-01 14:14:18 -07:00
Bill Williams
846b0588c2 pu cloud status back 2019-11-01 11:40:35 -07:00
Bill Williams
ad44ff0221 remove 403 upgrade from this build 2019-11-01 10:00:39 -07:00
Bill Williams
513647ceef remove unnecessary nopoll_con_ref_count 2019-10-31 15:26:51 -07:00
Bill Williams
2ec3443b1d update parodus shutdown 2019-10-29 11:34:29 -07:00
shilpa24balaji
55e10aa051 Merge pull request #325 from shilpa24balaji/3.12_p3b
Update retry time in connection-health-file
2019-10-25 11:56:33 -07:00
Shilpa Seshadri
879a585b66 Update retry time in connection-health-file 2019-10-24 18:20:20 -07:00
shilpa24balaji
ea3534678b Merge pull request #321 from xmidt-org/unref_crash
nopoll_conn_unref crash fix
2019-09-18 16:49:19 -07:00
Shilpa Seshadri
6ebb62ead4 Removing the additional conn_unref as conn_close handles this 2019-09-18 11:18:26 -07:00
Shilpa Seshadri
5ec16a7370 Re-order the cloud status update to prevent the nopoll_conn_unref crash 2019-09-16 16:26:56 -07:00
shilpa24balaji
7b81cb4efd Update README.md 2019-09-12 17:12:48 -07:00
shilpa24balaji
4c6a6a99e6 Merge pull request #320 from xmidt-org/event_handler
Ping Status change event handler
2019-09-12 16:42:01 -07:00
shilpa24balaji
106e1bfeb3 Merge pull request #318 from bill1600/waitconrdy
initialize wait_status in wait_connection_ready
2019-09-10 10:28:27 -07:00
Shilpa Seshadri
4f01170670 Handler definition for Ping Status change event 2019-09-09 16:51:39 -07:00
shilpa24balaji
f37d1911d6 Merge pull request #319 from xmidt-org/master
Sync from master branch
2019-09-09 13:13:29 -07:00
Bill Williams
3a436999fc initialize wait_status in wait_connection_ready 2019-09-06 11:56:56 -07:00
shilpa24balaji
016c80960c Merge pull request #316 from guruchandru/parodus_event
Parodus cloud Status update and Unit tests
2019-08-22 16:34:48 -07:00
Guru Chandru
b286857a22 Parodus cloud Status update and Unit tests 2019-08-22 11:50:56 +05:30
Shilpa Seshadri
f998106aed Log reconnect reason and update change log 2019-08-19 21:46:45 -07:00
shilpa24balaji
2d209b2a0d Merge pull request #315 from xmidt-org/event_handler
Pause connection retry when interface is down
2019-08-19 16:41:41 -07:00
Shilpa Seshadri
3f471100db Pause retry when interface is down and until its up 2019-08-17 03:43:50 -07:00
shilpa24balaji
ddc04f9da0 Merge pull request #313 from guruchandru/parodus_checkin
Parodus cloud-status shows "online" when connection is closed during …
2019-08-15 15:34:09 -07:00
Guru Chandru
a23615f3a5 Parodus cloud-status shows "online" when connection is closed during interface-down 2019-08-14 18:39:01 +05:30
shilpa24balaji
b1caff4a1a Merge pull request #312 from guruchandru/parodus_handler
parodus event handler to listen to interface_down and interface_up event
2019-08-09 12:41:59 -07:00
Sadhyama Vengilat
11c9052d77 parodus event handler to listen to interface_down and interface_up event 2019-08-07 12:19:38 +05:30
guruchandru
5ceb57a8c3 Merge pull request #1 from bill1600/sysevent
add pause/resume heartBeatTimer
2019-08-06 10:48:59 +05:30
guruchandru
c4ebe239ac Merge branch 'parodus_handler' into sysevent 2019-08-06 10:39:45 +05:30
shilpa24balaji
1622c44c89 Merge pull request #307 from gbuddappagari/parodus_onboard
RDKB-20643:Add OnBoarding logs
2019-07-24 20:15:06 -07:00
shilpa24balaji
fb542586e7 Update CMakeLists.txt 2019-07-24 20:13:40 -07:00
Gayathri Buddappagari
0afb87c29b RDKB-20643:Add OnBoarding logs 2019-07-15 17:02:01 +05:30
shilpa24balaji
f168e4d148 Merge pull request #308 from bill1600/nopoll_102
Use nopoll version 1.0.2
2019-07-02 14:52:36 -07:00
Bill Williams
97570a24d5 Use nopoll version 1.0.2 2019-07-02 13:24:20 -07:00
shilpa24balaji
95b6f75284 Merge pull request #306 from bill1600/newauthtoken
request new auth token on every retry, not just after 403
2019-06-12 11:38:10 -07:00
Bill Williams
f87e69c07b no need for backoff after 403 2019-06-11 14:20:45 -07:00
Bill Williams
647905639c refine connect/auth-token logic 2019-06-05 08:56:28 -07:00
Bill Williams
ceadc4b51f refine fetch auth token 2019-06-03 16:55:29 -07:00
Bill Williams
38dee179e7 request new auth token on every retry, not just after 403 2019-05-30 13:44:49 -07:00
shilpa24balaji
9feafedff8 Merge pull request #302 from bill1600/clrtoken
requestNewAuthToken will clear token if it fails
2019-05-21 17:49:33 -07:00
Bill Williams
2807f8e43a add test_auth_token_more.c 2019-05-16 13:48:02 -07:00
Bill Williams
5132675700 add unit tests for auth_token 2019-05-16 13:41:19 -07:00
Bill Williams
e166b9fdf5 use memset to clear auth token in requestNewAuthToken 2019-05-14 13:34:35 -07:00
Bill Williams
60789f0ec8 requestNewAuthToken will clear token if it fails 2019-05-14 11:51:40 -07:00
Bill Williams
3fb0708b15 add pause/resume heartBeatTimer 2019-05-07 16:19:37 -07:00
shilpa24balaji
65098e36cb Merge pull request #298 from bill1600/nano_115
Update to use nanomsg v 1.1.4
2019-04-24 10:30:41 -07:00
shilpa24balaji
c585300f76 Merge pull request #297 from bill1600/test_upstream
Add unit test for re-registrations
2019-04-24 10:27:48 -07:00
Bill Williams
e4e78118cf Use nanomsg version 1.1.4 2019-04-23 17:12:48 -07:00
Bill Williams
8b4541b570 Update to use nanomsg v 1.1.5 2019-04-23 13:29:35 -07:00
Bill Williams
acc542647b Add unit test for re-registrations 2019-04-12 09:09:23 -07:00
shilpa24balaji
da6614b19d Merge pull request #294 from bill1600/cnheal
Add logic to save parodus connection status in health file
2019-04-04 11:28:23 -07:00
Bill Williams
096271279d new self heal version woth merged close/endpoint 2019-04-01 09:22:40 -07:00
shilpa24balaji
50176fb120 Merge pull request #292 from bill1600/close_endpt
Fix nanomsg client close handling
2019-03-29 14:31:57 -07:00
Bill Williams
2ad896abc6 log all nn_close 2019-03-27 11:35:16 -07:00
Bill Williams
f58f85bc32 close client when deleting from client list 2019-03-26 16:54:52 -07:00
Bill Williams
4fef26c082 use endpoint in nn_shutdown and log nn_close errors 2019-03-26 16:26:09 -07:00
shilpa24balaji
1995a664ad Merge pull request #291 from sadhyama/master
Rename command line options for MTLS cert and Key #290
2019-03-22 10:39:44 -07:00
Weston Schmidt
f1b2add244 Merge branch 'nosinovacao-feature_mutual_auth_v1' 2019-03-20 09:08:47 -07:00
Weston Schmidt
13739786a0 Resolve the merge conflicts in PR 246. Remove the ifdef flag as this should always be available. Fix a mistake in the commandline option parsing of the C flag ... needs to be C:. 2019-03-20 09:05:20 -07:00
Sadhyama Vengilat
4fc082cb43 Updated CHANGELOG.md 2019-03-19 17:29:26 +05:30
Sadhyama Vengilat
08feef216e Rename command line options for MTLS cert and Key #290 2019-03-19 17:19:00 +05:30
Nuno Martins
3bb48b48c0 Added Security Feature: Mutual Authentication (mTLS or two way TLS)
This change adds support for two new program parameters
-q "client_cert_path" and -k "client key path"
Where here client is the CPE, so It will be the CPE cert and
corresponding key.

Having those two parameters we are in position to pass them
on the nopoll_conn_opts_set_ssl_certs function. This function,
previously, was being set with NULL values.

As most parameters have a path with 64 characters, we also created
those (cert and key) paths with that length.

We also changed the README.md accordingly, to show how to enable
and use this feature.

Signed-off-by: Nuno Martins <nuno.mmartins@parceiros.nos.pt>
2018-10-08 16:16:08 +01:00
57 changed files with 2499 additions and 533 deletions

24
.github/scripts/get_sonarcloud.sh vendored Executable file
View File

@@ -0,0 +1,24 @@
#!/bin/bash
# SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
# SPDX-License-Identifier: Apache-2.0
curl -s -L -O https://sonarcloud.io/static/cpp/build-wrapper-linux-x86.zip
unzip -q -o build-wrapper-linux-x86.zip
SONAR_VERSION=`curl -s https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/ |grep -o "sonar-scanner-cli-[0-9.]*-linux.zip"|sort -r|uniq|head -n 1`
curl -s -L -O https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/$SONAR_VERSION
curl -s -L -O https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/$SONAR_VERSION.sha256
echo " $SONAR_VERSION" >> $SONAR_VERSION.sha256
sha256sum -c $SONAR_VERSION.sha256
if [[ $? -ne 0 ]]
then
exit 1
fi
unzip -q $SONAR_VERSION
output=`ls | grep -o "sonar-scanner-[0-9.]*-linux"`
echo "Using $output"
mv $output sonar-scanner

50
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,50 @@
# SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
# SPDX-License-Identifier: Apache-2.0
name: LGTM Analysis
on:
create:
pull_request:
push:
branches:
- main
schedule:
- cron: '12 9 * * 3'
jobs:
codeql:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Install the dependent packages
- name: Install packages
run: |
sudo apt update
sudo apt-get -y install valgrind libcunit1 libcunit1-doc libcunit1-dev libmsgpack-dev gcovr libtool
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: cpp
queries: security-extended
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

71
.github/workflows/push.yml vendored Normal file
View File

@@ -0,0 +1,71 @@
# SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
# SPDX-License-Identifier: Apache-2.0
name: CI
on:
pull_request_target:
push:
paths-ignore:
- 'AUTHORS'
- 'LICENSE'
- 'NOTICE'
- '**.md'
- '.gitignore'
tags-ignore:
- 'v[0-9]+.[0-9]+.[0-9]+'
branches:
- main
- master
jobs:
test:
name: Unit Tests
runs-on: [ ubuntu-latest ]
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v3
with:
fetch-depth: 0
# Install the dependent packages
- name: Install packages
run: |
sudo apt update
sudo apt-get -y install valgrind libcunit1 libcunit1-doc libcunit1-dev libmsgpack-dev gcovr libtool
pip install codecov
- name: Make Build Directory
run: mkdir build
- name: Install sonar-scanner and build-wrapper
uses: sonarsource/sonarcloud-github-c-cpp@v2
- name: CMake
working-directory: build
run: |
cmake .. -DINTEGRATION_TESTING:BOOL=false -DDISABLE_VALGRIND:BOOL=${DISABLE_VALGRIND} -DENABLE_SESHAT:BOOL=true -DFEATURE_DNS_QUERY:BOOL=true
- name: Build
working-directory: build
run: |
build-wrapper-linux-x86-64 --out-dir bw-output make all test
- name: Merge GCOV Reports for Sonarcloud
working-directory: build
run: |
gcovr --sonarqube coverage.xml -r ..
- name: Upload SonarCloud
run: |
build/sonar-scanner/bin/sonar-scanner -Dsonar.host.url=https://sonarcloud.io -Dproject.settings=.sonar-project.properties -Dsonar.login=${{ secrets.SONAR_TOKEN }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload Codecov.io
uses: codecov/codecov-action@e28ff129e5465c2c0dcc6f003fc735cb6ae0c673 # v4.5.0
with:
directory: .
flags: unittests
fail_ci_if_error: true

49
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
# SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
# SPDX-License-Identifier: Apache-2.0
name: release
on:
push:
tags:
# Push events to matching v#.#.#*, ex: v1.2.3, v.2.4.6-beta
- 'v[0-9]+.[0-9]+.[0-9]+*'
jobs:
release:
runs-on: [ ubuntu-latest ]
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Determine repo name
run: |
echo "repo_name=$(echo '${{ github.repository }}' | awk -F '/' '{print $2}')" >> $GITHUB_ENV
echo "version=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
echo "release_slug=$(echo '${{ github.repository }}' | awk -F '/' '{print $2}')-${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
shell: bash
- name: Create tarball and sha256
run: |
git archive --format=tar.gz -o ${release_slug}.tar.gz --prefix=${release_slug}/ ${version}
git archive --format=zip -o ${release_slug}.zip --prefix=${release_slug}/ ${version}
sha256sum ${release_slug}.tar.gz ${release_slug}.zip > ${release_slug}-sha256sums.txt
mkdir artifacts
cp ${release_slug}* artifacts/.
- name: Prepare Release Body
id: prep
run: |
export version=${GITHUB_REF#refs/tags/}
export NOTES=$(cat CHANGELOG.md | perl -0777 -ne 'print "$1\n" if /.*## \[${version}\]\s(.*?)\s+## \[(v\d+.\d+.\d+)\].*/s')
export TODAY=`date +'%m/%d/%Y'`
echo ::set-output name=rname::$(echo ${version} ${TODAY})
echo ::set-output name=body::${NOTES}
- name: create release
id: create_release
uses: ncipollo/release-action@v1
with:
name: ${{ steps.prep.outputs.rname }}
draft: false
prerelease: false
bodyFile: ${{ steps.prep.outputs.body }}
artifacts: "artifacts/*"
token: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token

33
.github/workflows/tag.yml vendored Normal file
View File

@@ -0,0 +1,33 @@
# SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
# SPDX-License-Identifier: Apache-2.0
name: tag
on:
push:
paths:
- "CHANGELOG.md" # only try to tag if the CHANGELOG has been updated.
branches:
- main
jobs:
build:
runs-on: [ ubuntu-latest ]
steps:
- uses: actions/checkout@v2
with:
token: '${{ secrets.PERSONAL_ACCESS_TOKEN }}'
fetch-depth: 0
- name: set up bot
run: |
git config --global user.name "xmidt-bot"
git config --global user.email "$BOT_EMAIL"
- name: export variables and tag commit
run: |
export OLD_VERSION=$(git describe --tags `git rev-list --tags --max-count=1` | tail -1)
export TAG=$(cat CHANGELOG.md | perl -0777 -ne 'print "$1" if /.*## \[Unreleased\]\s+## \[(v\d+.\d+.\d+)\].*/s')
export BINVER=$(cat CMakeLists.txt | perl -0777 -ne 'print "v$1" if /.*project\s*\(.*\s*VERSION\s*(\d+.\d+.\d+).*\s*\)/s')
export TODAY=`date +'%m/%d/%Y'`
export NOTES=$(cat CHANGELOG.md | perl -0777 -ne 'print "$ENV{TODAY}\n\n$1\n" if /.*## \[$ENV{TAG}\]\s(.*?)\s+## \[(v\d+.\d+.\d+)\].*/s')
if [[ "$TAG" != "" && "$TAG" != "$BINVER" ]]; then echo "CHANGELOG.md($TAG) and CMakeLists.txt VERSION($BINVER) do not match"; fi
if [[ "$TAG" != "" && "$TAG" != "$OLD_VERSION" && "$TAG" == "$BINVER" ]]; then git tag -a "$TAG" -m "$NOTES"; git push origin --tags; echo $?; fi

2
.gitignore vendored
View File

@@ -34,3 +34,5 @@
tags
build/
tests/jwt_key.tst

34
.sonar-project.properties Normal file
View File

@@ -0,0 +1,34 @@
# SPDX-FileCopyrightText: 2021 Comcast Cable Communications Management, LLC
# SPDX-License-Identifier: Apache-2.0
# Reference:
# https://github.com/SonarSource/sonarcloud_example_go-sqscanner-travis/blob/master/sonar-project.properties
# =====================================================
# Standard properties
# =====================================================
sonar.organization=xmidt-org
sonar.projectKey=xmidt-org_parodus
sonar.projectName=parodus
sonar.sources=src
# =====================================================
# Meta-data for the project
# =====================================================
sonar.links.homepage=https://github.com/xmidt-org/parodus
sonar.links.ci=https://github.com/xmidt-org/parodus/actions
sonar.links.scm=https://github.com/xmidt-org/parodus
sonar.links.issue=https://github.com/xmidt-org/parodus/issues
# =====================================================
# Properties specific to C
# =====================================================
sonar.cfamily.build-wrapper-output=build/bw-output
sonar.cfamily.threads=2
sonar.cfamily.cache.enabled=false
sonar.coverageReportPaths=build/coverage.xml

View File

@@ -1,43 +0,0 @@
dist: trusty
sudo: required
language: c
compiler:
- gcc
addons:
coverity_scan:
project:
name: "Comcast/parodus"
description: "C implementation of the WebPA client coordinator"
notification_email: weston_schmidt@alumni.purdue.edu
build_command_prepend: "mkdir coverity_build && cd coverity_build && cmake .."
build_command: "make"
branch_pattern: ignore
before_install:
- sudo pip install codecov
- echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca-
install:
- sudo apt-get update -qq
- sudo apt-get install -y -qq check libcunit1 libcunit1-dev uuid-dev valgrind
script:
- mkdir build
- cd build
- cmake .. -DINTEGRATION_TESTING:BOOL=false -DDISABLE_VALGRIND:BOOL=false -DENABLE_SESHAT:BOOL=true -DFEATURE_DNS_QUERY:BOOL=true
- make
- export ARGS="-V"
- make test
after_success:
- codecov
env:
global:
- secure: EwQu1WDUgIF5qM5tnKj/+NCPz9t15y289bbqFo0wDhyfTlJGS9buQeJNeVLtNJBEOngpo+AkaPGvh/d9NZ0vLdxu+K/e+HhA6kOTxUrCHD8+4oX9XpVs/XvQmD1COlJYeeqd8bJMKtlFtonGdMJogxpEFQzv4fQjmoARvL2ciV4OB0MBcD5Lsb72L3a0aJT69F6WFuDpgGj2eIQyCDSTPNIi2X7EA8R33lxnntFDn8Vj6qSBbVOI2S5R5S+JUCMp1Q1ZbEqmh6j+wKtszWj8wGqfz8Ol5+GYl511bExb+hwvV5zen0Ol0+2LQmSpYhbQZ7prfI8AclLLwhDUrP+WDOv34vwd4EWQ1OoLqG23HbBygCxPSBIB6ZxPtVkzjVlOK8qqIB5QXqCyq8sPKlrXfntOQ+Ha938cIA+A0ag+26MLbhDGj8k3Os7BdY/oqNTKADZQdxfGKhCiA9qO2clpMyRXoE0q6hv9dYoG/2c4sxH8DKsT8XY/QbGmiBsk0DWHcpxkObCsHUxVKi+gIBGSL/tSjz2IJfQVZkdl2hhcyStGuPKbiwAlW3HydMk0VgRhVmHBIc41Cv7vPdMEVf/XiFhr2utRX468M/LR8vkhhokKl1xkVIiquwCPYPzZVAFARHTlaBMhz9kQVtTAHf2JkHuM9XcLWKW996FiSeswKyI=
- secure: LQK36EsQdIJw7eSW1yz+yh3+yJdp8cznynBjE3whOEVI2KHZimr+vtK5hxE6TH0QjYyrb/BFgRql6CtLprpaABSEC9gpqpahu50jiAkjKC8DtfSloAbH5jj+ZllaPjURocerllNLVZxiRM/WCuJAy0nzBpAyx62YmVlEYi+zYD67d3wG6gLwso6l2DWuPPze6t5NmbUmH9hNk52++TZalwMtZFdibQoYm64vCTT5gycujw6ZDa8GD0m+Yryvc20kLlWPOVS9lN1iEGo98/gj8Ops8w0iw6k7SfEkvvFsKEUDr77wAN5Tk4tGq7odVrD/y3W9AsHkkSb1B6RqVWkcW3SjCAQc03jhdaBxXwcoJZcYahY21CB12EP7p0HSjEbvIzNpk0D9MulsGaMPlOudnKdG0/kmD7oIAiXjfC7PiPBBFIc/cVF5VAKNTUInEVfcKvlLpqDatwjB+qgb7pld24dUPuJw+yOgglk7J7xckJYHFTHhk0PWI5oN66dndj3yyJp4dz1v64ViFFTG4PO4YPJydZxRxolg1eGMuG0UIYJK6RWcSQ+ZPBm4p78J8xfHtgUkvWvrHJoXC1qAzqx1XRzbHEeTJgbKgLrWY+B6nbNotw1RDX4lNDirp5EI6GqezoFJToZkqe3MRs8DrqhaFjUbbEzAxznRWmxnWNN3Ujc=
# The next declaration is the encrypted COVERITY_SCAN_TOKEN, created
# via the "travis encrypt" command using the project repo's public key
- secure: "V/W4Z9/3uXpS83CvlZ1XfDAbHPIA2ID5G5s9GPcsUqoOASQdc6Y/DPejUlot+DgtiHOEdTr9n5iWDOuxqjcVnjVd6ag9i2m0PMqDhPj3fnUJM6dAeXIBda/qSuTsJTX4cIwb371R77cLcIUm35IEOSIAQOBCjh7RCf3ivGPUp+wobTonkNzDw6xqO90hx7NLnxwGSCcaNBFKOcLL0e7DXspp18lTWCSSaHELzXOyLlhZnWhC5tiFUIZk1ixm/cO1YEQH9AzgPJ5OYs+On0j8VT8XWMsxHu0zfkZkdZMAEOQbO6u4HBDePIfp+PoF1LwtX/UXfaEkUHZ0kNVXHfsN/KP7NHgTbASe9EXp+R4pcKEy4ZEbx+xpp7FlMQSJYiYiQbJ2FBrjwRPreXiHyCqn8htd0YNOTH4UykvO3NYxlTaMf9aE041lnLjUY18TuXrILz6SzMsGV+nYqfIci/NPuj/57k7nw127a93S4Mr/phXts9ZL8I7kagd8wKv3m5+7rmIfuSfS2kg2pTa0hk5uMqFWLG8AilUQ5t1ChylzPcl/Gdgi9OP0pG2WyUmkqOiSqhwwdg2ZCwptodwuonfbdKMSBuHOS8lLU1bGyCRdWsMoscSv/xn4t3ikzBsSDiKgI8xq2+aqQyHDeVneqAk1BbxiNIwoJeyVXq2EKU6MlgI="

12
.whitesource Normal file
View File

@@ -0,0 +1,12 @@
{
"scanSettings": {
"baseBranches": []
},
"checkRunSettings": {
"vulnerableCheckRunConclusionLevel": "failure",
"displayMode": "diff"
},
"issueSettings": {
"minSeverityLevel": "LOW"
}
}

View File

@@ -5,6 +5,46 @@ 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]
## [v1.1.5]
- Add additional HTTP headers for call to Themis from Convey
- Change default branch name to `main`
## [v1.1.4]
- on connect retry, requery jwt only if it failed before
- put two timestamps in connection health file; start conn and current
- change health file update interval to 240sec
- use jitter in backoff delay
- sendMessage to check cloud status == ONLINE before sending
- when killed with SIGTERM, close will use msg in close reason file.
## [1.1.3]
- Add callback handler for ping status change event
- Fixed nopoll_conn_unref crash
- Update retry timestamp in connection-health-file
- fix so that parodus can be killed, even if in a connection fail loop
- provide signal handlers so we shut down properly when INCLUDE_BREAKPAD active
- send status code and reason in websocket close message
- dont try to install handler for signal 9
## [1.1.2]
- Add pause/resume heartBeatTimer
- parodus event handler to listen to interface_down and interface_up event
- Pause connection retry during interface_down event
## [1.1.1]
- Update to use nanomsg v. 1.1.4
- requestNewAuthToken will clear the token if it fails.
- request auth token on every retry, not just after 403
- update to use nopoll v 1.0.2
## [1.0.4]
- 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
## [1.0.3]
- Security: Added support to use auth token during initial connect to cloud
## [1.0.2] - 2019-02-08
@@ -55,6 +95,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Security
- Added command line arguments for secure token read and acquire. Token presented to cloud for authentication verification.
- Added support for override functions to support drop root capabilities for parodus process
## [1.0.0] - 2017-11-17
### Added
@@ -64,7 +105,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
- Initial creation
[Unreleased]: https://github.com/Comcast/parodus/compare/1.0.1...HEAD
[Unreleased]: https://github.com/Comcast/parodus/compare/v1.1.5...HEAD
[1.1.5]: https://github.com/Comcast/parodus/compare/v1.1.4...v1.1.5
[1.1.4]: https://github.com/Comcast/parodus/compare/1.1.3...v1.1.4
[1.1.3]: https://github.com/Comcast/parodus/compare/1.1.2...1.1.3
[1.1.2]: https://github.com/Comcast/parodus/compare/1.1.1...1.1.2
[1.1.1]: https://github.com/Comcast/parodus/compare/1.0.4...1.1.1
[1.0.4]: https://github.com/Comcast/parodus/compare/1.0.3...1.0.4
[1.0.3]: https://github.com/Comcast/parodus/compare/1.0.2...1.0.3
[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

@@ -14,6 +14,7 @@
cmake_minimum_required(VERSION 2.8.7)
#project(parodus VERSION 1.1.5)
project(parodus)
include(ExternalProject)
@@ -85,7 +86,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.1"
GIT_TAG "1.0.2"
CONFIGURE_COMMAND COMMAND <SOURCE_DIR>/autogen.sh --prefix=${PREFIX}
--includedir=${INCLUDE_DIR}
--libdir=${LIBRARY_DIR}
@@ -101,7 +102,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.2"
GIT_TAG "1.1.4"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libnanomsg STATIC SHARED IMPORTED)
@@ -152,7 +153,7 @@ add_dependencies(libcurl curl)
ExternalProject_Add(cimplog
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cimplog
GIT_REPOSITORY https://github.com/Comcast/cimplog.git
GIT_TAG "1.0.1"
GIT_TAG "1.0.2"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcimplog STATIC SHARED IMPORTED)

View File

@@ -1,10 +1,16 @@
<!--
SPDX-FileCopyrightText: 2016-2021 Comcast Cable Communications Management, LLC
SPDX-License-Identifier: Apache-2.0
-->
# parodus
[![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)
[![Build Status](https://github.com/xmidt-org/parodus/workflows/CI/badge.svg)](https://github.com/xmidt-org/parodus/actions)
[![codecov.io](http://codecov.io/github/xmidt-org/parodus/coverage.svg?branch=master)](http://codecov.io/github/xmidt-org/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)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=xmidt-org_parodus&metric=alert_status)](https://sonarcloud.io/dashboard?id=xmidt-org_parodus)
[![Language Grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/xmidt-org/parodus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/xmidt-org/parodus/context:cpp)
[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/xmidt-org/parodus/blob/master/LICENSE)
[![GitHub release](https://img.shields.io/github/release/xmidt-org/parodus.svg)](CHANGELOG.md)
C implementation of the XMiDT client coordinator
@@ -75,6 +81,12 @@ 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:

View File

@@ -14,8 +14,8 @@
set(SOURCES main.c mutex.c networking.c nopoll_helpers.c heartBeat.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 event_handler.c
crud_interface.c crud_tasks.c crud_internal.c close_retry.c auth_token.c privilege.c)
if (ENABLE_SESHAT)
set(SOURCES ${SOURCES} seshat_interface.c)

View File

@@ -25,6 +25,11 @@
#include "config.h"
#include "connection.h"
bool interface_down_event = false;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t interface_down_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -126,6 +131,27 @@ char* getWebpaConveyHeader()
return NULL;
}
int readFromFile(const char *file_name, char **data)
{
FILE *fp;
int ch_count = 0;
fp = fopen(file_name, "r+");
if (fp == NULL)
{
ParodusError("Failed to open file %s (errno %d)\n", file_name, errno);
return 0;
}
fseek(fp, 0, SEEK_END);
ch_count = ftell(fp);
fseek(fp, 0, SEEK_SET);
*data = (char *) malloc(sizeof(char) * (ch_count + 1));
fread(*data, 1, ch_count,fp);
(*data)[ch_count] ='\0';
fclose(fp);
return 1;
}
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *diff)
{
@@ -139,3 +165,47 @@ void timespec_diff(struct timespec *start, struct timespec *stop,
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_cond_signal(&interface_down_con);
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);
}
pthread_cond_t *get_interface_down_con(void)
{
return &interface_down_con;
}
pthread_mutex_t *get_interface_down_mut(void)
{
return &interface_down_mut;
}

View File

@@ -49,6 +49,7 @@
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define UNUSED(x) (void )(x)
#define NANO_SOCKET_SEND_TIMEOUT_MS 2000
#define NANO_SOCKET_RCV_TIMEOUT_MS 500
@@ -107,6 +108,8 @@ typedef struct {
//--- Used in connection.c for backoff delay timer
typedef struct {
unsigned long start_time;
struct timespec ts;
int count;
int max_count;
int delay;
@@ -124,7 +127,7 @@ typedef struct {
// wait_connection_ready, and nopoll_connect
typedef struct {
noPollCtx *nopoll_ctx;
server_list_t server_list;
server_list_t *server_list;
server_t *current_server;
header_info_t header_info;
char *extra_headers; // need to be freed
@@ -136,7 +139,6 @@ typedef struct {
/*----------------------------------------------------------------------------*/
extern bool g_shutdown;
extern ParodusMsg *ParodusMsgQ;
int numLoops;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
@@ -154,9 +156,30 @@ char* getWebpaConveyHeader();
void *CRUDHandlerTask();
void addCRUDmsgToQueue(wrp_msg_t *crudMsg);
int readFromFile(const char *file_name, char **data);
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();
pthread_cond_t *get_interface_down_con();
pthread_mutex_t *get_interface_down_mut();
#ifdef __cplusplus
}
#endif

View File

@@ -24,6 +24,7 @@
#include <stdio.h>
#include <fcntl.h>
#include "config.h"
#include "connection.h"
#include "auth_token.h"
#include "ParodusInternal.h"
#include <cjwt/cjwt.h>
@@ -31,16 +32,22 @@
#include <curl/curl.h>
#include <uuid/uuid.h>
#define MAX_BUF_SIZE 128
#define MAX_BUF_SIZE 256
#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);
void createCurlheader(struct curl_slist *list, struct curl_slist **header_list);
long g_response_code;
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int getGlobalResponseCode()
{
return g_response_code;
}
/*
* @brief Initialize curl object with required options. create newToken using libcurl.
* @param[out] newToken auth token string obtained from JWT curl response
@@ -57,29 +64,18 @@ int requestNewAuthToken(char *newToken, size_t len, int r_count)
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)
{
//this memory will be dynamically grown by write call back fn as required
data.data = (char *) malloc(sizeof(char) * 1);
if(NULL == data.data)
{
ParodusError("Failed to allocate memory.\n");
return -1;
}
data.data[0] = '\0';
createCurlheader(mac_header, serial_header, uuid_header, transaction_uuid, list, &headers_list);
createCurlheader(list, &headers_list);
curl_easy_setopt(curl, CURLOPT_URL, get_parodus_cfg()->token_server_url);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT_SEC);
@@ -124,8 +120,8 @@ int requestNewAuthToken(char *newToken, size_t len, int r_count)
/* 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);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &g_response_code);
ParodusInfo("themis curl response %d http_code %d\n", res, g_response_code);
time_res = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total);
if(time_res == 0)
@@ -137,31 +133,32 @@ int requestNewAuthToken(char *newToken, size_t len, int r_count)
{
ParodusError("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
if(data.data)
{
free(data.data);
data.data = NULL;
}
data.size = 0;
memset (data.data, 0, len);
return -1;
}
else
{
if(response_code == 200)
if(getGlobalResponseCode() == 200)
{
ParodusInfo("cURL success\n");
strncpy(newToken, data.data, len);
}
}
if(data.data)
{
free(data.data);
data.data = NULL;
else
{
ParodusError("Failed response from auth token server %s\n", data.data);
curl_easy_cleanup(curl);
data.size = 0;
memset (data.data, 0, len);
return -1;
}
}
curl_easy_cleanup(curl);
}
else
{
ParodusError("curl init failure\n");
data.size = 0;
memset (data.data, 0, len);
return -1;
}
@@ -179,6 +176,7 @@ 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 )
@@ -225,28 +223,23 @@ void getAuthToken(ParodusCfg *cfg)
*/
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);
char* tmp;
data->size += (size * nmemb);
data->size += n;
tmp = realloc(data->data, data->size + 1); /* +1 for '\0' */
if(tmp) {
data->data = tmp;
} else {
if(data->data) {
free(data->data);
}
ParodusError("Failed to allocate memory for data\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 size * nmemb;
return n;
}
/* @brief function to generate random uuid.
@@ -268,52 +261,60 @@ char* generate_trans_uuid()
}
/* @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] h the auth headers to populate
* @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)
void createCurlheader(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;
}
char buf[MAX_BUF_SIZE];
char *uuid = 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;
}
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Mac-Address: %s", get_parodus_cfg()->hw_mac);
ParodusPrint("mac_header formed %s\n", buf);
list = curl_slist_append(list, buf);
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;
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Serial-Number: %s", get_parodus_cfg()->hw_serial_number);
ParodusPrint("serial_header formed %s\n", buf);
list = curl_slist_append(list, buf);
uuid = generate_trans_uuid();
if(uuid !=NULL) {
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Uuid: %s", uuid);
ParodusInfo("uuid_header formed %s\n", buf);
list = curl_slist_append(list, buf);
free(uuid);
} else {
ParodusError("Failed to generate transaction_uuid\n");
}
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Partner-Id: %s", get_parodus_cfg()->partner_id);
ParodusInfo("partnerid_header formed %s\n", buf);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Hardware-Model: %s", get_parodus_cfg()->hw_model);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Hardware-Manufacturer: %s", get_parodus_cfg()->hw_manufacturer);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Firmware-Name: %s", get_parodus_cfg()->fw_name);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Protocol: %s", get_parodus_cfg()->webpa_protocol);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Interface-Used: %s", get_parodus_cfg()->webpa_interface_used);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Last-Reboot-Reason: %s", get_parodus_cfg()->hw_last_reboot_reason);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Last-Reconnect-Reason: %s", get_global_reconnect_reason());
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Boot-Retry-Wait: %d", get_parodus_cfg()->boot_retry_wait);
list = curl_slist_append(list, buf);
*header_list = list;
}

View File

@@ -76,7 +76,11 @@ int addToList( wrp_msg_t **msg)
if(rc < 0)
{
ParodusError ("Unable to connect socket (errno=%d, %s)\n",errno, strerror(errno));
nn_close (sock);
if (nn_close (sock) < 0)
{
ParodusError ("nn_close socket=%d (err=%d, %s)\n",
sock, errno, strerror(errno));
}
}
else
@@ -87,6 +91,7 @@ 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);
@@ -219,6 +224,16 @@ 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");
@@ -279,3 +294,24 @@ int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize)
release_global_node ();
return 0;
}
//To check client registration status with parodus.
int checkClientStatus(char *serviceName)
{
reg_list_item_t *temp = NULL;
temp = get_global_node();
while (NULL != temp)
{
ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
// Sending message to registered clients
if( strcmp(serviceName, temp->service_name) == 0)
{
release_global_node ();
return 1;
}
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
release_global_node ();
return 0;
}

View File

@@ -30,6 +30,7 @@
typedef struct reg_list_item
{
int sock;
int endpoint;
char service_name[32];
char url[100];
struct reg_list_item *next;
@@ -55,7 +56,7 @@ int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize);
reg_list_item_t * get_global_node(void);
void release_global_node (void);
int checkClientStatus();
#ifdef __cplusplus
}
#endif

View File

@@ -214,8 +214,13 @@ int parse_webpa_url__ (const char *full_url,
if(openBracket != NULL){
//Remove [ from server address
char *remove = server_addr;
int i;
// Strings can overlap, so don't use strncpy()
remove++;
parStrncpy (server_addr, remove, server_addr_buflen);
for( i = 0; i < server_addr_buflen; i++ ) {
server_addr[i] = remove[i];
}
closeBracket = strchr(server_addr,']');
if(closeBracket != NULL){
//Remove ] by making it as null
@@ -365,6 +370,10 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
{"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'},
{"close-reason-file", required_argument, 0, 'R'},
{"mtls-client-key-path", required_argument, 0, 'K'},
{"mtls-client-cert-path", required_argument, 0,'M'},
{0, 0, 0, 0}
};
int c;
@@ -380,6 +389,8 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
cfg->jwt_algo = 0;
parStrncpy (cfg->jwt_key, "", sizeof(cfg->jwt_key));
cfg->crud_config_file = NULL;
cfg->connection_health_file = NULL;
cfg->close_reason_file = NULL;
cfg->client_cert_path = NULL;
cfg->token_server_url = NULL;
cfg->cloud_status = NULL;
@@ -390,8 +401,9 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "m:s:f:d:r:n:b:u:t:o:i:l:p:e:D:j:a:k:c:T:w:J:46:C",
long_options, &option_index);
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:R:K:M",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
@@ -431,6 +443,7 @@ 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,21 +541,41 @@ int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
ParodusInfo("boot_retry_wait is %d\n",cfg->boot_retry_wait);
break;
case 'C':
cfg->crud_config_file = strdup(optarg);
ParodusInfo("crud_config_file is %s\n", cfg->crud_config_file);
break;
case 'S':
cfg->connection_health_file = strdup(optarg);
ParodusInfo("connection_health_file is %s\n", cfg->connection_health_file);
break;
case 'P':
case 'R':
cfg->close_reason_file = strdup(optarg);
ParodusInfo("sigterm_close_reason_file is %s\n", cfg->close_reason_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':
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;
@@ -616,6 +649,8 @@ 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->close_reason_file = NULL;
cfg->client_cert_path = NULL;
cfg->token_server_url = NULL;
@@ -767,6 +802,24 @@ 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->close_reason_file != NULL)
{
cfg->close_reason_file = strdup(config->close_reason_file);
}
else
{
ParodusPrint("close_reason_file is NULL. set to empty\n");
}
if(config->crud_config_file != NULL)
{
cfg->crud_config_file = strdup(config->crud_config_file);

View File

@@ -75,7 +75,7 @@ typedef struct
char hw_serial_number[64];
char hw_manufacturer[64];
char hw_mac[64];
char hw_last_reboot_reason[64];
char hw_last_reboot_reason[128];
char fw_name[64];
unsigned int boot_time;
unsigned int webpa_ping_timeout;
@@ -101,6 +101,10 @@ typedef struct
char token_read_script[64];
char *client_cert_path;
char *token_server_url;
char *connection_health_file;
char *close_reason_file;
char *mtls_client_key_path;
char *mtls_client_cert_path;
char *crud_config_file;
char *cloud_status;
char *cloud_disconnect;

View File

@@ -33,6 +33,7 @@
#include "spin_thread.h"
#include "service_alive.h"
#include "seshat_interface.h"
#include "event_handler.h"
#include "crud_interface.h"
#include "heartBeat.h"
#include "close_retry.h"
@@ -73,7 +74,9 @@ void createSocketConnection(void (* initKeypress)())
{
//ParodusCfg *tmpCfg = (ParodusCfg*)config_in;
noPollCtx *ctx;
server_list_t server_list;
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;
@@ -94,9 +97,14 @@ void createSocketConnection(void (* initKeypress)())
nopoll_log_set_handler (ctx, __report_log, NULL);
#endif
if(!createNopollConnection(ctx))
EventHandler();
set_server_list_null (&server_list);
create_conn_rtn = createNopollConnection(ctx, &server_list);
if(!create_conn_rtn)
{
ParodusError("Unrecovered error, terminating the process\n");
OnboardLog("Unrecovered error, terminating the process\n");
abort();
}
packMetaData();
@@ -140,8 +148,14 @@ void createSocketConnection(void (* initKeypress)())
{
ParodusError("ping wait time > %d . Terminating the connection with WebPA server and retrying\n", webpa_ping_timeout_ms / 1000);
ParodusInfo("Reconnect detected, setting Ping_Miss reason for Reconnect\n");
OnboardLog("Reconnect detected, setting Ping_Miss reason for Reconnect\n");
set_global_reconnect_reason("Ping_Miss");
set_global_reconnect_status(true);
// Invoke the ping status change event callback as "missed" ping
if(NULL != on_ping_status_change)
{
on_ping_status_change("missed");
}
set_close_retry();
}
else
@@ -157,15 +171,17 @@ void createSocketConnection(void (* initKeypress)())
if( false == seshat_registered ) {
seshat_registered = __registerWithSeshat();
}
if (get_interface_down_event ())
if (0 != wait_while_interface_down ())
break;
if(get_close_retry())
{
ParodusInfo("close_retry is %d, hence closing the connection and retrying\n", get_close_retry());
close_and_unref_connection(get_global_conn());
close_and_unref_connection(get_global_conn(), false);
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);
@@ -177,7 +193,7 @@ void createSocketConnection(void (* initKeypress)())
free(get_parodus_cfg()->cloud_disconnect);
reset_cloud_disconnect_reason(get_parodus_cfg());
}
createNopollConnection(ctx);
createNopollConnection(ctx, &server_list);
}
} while(!get_close_retry() && !g_shutdown);
@@ -203,13 +219,17 @@ void createSocketConnection(void (* initKeypress)())
deleteAllClients ();
close_and_unref_connection(get_global_conn());
ParodusInfo ("reconnect reason at close %s\n", get_global_reconnect_reason());
close_and_unref_connection(get_global_conn(), true);
nopoll_ctx_unref(ctx);
nopoll_cleanup_library();
curl_global_cleanup();
}
void shutdownSocketConnection(void) {
void shutdownSocketConnection(char *reason) {
set_global_shutdown_reason (reason);
g_shutdown = true;
reset_interface_down_event ();
terminate_backoff_delay ();
}

View File

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

View File

@@ -38,11 +38,36 @@
#define HTTP_CUSTOM_HEADER_COUNT 5
#define INITIAL_CJWT_RETRY -2
#define UPDATE_HEALTH_FILE_INTERVAL_SECS 240
/* Close codes defined in RFC 6455, section 11.7. */
enum {
CloseNormalClosure = 1000,
CloseGoingAway = 1001,
CloseProtocolError = 1002,
CloseUnsupportedData = 1003,
CloseNoStatus = 1005,
CloseAbnormalClosure = 1006,
CloseInvalidFramePayloadData = 1007,
ClosePolicyViolation = 1008,
CloseMessageTooBig = 1009,
CloseMandatoryExtension = 1010,
CloseInternalServerErr = 1011,
CloseServiceRestart = 1012,
CloseTryAgainLater = 1013,
CloseTLSHandshake = 1015
};
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
parodusOnPingStatusChangeHandler on_ping_status_change;
pthread_mutex_t backoff_delay_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t backoff_delay_con=PTHREAD_COND_INITIALIZER;
static char *shutdown_reason = SHUTDOWN_REASON_PARODUS_STOP; /* goes in the close message */
static char *reconnect_reason = "webpa_process_starts";
static int cloud_disconnect_max_time = 5;
static noPollConn *g_conn = NULL;
@@ -65,6 +90,16 @@ void set_global_conn(noPollConn *conn)
g_conn = conn;
}
char *get_global_shutdown_reason()
{
return shutdown_reason;
}
void set_global_shutdown_reason(char *reason)
{
shutdown_reason = reason;
}
char *get_global_reconnect_reason()
{
return reconnect_reason;
@@ -199,23 +234,114 @@ void init_backoff_timer (backoff_timer_t *timer, int max_count)
timer->count = 1;
timer->max_count = max_count;
timer->delay = 1;
clock_gettime (CLOCK_REALTIME, &timer->ts);
timer->start_time = time(NULL);
}
int update_backoff_delay (backoff_timer_t *timer)
unsigned 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;
return (unsigned) timer->delay;
}
static void backoff_delay (backoff_timer_t *timer)
void add_timespec (struct timespec *t1, struct timespec *t2)
{
update_backoff_delay (timer);
ParodusInfo("Waiting with backoffRetryTime %d seconds\n", timer->delay);
sleep (timer->delay);
t2->tv_sec += t1->tv_sec;
t2->tv_nsec += t1->tv_nsec;
if (t2->tv_nsec >= 1000000000) {
t2->tv_sec += 1;
t2->tv_nsec -= 1000000000;
}
}
unsigned calc_random_secs (int random_num, unsigned max_secs)
{
unsigned delay_secs = (unsigned) random_num & max_secs;
if (delay_secs < 3)
return delay_secs + 3;
else
return delay_secs;
}
unsigned calc_random_nsecs (int random_num)
{
/* random _num is in range 0..2147483648 */
unsigned n = (unsigned) random_num >> 1;
/* n is in range 0..1073741824 */
if (n < 1000000000)
return n;
return n - 1000000000;
}
void calc_random_expiration (int random_num1, int random_num2, backoff_timer_t *timer, struct timespec *ts)
{
unsigned max_secs = update_backoff_delay (timer); // 3,7,15,31
struct timespec ts_delay = {3, 0};
if (max_secs > 3) {
ts_delay.tv_sec = calc_random_secs (random_num1, max_secs);
ts_delay.tv_nsec = calc_random_nsecs (random_num2);
}
ParodusInfo("Waiting max delay %u backoffRetryTime %ld secs %ld usecs\n",
max_secs, ts_delay.tv_sec, ts_delay.tv_nsec/1000);
/* Add delay to expire time */
add_timespec (&ts_delay, ts);
}
void terminate_backoff_delay (void)
{
pthread_mutex_lock (&backoff_delay_mut);
pthread_cond_signal(&backoff_delay_con);
pthread_mutex_unlock (&backoff_delay_mut);
}
#define BACKOFF_ERR -1
#define BACKOFF_SHUTDOWN 1
#define BACKOFF_DELAY_TAKEN 0
void start_conn_in_progress (unsigned long start_time);
/* backoff_delay
*
* delays for the number of seconds specified in parameter timer
* g_shutdown can break out of the delay.
*
* returns -1 pthread_cond_timedwait error
* 1 shutdown
* 0 delay taken
*/
static int backoff_delay (backoff_timer_t *timer)
{
struct timespec ts;
int rtn;
// periodically update the health file.
clock_gettime (CLOCK_REALTIME, &ts);
if ((ts.tv_sec - timer->ts.tv_sec) >= UPDATE_HEALTH_FILE_INTERVAL_SECS) {
start_conn_in_progress (timer->start_time);
timer->ts.tv_sec += UPDATE_HEALTH_FILE_INTERVAL_SECS;
}
calc_random_expiration (random(), random(), timer, &ts);
pthread_mutex_lock (&backoff_delay_mut);
// The condition variable will only be set if we shut down.
rtn = pthread_cond_timedwait (&backoff_delay_con, &backoff_delay_mut, &ts);
pthread_mutex_unlock (&backoff_delay_mut);
if (g_shutdown)
return BACKOFF_SHUTDOWN;
if ((rtn != 0) && (rtn != ETIMEDOUT)) {
ParodusError ("pthread_cond_timedwait error (%d) in backoff_delay.\n", rtn);
return BACKOFF_ERR;
}
return BACKOFF_DELAY_TAKEN;
}
//--------------------------------------------------------------------
@@ -293,17 +419,7 @@ char *build_extra_hdrs (header_info_t *header_info)
//--------------------------------------------------------------------
void set_current_server (create_connection_ctx_t *ctx)
{
ctx->current_server = get_current_server (&ctx->server_list);
}
void set_extra_headers (create_connection_ctx_t *ctx, int reauthorize)
{
if (reauthorize && (get_parodus_cfg()->client_cert_path !=NULL && strlen(get_parodus_cfg()->client_cert_path) >0))
{
getAuthToken(get_parodus_cfg());
}
ctx->extra_headers = build_extra_hdrs (&ctx->header_info);
ctx->current_server = get_current_server (ctx->server_list);
}
void free_extra_headers (create_connection_ctx_t *ctx)
@@ -311,11 +427,26 @@ 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);
if (NULL != ctx->server_list)
free_server_list (ctx->server_list);
}
@@ -332,8 +463,10 @@ int find_servers (server_list_t *server_list)
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
if (parse_server_url (get_parodus_cfg()->webpa_url, default_server) < 0) {
ParodusError ("Invalid Default URL\n");
return FIND_INVALID_DEFAULT;
}
ParodusInfo("default server_Address %s\n", default_server->server_addr);
ParodusInfo("default port %u\n", default_server->port);
#ifdef FEATURE_DNS_QUERY
@@ -351,7 +484,6 @@ int find_servers (server_list_t *server_list)
return FIND_SUCCESS;
}
//--------------------------------------------------------------------
// connect to current server
int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
@@ -387,8 +519,10 @@ int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
}
if ((NULL == connection) && (!is_ipv6)) {
if((checkHostIp(server->server_addr) == -2)) {
if (check_timer_expired (&ctx->connect_timer, 15*60*1000)) {
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);
@@ -404,14 +538,14 @@ int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
//--------------------------------------------------------------------
// Return codes for wait_connection_ready
#define WAIT_SUCCESS 0
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define WAIT_FAIL 2
#define FREE_NON_NULL_PTR(ptr) if (NULL != ptr) free(ptr)
int wait_connection_ready (create_connection_ctx_t *ctx)
{
int wait_status;
int wait_status = 0;
char *redirectURL = NULL;
if(nopoll_conn_wait_for_status_until_connection_ready(get_global_conn(), 10,
@@ -423,12 +557,12 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
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);
ParodusInfo("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) {
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;
@@ -440,10 +574,12 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
FREE_NON_NULL_PTR (redirectURL);
if(wait_status == 403)
{
ParodusError("Received Unauthorized response with status: %d\n", wait_status);
free_extra_headers (ctx);
set_extra_headers (ctx, true);
return WAIT_ACTION_RETRY;
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");
@@ -453,9 +589,9 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
//--------------------------------------------------------------------
// Return codes for connect_and_wait
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define CONN_WAIT_RETRY_DNS 2
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define CONN_WAIT_FAIL 2
int connect_and_wait (create_connection_ctx_t *ctx)
{
@@ -486,7 +622,7 @@ int connect_and_wait (create_connection_ctx_t *ctx)
} // nopoll_connected
if (nopoll_connected) {
close_and_unref_connection(get_global_conn());
close_and_unref_connection(get_global_conn(), false);
set_global_conn(NULL);
}
@@ -499,7 +635,7 @@ int connect_and_wait (create_connection_ctx_t *ctx)
continue;
}
return CONN_WAIT_RETRY_DNS;
return CONN_WAIT_FAIL;
}
}
@@ -512,20 +648,61 @@ int keep_trying_to_connect (create_connection_ctx_t *ctx,
{
int rtn;
while (true)
while (!g_shutdown)
{
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
// If interface down event is set, stop retry
// and wait till interface is up again.
if(get_interface_down_event()) {
if (0 != wait_while_interface_down())
return false;
start_conn_in_progress(backoff_timer->start_time);
ParodusInfo("Interface is back up, re-initializing the convey header\n");
// Reset the reconnect reason by initializing the convey header again
((header_info_t *)(&ctx->header_info))->conveyHeader = getWebpaConveyHeader();
ParodusInfo("Received reconnect_reason as:%s\n", reconnect_reason);
} else {
if (backoff_delay (backoff_timer) // 3,7,15,31 ..
!= BACKOFF_DELAY_TAKEN) // shutdown or cond wait error
return false;
}
if (rtn == CONN_WAIT_FAIL) {
return false;
}
// else retry
}
return false;
}
int wait_while_interface_down()
{
int rtn;
ParodusError("Interface is down, hence waiting until its up\n");
close_and_unref_connection (get_global_conn(), false);
set_global_conn(NULL);
while (get_interface_down_event ()) {
pthread_mutex_lock(get_interface_down_mut());
rtn = pthread_cond_wait(get_interface_down_con(), get_interface_down_mut());
pthread_mutex_unlock (get_interface_down_mut());
if (rtn != 0)
ParodusError
("Error on pthread_cond_wait (%d) in wait_while_interface_down\n", rtn);
if ((rtn != 0) || g_shutdown) {
return -1;
}
}
return 0;
}
//--------------------------------------------------------------------
@@ -533,11 +710,10 @@ int keep_trying_to_connect (create_connection_ctx_t *ctx,
* @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)
int createNopollConnection(noPollCtx *ctx, server_list_t *server_list)
{
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;
@@ -552,37 +728,60 @@ int createNopollConnection(noPollCtx *ctx)
max_retry_count = (int) get_parodus_cfg()->webpa_backoff_max;
ParodusPrint("max_retry_count is %d\n", max_retry_count );
memset (&conn_ctx, 0, sizeof(create_connection_ctx_t));
conn_ctx.nopoll_ctx = ctx;
init_expire_timer (&conn_ctx.connect_timer);
init_header_info (&conn_ctx.header_info);
set_extra_headers (&conn_ctx, false);
set_server_list_null (&conn_ctx.server_list);
init_backoff_timer (&backoff_timer, max_retry_count);
/* look up server information if we don't already have it */
if (server_is_null (&server_list->defaults))
if (find_servers (server_list) == FIND_INVALID_DEFAULT) {
return nopoll_false;
}
conn_ctx.server_list = server_list;
init_backoff_timer (&backoff_timer, max_retry_count);
start_conn_in_progress (backoff_timer.start_time);
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))
if (keep_trying_to_connect (&conn_ctx, &backoff_timer)) {
// Don't reuse the redirect server during reconnect
free_server (&conn_ctx.server_list->redirect);
break;
// retry dns query
}
/* if we failed to connect, don't reuse the redirect server */
free_server (&conn_ctx.server_list->redirect);
#ifdef FEATURE_DNS_QUERY
/* if we don't already have a valid jwt, look up server information */
if (server_is_null (&conn_ctx.server_list->jwt))
if (find_servers (conn_ctx.server_list) == FIND_INVALID_DEFAULT) {
/* since we already found a default server, we don't expect FIND_INVALID_DEFAULT */
g_shutdown = true;
}
#endif
}
if(conn_ctx.current_server->allow_insecure <= 0)
{
ParodusInfo("Connected to server over SSL\n");
OnboardLog("Connected to server over SSL\n");
}
else
{
ParodusInfo("Connected to server\n");
OnboardLog("Connected to server\n");
}
get_parodus_cfg()->cloud_status = CLOUD_STATUS_ONLINE;
ParodusInfo("cloud_status set as %s after successful connection\n", get_parodus_cfg()->cloud_status);
// Invoke the ping status change event callback as "received" ping
if(NULL != on_ping_status_change)
{
on_ping_status_change("received");
}
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);
@@ -590,8 +789,7 @@ int createNopollConnection(noPollCtx *ctx)
}
free_extra_headers (&conn_ctx);
free_header_info (&conn_ctx.header_info);
free_server_list (&conn_ctx.server_list);
free_header_info (&conn_ctx.header_info);
// Reset close_retry flag and heartbeatTimer once the connection retry is successful
ParodusPrint("createNopollConnection(): reset_close_retry\n");
@@ -601,7 +799,7 @@ int createNopollConnection(noPollCtx *ctx)
set_global_reconnect_status(false);
ParodusPrint("LastReasonStatus reset after successful connection\n");
setMessageHandlers();
stop_conn_in_progress ();
return nopoll_true;
}
@@ -628,13 +826,20 @@ static char* build_extra_headers( const char *auth, const char *device_id,
static noPollConnOpts * createConnOpts (char * extra_headers, bool secure)
{
noPollConnOpts * opts;
char * mtls_client_cert_path = NULL;
char * mtls_client_key_path = NULL;
opts = nopoll_conn_opts_new ();
if(secure)
{
if(strlen(get_parodus_cfg()->cert_path) > 0)
{
nopoll_conn_opts_set_ssl_certs(opts, NULL, NULL, NULL, get_parodus_cfg()->cert_path);
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_ssl_peer_verify (opts, nopoll_true);
nopoll_conn_opts_set_ssl_protocol (opts, NOPOLL_METHOD_TLSV1_2);
@@ -644,14 +849,88 @@ static noPollConnOpts * createConnOpts (char * extra_headers, bool secure)
return opts;
}
void close_and_unref_connection(noPollConn *conn)
static void close_conn ( noPollConn *conn, bool is_shutting_down)
{
const char *effective_reason = get_global_shutdown_reason();
if (NULL == effective_reason) {
effective_reason = SHUTDOWN_REASON_SYSTEM_RESTART;
}
else if (strcmp (effective_reason, SHUTDOWN_REASON_SIGTERM) == 0) {
char *sigterm_reason;
char *reason_file = get_parodus_cfg()->close_reason_file;
if ((NULL != reason_file) && readFromFile (reason_file, &sigterm_reason) &&
(strlen(sigterm_reason) != 0))
{
nopoll_conn_close_ext(conn, CloseNormalClosure, sigterm_reason,
strlen (sigterm_reason));
ParodusInfo ("Closed by SIGTERM, reason: %s\n", sigterm_reason);
if (is_shutting_down)
ParodusInfo ("shutdown reason at close %s\n", sigterm_reason);
free (sigterm_reason);
return;
}
/* file could not be read. use canned message. */
effective_reason = SHUTDOWN_REASON_SYSTEM_RESTART;
ParodusError ("Closed by SIGTERM, but no reason file\n");
}
nopoll_conn_close_ext(conn, CloseNormalClosure, effective_reason,
strlen (effective_reason));
if (is_shutting_down)
ParodusInfo ("shutdown reason at close %s\n", effective_reason);
}
void close_and_unref_connection(noPollConn *conn, bool is_shutting_down)
{
if (conn) {
nopoll_conn_close(conn);
if (0 < nopoll_conn_ref_count (conn)) {
nopoll_conn_unref(conn);
}
close_conn (conn, is_shutting_down);
get_parodus_cfg()->cloud_status = CLOUD_STATUS_OFFLINE;
ParodusInfo("cloud_status set as %s after connection close\n", get_parodus_cfg()->cloud_status);
}
}
void write_conn_in_prog_file (bool is_starting, unsigned long start_time)
{
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);
if (is_starting)
fprintf (fp, "{START=%lu,%lu}\n", start_time, timestamp);
else
fprintf (fp, "{STOP=%lu}\n", timestamp);
fclose (fp);
}
void start_conn_in_progress (unsigned long start_time)
{
write_conn_in_prog_file (true, start_time);
}
void stop_conn_in_progress (void)
{
write_conn_in_prog_file (false, 0);
}
void registerParodusOnPingStatusChangeHandler(parodusOnPingStatusChangeHandler callback_func)
{
on_ping_status_change = callback_func;
}

View File

@@ -33,22 +33,37 @@ extern "C" {
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
#define SHUTDOWN_REASON_PARODUS_STOP "parodus_stopping"
#define SHUTDOWN_REASON_SYSTEM_RESTART "system_restarting"
#define SHUTDOWN_REASON_SIGTERM "SIGTERM"
/**
* parodusOnPingStatusChangeHandler - Function pointer
* Used to define callback function to do additional processing
* when websocket Ping status change event
* i.e. ping_miss or ping receive after miss
*/
typedef void (*parodusOnPingStatusChangeHandler) (char * status);
extern parodusOnPingStatusChangeHandler on_ping_status_change;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
int createNopollConnection(noPollCtx *);
void set_server_list_null (server_list_t *server_list);
int createNopollConnection(noPollCtx *, server_list_t *);
/**
* @brief Interface to terminate WebSocket client connections and clean up resources.
*/
void close_and_unref_connection(noPollConn *);
void close_and_unref_connection(noPollConn *conn, bool is_shutting_down);
noPollConn *get_global_conn(void);
void set_global_conn(noPollConn *);
char *get_global_shutdown_reason();
void set_global_shutdown_reason(char *reason);
char *get_global_reconnect_reason();
void set_global_reconnect_reason(char *reason);
@@ -57,6 +72,21 @@ 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 (unsigned long start_time);
void stop_conn_in_progress (void);
// To Register parodusOnPingStatusChangeHandler Callback function
void registerParodusOnPingStatusChangeHandler(parodusOnPingStatusChangeHandler on_ping_status_change);
// To stop connection and wait duing interface down state
int wait_while_interface_down (void);
void terminate_backoff_delay (void);
#ifdef __cplusplus
}
#endif

View File

@@ -26,6 +26,9 @@
#include "config.h"
#include "connection.h"
#include "close_retry.h"
#include "client_list.h"
#define SERVICE_STATUS "service-status"
static void freeObjArray(char *(*obj)[], int size);
static int writeIntoCrudJson(cJSON *res_obj, char * object, cJSON *objValue, int freeFlag);
@@ -33,6 +36,7 @@ static int parse_dest_elements_to_string(wrp_msg_t *reqMsg, char *(*obj)[]);
static char* strdupptr( const char *s, const char *e );
static int ConnDisconnectFromCloud(char *reason);
static int validateDisconnectString(char *reason);
static int getClientStatus(char *service, cJSON **jsonresponse);
int writeToJSON(char *data)
{
@@ -58,22 +62,7 @@ int writeToJSON(char *data)
int readFromJSON(char **data)
{
FILE *fp;
int ch_count = 0;
fp = fopen(get_parodus_cfg()->crud_config_file, "r+");
if (fp == NULL)
{
ParodusError("Failed to open file %s\n", get_parodus_cfg()->crud_config_file);
return 0;
}
fseek(fp, 0, SEEK_END);
ch_count = ftell(fp);
fseek(fp, 0, SEEK_SET);
*data = (char *) malloc(sizeof(char) * (ch_count + 1));
fread(*data, 1, ch_count,fp);
(*data)[ch_count] ='\0';
fclose(fp);
return 1;
return readFromFile (get_parodus_cfg()->crud_config_file, data);
}
/*
* @res_obj json object to add it in crud config json file
@@ -654,10 +643,17 @@ int retrieveObject( wrp_msg_t *reqMsg, wrp_msg_t **response )
}
ParodusInfo( "Number of object level %d\n", objlevel );
if(objlevel == 3 && ((obj[3] !=NULL) && strstr(obj[3] ,"tags") == NULL))
if((objlevel == 3 && ((obj[3] !=NULL) && strstr(obj[3] ,"tags") == NULL)) || (objlevel == 4 && ((obj[3] !=NULL) && strstr(obj[3] ,"service-status") != NULL)))
{
inMemStatus = retrieveFromMemory(obj[3], &inMemResponse );
//To support dest "mac:14xxxxxxxxxx/parodus/service-status/service" to retrieve online/offline status of registered clients.
if(strstr(obj[3] ,"service-status") !=NULL)
{
inMemStatus = getClientStatus(obj[4], &inMemResponse );
}
else
{
inMemStatus = retrieveFromMemory(obj[3], &inMemResponse );
}
if(inMemStatus == 0)
{
@@ -1346,6 +1342,7 @@ static int ConnDisconnectFromCloud(char *disconn_reason)
if(!close_retry)
{
ParodusInfo("Reconnect detected, setting reason %s for Reconnect\n", disconn_reason);
OnboardLog("Reconnect detected, setting reason %s for Reconnect\n", disconn_reason);
set_global_reconnect_reason(disconn_reason);
set_global_reconnect_status(true);
set_close_retry();
@@ -1627,3 +1624,27 @@ static int validateDisconnectString(char *reason)
}
return rv;
}
static int getClientStatus(char *service, cJSON **jsonresponse)
{
char regstatus[16] ={0};
*jsonresponse = cJSON_CreateObject();
if(service == NULL)
{
ParodusError("service is NULL\n");
return -1;
}
if(checkClientStatus(service))
{
strncpy(regstatus, "online", sizeof(regstatus)-1);
}
else
{
strncpy(regstatus, "offline", sizeof(regstatus)-1);
}
ParodusPrint("getClientStatus: service:%s value:%s\n", service, regstatus);
cJSON_AddItemToObject( *jsonresponse, SERVICE_STATUS , cJSON_CreateString(regstatus));
return 0;
}

View File

@@ -121,6 +121,9 @@ void listenerOnMessage(void * msg, size_t msgSize)
ParodusInfo("Received downstream dest as :%s and transaction_uuid :%s\n", dest,
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.transaction_uuid :
((WRP_MSG_TYPE__EVENT == msgType) ? "NA" : message->u.crud.transaction_uuid)));
OnboardLog("%s\n",
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.transaction_uuid :
((WRP_MSG_TYPE__EVENT == msgType) ? "NA" : message->u.crud.transaction_uuid)));
free(destVal);

26
src/event_handler.c Normal file
View File

@@ -0,0 +1,26 @@
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
* Copyright [2014] [Cisco Systems, Inc.]
* 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.
*/
/* This is a stub file that will be overridden in a patch */
#include "event_handler.h"
void EventHandler()
{
}

21
src/event_handler.h Normal file
View File

@@ -0,0 +1,21 @@
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
* Copyright [2014] [Cisco Systems, Inc.]
* 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.
*/
void EventHandler();
#define LOGGING_INTERVAL_SECS ( 60 * 60 )

View File

@@ -22,8 +22,10 @@
*/
#include "heartBeat.h"
#include <stdbool.h>
volatile unsigned int heartBeatTimer = 0;
volatile bool paused = false;
pthread_mutex_t heartBeat_mut=PTHREAD_MUTEX_INITIALIZER;
@@ -49,8 +51,27 @@ void reset_heartBeatTimer()
void increment_heartBeatTimer(unsigned int inc_time_ms)
{
pthread_mutex_lock (&heartBeat_mut);
heartBeatTimer += inc_time_ms;
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

@@ -39,6 +39,12 @@ 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

View File

@@ -19,14 +19,15 @@
#include "stdlib.h"
#include "config.h"
#include "auth_token.h"
#include "connection.h"
#include "conn_interface.h"
#include "parodus_log.h"
#include <curl/curl.h>
#ifdef INCLUDE_BREAKPAD
#include "breakpad_wrapper.h"
#else
#include "signal.h"
#endif
#include "signal.h"
#include "privilege.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -36,54 +37,80 @@
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
/* none */
typedef void Sigfunc(int);
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/* none */
int numLoops;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
#ifndef INCLUDE_BREAKPAD
static void sig_handler(int sig);
Sigfunc *
signal (int signo, Sigfunc *func)
{
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset (&act.sa_mask);
act.sa_flags = 0;
if (signo == SIGALRM) {
#ifdef SA_INTERRUPT
act.sa_flags |= SA_INTERRUPT; /* SunOS 4.x */
#endif
} else {
#ifdef SA_RESTART
act.sa_flags |= SA_RESTART; /* SVR4, 4.4BSD */
#endif
}
if (sigaction (signo, &act, &oact) < 0) {
ParodusError ("Signal Handler for signal %d not installed!\n", signo);
return (SIG_ERR);
}
return (oact.sa_handler);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( int argc, char **argv)
{
#ifdef INCLUDE_BREAKPAD
breakpad_ExceptionHandler();
#else
set_global_shutdown_reason (SHUTDOWN_REASON_PARODUS_STOP);
signal(SIGTERM, sig_handler);
signal(SIGINT, sig_handler);
signal(SIGINT, sig_handler);
signal(SIGUSR1, sig_handler);
signal(SIGUSR2, sig_handler);
signal(SIGQUIT, sig_handler);
signal(SIGHUP, sig_handler);
signal(SIGALRM, sig_handler);
#ifdef INCLUDE_BREAKPAD
/* breakpad handles the signals SIGSEGV, SIGBUS, SIGFPE, and SIGILL */
breakpad_ExceptionHandler();
#else
signal(SIGSEGV, sig_handler);
signal(SIGBUS, sig_handler);
signal(SIGKILL, sig_handler);
signal(SIGFPE, sig_handler);
signal(SIGILL, sig_handler);
signal(SIGQUIT, sig_handler);
signal(SIGHUP, sig_handler);
signal(SIGALRM, sig_handler);
#endif
ParodusCfg *cfg;
ParodusInfo ("RAND_MAX is %ld (0x%lx)\n", RAND_MAX, RAND_MAX);
srandom (getpid());
/* TODO not ideal, but it fixes a more major problem for now. */
cfg = get_parodus_cfg();
memset(cfg,0,sizeof(ParodusCfg));
ParodusInfo("********** Starting component: Parodus **********\n ");
drop_root_privilege();
setDefaultValuesToCfg(cfg);
if (0 != parseCommandLine(argc,argv,cfg)) {
abort();
}
curl_global_init(CURL_GLOBAL_DEFAULT);
getAuthToken(cfg);
createSocketConnection( NULL);
@@ -98,7 +125,6 @@ const char *rdk_logger_module_fetch(void)
/*----------------------------------------------------------------------------*/
/* Internal functions */
/*----------------------------------------------------------------------------*/
#ifndef INCLUDE_BREAKPAD
static void sig_handler(int sig)
{
@@ -106,17 +132,25 @@ static void sig_handler(int sig)
{
signal(SIGINT, sig_handler); /* reset it to this function */
ParodusInfo("SIGINT received!\n");
shutdownSocketConnection();
shutdownSocketConnection(SHUTDOWN_REASON_PARODUS_STOP);
}
else if ( sig == SIGUSR1 )
{
signal(SIGUSR1, sig_handler); /* reset it to this function */
ParodusInfo("SIGUSR1 received!\n");
shutdownSocketConnection(SHUTDOWN_REASON_SYSTEM_RESTART);
}
else if ( sig == SIGUSR2 )
{
signal(SIGUSR2, sig_handler); /* reset it to this function */
ParodusInfo("SIGUSR2 received!\n");
}
else if ( sig == SIGTERM )
{
signal(SIGTERM, sig_handler); /* reset it to this function */
ParodusInfo("SIGTERM received!\n");
shutdownSocketConnection(SHUTDOWN_REASON_SIGTERM);
}
else if ( sig == SIGCHLD )
{
signal(SIGCHLD, sig_handler); /* reset it to this function */
@@ -135,8 +169,7 @@ static void sig_handler(int sig)
else
{
ParodusInfo("Signal %d received!\n", sig);
shutdownSocketConnection();
shutdownSocketConnection(SHUTDOWN_REASON_PARODUS_STOP);
}
}
#endif

View File

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

View File

@@ -167,16 +167,25 @@ void listenerOnCloseMessage (noPollCtx * ctx, noPollConn * conn, noPollPtr user_
if( closeStatus == 1006 && !get_global_reconnect_status())
{
ParodusInfo("Reconnect detected, setting default Reconnect reason %s\n",defaultReason);
OnboardLog("Reconnect detected, setting default Reconnect reason %s\n",defaultReason);
set_global_reconnect_reason(defaultReason);
set_global_reconnect_status(true);
}
else if(!get_global_reconnect_status())
{
ParodusInfo("Reconnect detected, setting Reconnect reason as Unknown\n");
OnboardLog("Reconnect detected, setting Reconnect reason as Unknown\n");
set_global_reconnect_reason("Unknown");
}
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");
set_close_retry();
ParodusPrint("listenerOnCloseMessage(): mutex unlock in producer thread\n");
}

View File

@@ -26,6 +26,7 @@
#include "nopoll_helpers.h"
#include "nopoll_handlers.h"
#include "time.h"
#include "config.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -49,49 +50,33 @@ void setMessageHandlers()
nopoll_conn_set_on_close(get_global_conn(), (noPollOnCloseHandler)listenerOnCloseMessage, NULL);
}
static int cloud_status_is_online (void)
{
const char *status = get_parodus_cfg()->cloud_status;
if (NULL == status)
return false;
return (strcmp (status, CLOUD_STATUS_ONLINE) == 0);
}
/** To send upstream msgs to server ***/
void sendMessage(noPollConn *conn, void *msg, size_t len)
{
int bytesWritten = 0;
static int connErr=0;
long timeDiff = 0;
if (!cloud_status_is_online ()) {
ParodusError("Failed to send msg upstream as connection is not OK\n");
OnboardLog("Failed to send msg upstream as connection is not OK\n");
return;
}
ParodusInfo("sendMessage length %zu\n", len);
if(nopoll_conn_is_ok(conn) && nopoll_conn_is_ready(conn))
bytesWritten = sendResponse(conn, msg, len);
ParodusPrint("Number of bytes written: %d\n", bytesWritten);
if (bytesWritten != (int) len)
{
//bytesWritten = nopoll_conn_send_binary(conn, msg, len);
bytesWritten = sendResponse(conn, msg, len);
ParodusPrint("Number of bytes written: %d\n", bytesWritten);
if (bytesWritten != (int) 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");
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");
kill(getpid(),SIGTERM);
}
}
ParodusError("Failed to send bytes %zu, bytes written were=%d (errno=%d, %s)..\n", len, bytesWritten, errno, strerror(errno));
}
}
@@ -149,6 +134,7 @@ 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,3 +33,9 @@
#define ParodusError(...) cimplog_error(LOGGING_MODULE, __VA_ARGS__)
#define ParodusInfo(...) cimplog_info(LOGGING_MODULE, __VA_ARGS__)
#define ParodusPrint(...) cimplog_debug(LOGGING_MODULE, __VA_ARGS__)
#ifdef FEATURE_SUPPORT_ONBOARD_LOGGING
#define OnboardLog(...) onboarding_log(LOGGING_MODULE, __VA_ARGS__)
#else
#define OnboardLog(...)
#endif

View File

@@ -178,6 +178,7 @@ 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++)

6
src/privilege.c Normal file
View File

@@ -0,0 +1,6 @@
#include "privilege.h"
void drop_root_privilege()
{
}

2
src/privilege.h Normal file
View File

@@ -0,0 +1,2 @@
/* This is a stub function that will be overridden in a patch */
void drop_root_privilege();

View File

@@ -139,6 +139,7 @@ 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;
}
}
@@ -146,6 +147,7 @@ int analyze_jwt (const cjwt_t *jwt, char **url_buf, unsigned int *port)
url_buf, port);
if (http_match < 0) {
ParodusError ("Invalid endpoint claim in JWT\n");
OnboardLog("Invalid endpoint claim in JWT\n");
return TOKEN_ERR_BAD_ENDPOINT;
}
ParodusInfo ("JWT is_http strncmp: %d\n", http_match);

View File

@@ -190,6 +190,16 @@ 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
@@ -234,7 +244,7 @@ void *processUpstreamMessage()
if(rv > 0)
{
msgType = msg->msg_type;
if(msgType == 9)
if(msgType == WRP_MSG_TYPE__SVC_REGISTRATION)
{
ParodusInfo("\n Nanomsg client Registration for Upstream\n");
//Extract serviceName and url & store it in a linked list for reg_clients
@@ -249,12 +259,16 @@ void *processUpstreamMessage()
{
ParodusInfo("match found, client is already registered\n");
parStrncpy(temp->url,msg->u.reg.url, sizeof(temp->url));
if(nn_shutdown(temp->sock, 0) < 0)
if(nn_shutdown(temp->sock, temp->endpoint) < 0)
{
ParodusError ("nn_shutdown socket=%d err=%d\n",
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);
}
nn_close (temp->sock);
temp->sock = nn_socket(AF_SP,NN_PUSH );
if(temp->sock >= 0)
@@ -272,6 +286,7 @@ void *processUpstreamMessage()
}
else
{
temp->endpoint = rc;
ParodusInfo("Client registered before. Sending ack on socket %d\n", temp->sock);
status =sendAuthStatus(temp);
@@ -403,12 +418,42 @@ void *processUpstreamMessage()
ParodusError("Failed to get device_id\n");
}
}
else
else if((WRP_MSG_TYPE__UPDATE == msgType) || (WRP_MSG_TYPE__DELETE == msgType))
{
ParodusPrint("UPDATE/DELETE request\n");
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. 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);
}
}
}
}
}
}
else
{
@@ -575,6 +620,7 @@ void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
else
{
ParodusInfo("close_retry is %d, unable to send response as connection retry is in progress\n", close_retry);
OnboardLog("close_retry is %d, unable to send response as connection retry is in progress\n", close_retry);
}
free(appendData);
appendData =NULL;

View File

@@ -16,7 +16,9 @@ set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -g -fprofile-arcs -ftest-coverage
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DTEST ")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -W -g -fprofile-arcs -ftest-coverage -O0")
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_SRC ../src/string_helpers.c ../src/mutex.c
../src/time.c ../src/config.c ../src/spin_thread.c
../src/event_handler.c ../src/token.c)
set (PARODUS_COMMON_LIBS gcov -lcunit -lcimplog -lwrp-c
-luuid -lmsgpackc -lnopoll -lnanomsg -lpthread
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
@@ -88,16 +90,16 @@ target_link_libraries (test_spin_thread_e ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_spin_thread success
#-------------------------------------------------------------------------------
add_test(NAME test_spin_thread_s COMMAND ${MEMORY_CHECK} ./test_spin_thread_s)
add_executable(test_spin_thread_s test_spin_thread_s.c ../src/spin_thread.c)
target_link_libraries (test_spin_thread_s ${PARODUS_COMMON_LIBS} )
# add_test(NAME test_spin_thread_s COMMAND ${MEMORY_CHECK} ./test_spin_thread_s)
# add_executable(test_spin_thread_s test_spin_thread_s.c ../src/spin_thread.c)
# target_link_libraries (test_spin_thread_s ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_string_helpers
#-------------------------------------------------------------------------------
add_test(NAME test_string_helpers COMMAND ${MEMORY_CHECK} ./test_string_helpers)
add_executable(test_string_helpers test_string_helpers.c ../src/string_helpers.c)
target_link_libraries (test_string_helpers ${PARODUS_COMMON_LIBS} )
# add_test(NAME test_string_helpers COMMAND ${MEMORY_CHECK} ./test_string_helpers)
# add_executable(test_string_helpers test_string_helpers.c ../src/string_helpers.c)
# target_link_libraries (test_string_helpers ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_nopoll_handlers
@@ -193,6 +195,17 @@ 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
#-------------------------------------------------------------------------------
@@ -211,7 +224,8 @@ 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 )
add_executable(test_crud_internal test_crud_internal.c ../src/config.c ../src/close_retry.c
../src/ParodusInternal.c ../src/string_helpers.c ../src/crud_internal.c ../src/client_list.c)
target_link_libraries (test_crud_internal -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
@@ -222,6 +236,17 @@ add_executable(test_upstream test_upstream.c ../src/upstream.c ../src/close_retr
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 -lnanomsg)
#-------------------------------------------------------------------------------
# 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)
#-------------------------------------------------------------------------------
@@ -261,6 +286,8 @@ set(CONIFC_SRC test_conn_interface.c
../src/mutex.c
../src/heartBeat.c
../src/close_retry.c
../src/event_handler.c
../src/client_list.c
)
if (ENABLE_SESHAT)
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface.c)
@@ -298,7 +325,7 @@ set(TOKEN_SRC ../src/conn_interface.c ../src/config.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
../src/close_retry.c ../src/event_handler.c
)
if (ENABLE_SESHAT)

104
tests/mock_event_handler.c Normal file
View File

@@ -0,0 +1,104 @@
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
* Copyright [2014] [Cisco Systems, Inc.]
* 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.
*/
/* This is a test version of event_handler.c that can be used
* to simulate interface down, interface up event
* You overwrite event_handler.c in the src diectory with this
* version. It will generate interface down / interface up events
* at random intervals between 60 secs and 124 secs
*/
#include "parodus_log.h"
#include "event_handler.h"
#include "connection.h"
#include "config.h"
#include "heartBeat.h"
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "time.h"
#include "close_retry.h"
extern bool g_shutdown;
static pthread_t sysevent_tid;
static void start_interface_down (void)
{
set_interface_down_event();
ParodusInfo("Interface_down_event is set\n");
pause_heartBeatTimer();
}
static void end_interface_down (void)
{
reset_interface_down_event();
ParodusInfo("Interface_down_event is reset\n");
resume_heartBeatTimer();
set_close_retry();
}
// waits from 60 to 124 secs
int wait_random (const char *msg)
{
#define HALF_SEC 500000l
long delay = (random() >> 5) + 60000000l;
long secs, usecs;
struct timeval timeout;
secs = delay / 1000000;
usecs = delay % 1000000;
ParodusInfo ("Waiting %ld secs %ld usecs for %s\n", secs, usecs, msg);
while (!g_shutdown) {
timeout.tv_sec = 0;
if (delay <= HALF_SEC) {
timeout.tv_usec = delay;
select (0, NULL, NULL, NULL, &timeout);
return 0;
}
timeout.tv_usec = HALF_SEC;
delay -= HALF_SEC;
select (0, NULL, NULL, NULL, &timeout);
}
return -1;
}
static void *parodus_sysevent_handler (void *data)
{
while (!g_shutdown) {
if (wait_random ("interface down") != 0)
break;
start_interface_down ();
wait_random ("interface up");
end_interface_down ();
}
ParodusInfo ("Exiting event handler\n");
return data;
}
void EventHandler()
{
ParodusInfo ("RAND_MAX is %ld (0x%lx)\n", RAND_MAX, RAND_MAX);
srandom (getpid());
pthread_create(&sysevent_tid, NULL, parodus_sysevent_handler, NULL);
}

View File

@@ -40,21 +40,46 @@ typedef enum {
CURLINFO_TOTAL_TIME
} CURLINFO;
struct token_data test_data;
int curl_easy_perform(CURL *curl)
{
UNUSED(curl);
char *msg = "response";
int rtn;
function_called();
return (int) mock();
rtn = (int) mock();
if (0 == rtn)
write_callback_fn (msg, 1, strlen(msg), &test_data);
return rtn;
}
extern int g_response_code;
void setGlobalResponseCode (int response_code)
{
g_response_code = response_code;
}
int curl_easy_getinfo(CURL *curl, CURLINFO CURLINFO_RESPONSE_CODE, long response_code)
{
UNUSED(curl);
UNUSED(CURLINFO_RESPONSE_CODE);
UNUSED(response_code);
if (0 != g_response_code)
{
response_code= g_response_code;
ParodusInfo("response_code is %ld\n", response_code);
}
function_called();
return (int) mock();
}
char* get_global_reconnect_reason()
{
return "none";
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -67,6 +92,7 @@ void getAuthToken_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()
@@ -77,8 +103,10 @@ void getAuthToken_MacNull()
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];
@@ -106,7 +134,7 @@ void test_requestNewAuthToken_init_fail ()
assert_int_equal (output, -1);
free(cfg.token_server_url);
}
#endif
void test_requestNewAuthToken_failure ()
{
@@ -121,6 +149,8 @@ void test_requestNewAuthToken_failure ()
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);
@@ -132,6 +162,7 @@ void test_requestNewAuthToken_failure ()
requestNewAuthToken (token, sizeof(token), 2);
assert_int_equal (output, -1);
assert_int_equal (0, (int) token[0]);
free(cfg.token_server_url);
}
@@ -150,6 +181,9 @@ void test_requestNewAuthToken ()
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
test_data.size = 0;
test_data.data = token;
setGlobalResponseCode(200);
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
@@ -160,6 +194,7 @@ void test_requestNewAuthToken ()
output = requestNewAuthToken (token, sizeof(token), 1);
assert_int_equal (output, 0);
assert_string_equal (token, "response");
free(cfg.token_server_url);
}
@@ -197,6 +232,9 @@ void test_getAuthToken ()
expect_function_calls (curl_easy_getinfo, 1);
/* To test curl success case */
test_data.size = 0;
test_data.data = cfg.webpa_auth_token;
setGlobalResponseCode(200);
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
@@ -207,7 +245,7 @@ void test_getAuthToken ()
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);
}
@@ -224,6 +262,7 @@ void test_getAuthTokenFailure ()
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);
@@ -261,23 +300,118 @@ void test_getAuthTokenFailure ()
void test_write_callback_fn ()
{
void *buffer;
size_t size = 1;
size_t nmemb =8;
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;
buffer = strdup("response");
data.data = (char *) malloc(sizeof(char) * 5);
data.data = (char *) malloc(max_data_size);
data.data[0] = '\0';
out_len = write_callback_fn(buffer, size, nmemb, &data);
assert_string_equal(data.data, buffer);
assert_int_equal( out_len, strlen(buffer));
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);
}
void test_requestNewAuthToken_non200 ()
{
char token[1024];
ParodusCfg cfg;
int output;
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;
setGlobalResponseCode(404);
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, -1);
assert_string_equal (token, "");
ParodusInfo("requestNewAuthToken output: %d token empty len: %lu\n", output, strlen(token));
free(cfg.token_server_url);
}
void test_getAuthTokenFailure_non200 ()
{
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, 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);
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);
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);
setGlobalResponseCode(504);
getAuthToken(&cfg);
assert_string_equal( cfg.webpa_auth_token, "");
free(cfg.client_cert_path);
free(cfg.token_server_url);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -285,14 +419,16 @@ void test_write_callback_fn ()
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_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),
cmocka_unit_test(test_write_callback_fn),
cmocka_unit_test(test_requestNewAuthToken_non200),
cmocka_unit_test(test_getAuthTokenFailure_non200)
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -0,0 +1,116 @@
/**
* 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();
}
char* get_global_reconnect_reason()
{
return "none";
}
/*----------------------------------------------------------------------------*/
/* 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

@@ -32,6 +32,8 @@ pthread_t test_tid2;
static void *client_rcv_task();
static void *client2_rcv_task();
int numLoops;
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/

View File

@@ -53,6 +53,11 @@ void create_token_script(char *fname)
system(command);
}
char* get_global_reconnect_reason()
{
return "none";
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -116,6 +121,8 @@ void test_setParodusConfig()
assert_string_equal(cfg.jwt_key, temp->jwt_key);
#endif
assert_string_equal(cfg.crud_config_file, temp->crud_config_file);
free(cfg.crud_config_file);
}
void test_getParodusConfig()
@@ -299,8 +306,9 @@ void test_loadParodusCfg()
{
ParodusCfg tmpcfg;
ParodusCfg *Cfg = NULL;
Cfg = (ParodusCfg*)malloc(sizeof(ParodusCfg));
char protocol[32] = {'\0'};
Cfg = (ParodusCfg*)malloc(sizeof(ParodusCfg));
memset(Cfg, 0, sizeof(ParodusCfg));
parStrncpy(Cfg->hw_model, "TG1682", sizeof(Cfg->hw_model));
parStrncpy(Cfg->hw_serial_number, "Fer23u948590", sizeof(Cfg->hw_serial_number));
@@ -351,6 +359,14 @@ void test_loadParodusCfg()
assert_string_equal(tmpcfg.seshat_url, "ipc://tmp/seshat_service.url");
#endif
assert_string_equal(tmpcfg.crud_config_file, "parodus_cfg.json");
free(tmpcfg.client_cert_path);
free(tmpcfg.token_server_url);
free(tmpcfg.crud_config_file);
free(Cfg->crud_config_file);
free(Cfg->client_cert_path);
free(Cfg->token_server_url);
free(Cfg);
}
@@ -422,6 +438,8 @@ void test_setDefaultValuesToCfg()
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);
free(cfg);
}
void err_setDefaultValuesToCfg()

View File

@@ -33,6 +33,7 @@
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
static char *reconnect_reason = "webpa_process_starts";
UpStreamMsg *UpStreamMsgQ;
ParodusMsg *ParodusMsgQ;
pthread_mutex_t g_mutex=PTHREAD_MUTEX_INITIALIZER;
@@ -41,14 +42,26 @@ 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;
int numLoops;
parodusOnPingStatusChangeHandler on_ping_status_change;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
int createNopollConnection(noPollCtx *ctx)
void set_server_list_null (server_list_t *server_list)
{
UNUSED(ctx);
UNUSED(server_list);
}
int find_servers (server_list_t *server_list)
{
UNUSED(server_list);
return FIND_SUCCESS;
}
int createNopollConnection(noPollCtx *ctx, server_list_t *server_list)
{
UNUSED(ctx); UNUSED(server_list);
function_called();
return (int) mock();
}
@@ -74,6 +87,53 @@ noPollMutexUnlock mutex_unlock
UNUSED(mutex_create); UNUSED(mutex_destroy); UNUSED(mutex_lock); UNUSED(mutex_unlock);
function_called();
}
char *get_global_reconnect_reason()
{
return reconnect_reason;
}
char *get_global_shutdown_reason()
{
return SHUTDOWN_REASON_PARODUS_STOP;
}
void set_global_shutdown_reason(char *reason)
{
UNUSED(reason);
}
void start_conn_in_progress (unsigned long start_time)
{
UNUSED(start_time);
}
void stop_conn_in_progress (void)
{
}
void reset_interface_down_event (void)
{
}
bool get_interface_down_event (void)
{
return false;
}
void set_interface_down_event (void)
{
}
int wait_while_interface_down (void)
{
return 0;
}
void terminate_backoff_delay (void)
{
}
void packMetaData()
{
function_called();
@@ -131,12 +191,19 @@ void set_global_reconnect_status(bool status)
function_called();
}
void close_and_unref_connection(noPollConn *conn)
void close_and_unref_connection(noPollConn *conn, bool is_shutting_down)
{
UNUSED(conn);
UNUSED(conn); UNUSED(is_shutting_down);
function_called();
}
int readFromFile(const char *file_name, char **data)
{
UNUSED(file_name);
*data = strdup ("parodus_stopping");
return 1;
}
void nopoll_cleanup_library ()
{
function_called();
@@ -225,9 +292,6 @@ void timespec_diff(struct timespec *start, struct timespec *stop,
diff->tv_nsec = 1000;
}
void deleteAllClients (void)
{
}
/*----------------------------------------------------------------------------*/
/* Tests */
@@ -300,7 +364,6 @@ 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);
}

View File

@@ -15,15 +15,14 @@
*/
#include <stdarg.h>
#include <CUnit/Basic.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <assert.h>
#include <CUnit/Basic.h>
#include <nopoll.h>
#include <pthread.h>
#include "../src/ParodusInternal.h"
#include "../src/connection.h"
@@ -38,6 +37,11 @@ extern void init_expire_timer (expire_timer_t *timer);
extern int check_timer_expired (expire_timer_t *timer, long timeout_ms);
extern void init_backoff_timer (backoff_timer_t *timer, int max_count);
extern int update_backoff_delay (backoff_timer_t *timer);
extern void add_timespec (struct timespec *t1, struct timespec *t2);
extern unsigned calc_random_secs (int random_num, unsigned max_secs);
extern unsigned calc_random_nsecs (int random_num);
void calc_random_expiration (int random_num1, int random_num2,
backoff_timer_t *timer, struct timespec *ts);
extern int init_header_info (header_info_t *header_info);
extern void free_header_info (header_info_t *header_info);
extern char *build_extra_hdrs (header_info_t *header_info);
@@ -58,9 +62,10 @@ extern int keep_trying_to_connect (create_connection_ctx_t *ctx,
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool close_retry;
bool LastReasonStatus;
pthread_mutex_t close_mut;
bool interface_down_event = false;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t interface_down_con=PTHREAD_COND_INITIALIZER;
// Mock values
bool g_shutdown = false;
@@ -80,6 +85,42 @@ char* getWebpaConveyHeader()
return (char*) "WebPA-1.6 (TG1682)";
}
void set_interface_down_event()
{
interface_down_event = true;
}
void reset_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = false;
pthread_cond_signal(&interface_down_con);
pthread_mutex_unlock (&interface_down_mut);
}
bool get_interface_down_event()
{
return interface_down_event;
}
pthread_cond_t *get_interface_down_con(void)
{
return &interface_down_con;
}
pthread_mutex_t *get_interface_down_mut(void)
{
return &interface_down_mut;
}
int readFromFile(const char *file_name, char **data)
{
UNUSED(file_name);
*data = strdup ("parodus_stopping");
return 1;
}
noPollConn * nopoll_conn_new_opts (noPollCtx * ctx, noPollConnOpts * opts, const char * host_ip, const char * host_port, const char * host_name,const char * get_url,const char * protocols, const char * origin)
{
UNUSED(host_port); UNUSED(host_name); UNUSED(get_url); UNUSED(protocols);
@@ -117,6 +158,8 @@ nopoll_bool nopoll_conn_wait_for_status_until_connection_ready (noPollConn * co
int timeout, int *status, char ** message)
{
UNUSED(conn); UNUSED(timeout);
*message = NULL;
if (mock_wait_status >= 1000) {
*status = mock_wait_status / 1000;
mock_wait_status = mock_wait_status % 1000;
@@ -146,11 +189,9 @@ void nopoll_conn_close (noPollConn *conn)
UNUSED(conn);
}
int nopoll_conn_ref_count (noPollConn *conn)
void nopoll_conn_close_ext (noPollConn *conn, int status, const char *reason, int reason_size)
{
UNUSED(conn);
function_called ();
return (nopoll_bool) mock();
UNUSED(conn); UNUSED(status); UNUSED(reason); UNUSED(reason_size);
}
int checkHostIp(char * serverIP)
@@ -198,6 +239,7 @@ int allow_insecure_conn (char **server_addr, unsigned int *port)
/* Tests */
/*----------------------------------------------------------------------------*/
void test_get_global_conn()
{
assert_null(get_global_conn());
@@ -224,7 +266,7 @@ void test_set_global_reconnect_reason()
void test_closeConnection()
{
close_and_unref_connection(get_global_conn());
close_and_unref_connection(get_global_conn(), false);
}
void test_server_is_null()
@@ -301,13 +343,67 @@ void test_expire_timer()
void test_backoff_delay_timer()
{
struct timespec t1;
struct timespec t2;
backoff_timer_t btimer;
init_backoff_timer (&btimer, 5);
assert_int_equal (3, update_backoff_delay (&btimer));
assert_int_equal (7, update_backoff_delay (&btimer));
assert_int_equal (15, update_backoff_delay (&btimer));
assert_int_equal (31, update_backoff_delay (&btimer));
assert_int_equal (31, update_backoff_delay (&btimer));
t1.tv_sec = 3; t1.tv_nsec = 0;
t2.tv_sec = 3; t2.tv_nsec = 0;
add_timespec (&t1, &t2);
assert_int_equal (6, t2.tv_sec);
assert_int_equal (0, t2.tv_nsec);
t1.tv_sec = 3; t1.tv_nsec = 500*1000000;
t2.tv_sec = 3; t2.tv_nsec = 499*1000000;
add_timespec (&t1, &t2);
assert_int_equal (6, t2.tv_sec);
assert_int_equal (999*1000000, t2.tv_nsec);
t1.tv_sec = 3; t1.tv_nsec = 500*1000000;
t2.tv_sec = 3; t2.tv_nsec = 501*1000000;
add_timespec (&t1, &t2);
assert_int_equal (7, t2.tv_sec);
assert_int_equal (1000000, t2.tv_nsec);
assert_int_equal (3, calc_random_secs (0, 7));
assert_int_equal (4, calc_random_secs (1, 7));
assert_int_equal (7, calc_random_secs (15, 7));
assert_int_equal (3, calc_random_secs (16, 15));
assert_int_equal (14, calc_random_secs (30,15));
assert_int_equal (250000, calc_random_nsecs (500000));
assert_int_equal (1, calc_random_nsecs (2000000002));
init_backoff_timer (&btimer, 5);
t1.tv_sec = 0; t1.tv_nsec = 0;
/* max delay is 3 */
calc_random_expiration (0, 0, &btimer, &t1);
assert_int_equal (3, t1.tv_sec);
assert_int_equal (0, t1.tv_nsec);
t1.tv_sec = 0; t1.tv_nsec = 0;
/* max delay is 7*/
calc_random_expiration (15, 1073741824, &btimer, &t1);
assert_int_equal (7, t1.tv_sec);
assert_int_equal (536870912, t1.tv_nsec);
t1.tv_sec = 0; t1.tv_nsec = 0;
/* max delay is 15 */
calc_random_expiration (30, 2000000002, &btimer, &t1);
assert_int_equal (14, t1.tv_sec);
assert_int_equal (1, t1.tv_nsec);
t1.tv_sec = 0; t1.tv_nsec = 0;
/* max delay is 31 */
calc_random_expiration (32, 1, &btimer, &t1);
assert_int_equal (3, t1.tv_sec);
assert_int_equal (0, t1.tv_nsec);
}
@@ -363,16 +459,28 @@ void test_extra_headers ()
void test_set_current_server()
{
server_list_t server_list;
create_connection_ctx_t ctx;
memset (&ctx, 0xFF, sizeof(ctx));
memset (&server_list, 0xFF, sizeof(server_list));
memset (&ctx, 0, sizeof(ctx));
ctx.server_list = &server_list;
set_current_server (&ctx);
assert_ptr_equal (&ctx.server_list.redirect, ctx.current_server);
set_server_null (&ctx.server_list.redirect);
assert_ptr_equal (&ctx.server_list->redirect, ctx.current_server);
set_server_null (&ctx.server_list->redirect);
set_current_server (&ctx);
assert_ptr_equal (&ctx.server_list.jwt, ctx.current_server);
set_server_null (&ctx.server_list.jwt);
assert_ptr_equal (&ctx.server_list->jwt, ctx.current_server);
set_server_null (&ctx.server_list->jwt);
set_current_server (&ctx);
assert_ptr_equal (&ctx.server_list.defaults, ctx.current_server);
assert_ptr_equal (&ctx.server_list->defaults, ctx.current_server);
}
void init_cfg_header_info (ParodusCfg *cfg)
{
parStrncpy(cfg->hw_mac , "123567892366", sizeof(cfg->hw_mac));
parStrncpy(cfg->hw_model, "TG1682", sizeof(cfg->hw_model));
parStrncpy(cfg->hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg->hw_manufacturer));
parStrncpy(cfg->fw_name , "2.364s2", sizeof(cfg->fw_name));
parStrncpy(cfg->webpa_protocol , "WebPA-1.6", sizeof(cfg->webpa_protocol));
}
void test_set_extra_headers ()
@@ -391,12 +499,8 @@ void test_set_extra_headers ()
cfg.client_cert_path = strdup("testcert");
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
init_cfg_header_info (&cfg);
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
set_parodus_cfg(&cfg);
rtn = init_header_info (&ctx.header_info);
@@ -578,22 +682,17 @@ void test_nopoll_connect ()
// Return codes for wait_connection_ready
#define WAIT_SUCCESS 0
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define WAIT_FAIL 2
void test_wait_connection_ready ()
{
server_list_t server_list;
create_connection_ctx_t ctx;
ParodusCfg Cfg;
const char *expected_extra_headers =
"\r\nAuthorization: Bearer Auth---"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
"\r\nX-WebPA-Convey: WebPA-1.6 (TG1682)";
set_server_list_null (&server_list);
memset(&ctx,0,sizeof(ctx));
set_server_list_null (&ctx.server_list);
ctx.server_list = &server_list;
mock_wait_status = 0;
mock_redirect = NULL;
@@ -605,7 +704,7 @@ void test_wait_connection_ready ()
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_FAIL);
mock_wait_status = 503;
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
@@ -622,51 +721,40 @@ void test_wait_connection_ready ()
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_ACTION_RETRY);
assert_string_equal (ctx.server_list.redirect.server_addr, "mydns.mycom.net");
assert_int_equal (ctx.server_list.redirect.port, 8080);
assert_int_equal (0, ctx.server_list.redirect.allow_insecure);
assert_ptr_equal (ctx.current_server, &ctx.server_list.redirect);
free_server (&ctx.server_list.redirect);
assert_string_equal (ctx.server_list->redirect.server_addr, "mydns.mycom.net");
assert_int_equal (ctx.server_list->redirect.port, 8080);
assert_int_equal (0, ctx.server_list->redirect.allow_insecure);
assert_ptr_equal (ctx.current_server, &ctx.server_list->redirect);
free_server (&ctx.server_list->redirect);
mock_wait_status = 303;
mock_redirect = "http://mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_ACTION_RETRY);
assert_string_equal (ctx.server_list.redirect.server_addr, "mydns.mycom.net");
assert_int_equal (ctx.server_list.redirect.port, 80);
assert_int_equal (1, ctx.server_list.redirect.allow_insecure);
assert_ptr_equal (ctx.current_server, &ctx.server_list.redirect);
free_server (&ctx.server_list.redirect);
assert_string_equal (ctx.server_list->redirect.server_addr, "mydns.mycom.net");
assert_int_equal (ctx.server_list->redirect.port, 80);
assert_int_equal (1, ctx.server_list->redirect.allow_insecure);
assert_ptr_equal (ctx.current_server, &ctx.server_list->redirect);
free_server (&ctx.server_list->redirect);
mock_wait_status = 403;
memset(&Cfg, 0, sizeof(ParodusCfg));
parStrncpy (Cfg.webpa_auth_token, "Auth---", sizeof (Cfg.webpa_auth_token));
parStrncpy(Cfg.hw_model, "TG1682", sizeof(Cfg.hw_model));
parStrncpy(Cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(Cfg.hw_manufacturer));
parStrncpy(Cfg.hw_mac , "123567892366", sizeof(Cfg.hw_mac));
parStrncpy(Cfg.fw_name , "2.364s2", sizeof(Cfg.fw_name));
parStrncpy(Cfg.webpa_protocol , "WebPA-1.6", sizeof(Cfg.webpa_protocol));
set_parodus_cfg(&Cfg);
init_header_info (&ctx.header_info);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_ACTION_RETRY);
assert_string_equal (ctx.extra_headers, expected_extra_headers);
free_extra_headers (&ctx);
free_header_info (&ctx.header_info);
}
// Return codes for connect_and_wait
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define CONN_WAIT_RETRY_DNS 2
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define CONN_WAIT_RETRY_DNS 2
void test_connect_and_wait ()
{
server_list_t server_list;
create_connection_ctx_t ctx;
noPollCtx test_nopoll_ctx;
server_t test_server;
@@ -683,7 +771,9 @@ void test_connect_and_wait ()
mock_wait_status = 0;
set_server_list_null (&server_list);
memset(&ctx,0,sizeof(ctx));
ctx.server_list = &server_list;
ctx.nopoll_ctx = &test_nopoll_ctx;
ctx.current_server = &test_server;
ctx.extra_headers = test_extra_headers;
@@ -707,8 +797,6 @@ void test_connect_and_wait ()
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_RETRY_DNS);
Cfg.flags = 0;
@@ -718,8 +806,6 @@ void test_connect_and_wait ()
expect_function_call (nopoll_conn_new_opts);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_RETRY_DNS);
will_return (nopoll_conn_new_opts, &connection1);
@@ -757,8 +843,6 @@ void test_connect_and_wait ()
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
@@ -769,8 +853,6 @@ void test_connect_and_wait ()
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
@@ -790,8 +872,6 @@ void test_connect_and_wait ()
mock_redirect = "mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_RETRY_DNS);
will_return (nopoll_conn_tls_new, &connection1);
@@ -802,40 +882,34 @@ void test_connect_and_wait ()
mock_redirect = "https://mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_ACTION_RETRY);
}
void test_keep_trying ()
{
int rtn;
server_list_t server_list;
create_connection_ctx_t ctx;
noPollCtx test_nopoll_ctx;
server_t test_server;
backoff_timer_t backoff_timer;
ParodusCfg Cfg;
char *test_extra_headers =
"\r\nAuthorization: Bearer SER_MAC Fer23u948590 123567892366"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
"\r\nX-WebPA-Convey: WebPA-1.6 (TG1682)";
memset(&Cfg, 0, sizeof(ParodusCfg));
parStrncpy (Cfg.webpa_url, "http://mydns.mycom.net:8080", sizeof(Cfg.webpa_url));
init_cfg_header_info (&Cfg);
mock_wait_status = 0;
set_server_list_null (&server_list);
memset(&ctx,0,sizeof(ctx));
ctx.server_list = &server_list;
ctx.nopoll_ctx = &test_nopoll_ctx;
ctx.current_server = &test_server;
ctx.extra_headers = test_extra_headers;
test_server.allow_insecure = 1;
test_server.server_addr = "mydns.mycom.net";
test_server.port = 8080;
server_list.defaults.allow_insecure = 1;
server_list.defaults.server_addr = "mydns.mycom.net";
server_list.defaults.port = 8080;
set_current_server (&ctx);
Cfg.flags = 0;
set_parodus_cfg(&Cfg);
@@ -849,7 +923,7 @@ void test_keep_trying ()
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, true);
test_server.allow_insecure = 0;
server_list.defaults.allow_insecure = 0;
Cfg.flags = FLAGS_IPV4_ONLY;
set_parodus_cfg(&Cfg);
@@ -861,8 +935,6 @@ void test_keep_trying ()
mock_redirect = "https://mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
@@ -881,16 +953,12 @@ void test_keep_trying ()
mock_redirect = "https://mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
init_backoff_timer (&backoff_timer, 5);
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, false);
@@ -913,8 +981,6 @@ void test_keep_trying ()
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
init_backoff_timer (&backoff_timer, 5);
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, false);
@@ -924,8 +990,182 @@ void test_create_nopoll_connection()
{
int rtn;
ParodusCfg cfg;
server_list_t server_list;
noPollCtx test_nopoll_ctx;
set_server_list_null (&server_list);
memset(&cfg,0,sizeof(cfg));
cfg.flags = 0;
parStrncpy (cfg.webpa_url, "mydns.mycom.net:8080", sizeof(cfg.webpa_url));
cfg.boot_time = 25;
parStrncpy (cfg.hw_last_reboot_reason, "Test reason", sizeof(cfg.hw_last_reboot_reason));
cfg.webpa_backoff_max = 30;
parStrncpy (cfg.webpa_auth_token, "Auth---", sizeof (cfg.webpa_auth_token));
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
set_parodus_cfg(&cfg);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_false);
parStrncpy (cfg.webpa_url, "http://mydns.mycom.net:8080", sizeof(cfg.webpa_url));
set_parodus_cfg(&cfg);
set_server_list_null (&server_list);
mock_wait_status = 0;
will_return (nopoll_conn_new_opts, &connection1);
expect_function_call (nopoll_conn_new_opts);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
parStrncpy (cfg.webpa_url, "https://mydns.mycom.net:8080", sizeof(cfg.webpa_url));
cfg.flags = 0;
set_parodus_cfg(&cfg);
set_server_list_null (&server_list);
will_return (nopoll_conn_tls_new6, &connection1);
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
set_server_list_null (&server_list);
will_return (nopoll_conn_tls_new6, &connection1);
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
mock_wait_status = 302;
mock_redirect = "https://mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_tls_new6, &connection1);
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
mock_wait_status = 0;
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
#ifdef FEATURE_DNS_QUERY
cfg.acquire_jwt = 1;
cfg.flags = FLAGS_IPV4_ONLY;
set_parodus_cfg(&cfg);
set_server_list_null (&server_list);
will_return (allow_insecure_conn, -1);
expect_function_call (allow_insecure_conn);
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
mock_server_addr = "mydns.myjwtcom.net";
mock_port = 80;
will_return (allow_insecure_conn, 0);
expect_function_call (allow_insecure_conn);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
set_server_list_null (&server_list);
mock_server_addr = "mydns.myjwtcom.net";
mock_port = 80;
will_return (allow_insecure_conn, 0);
expect_function_call (allow_insecure_conn);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
cfg.flags = 0;
set_parodus_cfg(&cfg);
set_server_list_null (&server_list);
will_return (allow_insecure_conn, -1);
expect_function_call (allow_insecure_conn);
will_return (nopoll_conn_tls_new6, &connection1);
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
mock_wait_status = 0;
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
#endif
}
void test_get_interface_down_event()
{
assert_false(get_interface_down_event());
set_interface_down_event();
}
void *a()
{
sleep(15);
reset_interface_down_event();
pthread_exit(0);
return NULL;
}
void test_interface_down_retry()
{
int rtn;
ParodusCfg cfg;
noPollCtx test_nopoll_ctx;
server_list_t server_list;
pthread_t thread_a;
pthread_create(&thread_a, NULL, a, NULL);
memset(&cfg,0,sizeof(cfg));
cfg.flags = 0;
parStrncpy (cfg.webpa_url, "mydns.mycom.net:8080", sizeof(cfg.webpa_url));
@@ -939,7 +1179,8 @@ void test_create_nopoll_connection()
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
set_parodus_cfg(&cfg);
rtn = createNopollConnection (&test_nopoll_ctx);
set_server_list_null (&server_list);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_false);
parStrncpy (cfg.webpa_url, "http://mydns.mycom.net:8080", sizeof(cfg.webpa_url));
@@ -953,7 +1194,8 @@ void test_create_nopoll_connection()
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx);
set_server_list_null (&server_list);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
parStrncpy (cfg.webpa_url, "https://mydns.mycom.net:8080", sizeof(cfg.webpa_url));
@@ -964,23 +1206,20 @@ void test_create_nopoll_connection()
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx);
set_server_list_null (&server_list);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
will_return (nopoll_conn_tls_new6, &connection1);
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
@@ -989,15 +1228,11 @@ void test_create_nopoll_connection()
mock_redirect = "https://mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new6, &connection1);
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
will_return (nopoll_conn_is_ok, nopoll_true);
@@ -1005,7 +1240,8 @@ void test_create_nopoll_connection()
mock_wait_status = 0;
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx);
set_server_list_null (&server_list);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
#ifdef FEATURE_DNS_QUERY
@@ -1029,7 +1265,8 @@ void test_create_nopoll_connection()
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx);
set_server_list_null (&server_list);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
cfg.flags = 0;
@@ -1041,8 +1278,6 @@ void test_create_nopoll_connection()
expect_function_call (nopoll_conn_tls_new6);
will_return (nopoll_conn_is_ok, nopoll_false);
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_ref_count, 0);
expect_function_call (nopoll_conn_ref_count);
mock_wait_status = 0;
will_return (nopoll_conn_tls_new, &connection1);
expect_function_call (nopoll_conn_tls_new);
@@ -1050,12 +1285,12 @@ void test_create_nopoll_connection()
expect_function_call (nopoll_conn_is_ok);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_true);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
rtn = createNopollConnection (&test_nopoll_ctx);
set_server_list_null (&server_list);
rtn = createNopollConnection (&test_nopoll_ctx, &server_list);
assert_int_equal (rtn, nopoll_true);
#endif
}
pthread_join(thread_a, NULL);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
@@ -1083,7 +1318,9 @@ int main(void)
cmocka_unit_test(test_wait_connection_ready),
cmocka_unit_test(test_connect_and_wait),
cmocka_unit_test(test_keep_trying),
cmocka_unit_test(test_create_nopoll_connection)
cmocka_unit_test(test_create_nopoll_connection),
cmocka_unit_test(test_get_interface_down_event),
cmocka_unit_test(test_interface_down_retry)
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -32,8 +32,10 @@
#include "../src/connection.h"
#include "../src/close_retry.h"
bool LastReasonStatus;
pthread_mutex_t close_mut;
char *get_global_reconnect_reason()
{
return "parodus_stopping";
}
void set_global_reconnect_reason(char *reason)
{

View File

@@ -21,17 +21,18 @@
#include <nopoll_private.h>
#include <pthread.h>
#include "../src/ParodusInternal.h"
#include "../src/nopoll_handlers.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
volatile unsigned int heartBeatTimer;
bool LastReasonStatus;
bool interface_down_event = false;
int closeReason = 0;
pthread_mutex_t close_mut;
bool close_retry;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t interface_down_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -46,6 +47,24 @@ bool get_global_reconnect_status()
return LastReasonStatus;
}
void set_interface_down_event()
{
interface_down_event = true;
}
void reset_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = false;
pthread_cond_signal(&interface_down_con);
pthread_mutex_unlock (&interface_down_mut);
}
bool get_interface_down_event()
{
return interface_down_event;
}
void set_global_reconnect_status(bool status)
{
(void) status ;
@@ -179,6 +198,30 @@ void test_listenerOnPingMessage()
listenerOnPingMessage(NULL, NULL, NULL, NULL);
}
void test_getInterfaceDownEvent()
{
set_interface_down_event();
CU_ASSERT_TRUE(get_interface_down_event());
}
void test_interfaceDownEvent()
{
char str[] = "SSL_Socket_Close";
set_global_reconnect_status(true);
set_interface_down_event();
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
}
void test_noInterfaceDownEvent()
{
char str[] = "SSL_Socket_Close";
set_global_reconnect_status(true);
reset_interface_down_event();
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
}
void add_suites( CU_pSuite *suite )
{
ParodusInfo("--------Start of Test Cases Execution ---------\n");
@@ -186,6 +229,9 @@ void add_suites( CU_pSuite *suite )
CU_add_test( *suite, "Test 1", test_listenerOnMessage_queue );
CU_add_test( *suite, "Test 2", test_listenerOnCloseMessage );
CU_add_test( *suite, "Test 3", test_listenerOnPingMessage );
CU_add_test( *suite, "Test 4", test_getInterfaceDownEvent );
CU_add_test( *suite, "Test 5", test_interfaceDownEvent );
CU_add_test( *suite, "Test 6", test_noInterfaceDownEvent );
}
/*----------------------------------------------------------------------------*/

View File

@@ -30,10 +30,7 @@
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
volatile unsigned int heartBeatTimer;
bool LastReasonStatus;
pthread_mutex_t close_mut;
bool close_retry;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -48,6 +45,11 @@ bool get_global_reconnect_status()
return LastReasonStatus;
}
bool get_interface_down_event()
{
return false;
}
void set_global_reconnect_status(bool status)
{
(void) status ;

View File

@@ -16,12 +16,14 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
#include "../src/parodus_log.h"
#include "../src/nopoll_helpers.h"
#include "../src/config.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -31,7 +33,9 @@
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
static noPollConn *conn;
static noPollConn *conn = NULL;
static ParodusCfg cfg;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -53,6 +57,12 @@ nopoll_bool nopoll_conn_is_ready( noPollConn *conn )
return (nopoll_bool)mock();
}
ParodusCfg *get_parodus_cfg(void)
{
function_called();
return &cfg;
}
int __nopoll_conn_send_common (noPollConn * conn, const char * content, long length, nopoll_bool has_fin, long sleep_in_header, noPollOpCode frame_type)
{
UNUSED(has_fin); UNUSED(sleep_in_header); UNUSED(frame_type); UNUSED(content);
@@ -116,6 +126,11 @@ int kill(pid_t pid, int sig)
return (int) mock();
}
bool get_interface_down_event()
{
return false;
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -206,13 +221,8 @@ void test_sendMessage()
{
int len = strlen("Hello Parodus!");
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);
cfg.cloud_status = CLOUD_STATUS_ONLINE;
expect_function_calls (get_parodus_cfg, 1);
expect_value(__nopoll_conn_send_common, (intptr_t)conn, (intptr_t)conn);
expect_value(__nopoll_conn_send_common, length, len);
@@ -222,81 +232,23 @@ void test_sendMessage()
sendMessage(conn, "Hello Parodus!", len);
}
void connStuck_sendMessage()
void test_sendMessageOffline()
{
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);
int len = strlen("Hello Parodus!");
cfg.cloud_status = CLOUD_STATUS_OFFLINE;
expect_function_calls (get_parodus_cfg, 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!");
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);
cfg.cloud_status = CLOUD_STATUS_ONLINE;
expect_function_calls (get_parodus_cfg, 1);
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-2);
@@ -314,11 +266,13 @@ void err_sendMessageConnNull()
{
int len = strlen("Hello Parodus!");
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);
cfg.cloud_status = CLOUD_STATUS_ONLINE;
expect_function_calls (get_parodus_cfg, 1);
expect_function_call(getCurrentTime);
expect_value(__nopoll_conn_send_common, (intptr_t)conn, NULL);
expect_value(__nopoll_conn_send_common, length, len);
will_return(__nopoll_conn_send_common, len);
expect_function_calls(__nopoll_conn_send_common, 1);
sendMessage(NULL, "Hello Parodus!", len);
}
@@ -343,7 +297,7 @@ 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(test_sendMessageOffline),
cmocka_unit_test(err_sendMessage),
cmocka_unit_test(err_sendMessageConnNull),
cmocka_unit_test(test_reportLog),

View File

@@ -32,6 +32,7 @@ static void *client_rcv_task();
static void *keep_alive_thread();
static void add_client();
int sock1;
int numLoops;
pthread_t threadId;
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;

View File

@@ -160,6 +160,7 @@ 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;
int numLoops;
pthread_cond_t *get_global_crud_con(void)
{

View File

@@ -26,12 +26,12 @@
#include <pthread.h>
#include "../src/token.h"
int numLoops;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;

View File

@@ -273,6 +273,10 @@ void test_handleUpstreamNull()
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();
}
@@ -294,6 +298,10 @@ void test_handle_upstream()
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);

249
tests/test_upstream_sock.c Normal file
View File

@@ -0,0 +1,249 @@
/**
* 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);
}