Compare commits

..

140 Commits

Author SHA1 Message Date
shilpa24balaji
6a6e745a08 Merge pull request #314 from guruchandru/iface_event
Pause retry during interface down event
2019-08-16 13:10:30 -07:00
Guru Chandru
ab04248411 Pause retry during interface down event 2019-08-16 15:45:01 +05:30
Shilpa Seshadri
b1f6fcb108 Merge branch 'master' of https://github.com/Comcast/parodus into iface_event 2019-08-15 21:19:12 -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
Shilpa Seshadri
0db61c7ca9 Pause retry during interface down event 2019-08-15 14:24:15 -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
shilpa24balaji
2bde60e885 Merge pull request #289 from bill1600/camera
fix mutex error in service alive
2019-03-17 19:30:34 -07:00
Bill Williams
5d05150249 fix mutex error in service alive 2019-03-17 16:57:20 -07:00
shilpa24balaji
40bf7eeb0e Merge pull request #287 from bill1600/shutfail
add nn_close to nn_shutdown
2019-03-05 15:50:51 -08:00
Bill Williams
fcec26a25f fix test_upstream test 2019-03-04 15:48:41 -08:00
Bill Williams
1b71082e77 add nn_close to nn_shutdown 2019-03-04 15:28:00 -08:00
shilpa24balaji
4085c56ed6 Merge pull request #284 from sadhyama/master
Move auth token request code to separate file
2019-02-18 14:07:15 -08:00
shilpa24balaji
0b700e57ff Merge pull request #283 from sadhyama/master
Add support to use auth token during initial connect to cloud
2019-02-15 12:51:21 -08:00
shilpa24balaji
1b903521d2 Update connection.c 2019-02-15 12:43:14 -08:00
shilpa24balaji
3814f873bc Update CHANGELOG.md 2019-02-15 12:41:48 -08:00
shilpa24balaji
8a3e4507ef Update config.c 2019-02-15 12:41:13 -08:00
shilpa24balaji
c7c93254ff Update README.md 2019-02-15 12:38:45 -08:00
shilpa24balaji
0875751c3f Update CHANGELOG.md 2019-02-15 12:34:22 -08:00
shilpa24balaji
c2edbbc074 Update CHANGELOG.md 2019-02-15 12:33:41 -08:00
Sadhyama Vengilat
7b03fad90f Unit tests on auth token request 2019-02-10 11:11:29 +05:30
Sadhyama Vengilat
a5081a5cfa Move auth jwt request code to separate file 2019-02-10 10:54:56 +05:30
Sadhyama Vengilat
25a6a99c69 Added unit tests for themis curl changes 2019-02-10 01:58:16 +05:30
Sadhyama Vengilat
5a60847e28 Themis JWT token fetch using libcurl 2019-02-09 20:28:27 +05:30
Sadhyama Vengilat
29f00e5850 Remove themis create read scripts command line arguments 2019-02-09 20:25:56 +05:30
Sadhyama Vengilat
4bd9e87125 Add new cmd line argument for client-cert-path and token-server-url 2019-02-09 20:19:06 +05:30
Sadhyama Vengilat
56ab5f13fe Add libcurl dependency in parodus 2019-02-09 20:12:32 +05:30
shilpa24balaji
57ca4084ce Update CHANGELOG.md 2019-02-08 16:11:19 -08:00
shilpa24balaji
b001964b71 Merge pull request #281 from sadhyama/parodus-interface
To correct the spelling 'webpa-inteface-used' in convey header
2019-02-07 13:05:10 -08:00
Sadhyama Vengilat
c33bb6c1c3 To correct the spelling 'webpa-inteface-used' in convey header 2019-02-07 16:42:42 +05:30
shilpa24balaji
379e63be00 Merge pull request #280 from bill1600/svcalive
Svcalive
2019-02-05 16:20:35 -08:00
bill1600
062fdc2ce0 Merge branch 'master' into svcalive 2019-01-28 16:09:08 -08:00
Bill Williams
200522c997 change svc alive back to separate thread. Shut it down with pthread_cond_timedwait 2019-01-28 15:53:29 -08:00
Bill Williams
62540e8db8 fix main loop to keep calling svc_alive_task during cloud disconnect retry 2019-01-25 14:08:27 -08:00
shilpa24balaji
f155dd601c Merge pull request #278 from sadhyama/master
Refactored Upstream Retrieve flow
2019-01-25 12:33:32 -08:00
shilpa24balaji
b9a5770bf9 Merge pull request #277 from gbuddappagari/master
To enable valgrind
2019-01-14 10:30:30 -08:00
Sadhyama Vengilat
a717b0a909 Updated changelog 2019-01-12 12:33:58 +05:30
Sadhyama Vengilat
a7b1a145a5 Added unit tests for upstream refactor changes 2019-01-12 12:32:00 +05:30
Sadhyama Vengilat
7bc498b376 Refactor Upstream Retrieve mechanism 2019-01-12 12:15:02 +05:30
Gayathri
fe00e55fff To enable valgrind 2019-01-11 09:52:55 +05:30
shilpa24balaji
66104dcabc Merge pull request #275 from gbuddappagari/leak_fix
Fixed issues in CRUD message processing
2019-01-10 09:24:24 -08:00
Gayathri
aedd9c972a To fix memory corruption 2019-01-10 11:03:05 +05:30
shilpa24balaji
99b09179f2 Merge pull request #274 from bill1600/fixleaks
Fixleaks
2019-01-08 23:49:35 -08:00
shilpa24balaji
92020ec6ec Update CMakeLists.txt 2019-01-08 16:57:35 -08:00
shilpa24balaji
9057322fd7 Update CMakeLists.txt 2019-01-08 16:52:39 -08:00
Bill Williams
55c70f3c6f resolve conflict 2019-01-08 14:49:31 -08:00
Bill Williams
7c07a5dd63 fix test_downstream 2019-01-08 14:38:55 -08:00
Bill Williams
cdd0a9e355 remove unneeded patch, and fix tests 2019-01-08 10:20:34 -08:00
shilpa24balaji
392085b01b Merge pull request #271 from gbuddappagari/master
To fix memory leak in upstream event message flow
2019-01-07 20:12:28 -08:00
Sadhyama Vengilat
bd67050c80 Fix build failure when FEATURE_DNS_QUERY is disabled 2019-01-08 08:56:00 +05:30
Sadhyama Vengilat
cea408a33c Fix RETRIEVE response processing issue due to mac check 2019-01-08 08:43:19 +05:30
Gayathri
d1522346b4 To fix crash in CRUD request processing 2019-01-09 15:21:13 +05:30
Bill Williams
22feddeadc properly shut down tasks, and fix memory leaks 2019-01-07 14:24:55 -08:00
Gayathri
df2729084d To fix memory leak in upstream event message flow 2019-01-04 18:34:27 +05:30
shilpa24balaji
8a61e66456 Merge pull request #267 from bill1600/untask_svc_alive
change serviceAlivetask to a function call from main
2018-12-18 14:09:17 -08:00
shilpa24balaji
8a737d6c18 Merge branch 'master' into untask_svc_alive 2018-12-18 14:08:50 -08:00
Bill Williams
905cb3bade update change log 2018-12-18 13:39:25 -08:00
Shilpa Seshadri
a2d7dfeb95 Log time difference in connect time and boot time only during boot time
and not during reconnect
2018-12-17 23:21:04 -08:00
shilpa24balaji
342a8ed250 Merge pull request #268 from bill1600/send_mutex
Send mutex. put mutex lock into get_global_node
2018-12-13 15:41:20 -08:00
Bill Williams
97da13ffcc put mutex lock into get_global_node 2018-12-13 14:07:06 -08:00
Bill Williams
590a43a053 Merge branch 'master' of https://github.com/Comcast/parodus into send_mutex 2018-12-13 13:42:51 -08:00
Bill Williams
0e6e833301 put mutex lock in get_global_node 2018-12-13 13:33:33 -08:00
shilpa24balaji
4525e39de9 Merge pull request #261 from bill1600/send_mutex
Send mutex
2018-12-13 11:50:48 -08:00
shilpa24balaji
8d9e9c014a Merge branch 'master' into send_mutex 2018-12-13 11:49:10 -08:00
Bill Williams
9f6ddb2b78 change serviceAlivetask to a function call from main 2018-12-12 14:23:10 -08:00
shilpa24balaji
b48680c358 Merge pull request #265 from bill1600/backoff
Backoff
2018-12-11 15:15:30 -08:00
shilpa24balaji
2304951186 Merge pull request #266 from Comcast/partner_crash
Added NULL check in validate_partner_id
2018-12-11 14:25:00 -08:00
Bill Williams
85004c165c use max count not max delay time for backoff 2018-12-11 10:01:53 -08:00
Bill Williams
94b64af4a0 update changelog 2018-12-10 16:31:13 -08:00
Bill Williams
d190b8b10c backoff retry to include find_servers in loop 2018-12-10 16:29:30 -08:00
Shilpa Seshadri
4e24197d24 Added NULL check in validate_partner_id 2018-12-09 23:04:55 -08:00
shilpa24balaji
f4d544fc40 Merge pull request #263 from Comcast/mac_null
Added mac id null check in upstream retrieve message handling
2018-12-04 17:49:15 -08:00
Shilpa Seshadri
0972ff76fd Fixed unit tests and updated change log 2018-12-04 16:03:53 -08:00
shilpa24balaji
ae8a9beb8e Merge pull request #262 from vathikar/Mac_null
Added Code and  Test cases fot NULL check for MAC
2018-12-04 17:36:38 -08:00
Weston Schmidt
08ed64c822 Merge pull request #260 from Comcast/time_diff
Added log for time difference in connect time and boot time
2018-12-04 15:01:27 -08:00
Bill Williams
c2f6a64569 Updated change log for send_mutex change 2018-11-30 09:38:41 -08:00
Bill Williams
2f0244af11 make client list and nn_sends thread safe 2018-11-30 09:35:05 -08:00
vathikar
f0f2903106 Added Code and Test cases fot NULL check for MAC 2018-11-30 15:30:52 +05:30
Shilpa Seshadri
8c83c4ce01 Added log for time difference in connect time and boot time 2018-11-29 21:59:00 -08:00
shilpa24balaji
385a38f10a Merge pull request #259 from Comcast/tags
Update CMake git tags
2018-11-21 18:53:49 -08:00
Shilpa Seshadri
4abad4dc13 Reverting to old nanomsg to fix cmake error 2018-11-21 18:14:29 -08:00
Shilpa Seshadri
cbe184e00e Use git tag version instead of commit hash and fix unit tests 2018-11-21 17:54:43 -08:00
shilpa24balaji
25a6a6cc72 Merge pull request #257 from bill1600/revert_temp_ref_to_bill1600_seshat
revert temporary CMake reference to bill1600/seshat
2018-11-15 17:13:50 -08:00
Bill Williams
aabe6be96a revert temporary CMake reference to bill1600/seshat 2018-11-14 09:49:42 -08:00
shilpa24balaji
9aa18cea1c Merge pull request #253 from vathikar/master
Added NULL check for MAC
2018-11-12 12:51:17 -08:00
shilpa24balaji
2f762fe9a1 Merge pull request #256 from bill1600/revert_from_NNG
revert from NNG
2018-11-12 12:38:46 -08:00
shilpa24balaji
93363b35db Update CHANGELOG.md 2018-11-12 12:10:30 -08:00
Bill Williams
7e8edcaca4 revert from NNG 2018-11-12 11:55:01 -08:00
shilpa24balaji
81290ffd84 Merge pull request #251 from gbuddappagari/change_log
Modify changelog for partnerid change
2018-11-09 22:38:06 -08:00
vathikar
8a69bc3955 Added NULL check for MAC 2018-11-07 13:11:56 +05:30
Gayathri
3634aa0a70 Modify changelog for partnerid change 2018-10-25 16:38:36 +05:30
Weston Schmidt
08a09106cf Merge pull request #248 from Comcast/partner_icase
Partner-id comparison made case insensitive
2018-10-17 11:46:55 -07:00
Shilpa Seshadri
f730a41cdb Partner-id comparison made case insensitive 2018-10-16 23:34:29 -07:00
shilpa24balaji
f79eeb066a Merge pull request #247 from bill1600/5xx_tweak
add unit test for 503
2018-10-08 14:27:53 -07:00
shilpa24balaji
b4a8d8b2da Merge branch 'master' into 5xx_tweak 2018-10-08 14:13:50 -07:00
Bill Williams
b42051bf96 Updated change log for the connection retry change 2018-10-08 13:48:02 -07:00
shilpa24balaji
cd1d1ba52b Merge pull request #245 from Comcast/mem_fix
Memory leak fixes
2018-10-08 13:41:55 -07:00
Bill Williams
44554b0dfa add unit test for 503 2018-10-08 11:26:32 -07:00
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
Shilpa Seshadri
1addffdeb0 Memory leak fixes 2018-10-05 16:20:18 -07:00
shilpa24balaji
ce0c43d894 Merge pull request #242 from bill1600/nng_compat
switch from nanomsg to NNG
2018-10-05 12:01:34 -07:00
Bill Williams
4f1952ddcc Fix travis build by changing link order in tests/CMakeLists.txt 2018-10-05 10:55:51 -07:00
Bill Williams
eda3823ef0 Change CMakeLists.txt to use Comcast versions of seshat and libparodus 2018-10-05 07:57:27 -07:00
Bill Williams
774f308680 use NNG release v1.0.1 2018-10-04 15:09:04 -07:00
Bill Williams
130d8f2933 switch from nanomsg to NNG 2018-10-02 16:56:26 -07:00
65 changed files with 2547 additions and 988 deletions

View File

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

View File

@@ -5,8 +5,44 @@ 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]
- Refactor of connection code (simplification).
- Security: Added support to use auth token during initial connect to cloud
- Fix re-registration fails that lose a socket
- Fix mutex error in service alive
- Security: Mutual Authentication (mTLS or two way TLS)
- Rename command line options for MTLS cert and Key
- Update to use nanomsg v. 1.1.4
- requestNewAuthToken will clear the token if it fails.
- request auth token on every retry, not just after 403
- update to use nopoll v 1.0.2
- Add pause/resume heartBeatTimer
- parodus event handler to listen to interface_down and interface_up event
## [1.0.2] - 2019-02-08
- Refactored connection.c and updated corresponding unit tests
- Additional `/cloud-status` and `/cloud-disconnect` fields.
- Switched from nanomsg (Release 1.1.2) to NNG (Release v1.0.1)
- Memory leak fixes
- Changed connection logic (connection.c) for retries, and added unit test
- Partner-id comparison made case insensitive
- Reverted from NNG to nanomag (v1.1.2)
- reverted temporary CMake reference to https://github.com/bill1600/seshat
- Added log for time difference of parodus connect time and boot time
- added NULL check for device mac id in upstream retrieve message handling
- backoff retry to include find_servers in loop (connection.c)
- backoff max is max count not max delay
- used mutex protection to make client list and nn_sends thread safe
- put mutex lock into get_global_node
- change svc alive from a thread to a function called every 30 sec from main
- shut down tasks properly
- fix memory leaks
- Fixed memory leak in upstream event message flow
- Fixed crash in CRUD request processing
- Fixed issue on RETRIEVE respone processing
- Enabled valgrind
- Fixed main loop to keep calling svc_alive_task during a cloud disconnect and retry
- change svc alive back to a separate thread. Shut it down with pthread_cond_timedwait
- Refactored Upsteam RETRIEVE flow
- Fix re-registration to call nn_shutdown and nn_close, so we don't lose a socket.
## [1.0.1] - 2018-07-18
### Added
@@ -20,7 +56,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Configurable security flag and port.
- Default HTTP port to 80 and HTTPS port to 443.
- Updates to how `nopoll` is called have been implemented.
- Refactored connection.c and updated corresponding unit tests
### Fixed
- 64 bit pointer fixes (#144, #145).
@@ -40,6 +75,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Initial creation
[Unreleased]: https://github.com/Comcast/parodus/compare/1.0.1...HEAD
[1.0.2]: https://github.com/Comcast/parodus/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/Comcast/parodus/compare/1.0.0...1.0.1
[1.0.0]: https://github.com/Comcast/parodus/compare/79fa7438de2b14ae64f869d52f5c127497bf9c3f...1.0.0

View File

@@ -23,6 +23,7 @@ set(INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/_install)
set(PREFIX_DIR ${CMAKE_CURRENT_BINARY_DIR}/_prefix)
set(INCLUDE_DIR ${INSTALL_DIR}/include)
set(INCLUDE_UCRESOLV ${PREFIX_DIR}/ucresolv/src/ucresolv/include)
set(PATCHES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/patches)
set(LIBRARY_DIR ${INSTALL_DIR}/lib)
set(LIBRARY_DIR64 ${INSTALL_DIR}/lib64)
set(COMMON_LIBRARY_DIR ${INSTALL_DIR}/lib/${CMAKE_LIBRARY_ARCHITECTURE})
@@ -33,6 +34,7 @@ include_directories(${INCLUDE_DIR}
${INCLUDE_DIR}/cjson
${INCLUDE_DIR}/nopoll
${INCLUDE_DIR}/msgpack
${INCLUDE_DIR}/curl
${INCLUDE_DIR}/trower-base64
${INCLUDE_DIR}/wrp-c
${INCLUDE_DIR}/libparodus
@@ -71,7 +73,7 @@ if (NOT BUILD_YOCTO)
ExternalProject_Add(trower-base64
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/trower-base64
GIT_REPOSITORY https://github.com/Comcast/trower-base64.git
GIT_TAG "fbb9440ae2bc1118866baefcea7ff814f16613dd"
GIT_TAG "v1.1.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libtrower-base64 STATIC SHARED IMPORTED)
@@ -83,7 +85,7 @@ add_dependencies(libtrower-base64 trower-base64)
ExternalProject_Add(nopoll
PREFIX ${PREFIX_DIR}/nopoll
GIT_REPOSITORY https://github.com/Comcast/nopoll.git
GIT_TAG "739b740683b0615e5999bdeea756cbd593b7f1cc"
GIT_TAG "1.0.2"
CONFIGURE_COMMAND COMMAND <SOURCE_DIR>/autogen.sh --prefix=${PREFIX}
--includedir=${INCLUDE_DIR}
--libdir=${LIBRARY_DIR}
@@ -99,7 +101,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 "0c1aa2b288f6b167dbafe7e29c20e6fc7e71c000"
GIT_TAG "1.1.4"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libnanomsg STATIC SHARED IMPORTED)
@@ -112,7 +114,7 @@ ExternalProject_Add(cJSON
#PREFIX ${PREFIX_DIR}/cJSON
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cJSON
GIT_REPOSITORY https://github.com/DaveGamble/cJSON.git
GIT_TAG "aafb64a1c549b7b927e339df6d35b1d5059dc235"
GIT_TAG "v1.7.8"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcJSON STATIC SHARED IMPORTED)
@@ -124,7 +126,7 @@ add_dependencies(libcJSON cJSON)
ExternalProject_Add(msgpack
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/msgpack
GIT_REPOSITORY https://github.com/msgpack/msgpack-c.git
GIT_TAG "7a98138f27f27290e680bf8fbf1f8d1b089bf138"
GIT_TAG "cpp-3.1.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
-DMSGPACK_ENABLE_CXX=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
@@ -133,12 +135,24 @@ add_library(libmsgpack STATIC SHARED IMPORTED)
add_dependencies(libmsgpack msgpack)
# curl external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(curl
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/curl
GIT_REPOSITORY https://github.com/curl/curl.git
GIT_TAG "curl-7_63_0"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcurl STATIC SHARED IMPORTED)
add_dependencies(libcurl curl)
# cimplog external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(cimplog
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cimplog
GIT_REPOSITORY https://github.com/Comcast/cimplog.git
GIT_TAG "8a5fb3c2f182241d17f5342bea5b7688c28cd1fd"
GIT_TAG "1.0.2"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcimplog STATIC SHARED IMPORTED)
@@ -151,7 +165,7 @@ ExternalProject_Add(wrp-c
DEPENDS trower-base64 msgpack cimplog
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/wrp-c
GIT_REPOSITORY https://github.com/Comcast/wrp-c.git
GIT_TAG "c2bc9be9dad6b0e4f7f9138f3d1074702ace7976"
GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
-DMSGPACK_ENABLE_CXX=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
@@ -163,22 +177,6 @@ ExternalProject_Add(wrp-c
add_library(libwrp-c STATIC SHARED IMPORTED)
add_dependencies(libwrp-c wrp-c)
# libparodus external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(libparodus
DEPENDS trower-base64 msgpack nanomsg wrp-c
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/libparodus
GIT_REPOSITORY https://github.com/Comcast/libparodus.git
GIT_TAG "a7615d69bd5859e337f467fb7e33182da970a5de"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
-DMAIN_PROJ_BUILD=ON
-DMAIN_PROJ_LIB_PATH=${LIBRARY_DIR}
-DMAIN_PROJ_LIB64_PATH=${LIBRARY_DIR64}
-DMAIN_PROJ_COMMON_PATH=${COMMON_LIBRARY_DIR}
-DMAIN_PROJ_INCLUDE_PATH=${INCLUDE_DIR}
)
add_library(liblibparodus STATIC SHARED IMPORTED)
add_dependencies(liblibparodus libparodus)
if (ENABLE_SESHAT)
# libseshat external dependency
@@ -186,8 +184,8 @@ if (ENABLE_SESHAT)
ExternalProject_Add(libseshat
DEPENDS cJSON trower-base64 msgpack nanomsg wrp-c
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/libseshat
GIT_REPOSITORY https://github.com/comcast/seshat.git
GIT_TAG "470f8d5e9457755028aae6da65d3df9b62a53942"
GIT_REPOSITORY https://github.com/Comcast/seshat.git
GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
-DMAIN_PROJ_BUILD=ON
-DMAIN_PROJ_LIB_PATH=${LIBRARY_DIR}
@@ -206,7 +204,8 @@ endif (ENABLE_SESHAT)
ExternalProject_Add(cjwt
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cjwt
GIT_REPOSITORY https://github.com/Comcast/cjwt.git
GIT_TAG "ddd077f0f00407f9657934492b252ee5cfcde535"
GIT_TAG "1b023c41bb2d6dbbf493c202ed81f06c84d5b51b"
#GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcjwt STATIC SHARED IMPORTED)
@@ -218,7 +217,7 @@ if (FEATURE_DNS_QUERY)
ExternalProject_Add(ucresolv
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/ucresolv
GIT_REPOSITORY https://github.com/Comcast/libucresolv.git
GIT_TAG "b58d49e165208791f84b44e3c079b1b4ef6d5c9d"
GIT_TAG "1.0.0"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libucresolv STATIC SHARED IMPORTED)

View File

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

View File

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

View File

@@ -25,6 +25,10 @@
#include "config.h"
#include "connection.h"
bool interface_down_event = false;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -139,3 +143,38 @@ 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_mutex_unlock (&interface_down_mut);
}
// set value of interface_down_event to true
void set_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = true;
pthread_mutex_unlock (&interface_down_mut);
}

View File

@@ -50,7 +50,8 @@
/* Macros */
/*----------------------------------------------------------------------------*/
#define UNUSED(x) (void )(x)
#define NANOMSG_SOCKET_TIMEOUT_MSEC 2000
#define NANO_SOCKET_SEND_TIMEOUT_MS 2000
#define NANO_SOCKET_RCV_TIMEOUT_MS 500
#ifndef TEST
#define FOREVER() 1
@@ -106,7 +107,8 @@ typedef struct {
//--- Used in connection.c for backoff delay timer
typedef struct {
int max_delay;
int count;
int max_count;
int delay;
} backoff_timer_t;
@@ -132,6 +134,7 @@ typedef struct {
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
extern bool g_shutdown;
extern ParodusMsg *ParodusMsgQ;
int numLoops;
/*----------------------------------------------------------------------------*/
@@ -154,6 +157,21 @@ void addCRUDmsgToQueue(wrp_msg_t *crudMsg);
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result);
/*------------------------------------------------------------------------------*/
/* For interface_down_event Flag */
/*------------------------------------------------------------------------------*/
// Get value of interface_down_event
bool get_interface_down_event();
// Reset value of interface_down_event to false
void reset_interface_down_event();
// Set value of interface_down_event to true
void set_interface_down_event();
#ifdef __cplusplus
}
#endif

302
src/auth_token.c Normal file
View File

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

57
src/auth_token.h Normal file
View File

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

View File

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

View File

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

View File

@@ -26,6 +26,17 @@
bool close_retry = false;
pthread_mutex_t close_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t close_con=PTHREAD_COND_INITIALIZER;
pthread_cond_t *get_global_close_retry_con(void)
{
return &close_con;
}
pthread_mutex_t *get_global_close_retry_mut(void)
{
return &close_mut;
}
// Get value of close_retry
bool get_close_retry()
@@ -48,8 +59,9 @@ void reset_close_retry()
// set value of close_retry to true
void set_close_retry()
{
pthread_mutex_lock (&close_mut);
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_cond_signal(&close_con);
pthread_mutex_unlock (&close_mut);
}

View File

@@ -31,6 +31,12 @@
extern "C" {
#endif
// Get the condition variable
pthread_cond_t *get_global_close_retry_con();
// Get the mutex variable
pthread_mutex_t *get_global_close_retry_mut();
// Get value of close_retry
bool get_close_retry();

View File

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

View File

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

View File

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

View File

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

View File

@@ -25,6 +25,7 @@
#include "time.h"
#include "token.h"
#include "config.h"
#include "auth_token.h"
#include "nopoll_helpers.h"
#include "mutex.h"
#include "spin_thread.h"
@@ -46,6 +47,7 @@ static char *reconnect_reason = "webpa_process_starts";
static int cloud_disconnect_max_time = 5;
static noPollConn *g_conn = NULL;
static bool LastReasonStatus = false;
static int init = 1;
static noPollConnOpts * createConnOpts (char * extra_headers, bool secure);
static char* build_extra_headers( const char *auth, const char *device_id,
const char *user_agent, const char *convey );
@@ -192,19 +194,20 @@ int check_timer_expired (expire_timer_t *timer, long timeout_ms)
}
//--------------------------------------------------------------------
void init_backoff_timer (backoff_timer_t *timer, int max_delay)
void init_backoff_timer (backoff_timer_t *timer, int max_count)
{
timer->max_delay = max_delay;
timer->count = 1;
timer->max_count = max_count;
timer->delay = 1;
}
int update_backoff_delay (backoff_timer_t *timer)
{
if (timer->delay < timer->max_delay)
if (timer->count < timer->max_count) {
timer->count += 1;
timer->delay = timer->delay + timer->delay + 1;
// 3,7,15,31 ..
if (timer->delay > timer->max_delay)
timer->delay = timer->max_delay;
}
return timer->delay;
}
@@ -293,22 +296,25 @@ 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 && (strlen(get_parodus_cfg()->token_acquisition_script) >0))
{
createNewAuthToken(get_parodus_cfg()->webpa_auth_token,
sizeof(get_parodus_cfg()->webpa_auth_token));
}
ctx->extra_headers = build_extra_hdrs (&ctx->header_info);
}
void free_extra_headers (create_connection_ctx_t *ctx)
{
FREE_PTR_VAR (ctx->extra_headers)
}
void 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);
@@ -383,10 +389,12 @@ int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6)
NULL, default_url,NULL,NULL);
}
}
if (NULL == connection) {
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);
@@ -402,9 +410,11 @@ 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;
@@ -412,7 +422,10 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
if(nopoll_conn_wait_for_status_until_connection_ready(get_global_conn(), 10,
&wait_status, &redirectURL))
{
FREE_NON_NULL_PTR (redirectURL);
return WAIT_SUCCESS;
}
if(wait_status == 307 || wait_status == 302 || wait_status == 303) // only when there is a http redirect
{
char *redirect_ptr = redirectURL;
@@ -430,15 +443,15 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
set_current_server (ctx); // set current server to redirect server
return WAIT_ACTION_RETRY;
}
if (NULL != redirectURL) {
free (redirectURL);
}
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");
@@ -448,9 +461,9 @@ int wait_connection_ready (create_connection_ctx_t *ctx)
//--------------------------------------------------------------------
// Return codes for connect_and_wait
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define CONN_WAIT_RETRY_DNS 2
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define CONN_WAIT_RETRY_DNS 2
int connect_and_wait (create_connection_ctx_t *ctx)
{
@@ -503,25 +516,23 @@ int connect_and_wait (create_connection_ctx_t *ctx)
// a) success, or
// b) need to requery dns
int keep_trying_to_connect (create_connection_ctx_t *ctx,
int max_retry_sleep,
int query_dns_status)
backoff_timer_t *backoff_timer)
{
backoff_timer_t backoff_timer;
int rtn;
init_backoff_timer (&backoff_timer, max_retry_sleep);
while (true)
{
set_extra_headers (ctx);
rtn = connect_and_wait (ctx);
if (rtn == CONN_WAIT_SUCCESS)
return true;
if (rtn == CONN_WAIT_ACTION_RETRY) // if redirected or build_headers
continue;
backoff_delay (&backoff_timer); // 3,7,15,31 ..
backoff_delay (backoff_timer); // 3,7,15,31 ..
if (rtn == CONN_WAIT_RETRY_DNS)
if (query_dns_status < 0)
return false; //find_server again
return false; //find_server again
// else retry
}
}
@@ -536,8 +547,11 @@ int keep_trying_to_connect (create_connection_ctx_t *ctx,
int createNopollConnection(noPollCtx *ctx)
{
create_connection_ctx_t conn_ctx;
int max_retry_sleep;
int max_retry_count;
int query_dns_status;
struct timespec connect_time,*connectTimePtr;
connectTimePtr = &connect_time;
backoff_timer_t backoff_timer;
if(ctx == NULL) {
return nopoll_false;
@@ -547,38 +561,56 @@ int createNopollConnection(noPollCtx *ctx)
ParodusInfo("Received reboot_reason as:%s\n", get_parodus_cfg()->hw_last_reboot_reason);
ParodusInfo("Received reconnect_reason as:%s\n", reconnect_reason);
max_retry_sleep = (int) get_parodus_cfg()->webpa_backoff_max;
ParodusPrint("max_retry_sleep is %d\n", max_retry_sleep );
max_retry_count = (int) get_parodus_cfg()->webpa_backoff_max;
ParodusPrint("max_retry_count is %d\n", max_retry_count );
memset (&conn_ctx, 0, sizeof(create_connection_ctx_t));
conn_ctx.nopoll_ctx = ctx;
init_expire_timer (&conn_ctx.connect_timer);
init_header_info (&conn_ctx.header_info);
set_extra_headers (&conn_ctx, false);
set_server_list_null (&conn_ctx.server_list);
init_backoff_timer (&backoff_timer, max_retry_count);
while (true)
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, max_retry_sleep, query_dns_status))
if (keep_trying_to_connect (&conn_ctx, &backoff_timer))
break;
// retry dns query
// If close_retry is reset due to interface down event, stop retry
// and wait till close_retry is set again.
if(!get_close_retry() && get_interface_down_event()) {
pthread_mutex_lock(get_global_close_retry_mut());
pthread_cond_wait(get_global_close_retry_con(), get_global_close_retry_mut());
pthread_mutex_unlock (get_global_close_retry_mut());
//&conn_ctx.header_info->conveyHeader = getWebpaConveyHeader();
}
}
if(conn_ctx.current_server->allow_insecure <= 0)
{
ParodusInfo("Connected to server over SSL\n");
OnboardLog("Connected to server over SSL\n");
}
else
{
ParodusInfo("Connected to server\n");
OnboardLog("Connected to server\n");
}
get_parodus_cfg()->cloud_status = CLOUD_STATUS_ONLINE;
ParodusInfo("cloud_status set as %s after successful connection\n", get_parodus_cfg()->cloud_status);
if((get_parodus_cfg()->boot_time != 0) && init) {
getCurrentTime(connectTimePtr);
ParodusInfo("connect_time-diff-boot_time=%d\n", connectTimePtr->tv_sec - get_parodus_cfg()->boot_time);
init = 0; //set init to 0 so that this is logged only during process start up and not during reconnect
}
free_extra_headers (&conn_ctx);
free_header_info (&conn_ctx.header_info);
free_server_list (&conn_ctx.server_list);
@@ -618,13 +650,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);
@@ -645,3 +684,38 @@ void close_and_unref_connection(noPollConn *conn)
}
}
void write_conn_in_prog_file (const char *msg)
{
int fd;
FILE *fp;
unsigned long timestamp;
ParodusCfg *cfg = get_parodus_cfg();
if (NULL == cfg->connection_health_file)
return;
fd = open (cfg->connection_health_file, O_CREAT | O_WRONLY | O_SYNC, 0666);
if (fd < 0) {
ParodusError ("Error(1) %d opening file %s\n", errno, cfg->connection_health_file);
return;
}
ftruncate (fd, 0);
fp = fdopen (fd, "w");
if (fp == NULL) {
ParodusError ("Error(2) %d opening file %s\n", errno, cfg->connection_health_file);
return;
}
timestamp = (unsigned long) time(NULL);
fprintf (fp, "{%s=%lu}\n", msg, timestamp);
fclose (fp);
}
void start_conn_in_progress (void)
{
write_conn_in_prog_file ("START");
}
void stop_conn_in_progress (void)
{
write_conn_in_prog_file ("STOP");
}

View File

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

View File

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

View File

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

View File

@@ -1346,6 +1346,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();

View File

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

View File

@@ -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

@@ -18,8 +18,10 @@
#include <string.h>
#include "stdlib.h"
#include "config.h"
#include "auth_token.h"
#include "conn_interface.h"
#include "parodus_log.h"
#include <curl/curl.h>
#ifdef INCLUDE_BREAKPAD
#include "breakpad_wrapper.h"
#else
@@ -80,7 +82,7 @@ int main( int argc, char **argv)
if (0 != parseCommandLine(argc,argv,cfg)) {
abort();
}
getAuthToken(cfg);
curl_global_init(CURL_GLOBAL_DEFAULT);
createSocketConnection( NULL);
@@ -103,7 +105,7 @@ static void sig_handler(int sig)
{
signal(SIGINT, sig_handler); /* reset it to this function */
ParodusInfo("SIGINT received!\n");
exit(0);
shutdownSocketConnection();
}
else if ( sig == SIGUSR1 )
{
@@ -132,7 +134,7 @@ static void sig_handler(int sig)
else
{
ParodusInfo("Signal %d received!\n", sig);
exit(0);
shutdownSocketConnection();
}
}

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

@@ -73,25 +73,35 @@ void sendMessage(noPollConn *conn, void *msg, size_t len)
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);
OnboardLog("Failed to send msg upstream as connection is not OK\n");
if( timeDiff >= (10*60*1000))
if(get_interface_down_event())
{
ParodusError("Unable to connect to server since interface is down\n");
}
else
{
if (connErr == 0)
{
ParodusError("conn got stuck for over 10 minutes; crashing service.\n");
kill(getpid(),SIGTERM);
getCurrentTime(connStuck_startPtr);
ParodusInfo("Conn got stuck, initialized the first timer\n");
connErr = 1;
}
else
{
getCurrentTime(connStuck_endPtr);
timeDiff = timeValDiff(connStuck_startPtr, connStuck_endPtr);
ParodusPrint("checking timeout difference:%ld\n", timeDiff);
}
if( timeDiff >= (10*60*1000))
{
ParodusError("conn got stuck for over 10 minutes; crashing service.\n");
OnboardLog("conn got stuck for over 10 minutes; crashing service.\n");
kill(getpid(),SIGTERM);
}
}
}
}
}
@@ -149,6 +159,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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -139,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);
@@ -527,7 +529,9 @@ int allow_insecure_conn(char **server_addr, unsigned int *port)
}
if (insecure >= 0) {
ParodusInfo ("JWT claims: %s\n", cJSON_Print (jwt->private_claims));
char *claim_str = cJSON_Print (jwt->private_claims);
ParodusInfo ("JWT claims: %s\n", claim_str);
free (claim_str);
}
cjwt_destroy(&jwt);

View File

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

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

View File

@@ -18,7 +18,7 @@ set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -W -g -fprofile-arcs -ftest-cove
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage -O0")
set (PARODUS_COMMON_SRC ../src/string_helpers.c ../src/mutex.c ../src/time.c ../src/config.c ../src/spin_thread.c ../src/token.c)
set (PARODUS_COMMON_LIBS gcov -lcunit -lcimplog -lwrp-c
-luuid -lpthread -lmsgpackc -lnopoll -lnanomsg
-luuid -lmsgpackc -lnopoll -lnanomsg -lpthread
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
@@ -71,26 +71,6 @@ add_test(NAME test_nopoll_helpers COMMAND ${MEMORY_CHECK} ./test_nopoll_helpers)
add_executable(test_nopoll_helpers test_nopoll_helpers.c ../src/nopoll_helpers.c)
target_link_libraries (test_nopoll_helpers -Wl,--no-as-needed -lrt -lcmocka -lcimplog -lnopoll)
#-------------------------------------------------------------------------------
# libpd_test
#-------------------------------------------------------------------------------
add_executable (libpd_test libpd_test.c ../src/string_helpers.c)
target_link_libraries (libpd_test
cunit
-llibparodus
-lwrp-c
-luuid
-lmsgpackc
-ltrower-base64
-lnanomsg
-lcimplog
-lm
-lpthread
-lrt)
if (ENABLE_SESHAT)
target_link_libraries (libpd_test -llibseshat)
endif (ENABLE_SESHAT)
#-------------------------------------------------------------------------------
# test_time
#-------------------------------------------------------------------------------
@@ -137,13 +117,13 @@ target_link_libraries (test_nopoll_handlers_fragment -lnopoll -lcunit -lcimplog
#-------------------------------------------------------------------------------
# test_connection
#-------------------------------------------------------------------------------
add_test(NAME test_connection COMMAND ${MEMORY_CHECK} ./test_connection)
set (CONN_SRC ../src/connection.c
../src/string_helpers.c ../src/mutex.c ../src/time.c
../src/config.c ../src/spin_thread.c ../src/heartBeat.c ../src/close_retry.c)
#add_test(NAME test_connection COMMAND ${MEMORY_CHECK} ./test_connection)
#set (CONN_SRC ../src/connection.c
# ../src/string_helpers.c ../src/mutex.c ../src/time.c
# ../src/config.c ../src/auth_token.c ../src/spin_thread.c ../src/heartBeat.c ../src/close_retry.c)
#set(CONN_SRC ../src/connection.c ${PARODUS_COMMON_SRC})
add_executable(test_connection test_connection.c ${CONN_SRC})
target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka)
#add_executable(test_connection test_connection.c ${CONN_SRC})
#target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_connection - function createNopollConnection
@@ -161,7 +141,7 @@ target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka)
add_test(NAME test_client_list COMMAND ${MEMORY_CHECK} ./test_client_list)
#add_executable(test_client_list test_client_list.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/downstream.c ../src/connection.c ../src/nopoll_handlers.c ../src/ParodusInternal.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS})
set(CLIST_SRC test_client_list.c ../src/client_list.c
set(CLIST_SRC test_client_list.c ../src/client_list.c ../src/auth_token.c
../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c
../src/downstream.c ../src/connection.c ../src/nopoll_handlers.c ../src/heartBeat.c ../src/close_retry.c
../src/ParodusInternal.c ../src/thread_tasks.c ../src/conn_interface.c
@@ -175,7 +155,7 @@ endif (ENABLE_SESHAT)
add_executable(test_client_list ${CLIST_SRC})
#target_link_libraries (test_client_list ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS})
target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS})
target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_service_alive
@@ -183,7 +163,7 @@ target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS})
add_test(NAME test_service_alive COMMAND ${MEMORY_CHECK} ./test_service_alive)
#add_executable(test_service_alive test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS})
set(SVA_SRC test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ../src/heartBeat.c ../src/close_retry.c ${PARODUS_COMMON_SRC})
set(SVA_SRC test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/auth_token.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ../src/heartBeat.c ../src/close_retry.c ${PARODUS_COMMON_SRC})
if (ENABLE_SESHAT)
set(SVA_SRC ${SVA_SRC} ../src/seshat_interface.c)
else()
@@ -192,16 +172,36 @@ endif (ENABLE_SESHAT)
add_executable(test_service_alive ${SVA_SRC})
#target_link_libraries (test_service_alive ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS})
target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS})
target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_config
#-------------------------------------------------------------------------------
add_test(NAME test_config COMMAND ${MEMORY_CHECK} ./test_config)
add_executable(test_config test_config.c ../src/config.c ../src/string_helpers.c)
add_executable(test_config test_config.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_config -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_auth_token
#-------------------------------------------------------------------------------
add_test(NAME test_auth_token COMMAND ${MEMORY_CHECK} ./test_auth_token)
add_executable(test_auth_token test_auth_token.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_auth_token -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_auth_token_more
#-------------------------------------------------------------------------------
add_test(NAME test_auth_token_more COMMAND ${MEMORY_CHECK} ./test_auth_token_more)
add_executable(test_auth_token_more test_auth_token_more.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_auth_token_more -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
@@ -223,21 +223,38 @@ target_link_libraries (test_crud_tasks -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
add_test(NAME test_crud_internal COMMAND ${MEMORY_CHECK} ./test_crud_internal)
add_executable(test_crud_internal test_crud_internal.c ../src/config.c ../src/close_retry.c ../src/string_helpers.c ../src/crud_internal.c )
target_link_libraries (test_crud_internal -lcmocka ${PARODUS_COMMON_LIBS} )
target_link_libraries (test_crud_internal -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_upstream
#-------------------------------------------------------------------------------
add_test(NAME test_upstream COMMAND ${MEMORY_CHECK} ./test_upstream)
add_executable(test_upstream test_upstream.c ../src/upstream.c ../src/close_retry.c ../src/string_helpers.c)
target_link_libraries (test_upstream -lcmocka ${PARODUS_COMMON_LIBS} )
target_link_libraries (test_upstream -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
#-------------------------------------------------------------------------------
# test_upstream_sock
#-------------------------------------------------------------------------------
add_test(NAME test_upstream_sock COMMAND ${MEMORY_CHECK} ./test_upstream_sock)
add_executable(test_upstream_sock test_upstream_sock.c ../src/upstream.c
../src/client_list.c ../src/close_retry.c ../src/string_helpers.c)
target_link_libraries (test_upstream_sock -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll -lnanomsg
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
#-------------------------------------------------------------------------------
# test_downstream
#-------------------------------------------------------------------------------
add_test(NAME test_downstream COMMAND ${MEMORY_CHECK} ./test_downstream)
add_executable(test_downstream test_downstream.c ../src/downstream.c ../src/string_helpers.c)
target_link_libraries (test_downstream -lcmocka ${PARODUS_COMMON_LIBS} )
target_link_libraries (test_downstream -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
#-------------------------------------------------------------------------------
# test_downstream_more
@@ -273,14 +290,14 @@ else()
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_conn_interface ${CONIFC_SRC})
target_link_libraries (test_conn_interface -lcmocka ${PARODUS_COMMON_LIBS} )
target_link_libraries (test_conn_interface -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid )
#-------------------------------------------------------------------------------
# test_ParodusInternal
#-------------------------------------------------------------------------------
add_test(NAME test_ParodusInternal COMMAND ${MEMORY_CHECK} ./test_ParodusInternal)
add_executable(test_ParodusInternal test_ParodusInternal.c ../src/ParodusInternal.c ../src/config.c ../src/string_helpers.c)
target_link_libraries (test_ParodusInternal -lcmocka ${PARODUS_COMMON_LIBS} )
target_link_libraries (test_ParodusInternal -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_partners_check
@@ -299,7 +316,7 @@ set(TOKEN_SRC ../src/conn_interface.c ../src/config.c
../src/nopoll_handlers.c ../src/nopoll_helpers.c
../src/partners_check.c ../src/ParodusInternal.c
../src/upstream.c ../src/downstream.c
../src/networking.c
../src/networking.c ../src/auth_token.c
../src/thread_tasks.c ../src/time.c
../src/string_helpers.c ../src/mutex.c
../src/token.c ../src/heartBeat.c
@@ -320,7 +337,7 @@ endif (FEATURE_DNS_QUERY)
add_executable(test_token ${TOKEN_SRC} )
#target_link_libraries (test_token ${PARODUS_COMMON_LIBS} ${PARODUS_JWT_LIBS} -lcmocka )
target_link_libraries (test_token ${PARODUS_COMMON_LIBS} -lcmocka )
target_link_libraries (test_token ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_seshat_interface - registerWithSeshat
@@ -362,5 +379,5 @@ set(SIMPLE_SRC ${SIMPLE_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(simple ${SIMPLE_SRC})
target_link_libraries (simple ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} gcov -lnopoll -lnanomsg )
target_link_libraries (simple ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} gcov -lnopoll )
endif (INTEGRATION_TESTING)

View File

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

334
tests/test_auth_token.c Normal file
View File

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

View File

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

View File

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

View File

@@ -71,8 +71,8 @@ void test_mutex_close_retry() {
ParodusInfo("Threads execution is completed, close_retry is: %d\n", close_retry);
assert_int_equal(close_retry, 1);
pthread_create(&thread[3], NULL, test_mutex_reset_close_retry, NULL);
pthread_join(thread[3], NULL);
pthread_create(&thread[2], NULL, test_mutex_reset_close_retry, NULL);
pthread_join(thread[2], NULL);
close_retry = get_close_retry();
ParodusInfo("close_retry reset to: %d\n", close_retry);

View File

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

View File

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

View File

@@ -36,7 +36,7 @@ extern server_t *get_current_server (server_list_t *server_list);
extern int parse_server_url (const char *full_url, server_t *server);
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_delay);
extern void init_backoff_timer (backoff_timer_t *timer, int max_count);
extern int update_backoff_delay (backoff_timer_t *timer);
extern int init_header_info (header_info_t *header_info);
extern void free_header_info (header_info_t *header_info);
@@ -51,8 +51,7 @@ extern int nopoll_connect (create_connection_ctx_t *ctx, int is_ipv6);
extern int wait_connection_ready (create_connection_ctx_t *ctx);
extern int connect_and_wait (create_connection_ctx_t *ctx);
extern int keep_trying_to_connect (create_connection_ctx_t *ctx,
int max_retry_sleep,
int query_dns_status);
backoff_timer_t *backoff_timer);
/*----------------------------------------------------------------------------*/
@@ -64,6 +63,7 @@ bool LastReasonStatus;
pthread_mutex_t close_mut;
// Mock values
bool g_shutdown = false;
char *mock_server_addr;
unsigned int mock_port;
int mock_wait_status;
@@ -117,10 +117,17 @@ nopoll_bool nopoll_conn_wait_for_status_until_connection_ready (noPollConn * co
int timeout, int *status, char ** message)
{
UNUSED(conn); UNUSED(timeout);
*status = mock_wait_status;
*message = NULL;
if (mock_wait_status >= 1000) {
*status = mock_wait_status / 1000;
mock_wait_status = mock_wait_status % 1000;
} else {
*status = mock_wait_status;
}
if ((NULL != mock_redirect) &&
((mock_wait_status == 307) || (mock_wait_status == 302) ||
(mock_wait_status == 303)) )
((*status == 307) || (*status == 302) ||
(*status == 303)) )
{
*message = malloc (strlen(mock_redirect) + 10);
sprintf (*message, "Redirect:%s", mock_redirect);
@@ -297,12 +304,12 @@ void test_expire_timer()
void test_backoff_delay_timer()
{
backoff_timer_t btimer;
init_backoff_timer (&btimer, 30);
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 (30, update_backoff_delay (&btimer));
assert_int_equal (30, update_backoff_delay (&btimer));
assert_int_equal (31, update_backoff_delay (&btimer));
assert_int_equal (31, update_backoff_delay (&btimer));
}
@@ -370,13 +377,21 @@ void test_set_current_server()
assert_ptr_equal (&ctx.server_list.defaults, ctx.current_server);
}
void init_cfg_header_info (ParodusCfg *cfg)
{
parStrncpy(cfg->hw_mac , "123567892366", sizeof(cfg->hw_mac));
parStrncpy(cfg->hw_model, "TG1682", sizeof(cfg->hw_model));
parStrncpy(cfg->hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg->hw_manufacturer));
parStrncpy(cfg->fw_name , "2.364s2", sizeof(cfg->fw_name));
parStrncpy(cfg->webpa_protocol , "WebPA-1.6", sizeof(cfg->webpa_protocol));
}
void test_set_extra_headers ()
{
int rtn;
create_connection_ctx_t ctx;
ParodusCfg cfg;
const char *expected_extra_headers =
"\r\nAuthorization: Bearer SER_MAC Fer23u948590 123567892366"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
@@ -385,16 +400,10 @@ void test_set_extra_headers ()
memset(&cfg,0,sizeof(cfg));
memset (&ctx, 0, sizeof(ctx));
parStrncpy (cfg.token_acquisition_script, "../../tests/return_success.bsh",
sizeof(cfg.token_acquisition_script));
parStrncpy (cfg.token_read_script, "../../tests/return_ser_mac.bsh",
sizeof(cfg.token_read_script));
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));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
init_cfg_header_info (&cfg);
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
set_parodus_cfg(&cfg);
rtn = init_header_info (&ctx.header_info);
@@ -405,9 +414,9 @@ void test_set_extra_headers ()
assert_string_equal (ctx.header_info.conveyHeader, "WebPA-1.6 (TG1682)");
set_extra_headers (&ctx, true);
assert_string_equal (get_parodus_cfg()->webpa_auth_token,
"SER_MAC Fer23u948590 123567892366");
assert_string_equal (ctx.extra_headers, expected_extra_headers);
if(cfg.client_cert_path !=NULL) {
free(cfg.client_cert_path); }
free (ctx.extra_headers);
free_header_info (&ctx.header_info);
@@ -511,34 +520,58 @@ void test_nopoll_connect ()
test_server.allow_insecure = 1;
will_return (nopoll_conn_new_opts, NULL);
expect_function_call (nopoll_conn_new_opts);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
test_server.allow_insecure = 0;
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_int_equal (nopoll_connect (&ctx, false), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, -2);
//expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, -2);
expect_function_call (checkHostIp);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_int_equal (nopoll_connect (&ctx, false), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
//will_return (checkHostIp, -2);
//expect_function_call (checkHostIp);
//ctx.connect_timer.start_time.tv_sec -= (15*60);
//will_return(kill, 1);
//expect_function_call(kill);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_ptr_equal(NULL, get_global_conn());
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, -2);
expect_function_call (checkHostIp);
ctx.connect_timer.start_time.tv_sec -= (15*60);
will_return(kill, 1);
expect_function_call(kill);
assert_int_equal (nopoll_connect (&ctx, true), 0);
assert_int_equal (nopoll_connect (&ctx, false), 0);
assert_ptr_equal(NULL, get_global_conn());
init_expire_timer (&ctx.connect_timer);
@@ -552,19 +585,12 @@ void test_nopoll_connect ()
// Return codes for wait_connection_ready
#define WAIT_SUCCESS 0
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define WAIT_FAIL 2
void test_wait_connection_ready ()
{
create_connection_ctx_t ctx;
ParodusCfg Cfg;
const char *expected_extra_headers =
"\r\nAuthorization: Bearer Auth---"
"\r\nX-WebPA-Device-Name: mac:123567892366"
"\r\nX-WebPA-Device-Protocols: wrp-0.11,getset-0.1"
"\r\nUser-Agent: WebPA-1.6 (2.364s2; TG1682/ARRISGroup,Inc.;)"
"\r\nX-WebPA-Convey: WebPA-1.6 (TG1682)";
memset(&ctx,0,sizeof(ctx));
set_server_list_null (&ctx.server_list);
@@ -579,7 +605,12 @@ 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);
assert_int_equal (wait_connection_ready (&ctx), WAIT_FAIL);
mock_wait_status = 307;
mock_redirect = "mydns.mycom.net";
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
@@ -609,30 +640,18 @@ void test_wait_connection_ready ()
free_server (&ctx.server_list.redirect);
mock_wait_status = 403;
memset(&Cfg, 0, sizeof(ParodusCfg));
parStrncpy (Cfg.webpa_auth_token, "Auth---", sizeof (Cfg.webpa_auth_token));
parStrncpy(Cfg.hw_model, "TG1682", sizeof(Cfg.hw_model));
parStrncpy(Cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(Cfg.hw_manufacturer));
parStrncpy(Cfg.hw_mac , "123567892366", sizeof(Cfg.hw_mac));
parStrncpy(Cfg.fw_name , "2.364s2", sizeof(Cfg.fw_name));
parStrncpy(Cfg.webpa_protocol , "WebPA-1.6", sizeof(Cfg.webpa_protocol));
set_parodus_cfg(&Cfg);
init_header_info (&ctx.header_info);
will_return (nopoll_conn_wait_for_status_until_connection_ready, nopoll_false);
expect_function_call (nopoll_conn_wait_for_status_until_connection_ready);
assert_int_equal (wait_connection_ready (&ctx), WAIT_ACTION_RETRY);
assert_string_equal (ctx.extra_headers, expected_extra_headers);
free_extra_headers (&ctx);
free_header_info (&ctx.header_info);
}
// Return codes for connect_and_wait
#define CONN_WAIT_SUCCESS 0
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303 or 403
#define CONN_WAIT_RETRY_DNS 2
#define CONN_WAIT_ACTION_RETRY 1 // if wait_status is 307, 302, 303, or 403
#define CONN_WAIT_RETRY_DNS 2
void test_connect_and_wait ()
{
@@ -668,7 +687,18 @@ void test_connect_and_wait ()
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_RETRY_DNS);
mock_wait_status = 503;
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_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;
set_parodus_cfg(&Cfg);
@@ -694,8 +724,8 @@ void test_connect_and_wait ()
test_server.allow_insecure = 0;
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
assert_int_equal (connect_and_wait (&ctx), CONN_WAIT_RETRY_DNS);
Cfg.flags = 0;
@@ -703,8 +733,8 @@ void test_connect_and_wait ()
will_return (nopoll_conn_tls_new6, NULL);
expect_function_call (nopoll_conn_tls_new6);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
//will_return (checkHostIp, 0);
//expect_function_call (checkHostIp);
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
@@ -771,23 +801,18 @@ void test_keep_trying ()
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;
memset(&ctx,0,sizeof(ctx));
ctx.nopoll_ctx = &test_nopoll_ctx;
ctx.current_server = &test_server;
ctx.extra_headers = test_extra_headers;
test_server.allow_insecure = 1;
test_server.server_addr = "mydns.mycom.net";
@@ -802,7 +827,8 @@ void test_keep_trying ()
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 = keep_trying_to_connect (&ctx, 30, -1);
init_backoff_timer (&backoff_timer, 5);
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, true);
test_server.allow_insecure = 0;
@@ -823,24 +849,42 @@ void test_keep_trying ()
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 = keep_trying_to_connect (&ctx, 30, 0);
init_backoff_timer (&backoff_timer, 5);
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, true);
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
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);
mock_wait_status = 302503;
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);
rtn = keep_trying_to_connect (&ctx, 30, 0);
assert_int_equal (rtn, true);
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);
mock_wait_status = 0;
will_return (nopoll_conn_tls_new, NULL);
expect_function_call (nopoll_conn_tls_new);
will_return (checkHostIp, 0);
expect_function_call (checkHostIp);
init_backoff_timer (&backoff_timer, 5);
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, false);
mock_wait_status = 302;
mock_redirect = "mydns.mycom.net";
@@ -853,7 +897,8 @@ void test_keep_trying ()
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);
rtn = keep_trying_to_connect (&ctx, 30, -1);
init_backoff_timer (&backoff_timer, 5);
rtn = keep_trying_to_connect (&ctx, &backoff_timer);
assert_int_equal (rtn, false);
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -72,8 +72,8 @@ void test_mutexHeartBeatTimer() {
ParodusInfo("Threads execution is completed, heartBeatTimer is: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 10);
pthread_create(&thread[3], NULL, test_mutexResetTimer, NULL);
pthread_join(thread[3], NULL);
pthread_create(&thread[2], NULL, test_mutexResetTimer, NULL);
pthread_join(thread[2], NULL);
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer reset to: %d\n", heartBeatTimer);

View File

@@ -21,6 +21,7 @@
#include <nopoll_private.h>
#include <pthread.h>
#include "../src/ParodusInternal.h"
#include "../src/nopoll_handlers.h"
#include "../src/parodus_log.h"
@@ -46,6 +47,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

@@ -48,6 +48,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,6 +16,7 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
@@ -116,6 +117,11 @@ int kill(pid_t pid, int sig)
return (int) mock();
}
bool get_interface_down_event()
{
return false;
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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);
}