Compare commits

...

591 Commits

Author SHA1 Message Date
schmidtw
e3815115af Use newer codecove action. 2024-07-11 23:45:08 -07:00
Weston Schmidt
6dcabbcf5f Use the workflow from the upstream parodus repo. 2023-12-01 09:31:00 -08:00
Weston Schmidt
6782ae7868 Fix the path. 2023-11-28 00:51:34 -08:00
Weston Schmidt
e274b572dd Try the sonarcloud installer 2023-11-28 00:48:06 -08:00
Weston Schmidt
4107159696 Update push.yml 2023-11-28 00:14:03 -08:00
Weston Schmidt
94531a3faa Update push.yml 2023-11-28 00:10:22 -08:00
Weston Schmidt
373acb170a Update push.yml 2023-11-28 00:07:02 -08:00
Weston Schmidt
262a23e00e Update push.yml 2023-09-11 23:49:09 -07:00
Weston Schmidt
193706c21c Release 1.1.5 2021-06-02 18:46:53 -07:00
Weston Schmidt
dee98922a6 Update the readme links. 2021-06-02 18:28:37 -07:00
Weston Schmidt
b9fa918c15 Merge pull request #362 from xmidt-org/update-ci
Update the CI pipeline.
2021-06-02 18:25:04 -07:00
Weston Schmidt
a278a7017d Update the CI pipeline. 2021-06-02 18:17:54 -07:00
Weston Schmidt
69cf210a34 Merge pull request #359 from xmidt-org/whitesource/configure
Configure WhiteSource Bolt for GitHub
2021-06-02 18:06:27 -07:00
Weston Schmidt
77b587aa9d Merge pull request #361 from xmidt-org/proposed-add-auth-headers
Add additional headers to auth request
2021-06-02 16:44:07 -07:00
Weston Schmidt
441ecf702f Add additional headers to auth request
This adds the set of headers from the convey header into the auth
request in a way that doesn't require a change to Themis.
2021-06-02 00:57:51 -07:00
sadhyama
bdc2733d8e Merge pull request #360 from sadhyama/reb_reason
To increase reboot reason size
2021-02-03 19:35:33 +05:30
Sadhyama Vengilat
1f24671c0f To increase reboot reason size 2021-02-03 16:51:18 +05:30
whitesource-bolt-for-github[bot]
3de4ec59c1 Add .whitesource configuration file 2020-12-07 17:30:48 +00:00
sadhyama
a01ad8f15c Merge pull request #357 from sadhyama/part_id
Add partnerID header in auth token request
2020-11-16 14:42:18 +05:30
Sadhyama Vengilat
1d2e51e31e Add partnerID header in auth token request 2020-11-10 15:51:35 +05:30
Weston Schmidt
9e808acf7d Use the old default branch name for now. 2020-09-18 13:40:50 -07:00
Weston Schmidt
19f2fe1419 Merge pull request #356 from xmidt-org/add-sonar
Add sonar, travis and friends.
2020-09-15 18:55:34 -07:00
Weston Schmidt
b99c06a67b Disable the clang build for now. 2020-09-15 18:45:42 -07:00
Weston Schmidt
f57ebc1cd7 Disable string_helpers test for now since it fails... 2020-09-15 18:31:08 -07:00
Weston Schmidt
1df770a91b Remove the spin thread test due to what appear to be issues with travis-ci. 2020-09-15 18:23:09 -07:00
Weston Schmidt
a582bb3252 Fix several compilation errors (multiple definitions of global variables, remove overlapping strncpy() strings which cause latent bugs) to allow for code coverage to work. 2020-09-15 18:04:41 -07:00
Weston Schmidt
42dd20263b Ignore a test generated file. 2020-09-15 18:03:05 -07:00
Weston Schmidt
ac100c0f4e Disable valgrind for now to get updated builds working. 2020-09-15 12:06:22 -07:00
Weston Schmidt
290289f2f1 Remove the duplicate cmake line. 2020-09-15 12:00:00 -07:00
Weston Schmidt
8e9b98b697 Disable coverity since it makes the build always fail. 2020-09-15 11:52:04 -07:00
Weston Schmidt
b148d40c53 Disable valgrind for now to get updated builds working. 2020-09-15 11:51:18 -07:00
Weston Schmidt
dc6486f200 Add sonar, travis and friends. 2020-09-15 11:32:52 -07:00
shilpa24balaji
ad2d43b4f6 Merge pull request #354 from sadhyama/aker_blob
Webconfig communication to aker via parodus
2020-08-07 16:37:29 +05:30
Sadhyama Vengilat
54cfdd9c52 Support Retrieve with dest as mac:xxxxxxxxxxxx/parodus/service-status/service 2020-07-27 18:30:15 +05:30
Sadhyama Vengilat
19056ddfec Webconfig communication to aker via parodus 2020-07-17 01:11:35 +05:30
shilpa24balaji
1d85742497 Merge pull request #351 from krish-1/master
Code changes to drop root privilege
2020-04-01 20:57:12 -07:00
kjothi774
e29dd26d2b To drop root privilege for parodus process 2020-04-02 03:37:44 +00:00
kjothi774
5aae91763a To drop root privilege for parodus process 2020-04-02 03:03:12 +00:00
shilpa24balaji
9afa49140a Merge pull request #349 from bill1600/siglog
fix shutdown close msg to agree with splunk log
2020-03-27 18:25:40 -07:00
Bill Williams
4305dc8eef fix shutdown close msg to agree with splunk log 2020-03-26 09:30:26 -07:00
shilpa24balaji
f44fc2c8d9 Merge pull request #346 from bill1600/sigterm2
Parodus shutdown with SIGTERM to read close_reason file
2020-03-05 12:37:55 -08:00
Weston Schmidt
16543800d2 Merge pull request #344 from bill1600/jitter2
Jitter2
2020-03-03 11:04:18 -08:00
Bill Williams
bcb4840a41 update with requested changes 2020-02-27 16:54:51 -08:00
Bill Williams
b173828777 merge master 2020-02-13 10:50:21 -08:00
Bill Williams
2df8cdfeb5 change jitter calculation 2020-02-12 09:42:15 -08:00
shilpa24balaji
eba1309169 Merge pull request #342 from bill1600/cloudstat
check cloud status for sendMessage
2020-02-06 16:21:48 -08:00
Bill Williams
70c1c64550 fix/add unit tests for backoff delay 2020-02-04 13:41:27 -08:00
Bill Williams
e825c19ef3 use jitter in backoff delay 2020-02-04 10:22:17 -08:00
Bill Williams
95170d95c7 add unit test for cloud status offline 2020-02-03 13:13:31 -08:00
Bill Williams
33142a6ce7 add mock_event_handler for testing 2020-01-30 15:33:45 -08:00
Bill Williams
7b3ee1dd5a remove nopoll_conn_is_ok from sendMessage 2020-01-16 14:25:01 -08:00
Bill Williams
f2308e2966 remove nopoll_conn_is_ready test from sendMessage 2020-01-16 12:49:11 -08:00
Bill Williams
9c55157da7 fix test_nopoll_helpers 2020-01-15 13:41:57 -08:00
Bill Williams
1c254e28fe check cloud status for sendMessage 2020-01-15 12:06:09 -08:00
shilpa24balaji
8955787640 Merge pull request #340 from xmidt-org/revert-339-nopoll_timeout
Revert "To add Nopoll default connect timeout value"
2020-01-09 11:40:38 -08:00
shilpa24balaji
b633938bc7 Revert "To add Nopoll default connect timeout value" 2020-01-09 11:33:13 -08:00
shilpa24balaji
b0aeaf1fb2 Merge pull request #339 from guruchandru/nopoll_timeout
To add Nopoll default connect timeout value
2020-01-03 10:48:14 -08:00
Guru Chandru
ea726e0c10 To add Nopoll default connect timeout value 2020-01-03 14:14:51 +05:30
shilpa24balaji
cbdf5d2be9 Merge pull request #337 from bill1600/norequery
remerged noretrydns and two_times
2019-12-27 13:40:52 -08:00
shilpa24balaji
3d369cafb2 Merge pull request #338 from sadhyama/master
Unit tests for non 200 auth token response codes
2019-12-26 17:05:02 -08:00
Sadhyama Vengilat
c0dbdb5028 Unit tests for non 200 auth token response codes 2019-12-26 18:20:44 +05:30
shilpa24balaji
12a7765f98 Update event_handler.h 2019-12-25 22:09:05 -08:00
shilpa24balaji
88c87917a4 Update event_handler.c 2019-12-25 22:08:35 -08:00
shilpa24balaji
0905387d49 Free redirect server url during reconnect 2019-12-23 17:35:52 -08:00
Bill Williams
a8167fa417 change health file update interval to 240s 2019-12-20 14:30:01 -08:00
Bill Williams
6ab601e758 retrigger travis tests 2019-12-19 13:33:59 -08:00
Bill Williams
45536eb4e1 remerged noretrydns and two_times 2019-12-19 11:12:59 -08:00
shilpa24balaji
8208d3bfd0 Merge pull request #335 from sadhyama/auth_token
Fix Report failure on non-200 response code from auth token server
2019-12-17 12:35:04 -08:00
shilpa24balaji
4fc60b6b3c Merge pull request #330 from bill1600/idownunit
add unit tests for interface down
2019-12-17 12:33:51 -08:00
Sadhyama Vengilat
990d9df7e2 Fix Report failure on non-200 response code from auth token server 2019-12-12 21:17:02 +05:30
Weston Schmidt
fe52d9a55e Update README.md 2019-12-06 12:54:30 -08:00
shilpa24balaji
9cfc734c51 Merge pull request #331 from rajnishdey/errMsgUpdate
Change Info log level from error log level for "received temporary re…
2019-11-18 10:51:06 -08:00
Rajnish
153add9bec Change Info log level from error log level for "received temporary redirection response". 2019-11-18 11:28:43 -05:00
Bill Williams
8b553f8a29 add unit tests for interface down 2019-11-17 16:45:33 -08:00
shilpa24balaji
7679fdaf4a Merge pull request #327 from bill1600/ifcdown
update backoff delay and interface down logic
2019-11-15 12:27:41 -08:00
Bill Williams
1c09a80493 fix condition test in wait_while_interface_down 2019-11-14 15:31:28 -08:00
Bill Williams
bfad8ed44b fix deadlock in wait_while_interface_down 2019-11-14 10:56:47 -08:00
Bill Williams
17c7faff50 update backoff delay error logging 2019-11-12 15:12:53 -08:00
Bill Williams
01120da9ac backoff delay updates 2019-11-12 14:37:10 -08:00
shilpa24balaji
c7c6fb4926 Merge pull request #328 from bill1600/nosig9
Nosig9
2019-11-12 10:30:59 -08:00
Bill Williams
f4b2c252ae update changelog for nosig9 2019-11-12 10:18:40 -08:00
Bill Williams
8794ce2092 dont try to install handler for signal 9 2019-11-12 10:17:01 -08:00
Bill Williams
a61e97633b update backoff delay for interface down 2019-11-11 13:24:07 -08:00
shilpa24balaji
4d3d6ec99d Merge pull request #326 from bill1600/bkpshut
update parodus shutdown
2019-11-06 10:42:54 -08:00
shilpa24balaji
e6ac264e47 Update CHANGELOG.md 2019-11-06 10:31:53 -08:00
Bill Williams
70c9975ae9 remove leftover local test 2019-11-05 14:21:37 -08:00
Bill Williams
11a2b6f123 restore test_interface_down_retry 2019-11-04 15:29:43 -08:00
Bill Williams
81d8f59bbd fix so that parodus can be killed if it connection fail loop 2019-11-01 14:14:18 -07:00
Bill Williams
846b0588c2 pu cloud status back 2019-11-01 11:40:35 -07:00
Bill Williams
ad44ff0221 remove 403 upgrade from this build 2019-11-01 10:00:39 -07:00
Bill Williams
513647ceef remove unnecessary nopoll_con_ref_count 2019-10-31 15:26:51 -07:00
Bill Williams
2ec3443b1d update parodus shutdown 2019-10-29 11:34:29 -07:00
shilpa24balaji
55e10aa051 Merge pull request #325 from shilpa24balaji/3.12_p3b
Update retry time in connection-health-file
2019-10-25 11:56:33 -07:00
Shilpa Seshadri
879a585b66 Update retry time in connection-health-file 2019-10-24 18:20:20 -07:00
shilpa24balaji
ea3534678b Merge pull request #321 from xmidt-org/unref_crash
nopoll_conn_unref crash fix
2019-09-18 16:49:19 -07:00
Shilpa Seshadri
6ebb62ead4 Removing the additional conn_unref as conn_close handles this 2019-09-18 11:18:26 -07:00
Shilpa Seshadri
5ec16a7370 Re-order the cloud status update to prevent the nopoll_conn_unref crash 2019-09-16 16:26:56 -07:00
shilpa24balaji
7b81cb4efd Update README.md 2019-09-12 17:12:48 -07:00
shilpa24balaji
4c6a6a99e6 Merge pull request #320 from xmidt-org/event_handler
Ping Status change event handler
2019-09-12 16:42:01 -07:00
shilpa24balaji
106e1bfeb3 Merge pull request #318 from bill1600/waitconrdy
initialize wait_status in wait_connection_ready
2019-09-10 10:28:27 -07:00
Shilpa Seshadri
4f01170670 Handler definition for Ping Status change event 2019-09-09 16:51:39 -07:00
shilpa24balaji
f37d1911d6 Merge pull request #319 from xmidt-org/master
Sync from master branch
2019-09-09 13:13:29 -07:00
Bill Williams
3a436999fc initialize wait_status in wait_connection_ready 2019-09-06 11:56:56 -07:00
shilpa24balaji
016c80960c Merge pull request #316 from guruchandru/parodus_event
Parodus cloud Status update and Unit tests
2019-08-22 16:34:48 -07:00
Guru Chandru
b286857a22 Parodus cloud Status update and Unit tests 2019-08-22 11:50:56 +05:30
Shilpa Seshadri
f998106aed Log reconnect reason and update change log 2019-08-19 21:46:45 -07:00
shilpa24balaji
2d209b2a0d Merge pull request #315 from xmidt-org/event_handler
Pause connection retry when interface is down
2019-08-19 16:41:41 -07:00
Shilpa Seshadri
3f471100db Pause retry when interface is down and until its up 2019-08-17 03:43:50 -07:00
shilpa24balaji
ddc04f9da0 Merge pull request #313 from guruchandru/parodus_checkin
Parodus cloud-status shows "online" when connection is closed during …
2019-08-15 15:34:09 -07:00
Guru Chandru
a23615f3a5 Parodus cloud-status shows "online" when connection is closed during interface-down 2019-08-14 18:39:01 +05:30
shilpa24balaji
b1caff4a1a Merge pull request #312 from guruchandru/parodus_handler
parodus event handler to listen to interface_down and interface_up event
2019-08-09 12:41:59 -07:00
Sadhyama Vengilat
11c9052d77 parodus event handler to listen to interface_down and interface_up event 2019-08-07 12:19:38 +05:30
guruchandru
5ceb57a8c3 Merge pull request #1 from bill1600/sysevent
add pause/resume heartBeatTimer
2019-08-06 10:48:59 +05:30
guruchandru
c4ebe239ac Merge branch 'parodus_handler' into sysevent 2019-08-06 10:39:45 +05:30
shilpa24balaji
1622c44c89 Merge pull request #307 from gbuddappagari/parodus_onboard
RDKB-20643:Add OnBoarding logs
2019-07-24 20:15:06 -07:00
shilpa24balaji
fb542586e7 Update CMakeLists.txt 2019-07-24 20:13:40 -07:00
Gayathri Buddappagari
0afb87c29b RDKB-20643:Add OnBoarding logs 2019-07-15 17:02:01 +05:30
shilpa24balaji
f168e4d148 Merge pull request #308 from bill1600/nopoll_102
Use nopoll version 1.0.2
2019-07-02 14:52:36 -07:00
Bill Williams
97570a24d5 Use nopoll version 1.0.2 2019-07-02 13:24:20 -07:00
shilpa24balaji
95b6f75284 Merge pull request #306 from bill1600/newauthtoken
request new auth token on every retry, not just after 403
2019-06-12 11:38:10 -07:00
Bill Williams
f87e69c07b no need for backoff after 403 2019-06-11 14:20:45 -07:00
Bill Williams
647905639c refine connect/auth-token logic 2019-06-05 08:56:28 -07:00
Bill Williams
ceadc4b51f refine fetch auth token 2019-06-03 16:55:29 -07:00
Bill Williams
38dee179e7 request new auth token on every retry, not just after 403 2019-05-30 13:44:49 -07:00
shilpa24balaji
9feafedff8 Merge pull request #302 from bill1600/clrtoken
requestNewAuthToken will clear token if it fails
2019-05-21 17:49:33 -07:00
Bill Williams
2807f8e43a add test_auth_token_more.c 2019-05-16 13:48:02 -07:00
Bill Williams
5132675700 add unit tests for auth_token 2019-05-16 13:41:19 -07:00
Bill Williams
e166b9fdf5 use memset to clear auth token in requestNewAuthToken 2019-05-14 13:34:35 -07:00
Bill Williams
60789f0ec8 requestNewAuthToken will clear token if it fails 2019-05-14 11:51:40 -07:00
Bill Williams
3fb0708b15 add pause/resume heartBeatTimer 2019-05-07 16:19:37 -07:00
shilpa24balaji
65098e36cb Merge pull request #298 from bill1600/nano_115
Update to use nanomsg v 1.1.4
2019-04-24 10:30:41 -07:00
shilpa24balaji
c585300f76 Merge pull request #297 from bill1600/test_upstream
Add unit test for re-registrations
2019-04-24 10:27:48 -07:00
Bill Williams
e4e78118cf Use nanomsg version 1.1.4 2019-04-23 17:12:48 -07:00
Bill Williams
8b4541b570 Update to use nanomsg v 1.1.5 2019-04-23 13:29:35 -07:00
Bill Williams
acc542647b Add unit test for re-registrations 2019-04-12 09:09:23 -07:00
shilpa24balaji
da6614b19d Merge pull request #294 from bill1600/cnheal
Add logic to save parodus connection status in health file
2019-04-04 11:28:23 -07:00
Bill Williams
096271279d new self heal version woth merged close/endpoint 2019-04-01 09:22:40 -07:00
shilpa24balaji
50176fb120 Merge pull request #292 from bill1600/close_endpt
Fix nanomsg client close handling
2019-03-29 14:31:57 -07:00
Bill Williams
2ad896abc6 log all nn_close 2019-03-27 11:35:16 -07:00
Bill Williams
f58f85bc32 close client when deleting from client list 2019-03-26 16:54:52 -07:00
Bill Williams
4fef26c082 use endpoint in nn_shutdown and log nn_close errors 2019-03-26 16:26:09 -07:00
shilpa24balaji
1995a664ad Merge pull request #291 from sadhyama/master
Rename command line options for MTLS cert and Key #290
2019-03-22 10:39:44 -07:00
Weston Schmidt
f1b2add244 Merge branch 'nosinovacao-feature_mutual_auth_v1' 2019-03-20 09:08:47 -07:00
Weston Schmidt
13739786a0 Resolve the merge conflicts in PR 246. Remove the ifdef flag as this should always be available. Fix a mistake in the commandline option parsing of the C flag ... needs to be C:. 2019-03-20 09:05:20 -07:00
Sadhyama Vengilat
4fc082cb43 Updated CHANGELOG.md 2019-03-19 17:29:26 +05:30
Sadhyama Vengilat
08feef216e Rename command line options for MTLS cert and Key #290 2019-03-19 17:19:00 +05:30
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
shilpa24balaji
5f1650b009 Merge pull request #240 from sadhyama/close-retry
Fix parodus crash while sending notification to server
2018-09-25 00:22:47 -07:00
Sadhyama Vengilat
5cf95ac1ab Updated comment 2018-09-25 11:21:40 +05:30
Sadhyama Vengilat
c1e1a8ebdc Added unit tests for close_retry changes 2018-09-21 20:00:04 +05:30
Sadhyama Vengilat
d82c9ea187 Fix parodus crash while sending notification during connection retry 2018-09-21 19:51:22 +05:30
Sadhyama Vengilat
4562592536 Protect close_retry using mutex locks 2018-09-21 19:45:20 +05:30
Weston Schmidt
cdd333cc3a Merge pull request #238 from gbuddappagari/master
Used wrp_does_service_match() API to fix #236
2018-09-07 01:54:20 -07:00
Gayathri
7ae1d2a1c4 Used wrp_does_service_match() API to fix #236 2018-09-06 14:22:03 +05:30
Weston Schmidt
ed1ff2b105 Merge pull request #237 from gbuddappagari/master
To fix crash observed in #236 issue
2018-09-05 11:28:58 -07:00
Gayathri
166b7ec7c2 To fix crash observed in #236 issue 2018-09-05 16:29:06 +05:30
shilpa24balaji
97ac941a81 Merge pull request #234 from gbuddappagari/master
Modified validation logic for boot-time
2018-08-24 16:58:46 -07:00
Gayathri
844a1d925a Modified validation logic for boot-time 2018-08-20 18:16:46 +05:30
Weston Schmidt
ba690db3a1 Merge pull request #233 from sadhyama/master
To fix issue of WRP_MSG_TYPE__REQ response is not sending to server
2018-08-17 08:54:17 -07:00
Sadhyama Vengilat
a8d077dbf5 To fix issue of WRP_MSG_TYPE__REQ response is not sending to server 2018-08-17 18:51:41 +05:30
Weston Schmidt
2c3b8fc994 Merge pull request #230 from gbuddappagari/master
Allow a wildcard partner-id to match everything. #225
2018-08-07 07:12:47 -07:00
shilpa24balaji
35509cd5b2 Merge pull request #232 from bill1600/refactor_conn
Refactor conn
2018-08-06 00:16:50 -07:00
Bill Williams
4f74bc037d merge upstream.c and crud_internal.c 2018-08-03 09:29:02 -07:00
Bill Williams
9e3b32af69 refactored connection.c 2018-08-03 08:20:03 -07:00
shilpa24balaji
8a20d3a7c4 Merge pull request #231 from sadhyama/master
Changes to use modified wrp-c function for source/dest parsing
2018-08-02 21:29:00 -07:00
shilpa24balaji
19a0bc26af Merge pull request #229 from mrigaya/master
Add unit tests for heartBeat.c
2018-08-02 15:49:30 -07:00
Gayathri
558f007bdf Added comments 2018-08-02 10:53:35 +05:30
Sadhyama Vengilat
2ba26b37dc Changes to use modified wrp-c function for source/dest parsing 2018-07-31 11:04:45 +05:30
Weston Schmidt
da924e89a5 Merge pull request #228 from sadhyama/additional-fields
Added additional CRUD fields #208
2018-07-30 00:02:20 -07:00
Gayathri
6a1d908407 Avoiding triple pointer to get list of partner_ids 2018-07-27 13:14:34 +05:30
Gayathri
7b496769fc Returing with 403 error on mismatch of partner_id 2018-07-27 12:50:52 +05:30
Gayathri
1e05869ded To validate array of partner_ids 2018-07-26 18:26:27 +05:30
Gayathri
e7bf8cf468 Parse comma(,) separated partner_id to get partner_ids list 2018-07-26 17:15:28 +05:30
Sadhyama Vengilat
e40af91fa7 Incorporated review comments on crud additional fields 2018-07-25 18:25:58 +05:30
Sadhyama Vengilat
f88a3f11cc Merge remote-tracking branch 'upstream/master' into additional-fields 2018-07-25 18:12:04 +05:30
mrigaya
db07521d64 Add unit tests for heartBeat.c 2018-07-25 12:23:42 +05:30
Weston Schmidt
eb0281128d Merge pull request #227 from selvamKrish/ipv6_review_comment
Abort parodus process for invalid webpa url
2018-07-24 08:46:17 -07:00
Sadhyama Vengilat
7432b6f9fb Unit test cases for cloud-disconnect handling 2018-07-24 19:10:16 +05:30
Sadhyama Vengilat
db70ecf934 Unit test cases for cloud-status handling 2018-07-24 18:32:29 +05:30
Sadhyama Vengilat
c49a14cb00 Handled cloud-status retrieve requests from internal libparodus clients 2018-07-24 18:16:36 +05:30
Sadhyama Vengilat
b7e486994f Added crud field cloud-disconnect and handled cloud UPDATE request 2018-07-24 17:53:21 +05:30
Sadhyama Vengilat
9831cefd52 Added crud field cloud-status and handled cloud retrieve request 2018-07-24 17:39:27 +05:30
skrishnamoorthy01
ff7472be5d Abort the parodus process for invalid webpa url 2018-07-24 14:50:26 +05:30
Weston Schmidt
6f36fb7861 Merge pull request #226 from selvamKrish/ipv6_parsing
Fix to parse webpa-url IPv6 address properly #224
2018-07-23 10:04:54 -07:00
skrishnamoorthy01
d8b009b5d0 Fix to parse webpa-url IPv6 address properly #224 2018-07-23 18:02:10 +05:30
Weston Schmidt
8d7cc47e62 Update the changelog with the 1.0.1 release details & update the readme to automatically point to the latest release. 2018-07-18 11:51:29 -07:00
Weston Schmidt
326e83c177 Merge pull request #221 from Comcast/heart_beat
Heart beat Timer
2018-07-18 10:53:28 -07:00
Weston Schmidt
3df3876553 Merge pull request #223 from sadhyama/crud-handle
Handled few NULL cases for source, dest fields in CRUD requests
2018-07-18 10:51:56 -07:00
Sadhyama Vengilat
77f16d65db Handled few NULL cases for source, dest fields in CRUD requests 2018-07-18 20:18:18 +05:30
Shilpa Seshadri
6e4f8e92d1 Add comments 2018-07-16 23:47:50 -07:00
Shilpa Seshadri
7b106585cd Heart Beat files 2018-07-16 23:40:44 -07:00
Shilpa Seshadri
cb3da5a343 Mutex lock for heart beat timer 2018-07-16 23:33:11 -07:00
Weston Schmidt
6e1a0fccf4 Merge pull request #219 from selvamKrish/ping_timeout
Fix unit test case failure for ping miss interval
2018-06-29 16:16:21 -07:00
shilpa24balaji
b7e5d47f65 Merge pull request #220 from sadhyama/master
Fix memory leaks on CRUD multiple sized test objects
2018-06-29 10:55:34 -07:00
shilpa24balaji
7e9d3c80c5 Merge pull request #218 from manderiasian/master
Fixes crash in parodus WEBPA-2468
2018-06-29 10:42:14 -07:00
skrishnamoorthy01
50d9271e90 Fix unit test case failure for ping miss interval 2018-06-29 18:28:33 +05:30
Sadhyama Vengilat
982cf14f55 Fix memory leaks on CRUD multiple sized test objects 2018-06-29 15:33:40 +05:30
mander207
91a9d4d679 Revert previous commit, the code was correct. 2018-06-28 22:06:48 -07:00
mander207
6bcae50f0e Fixing a possible bug where boot-time may be corrupted/random/etc... 2018-06-28 21:39:31 -07:00
mander207
e5ac5c0712 Chack for null before calling wrp_free_struct() 2018-06-28 19:19:09 -07:00
mander207
3e23aeb451 Fixes crash in parodus WEBPA-2468 Need to find out if the test is valid, since the crash happens because msgunpack returns an error, which is now handled correctly. 2018-06-28 19:05:33 -07:00
Weston Schmidt
a61de51dfe Merge pull request #217 from sadhyama/CRUD-exp-objects
Handled CRUD error cases related to "expires" data and to support multiple sized  test objects
2018-06-28 08:57:01 -07:00
Sadhyama Vengilat
dc099a553c Added unit tests for expires checks & CRUD multiple sized test objects 2018-06-28 19:11:26 +05:30
Sadhyama Vengilat
0b3b31fc6f Return error for DELETE request format other than parodus/tag/${name} 2018-06-28 19:08:30 +05:30
Sadhyama Vengilat
bebaf9efa0 Changes to support multiple sized test objects for CRUD 2018-06-28 19:06:26 +05:30
Sadhyama Vengilat
a8ecc96cdb Handled error case when CRUD request doesnot have expires data 2018-06-28 18:55:54 +05:30
Weston Schmidt
8f77883a11 Merge pull request #216 from manderiasian/master
Fixes XMIDT-466
2018-06-28 06:02:51 -07:00
mander207
602ba21a8d Disabling test_createSocketConnection2, don't know why it is failing or what it is testing 2018-06-27 22:04:33 -07:00
mander207
32dc7b4b93 Fix for https://ccp.sys.comcast.net/browse/XMIDT-466 2018-06-27 22:00:45 -07:00
mander207
de0eefbaa6 compiler complains that the string may get truncated, and it is correct, so increasing the size of string for snprintf() 2018-06-27 21:54:47 -07:00
shilpa24balaji
d636cfffe9 Merge pull request #214 from mrigaya/master
Add unit test for conn stuck case.
2018-06-27 09:51:22 -07:00
mrigaya
2af5845e76 Merge remote-tracking branch 'upstream/master' into master 2018-06-27 12:07:06 +05:30
mrigaya
a2079aabf1 Add unit test for conn stuck case. 2018-06-27 12:02:06 +05:30
Weston Schmidt
880e4a8765 Merge pull request #215 from sadhyama/master
Handled few error scenarios for CRUD request format with tag or tags
2018-06-26 12:28:40 -07:00
Sadhyama Vengilat
3d3c965807 Return error for request format other than parodus/tag/${name} 2018-06-26 19:05:15 +05:30
Weston Schmidt
2a4fa2ffc4 Merge pull request #213 from selvamKrish/fix_leak_crud
Fix more leak for crud request
2018-06-25 08:00:53 -07:00
skrishnamoorthy01
d0535521c7 Fix more leak for crud request 2018-06-25 15:25:12 +05:30
Weston Schmidt
5663981ac0 Merge pull request #211 from sadhyama/crud-mem-leak
To fix memory leaks on CRUD
2018-06-21 23:39:51 -07:00
Sadhyama Vengilat
844ee1c240 Modified dest parsing logic to extract pre-seperated strings 2018-06-20 19:06:52 +05:30
Sadhyama Vengilat
dc81484779 Merge remote-tracking branch 'upstream/master' into crud-mem-leak 2018-06-20 18:55:29 +05:30
shilpa24balaji
e0c69f5e29 Merge pull request #212 from manderiasian/master
Reset connection error trigger
2018-06-19 15:33:52 -07:00
mander207
3768ef17f1 Revert debug changes for now. 2018-06-19 15:13:59 -07:00
mander207
fbe267ee82 Fix the unit test 2018-06-19 14:43:08 -07:00
mander207
a619b59e23 Re-adding the debug code. 2018-06-19 14:42:44 -07:00
mander207
1ceedbf772 Looks like nopoll_conn_is_ok() and nopoll_conn_is_ready() may have some internal calls to each other, so my debug code change broke the mock unit tests, reverting that change but keeping the fix for the crash in there. Tested and verified with Mike T 2018-06-19 14:34:38 -07:00
mander207
d22f497e4e Reset connection error trigger 2018-06-19 13:41:52 -07:00
Sadhyama Vengilat
dd77f874b5 Incorporated review comments on CRUD 2018-06-19 20:29:35 +05:30
Sadhyama Vengilat
280166b4ca To fix memory leaks on CRUD 2018-06-18 19:38:18 +05:30
Sadhyama Vengilat
1012afeebf Retrieve for read-only objects should work even when crud cfg json doesnot exists 2018-06-18 19:30:09 +05:30
shilpa24balaji
d13daec5b1 Merge pull request #210 from manderiasian/master
Include pthread header file to fix the docker build
2018-06-15 12:26:48 -07:00
mander207
f57caffb2e Include pthread header file. 2018-06-15 11:23:42 -07:00
Weston Schmidt
b15a2cd638 Merge pull request #202 from sadhyama/parodus-master-CRUD
Parodus CRUD Interface
2018-06-12 15:13:34 -07:00
Sadhyama Vengilat
d2853fe742 Merge remote-tracking branch 'upstream/master' into parodus-master-CRUD 2018-06-11 16:15:39 +05:30
Weston Schmidt
3986da3885 Merge pull request #205 from mrigaya/master
Bring nopoll patch changes to parodus.
2018-06-08 11:36:45 -07:00
Weston Schmidt
38f855f1a3 Merge pull request #206 from selvamKrish/parodus_conn_stuck
Add timer logic to conn stuck issue
2018-06-08 11:36:07 -07:00
shilpa24balaji
bb16704bed Merge pull request #207 from manderiasian/master
Fix memroy leak. Fixes Issue #WEBPA-2459
2018-06-08 09:50:31 -07:00
mander207
ac74889b9a Fix memroy leak. Fixes Issue #WEBPA-2459 2018-06-08 08:47:16 -07:00
skrishnamoorthy01
cbeeb44702 Add timer logic to conn stuck issue 2018-06-08 16:45:00 +05:30
mrigaya
d6a6bf8549 Bring nopoll patch changes to parodus. 2018-06-08 16:27:51 +05:30
Sadhyama Vengilat
b5633ba8db Added few more tests on retrieve, update, delete cjosn file handling 2018-06-08 15:42:53 +05:30
Sadhyama Vengilat
05d24b6b57 Added tests which covers retrieve, update, delete CJSON file handling 2018-06-07 18:51:55 +05:30
Sadhyama Vengilat
375e3ef79a Added unit tests for createObject and retrieveObject 2018-06-05 02:00:29 +05:30
Sadhyama Vengilat
3fd1b5ce38 Added few unit tests for crud_internal.c 2018-06-01 12:12:25 +05:30
Sadhyama Vengilat
a9d9c6a538 Unit tests for CRUD request processing in crud_tasks.c 2018-05-31 19:31:17 +05:30
shilpa24balaji
4ea905e491 Merge pull request #204 from selvamKrish/update_nopoll_tag
Change nopoll tag to latest version
2018-05-31 00:35:40 -07:00
Sadhyama Vengilat
6a2db59bbe Added few more unit tests for downstream & upstream CRUD processing 2018-05-30 19:32:50 +05:30
skrishnamoorthy01
89ab46499a Change nopoll tag to latest version 2018-05-30 18:14:15 +05:30
Sadhyama Vengilat
6b6b943ef0 Updated README.md with crud config file option 2018-05-29 19:50:13 +05:30
Sadhyama Vengilat
7eec176414 Added unit tests for CRUD queue handling in crud_interface.c 2018-05-29 19:35:56 +05:30
Weston Schmidt
7a7e7acb19 Update the description. 2018-05-24 08:50:59 -07:00
Weston Schmidt
7328a559f8 Update the description. 2018-05-24 08:47:10 -07:00
Sadhyama Vengilat
a279ee71c9 Configurable command line option for crud config json file 2018-05-24 19:17:56 +05:30
Sadhyama Vengilat
facae2e9f4 CJSON file handling for CRUD UPDATE operation 2018-05-24 18:01:23 +05:30
Sadhyama Vengilat
f3e506e943 CJSON file handling for CRUD DELETE operation 2018-05-24 17:00:15 +05:30
Sadhyama Vengilat
38e5c0b5b5 CJSON file handling for CRUD RETRIEVE operation 2018-05-24 16:19:37 +05:30
Sadhyama Vengilat
e01ae80307 CRUD retrieve for read-only objects from in-memory 2018-05-24 15:31:38 +05:30
Sadhyama Vengilat
12a034f451 CJSON file handling for CREATE operation 2018-05-24 14:52:02 +05:30
Sadhyama Vengilat
a1e63ca251 Few modifications for build failures in tests 2018-05-24 12:21:43 +05:30
Sadhyama Vengilat
355b7d7bd3 Added getter setter functions to avoid extern 2018-05-24 12:10:26 +05:30
Sadhyama Vengilat
bbf5fc263c CRUD requests processing 2018-05-24 12:06:20 +05:30
Sadhyama Vengilat
45c1865cb1 Added queue mechanism to handle CRUD upsteam & downstream 2018-05-24 11:54:48 +05:30
shilpa24balaji
06f96abe41 Merge pull request #201 from Comcast/revert-197-master
Revert "Remove static char arrays from ParodusCfg structure. "
2018-05-23 17:40:26 -07:00
shilpa24balaji
ee9d7684c6 Revert "Remove static char arrays from ParodusCfg structure. " 2018-05-23 17:40:04 -07:00
shilpa24balaji
951be13bc0 Merge pull request #200 from Comcast/revert-199-master
Revert "Fix SEG FAULT (signal 11) caused by calling strlen(null)"
2018-05-23 17:39:40 -07:00
shilpa24balaji
c5819e4cb1 Revert "Fix SEG FAULT (signal 11) caused by calling strlen(null)" 2018-05-23 17:39:15 -07:00
Weston Schmidt
38d2596458 Merge pull request #199 from manderiasian/master
Fix SEG FAULT (signal 11) caused by calling strlen(null)
2018-05-23 14:19:21 -07:00
mander207
8c79a7712d Disable clean_up_parodus_cfg() for now, it raises error on free(), will fix it once I know what is going on 2018-05-23 14:15:18 -07:00
mander207
15d9b14e31 Use absolute path name for test file (based on Cmake vars) 2018-05-23 14:13:51 -07:00
mander207
c3d66f7a45 Use absolute path name for test file (based on Cmake vars) 2018-05-23 14:13:07 -07:00
mander207
659bb28ce7 Cleanup sig_handler(), add streeror() so we also get a Human readable error/signal string 2018-05-23 07:35:24 -07:00
mander207
0725e9f3ae Allocate memory for cfg->webpa_auth_token 2018-05-22 23:51:26 -07:00
mander207
3e264707e7 Fix clean_up_parodus_cfg(). Check for null before accessing token string fields. 2018-05-22 23:27:12 -07:00
shilpa24balaji
e6c41ee386 Merge pull request #197 from manderiasian/master
Remove static char arrays from ParodusCfg structure.
2018-05-18 14:53:04 -07:00
mander207
6b5f24f81b Fixed a bunch of issues, mostly related to FEATURE_DNS_QUERY 2018-05-17 17:00:56 -07:00
mander207
4dd693d2b5 Fix typos 2018-05-17 12:00:03 -07:00
mander207
8eb6ff8fa8 Move read_key_from_file() declaration to config.h 2018-05-17 11:59:13 -07:00
mander207
c067faa65a Remove define that I forgot and checked-in 2018-05-16 20:32:38 -07:00
mander207
e0ecd1bbd7 All Test Pass Now :-) :-) 2018-05-16 12:31:32 -07:00
mander207
a06d507422 Fix issues with parse command line, etc...disable test for git commit tag 2018-05-16 12:20:09 -07:00
mander207
a1b676e5fe Fix remaining access to null pointers (used to be array so strlen() would not have crashed) 2018-05-16 09:16:46 -07:00
mander207
4276e2dd24 Removed all refernces to static arrays in ParodusCfg structure 2018-05-15 20:41:15 -07:00
mander207
dc8f9f49f0 Using malloced strings vs static arrays 2018-05-15 18:25:55 -07:00
Weston Schmidt
0618690bf4 Merge pull request #195 from nosinovacao/fix_parse_webpa_url
fixes Comcast/parodus#194 parse_webpa_url function doesn't correctly return server address
2018-05-15 14:52:42 -07:00
Nuno Martins
7b1ef043ef fixes Comcast/parodus#194 parse_webpa_url function doesn't correctly return server address if it doesn't have port number
If the redirect returns a URL which has an URI with "/api/v2/" the
parse_webpa_url function must only return in address_buffer the server
and not the server/api/v2/ as shown in the test case
2018-05-15 17:41:24 +01:00
Weston Schmidt
1da5978eac Merge pull request #192 from Comcast/Minas
Correcting memory allocation for the flex array in partners_t struct.
2018-05-09 19:26:14 -07:00
Shilpa Seshadri
df96235321 Correcting memory allocation for the flex array in partners_t struct. 2018-05-09 16:02:23 -07:00
shilpa24balaji
9421a3d01a Merge pull request #186 from bill1600/master
Use length code when parsing rr recs in token.c
2018-04-13 08:25:36 -07:00
bill1600
c277ef4587 Merge pull request #188 from selvamKrish/fix_build
Fix for parodus compile error in test_token when seshat is enabled #187
2018-04-12 13:35:38 -07:00
Selvam Krishnamoorthy
472b769874 this commit fixes #187 2018-04-12 06:56:58 +05:30
Weston Schmidt
4e1f77c1df Merge pull request #185 from selvamKrish/fragment_pr
Handle fragment request in parodus
2018-04-10 17:40:18 -07:00
Bill Williams
b07ff93fd8 Use length code when parsing rr recs in token.c 2018-04-10 16:48:58 -07:00
skrishnamoorthy01
9aacf1cbb3 Add unit test for fragmented request 2018-04-09 17:07:07 +05:30
skrishnamoorthy01
5545dbc84f Handle fragment request in parodus 2018-04-06 12:27:02 +05:30
Weston Schmidt
755e15fd6c Merge pull request #184 from bill1600/master
remove comcast specific references in tests
2018-04-05 17:17:54 -07:00
shilpa24balaji
492688e6e7 Merge pull request #183 from gbuddappagari/master
Reset jwt status when acquire_jwt is 0
2018-04-03 21:22:22 -07:00
Bill Williams
9c98105e35 forgot to add key files required for test 2018-04-03 11:28:02 -07:00
Bill Williams
0a4ef718f6 remove comcast specific references in tests 2018-04-03 11:18:32 -07:00
Gayathri
7eba72b2af Reset jwt status when acquire_jwt is 0 2018-04-03 11:44:04 +05:30
Weston Schmidt
5af33bec8c Merge pull request #182 from gbuddappagari/master
Changed dns query retry logic
2018-04-02 11:37:29 -07:00
Gayathri
0f71f45ca6 Modified test cases to verify change in jwt validation logic 2018-03-30 14:53:16 +05:30
Gayathri
89da01fad0 Changed query dns retry logic & removed dns backoff retry 2018-03-29 16:33:42 +05:30
shilpa24balaji
0e927c0f26 Merge pull request #180 from selvamKrish/reconnect_reason_patch
Remove global variable LastReasonStatus and add getter setter func
2018-03-28 22:05:43 -07:00
skrishnamoorthy01
6bcc88c55a Incorporate review comments 2018-03-27 15:47:47 +05:30
skrishnamoorthy01
9cd80c1237 Resolved merge conflict 2018-03-27 15:21:45 +05:30
Weston Schmidt
20fc1bb8a0 Merge pull request #179 from Comcast/conn_fallback_support
Parodus conn fallback support
2018-03-26 10:28:59 -07:00
Weston Schmidt
46767bf392 Merge pull request #178 from gbuddappagari/parodus-git-tag
XMIDT-385: Use particular version of external dependencies
2018-03-26 10:25:47 -07:00
Selvam Krishnamoorthy
deec73c5a5 Parodus conn fallback support 2018-03-26 22:10:11 +05:30
Gayathri
b6f315bbb7 XMIDT-385: Use particular version of external dependencies 2018-03-26 18:04:34 +05:30
skrishnamoorthy01
202b5deb68 Remove global variable LastReasonStatus and add getter setter func 2018-03-26 16:43:42 +05:30
Weston Schmidt
a69acfeabb Merge pull request #177 from selvamKrish/pthread_kill
Fix pthread_kill issue in test_service_alive test case
2018-03-26 00:00:29 -07:00
skrishnamoorthy01
36dc370ef8 Fix pthread_kill test case 2018-03-23 18:47:01 +05:30
Bill Williams
587027ce78 fix for fedora-27, use ucresolv master 2018-03-22 14:21:29 -07:00
Shilpa Seshadri
a254fc17d7 Disable Coverity scan 2018-03-21 18:06:10 -07:00
Shilpa Seshadri
f3abee1a04 Disabling test_service_alive 2018-03-21 16:23:36 -07:00
Weston Schmidt
d85f790407 Merge pull request #175 from sadhyama/parodus-checkin
Fix for server_Address mismatch during initial conn & retry when CJWT is enabled
2018-03-21 14:25:11 -07:00
Sadhyama Vengilat
12565db6e9 Fix for server_Address mismatch during initial conn and retry when CJWT is enabled 2018-03-21 19:40:12 +05:30
Weston Schmidt
6a396c2197 Change kill() to be pthread_kill() so the arguments are correct. 2018-03-16 19:15:26 -07:00
Weston Schmidt
633cfe1636 Fix printf() statement. 2018-03-16 19:07:16 -07:00
Weston Schmidt
7e74d05196 Fix printf() statement. 2018-03-16 19:04:46 -07:00
Weston Schmidt
fc72633519 Fix a compiler warning. 2018-03-16 18:59:43 -07:00
Bill Williams
62aea40eb4 Use specific tag for libucresolv master 2018-03-14 11:43:16 -07:00
Weston Schmidt
c693a34a15 Merge pull request #171 from sadhyama/master
Added Backoff retry for dns_record nquery failure
2018-03-13 11:35:34 -07:00
Sadhyama Vengilat
d6fb9073ed Added Backoff retry for dns_record nquery failure 2018-03-13 19:42:42 +05:30
Weston Schmidt
136da0621e Merge pull request #165 from bill1600/master
remove references to comcast in readme. change dns-id param to dns-txt-url
2018-02-22 10:30:25 -08:00
Bill Williams
2aa134c9d4 remove references to comcast in readme. change dns-id param to dns-txt-url 2018-02-16 08:00:55 -08:00
Weston Schmidt
0a7d2f3a1a Merge pull request #163 from bill1600/master
cmd line parameter changes
2018-02-15 10:10:46 -08:00
Bill Williams
968727eece use parse_num_arg for nueric arguments 2018-02-07 16:38:48 -08:00
Bill Williams
bac0a6983d add test_standard_strncmp to test_createConnection 2018-02-07 14:03:55 -08:00
Bill Williams
f877b9c22f add config tests 2018-02-07 13:38:31 -08:00
Bill Williams
9b988c6878 add test_parse_mac_address to test_config 2018-02-07 09:38:07 -08:00
Bill Williams
91d7f4a02b add check of key file in test_config 2018-02-06 15:22:56 -08:00
Bill Williams
b74f73ee73 update test_config error tests 2018-02-06 12:47:22 -08:00
Bill Williams
df53862dec Merge branch 'master' of https://github.com/Comcast/parodus 2018-02-06 10:27:18 -08:00
Bill Williams
b85e78fb7b changes to disallow none, dns-id rule change and update readme 2018-02-06 10:21:51 -08:00
Weston Schmidt
38b8cbf4ac Merge pull request #162 from bill1600/master
fix test_errParseCommandLine
2018-01-30 17:31:55 -08:00
Bill Williams
4671e40b32 fix test_errParseCommandLine 2018-01-30 14:48:09 -08:00
Bill Williams
22278846e1 enable messages in tests in travis 2018-01-29 17:06:44 -08:00
Bill Williams
ed3ec23a47 fix test_errParseCommandLine 2018-01-29 16:21:21 -08:00
Weston Schmidt
b1b6883799 Merge pull request #160 from sadhyama/master
To update upstream token in configuration
2018-01-26 17:53:06 -08:00
Shilpa Seshadri
79b6861af6 Fixing compiler errors 2018-01-26 17:28:47 -08:00
shilpa24balaji
e298549510 Merge branch 'master' into master 2018-01-26 16:54:09 -08:00
Bill Williams
3a181d2ffe fix coverity issue CID 1464190. possible array overrun in connection.c 2018-01-25 11:50:22 -08:00
Bill Williams
be71810dea update README file to correspond with cmd line changes 2018-01-25 11:12:04 -08:00
Bill Williams
2bf902242f fix merge conflicts and verify they aren't really anything 2018-01-24 15:01:34 -08:00
Bill Williams
2b15321a77 use tag nopoll_yocto in CMakeLists.txt 2018-01-23 14:14:12 -08:00
Bill Williams
f21a00616a apply default ports 443 and 80 2018-01-22 13:37:26 -08:00
Sadhyama Vengilat
8df4ad3cbc To update upstream token in configuration 2018-01-22 17:12:31 +05:30
Bill Williams
7f2aa3f826 merge with latest parodus 2018-01-19 14:39:17 -08:00
shilpa24balaji
7946f585ee Merge pull request #159 from Comcast/remove-a-few-buffers
Clean up the header processing code a bit.
2018-01-18 11:35:51 -08:00
Weston Schmidt
5f10aae6c2 Make the whitespace consistent. 2018-01-17 16:09:39 -08:00
Weston Schmidt
e11927f8de Clean up the header processing code a bit. 2018-01-17 16:05:18 -08:00
Weston Schmidt
c478da9f7c Fix a buffer being too small and causing compiler warnings. 2018-01-17 15:36:14 -08:00
Weston Schmidt
0bdb8f96b8 Merge pull request #158 from sadhyama/master
Add cmd line args support for acquisition and read header
2018-01-17 13:30:09 -08:00
Sadhyama Vengilat
b1c9cdfa16 Add cmd line args support for acquisition and read header 2018-01-17 19:20:01 +05:30
Shilpa Seshadri
04cefb9037 Added sudo to run parodus with root permission to avoid port bind error 2018-01-16 12:29:22 -08:00
Weston Schmidt
21fe137755 Merge pull request #155 from gbuddappagari/master
Updating msgpack dependency version with 2.1.5.
2018-01-12 02:23:19 -08:00
Gayathri
807839f8c5 Updating msgpack dependency version with 2.1.5. 2018-01-12 12:26:03 +05:30
Bill Williams
bbf8813303 extract port from JWT endpoint 2018-01-11 13:50:47 -08:00
Weston Schmidt
e9ae72c79b Merge pull request #154 from gbuddappagari/master
Added tests for configurable secure flag
2018-01-10 22:16:13 -08:00
Gayathri
268b1a2e82 Added tests for configurable secure flag 2018-01-10 17:47:39 +05:30
Weston Schmidt
ca4132b9e3 Merge pull request #152 from sadhyama/master
Configurable secure flag and port
2018-01-09 13:07:14 -08:00
Bill Williams
7d8c0bcff2 update .travis.yml cmake cmd to specify FEATURE_DNS_QUERY 2018-01-09 11:46:36 -08:00
Bill Williams
0ba7f5b95a support fabric.xmidt.comcast.net 2018-01-09 09:44:30 -08:00
Sadhyama Vengilat
36735f588d Added method to set default values and removed loadParodusCfg 2018-01-08 19:32:06 +05:30
Sadhyama Vengilat
5f4d640467 Changes for Configurable secure flag and port 2018-01-08 14:20:36 +05:30
Weston Schmidt
7bc99bb48c Merge pull request #148 from sadhyama/master
Modified strcpy to strncpy
2017-12-15 15:58:11 -08:00
Sadhyama Vengilat
cf1e9c51d2 Modified strcpy to strncpy 2017-12-15 18:19:54 +05:30
Weston Schmidt
14241251d8 Merge pull request #147 from sadhyama/master
Handle 403 error from talaria in parodus
2017-12-14 20:24:55 -08:00
Sadhyama Vengilat
eb67134b10 Handle 403 error from talaria in parodus 2017-12-14 17:03:23 +05:30
Weston Schmidt
93f30417de Merge pull request #145 from armcc/master
spin_thread.c: don't assume pthread_t can be cast to int
2017-12-01 11:46:47 -08:00
Andre McCurdy
d282afca4f spin_thread.c: don't assume pthread_t can be cast to int
Fix build issues for 64bit targets.

Signed-off-by: Andre McCurdy <armccurdy@gmail.com>
2017-11-30 15:30:27 -08:00
Weston Schmidt
81dff2cef0 Merge pull request #144 from cableramki/master
Reduced duplicate code and fixed debug info to display based on messa…
2017-11-30 12:20:34 -08:00
Ramki Ananthakrishnan
a3991b3ed9 Reduced duplicate code and fixed debug info to display based on message type. 2017-11-29 15:43:30 -08:00
Weston Schmidt
afbb5c5fa0 Merge pull request #142 from cableramki/master
Added downstream support to pass through other types of WRP messages.
2017-11-17 07:06:43 -08:00
Ramki Ananthakrishnan
0003bc4a25 Fixed some discrepancies handling different message types and added tests. 2017-11-17 01:01:31 -08:00
shilpa24balaji
b83392f519 Merge pull request #143 from Comcast/revert-140-master
Revert "Configurable secure flag and port"
2017-11-16 22:41:40 -08:00
shilpa24balaji
50a8cd7911 Revert "Configurable secure flag and port" 2017-11-16 22:22:25 -08:00
Ramki Ananthakrishnan
5c388d1db7 Added changes from review. 2017-11-16 19:48:21 -08:00
Ramki Ananthakrishnan
aa596dd3c2 Added downstream support to pass through CRUD messages. 2017-11-16 18:55:12 -08:00
Weston Schmidt
7829ec3de6 Merge pull request #140 from gbuddappagari/master
Configurable secure flag and port
2017-11-15 09:15:02 -08:00
Gayathri
f214d119a3 Configurable secure flag and port 2017-11-15 17:25:40 +05:30
Weston Schmidt
99393a233d Merge pull request #139 from Comcast/decode_free
To fix the parodus crash during invalid message type decode and free
2017-11-07 21:11:05 -08:00
Shilpa Seshadri
8b8c3f0950 To fix the parodus crash during invalid message type decode and free 2017-11-07 19:23:04 -08:00
Weston Schmidt
a461a7da10 Update license details an support materials. 2017-11-03 19:01:13 -07:00
Weston Schmidt
61ee6aca96 Merge pull request #138 from gbuddappagari/master
Use correct deallocator
2017-10-30 00:05:33 -07:00
Gayathri
774ec17e4e Use correct deallocator 2017-10-30 11:58:41 +05:30
Weston Schmidt
1fdf4a46ef Merge pull request #137 from gbuddappagari/master
Change logic to retrieve token
2017-10-27 08:46:00 -07:00
Gayathri
b8a48a400d Added webpa-token command-line argument to tests 2017-10-27 18:14:13 +05:30
Gayathri
acdb5c9937 Change logic to retrieve token 2017-10-27 11:57:32 +05:30
Weston Schmidt
76505cd414 Merge pull request #136 from gbuddappagari/master
Add command-line argument to acquire JWT and add it to HTTP HEADERS
2017-10-25 07:47:37 -07:00
Gayathri
d270f480e9 Add JWT to HTTP HEADERS 2017-10-25 18:11:29 +05:30
Gayathri
7fb0ed583c Add new command-line argument to acquire JWT 2017-10-25 18:08:35 +05:30
shilpa24balaji
73a64224cd Merge pull request #135 from Comcast/feature-ipv6-options
Add --force-ipv4 and --force-ipv6 flags and fix some surprises along the way.
2017-10-23 14:05:35 -07:00
Weston Schmidt
fe70242243 Remove a resource leak. 2017-10-20 21:55:57 -07:00
Weston Schmidt
d111826d92 Update the tests. 2017-10-20 21:28:07 -07:00
Weston Schmidt
818b84257c Fix ssl-cert-path option decorator. 2017-10-20 20:35:32 -07:00
Weston Schmidt
b1078b53d6 Add --force-ipv4 and --force-ipv6 flags. 2017-10-20 20:35:03 -07:00
Weston Schmidt
54849bba00 Fix error: webpa-interface-used option. 2017-10-20 20:00:37 -07:00
Weston Schmidt
f9b6ae840d Move the secureFlag into a group of flags. 2017-10-20 19:58:27 -07:00
Weston Schmidt
831df10422 Fix a variable aliasing problem. 2017-10-20 19:52:14 -07:00
Weston Schmidt
c63867a936 Normalize the code format a bit. 2017-10-20 19:48:03 -07:00
Weston Schmidt
0b90f0fe3b Merge pull request #134 from sadhyama/master
To remove logging of sensitive data from request/response payload
2017-10-11 15:17:58 -07:00
Sadhyama Vengilat
429abeb6a5 To remove logging of sensitive data from request/response payload 2017-10-10 19:31:13 +05:30
Weston Schmidt
0acefa0c37 Merge pull request #132 from gbuddappagari/master
Set ssl cert path using command-line argument
2017-08-30 09:43:39 -07:00
Gayathri
36fc6a7e51 Set ssl cert path using command-line argument 2017-08-30 14:50:26 +05:30
shilpa24balaji
66c6ec779d Merge pull request #131 from gbuddappagari/master
Enabled peer verify and added cert path
2017-08-29 22:38:16 -07:00
Gayathri
e888235850 Enabled peer verify and added cert path 2017-08-30 11:04:28 +05:30
Weston Schmidt
678d6c5f2d Merge pull request #130 from selvamKrish/master
Intregate breakpad only in yocto
2017-08-12 22:47:19 -07:00
skrishnamoorthy01
80f82521bd Intregate breakpad only in yocto 2017-08-11 12:01:13 +05:30
shilpa24balaji
a73373e055 Merge pull request #129 from selvamKrish/master
Disable peer verify and fix fedora build issue for nopoll
2017-08-02 23:57:21 -07:00
Selvam Krishnamoorthy
a9f11e85c6 Fix fedora build issue for nopoll 2017-08-03 12:05:40 +05:30
Selvam Krishnamoorthy
72ec4daf74 Disable peer verify 2017-08-03 12:03:14 +05:30
Weston Schmidt
278c1199cd Merge pull request #127 from selvamKrish/master
Incorporate review comments for createConnOpts function
2017-08-01 09:40:56 -07:00
shilpa24balaji
75c446b220 Merge pull request #128 from gbuddappagari/master
nopoll opts set ssl certs
2017-08-01 00:10:56 -07:00
Gayathri
e78174f314 nopoll opts set ssl certs for yocto 2017-08-01 11:59:54 +05:30
skrishnamoorthy01
3ee3ec356d Incorporate review comments for createConnOpts function 2017-07-31 18:46:21 +05:30
shilpa24balaji
e09ae35682 Merge pull request #126 from sadhyama/master
Fixed travis build failure due to test_createConnection
2017-07-28 10:58:06 -07:00
Sadhyama Vengilat
9fbe242ec7 Fixed travis build failure due to test_createConnection 2017-07-28 15:50:51 +05:30
Weston Schmidt
275f5595ce Merge pull request #125 from selvamKrish/master
Modify parodus to use latest nopoll 0.4.4
2017-07-26 14:54:41 -07:00
Selvam Krishnamoorthy
a9b4b44504 Enable peer verify and use opts for http connection 2017-07-26 20:36:02 +05:30
skrishnamoorthy01
dbc7b99b31 Modify parodus to use latest nopoll 0.4.4 2017-07-25 20:18:37 +05:30
Weston Schmidt
b68ba089cd Merge pull request #124 from sadhyama/master
Fixed few more coverity defects
2017-07-20 08:00:33 -07:00
Sadhyama Vengilat
6a921bd396 Fixed few more coverity defects 2017-07-20 19:23:31 +05:30
Weston Schmidt
b02c30256c Merge pull request #123 from sadhyama/master
Fix for defects reported by coverity
2017-07-19 08:06:06 -07:00
Sadhyama Vengilat
9a09357fc3 Fix for defects reported by coverity 2017-07-19 15:20:16 +05:30
Weston Schmidt
19208e2d0f Merge pull request #122 from gbuddappagari/master
Configurable command-line arguments
2017-07-18 21:29:20 -07:00
Gayathri
aacbcf5360 Configurable command-line arguments 2017-07-17 19:23:46 +05:30
Weston Schmidt
63b9b50534 Merge pull request #120 from sadhyama/master
Modified all strcpy to use parStrncpy wrapper and added unit test for parodus git commit hash
2017-07-17 05:57:43 -07:00
Sadhyama Vengilat
7e5aefd10a Added unit test to validate parodus git version 2017-07-17 16:37:35 +05:30
Sadhyama Vengilat
912638d59b Modified all strcpy to use parStrncpy wrapper 2017-07-17 16:17:03 +05:30
Weston Schmidt
883814ba42 Merge pull request #118 from gbuddappagari/master
seshat and cjwt conditional compilation
2017-07-13 10:23:11 -07:00
Gayathri
718beac0bd Enable seshat and cjwt compiler flags 2017-07-13 17:00:23 +05:30
Gayathri
88c4315a68 Allow JWT token validation to be configurable at compile time 2017-07-13 15:41:00 +05:30
Gayathri
d4bf5dc099 Allow seshat registration to be configurable at compile time 2017-07-13 15:35:44 +05:30
Weston Schmidt
3e91b55197 Merge pull request #116 from sadhyama/master
Added parodus version along with git commit hash
2017-07-11 13:05:32 -07:00
Sadhyama Vengilat
48d94661a3 Added parodus version along with git commit hash 2017-07-10 16:25:04 +05:30
Weston Schmidt
0da33e5ec3 Merge pull request #114 from gbuddappagari/master
Correcting compiler macro for UCLIBC
2017-06-22 07:39:16 -07:00
Gayathri
f67f385584 Correcting compiler macro for UCLIBC 2017-06-22 18:39:52 +05:30
Weston Schmidt
c55a480830 Merge pull request #113 from gbuddappagari/master
To fix Yocto build issue
2017-06-20 09:44:45 -07:00
Gayathri
976810432e To fix Yocto build issue 2017-06-20 18:08:05 +05:30
Ramki A
451517ca2b Merge pull request #111 from bill1600/ctests
add unit tests for config.c relating to jwt tokens
2017-06-19 14:59:21 -07:00
Bill Williams
c96fd044de add unit tests for config.c relating to jwt tokens 2017-06-16 10:05:50 -07:00
Weston Schmidt
0e2bc12736 Merge pull request #109 from selvamKrish/master
Update patch for hostname validation
2017-06-14 10:16:50 -07:00
Weston Schmidt
6dbf2d479b Merge pull request #106 from bill1600/vtests
fix coverity errors and add unit tests
2017-06-14 10:16:07 -07:00
Bill Williams
f8a0179753 add parentheses and another test 2017-06-14 10:06:58 -07:00
Weston Schmidt
05fad15ac5 Merge pull request #108 from cableramki/master
Increased test coverage for conn_interface.
2017-06-14 09:57:14 -07:00
skrishnamoorthy01
6f96cf6529 Update patch for hostname validation 2017-06-14 19:07:15 +05:30
skrishnamoorthy01
5ab7f7a697 Revert "Update patch for hostname validation"
This reverts commit 0807c5623f.
2017-06-14 18:56:51 +05:30
skrishnamoorthy01
0807c5623f Update patch for hostname validation 2017-06-14 18:54:01 +05:30
Ramki Ananthakrishnan
5eebbb8f49 Fixed param transposition build error. 2017-06-12 20:45:14 -07:00
Ramki Ananthakrishnan
d19a6f0022 Increased test coverage for conn_interface. 2017-06-12 20:43:28 -07:00
Bill Williams
6aeb6a42b1 fix coverity errors and add unit tests 2017-06-12 13:24:29 -07:00
Weston Schmidt
7e5ec0d670 Merge pull request #102 from bill1600/utests
forgot to activate dns server call in connection.c, also added more u…
2017-06-12 09:36:46 -07:00
Bill Williams
58c3fe35db forgot to activate dns server call in connection.c, also added more unit tests 2017-06-10 17:12:21 -07:00
Weston Schmidt
056659c19e Merge pull request #101 from bill1600/cjwt
cjwt integration into parodus
2017-06-09 11:56:49 -07:00
Bill Williams
ee0d1dd6c0 remove commented code from token.c 2017-06-09 11:22:58 -07:00
Bill Williams
e2296b497c fix test_config by reordering 2017-06-09 09:18:57 -07:00
Bill Williams
3b2b14056c fix test_config by reordering 2017-06-09 08:48:45 -07:00
Bill Williams
5c17a9fc73 fix test_config by reordering libs 2017-06-09 08:29:01 -07:00
Bill Williams
d8e78ff982 reorder link libs in tests to resolve all syms in travis env 2017-06-09 08:02:58 -07:00
Bill Williams
1ecc3ad516 explicit reference to trower-base64 library 2017-06-08 16:56:46 -07:00
Bill Williams
dd6fc7551a BUILD_TESTING OFF in trower-base64 2017-06-08 16:07:57 -07:00
Bill Williams
40e7963d29 BUILD_TESTING OFF off for cjwt 2017-06-08 15:48:34 -07:00
Bill Williams
866eb6b128 dont need libssl-dev, need shared cjwt 2017-06-08 11:23:57 -07:00
Bill Williams
f927aba40c need libssl-dev 2017-06-08 10:20:27 -07:00
Bill Williams
a55d28d85d back up 2017-06-08 09:42:37 -07:00
Bill Williams
b222bf7a7b travis to install ssl and crypto, try 2 2017-06-08 09:36:43 -07:00
Bill Williams
699fabc6df travis to install ssl and crypto 2017-06-08 09:30:25 -07:00
Bill Williams
8007039712 change travis.yml to install check 2017-06-07 16:05:36 -07:00
Bill Williams
e11a52fb57 cjwt integration into parodus 2017-06-07 09:23:57 -07:00
cableramki
4944f0a527 Merge pull request #99 from cableramki/master
Added null check before string comparison to fix crash being seen by …
2017-06-06 12:37:17 -07:00
Ramki Ananthakrishnan
7732aa02f2 Added null check before string comparison to fix crash being seen by offshore team. 2017-06-06 12:27:21 -07:00
Weston Schmidt
52e048b5ab Merge pull request #98 from gbuddappagari/master
Remove simple.c integration test cases
2017-06-06 05:43:44 -07:00
Gayathri
434c84773a Remove simple.c integration test cases 2017-06-06 16:32:32 +05:30
Weston Schmidt
03d420f8f7 Merge pull request #97 from sadhyama/master
Fixed parodus client reconnect issue due to delay in sending keep alive
2017-06-05 19:14:40 -07:00
Sadhyama Vengilat
5f2d73e0af Fixed parodus client reconnect issue due to delay in sending keep alive 2017-06-05 18:08:26 +05:30
Weston Schmidt
8909054630 Merge pull request #96 from sadhyama/master
Added signal handler for parodus
2017-05-17 08:52:21 -07:00
Sadhyama Vengilat
a7ad3d9ea0 Added signal handler for parodus 2017-05-16 19:18:38 +05:30
cableramki
dd868da93f Merge pull request #95 from cableramki/master
Added update to the seshat registration status flag.
2017-05-11 13:20:05 -07:00
Ramki Ananthakrishnan
6f57f6e7c4 Added update to the seshat registration status flag. 2017-05-11 13:18:15 -07:00
Weston Schmidt
bf65687658 Merge pull request #94 from cableramki/master
Added retry behavior to seshat registration.
2017-05-09 23:14:57 -07:00
Ramki Ananthakrishnan
f05c67197d Downgrade error message for registration till seshat is available on all platforms. 2017-05-09 18:08:30 -07:00
Ramki Ananthakrishnan
b029551ddd Added retry behavior to seshat registration. 2017-05-09 13:44:52 -07:00
Weston Schmidt
ef52fb77a6 Merge pull request #93 from sadhyama/master
Logs are modified as per webpa telemetry data
2017-05-09 10:15:35 -07:00
Sadhyama Vengilat
d24717e56e Logs are modified as per webpa telemetry data 2017-05-09 18:49:45 +05:30
Weston Schmidt
85c2ccb91b Merge pull request #92 from sadhyama/master
Added log for Last Reboot reason
2017-05-05 07:02:58 -07:00
Sadhyama Vengilat
aff39c7671 Added log for Last Reboot reason 2017-05-05 18:58:31 +05:30
Weston Schmidt
e324314c2d Merge pull request #90 from sadhyama/master
To fix nanomsg linking issue on fedora and ubuntu 32 bit
2017-04-26 09:11:13 -07:00
Sadhyama Vengilat
d67235b877 To fix nanomsg linking issue on fedura and ubuntu 32 bit 2017-04-26 14:40:54 +05:30
Weston Schmidt
d1c3bc6a0a Merge pull request #89 from sadhyama/master
To fix travis build failure due to log flooding
2017-04-21 00:35:09 -07:00
Sadhyama Vengilat
fdcdbbf430 To fix travis build failure due to log flooding 2017-04-21 12:11:19 +05:30
Weston Schmidt
a68b2b8913 Merge pull request #88 from gbuddappagari/master
Use valgrind for debugging
2017-04-19 13:22:14 -07:00
Gayathri
0c17727af7 Fix valgrind errors 2017-04-18 18:26:44 +05:30
Gayathri
9113ce1dee Integrate valgrind 2017-04-18 15:54:48 +05:30
111 changed files with 18172 additions and 3796 deletions

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

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

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

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

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

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

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

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

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

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

2
.gitignore vendored
View File

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

34
.sonar-project.properties Normal file
View File

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

View File

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

12
.whitesource Normal file
View File

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

119
CHANGELOG.md Normal file
View File

@@ -0,0 +1,119 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [v1.1.5]
- Add additional HTTP headers for call to Themis from Convey
- Change default branch name to `main`
## [v1.1.4]
- on connect retry, requery jwt only if it failed before
- put two timestamps in connection health file; start conn and current
- change health file update interval to 240sec
- use jitter in backoff delay
- sendMessage to check cloud status == ONLINE before sending
- when killed with SIGTERM, close will use msg in close reason file.
## [1.1.3]
- Add callback handler for ping status change event
- Fixed nopoll_conn_unref crash
- Update retry timestamp in connection-health-file
- fix so that parodus can be killed, even if in a connection fail loop
- provide signal handlers so we shut down properly when INCLUDE_BREAKPAD active
- send status code and reason in websocket close message
- dont try to install handler for signal 9
## [1.1.2]
- Add pause/resume heartBeatTimer
- parodus event handler to listen to interface_down and interface_up event
- Pause connection retry during interface_down event
## [1.1.1]
- Update to use nanomsg v. 1.1.4
- requestNewAuthToken will clear the token if it fails.
- request auth token on every retry, not just after 403
- update to use nopoll v 1.0.2
## [1.0.4]
- Fix re-registration fails that lose a socket
- Fix mutex error in service alive
- Security: Mutual Authentication (mTLS or two way TLS)
- Rename command line options for MTLS cert and Key
## [1.0.3]
- Security: Added support to use auth token during initial connect to cloud
## [1.0.2] - 2019-02-08
- Refactored connection.c and updated corresponding unit tests
- Additional `/cloud-status` and `/cloud-disconnect` fields.
- Switched from nanomsg (Release 1.1.2) to NNG (Release v1.0.1)
- Memory leak fixes
- Changed connection logic (connection.c) for retries, and added unit test
- Partner-id comparison made case insensitive
- Reverted from NNG to nanomag (v1.1.2)
- reverted temporary CMake reference to https://github.com/bill1600/seshat
- Added log for time difference of parodus connect time and boot time
- added NULL check for device mac id in upstream retrieve message handling
- backoff retry to include find_servers in loop (connection.c)
- backoff max is max count not max delay
- used mutex protection to make client list and nn_sends thread safe
- put mutex lock into get_global_node
- change svc alive from a thread to a function called every 30 sec from main
- shut down tasks properly
- fix memory leaks
- Fixed memory leak in upstream event message flow
- Fixed crash in CRUD request processing
- Fixed issue on RETRIEVE respone processing
- Enabled valgrind
- Fixed main loop to keep calling svc_alive_task during a cloud disconnect and retry
- change svc alive back to a separate thread. Shut it down with pthread_cond_timedwait
- Refactored Upsteam RETRIEVE flow
- Fix re-registration to call nn_shutdown and nn_close, so we don't lose a socket.
## [1.0.1] - 2018-07-18
### Added
- Added command line arguments for secure token read and acquire.
- DNS check for <device-id>.<URL> to allow custom device handling logic (like test boxes, refurbishing, etc).
- Add check for matching `partner-id` for incoming WRP messages based on command line argument passed.
- CRUD operations to local namespace is now supported.
- Via CRUD calls, the custom metadata tag values are now supported.
### Changed
- Configurable security flag and port.
- Default HTTP port to 80 and HTTPS port to 443.
- Updates to how `nopoll` is called have been implemented.
### Fixed
- 64 bit pointer fixes (#144, #145).
- Handle `403` error from talaria (#147).
- Several additional NULL pointer checks & recovery logic blocks added.
- A scenario where ping requests are not responded to was fixed.
### Security
- Added command line arguments for secure token read and acquire. Token presented to cloud for authentication verification.
- Added support for override functions to support drop root capabilities for parodus process
## [1.0.0] - 2017-11-17
### Added
- Added the basic implementation.
## [0.0.1] - 2016-08-15
### Added
- Initial creation
[Unreleased]: https://github.com/Comcast/parodus/compare/v1.1.5...HEAD
[1.1.5]: https://github.com/Comcast/parodus/compare/v1.1.4...v1.1.5
[1.1.4]: https://github.com/Comcast/parodus/compare/1.1.3...v1.1.4
[1.1.3]: https://github.com/Comcast/parodus/compare/1.1.2...1.1.3
[1.1.2]: https://github.com/Comcast/parodus/compare/1.1.1...1.1.2
[1.1.1]: https://github.com/Comcast/parodus/compare/1.0.4...1.1.1
[1.0.4]: https://github.com/Comcast/parodus/compare/1.0.3...1.0.4
[1.0.3]: https://github.com/Comcast/parodus/compare/1.0.2...1.0.3
[1.0.2]: https://github.com/Comcast/parodus/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/Comcast/parodus/compare/1.0.0...1.0.1
[1.0.0]: https://github.com/Comcast/parodus/compare/79fa7438de2b14ae64f869d52f5c127497bf9c3f...1.0.0

BIN
CLA.pdf

Binary file not shown.

View File

@@ -14,6 +14,7 @@
cmake_minimum_required(VERSION 2.8.7)
#project(parodus VERSION 1.1.5)
project(parodus)
include(ExternalProject)
@@ -22,6 +23,8 @@ include(CTest)
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})
@@ -32,12 +35,24 @@ 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
${INCLUDE_DIR}/cimplog
${INCLUDE_DIR}/libseshat
)
${INCLUDE_DIR}/cjwt
)
# Get git commit hash
#-------------------------------------------------------------------------------
execute_process(
COMMAND git describe --tags --always
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_TAG
OUTPUT_STRIP_TRAILING_WHITESPACE
)
add_definitions("-DGIT_COMMIT_TAG=\"${GIT_COMMIT_TAG}\"")
# Compile options/flags
#-------------------------------------------------------------------------------
@@ -59,8 +74,8 @@ 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 "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
GIT_TAG "v1.1.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libtrower-base64 STATIC SHARED IMPORTED)
add_dependencies(libtrower-base64 trower-base64)
@@ -68,20 +83,11 @@ add_dependencies(libtrower-base64 trower-base64)
# nopoll external dependency
#-------------------------------------------------------------------------------
set(PATCHES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/patches)
set(NOPOLL_LOG_SRC ${PREFIX_DIR}/nopoll/src/nopoll/src/nopoll_log.c)
ExternalProject_Add(nopoll
PREFIX ${PREFIX_DIR}/nopoll
GIT_REPOSITORY https://github.com/ASPLes/nopoll.git
GIT_TAG "b18aacc06b4dc9700e0a261efc201a8e125e4328"
PATCH_COMMAND patch -p1 < ${PATCHES_DIR}/nopoll.patch
COMMAND touch NEWS README AUTHORS ChangeLog
COMMAND libtoolize --force
COMMAND aclocal
COMMAND autoheader --warnings=error
COMMAND automake --add-missing -Werror
COMMAND autoconf --force --warnings=error
CONFIGURE_COMMAND COMMAND <SOURCE_DIR>/configure --prefix=${PREFIX}
GIT_REPOSITORY https://github.com/Comcast/nopoll.git
GIT_TAG "1.0.2"
CONFIGURE_COMMAND COMMAND <SOURCE_DIR>/autogen.sh --prefix=${PREFIX}
--includedir=${INCLUDE_DIR}
--libdir=${LIBRARY_DIR}
${CUSTOM_HOST}
@@ -96,7 +102,7 @@ add_dependencies(libnopoll nopoll)
ExternalProject_Add(nanomsg
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/nanomsg
GIT_REPOSITORY https://github.com/nanomsg/nanomsg.git
#GIT_TAG "096998834451219ee7813d8977f6a4027b0ccb43"
GIT_TAG "1.1.4"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libnanomsg STATIC SHARED IMPORTED)
@@ -109,8 +115,8 @@ 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"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
GIT_TAG "v1.7.8"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcJSON STATIC SHARED IMPORTED)
add_dependencies(libcJSON cJSON)
@@ -121,7 +127,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 "c6e6dbc608366090c12b142b3832604e6aa12f54"
GIT_TAG "cpp-3.1.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
-DMSGPACK_ENABLE_CXX=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
@@ -130,13 +136,25 @@ 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 "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
GIT_TAG "1.0.2"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcimplog STATIC SHARED IMPORTED)
add_dependencies(libcimplog cimplog)
@@ -145,45 +163,79 @@ add_dependencies(libcimplog cimplog)
# wrp-c external dependency
#-------------------------------------------------------------------------------
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 "master"
GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
-DMSGPACK_ENABLE_CXX=OFF
-DMSGPACK_BUILD_EXAMPLES=OFF
-DBUILD_TESTING=OFF
-DMAIN_PROJ_BUILD=ON
-DMAIN_PROJ_LIB_PATH=${LIBRARY_DIR}
-DMAIN_PROJ_INCLUDE_PATH=${INCLUDE_DIR}
)
add_library(libwrp-c STATIC SHARED IMPORTED)
add_dependencies(libwrp-c wrp-c)
# libparodus external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(libparodus
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/libparodus
GIT_REPOSITORY https://github.com/Comcast/libparodus.git
GIT_TAG "master"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(liblibparodus STATIC SHARED IMPORTED)
add_dependencies(liblibparodus libparodus)
if (ENABLE_SESHAT)
# libseshat external dependency
#-------------------------------------------------------------------------------
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
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
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}
-DMAIN_PROJ_LIB64_PATH=${LIBRARY_DIR64}
-DMAIN_PROJ_COMMON_PATH=${COMMON_LIBRARY_DIR}
-DMAIN_PROJ_INCLUDE_PATH=${INCLUDE_DIR}
)
add_library(liblibseshat STATIC SHARED IMPORTED)
add_dependencies(liblibseshat libseshat)
include_directories(${INCLUDE_DIR}/libseshat)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_SESHAT ")
endif (ENABLE_SESHAT)
# libcjwt external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(cjwt
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cjwt
GIT_REPOSITORY https://github.com/Comcast/cjwt.git
GIT_TAG "1b023c41bb2d6dbbf493c202ed81f06c84d5b51b"
#GIT_TAG "1.0.1"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF
)
add_library(libcjwt STATIC SHARED IMPORTED)
add_dependencies(libcjwt cjwt)
if (FEATURE_DNS_QUERY)
# libucresolv external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(ucresolv
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/ucresolv
GIT_REPOSITORY https://github.com/Comcast/libucresolv.git
GIT_TAG "1.0.0"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libucresolv STATIC SHARED IMPORTED)
add_dependencies(libucresolv ucresolv)
include_directories(${INCLUDE_DIR}
${INCLUDE_DIR}/ucresolv
)
endif (FEATURE_DNS_QUERY)
if (BUILD_TESTING)
# cmocka external dependency
#-------------------------------------------------------------------------------
ExternalProject_Add(cmocka
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/_prefix/cmocka
GIT_REPOSITORY https://git.cryptomilk.org/projects/cmocka.git
GIT_TAG "master"
GIT_REPOSITORY https://github.com/elventear/cmocka.git
GIT_TAG "b71a3060699bc1a5b00e958be353772f42545ac2"
CMAKE_ARGS += -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR}
)
add_library(libcmocka STATIC SHARED IMPORTED)
@@ -191,7 +243,15 @@ add_dependencies(libcmocka cmocka)
endif (BUILD_TESTING)
endif ()
endif () # NOT BUILD_YOCTO
if (BUILD_YOCTO)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DBUILD_YOCTO ")
endif (BUILD_YOCTO)
if (FEATURE_DNS_QUERY)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DFEATURE_DNS_QUERY ")
endif (FEATURE_DNS_QUERY)
link_directories ( ${LIBRARY_DIR} ${COMMON_LIBRARY_DIR} ${LIBRARY_DIR64} )
add_subdirectory(src)

View File

@@ -1,5 +1,31 @@
If you would like to contribute code to this project you can do so
through GitHub by forking the repository and sending a pull request.
Contribution Guidelines
=======================
Before Comcast accepts your code into the project you must sign the
Comcast Contributor License Agreement ('CLA.pdf').
We love to see contributions to the project and have tried to make it easy to do so. If you would like to contribute code to this project you can do so through GitHub by forking the repository and sending a pull request.
Before Comcast merges your code into the project you must sign the [Comcast Contributor License Agreement (CLA)](https://gist.github.com/ComcastOSS/a7b8933dd8e368535378cda25c92d19a).
If you haven't previously signed a Comcast CLA, you'll automatically be asked to when you open a pull request. Alternatively, we can e-mail you a PDF that you can sign and scan back to us. Please send us an e-mail or create a new GitHub issue to request a PDF version of the CLA.
For more details about contributing to GitHub projects see
http://gun.io/blog/how-to-github-fork-branch-and-pull-request/
Documentation
-------------
If you contribute anything that changes the behavior of the
application, document it in the [README](https://github.com/Comcast/parodus/blob/master/README.md) or [wiki](https://github.com/Comcast/parodus/wiki)! This includes new features, additional variants of behavior and breaking changes.
Testing
-------
Tests are written using golang's standard testing tools, and are run prior to the PR being accepted.
Pull Requests
-------------
* should be narrowly focused with no more than 3 or 4 logical commits
* when possible, address no more than one issue
* should be reviewable in the GitHub code review tool
* should be linked to any issues it relates to (i.e. issue number after (#) in commit messages or pull request message)
* should conform to idiomatic golang code formatting

16
NOTICE Normal file
View File

@@ -0,0 +1,16 @@
parodus
Copyright 2017 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.
This product includes software developed at Comcast (http://www.comcast.com/).

103
README.md
View File

@@ -1,11 +1,22 @@
<!--
SPDX-FileCopyrightText: 2016-2021 Comcast Cable Communications Management, LLC
SPDX-License-Identifier: Apache-2.0
-->
# parodus
C implementation of the WebPA client coordinator
[![Build Status](https://travis-ci.org/Comcast/parodus.svg?branch=master)](https://travis-ci.org/Comcast/parodus)
[![codecov.io](http://codecov.io/github/Comcast/parodus/coverage.svg?branch=master)](http://codecov.io/github/Comcast/parodus?branch=master)
[![Build Status](https://github.com/xmidt-org/parodus/workflows/CI/badge.svg)](https://github.com/xmidt-org/parodus/actions)
[![codecov.io](http://codecov.io/github/xmidt-org/parodus/coverage.svg?branch=master)](http://codecov.io/github/xmidt-org/parodus?branch=master)
[![Coverity](https://img.shields.io/coverity/scan/11192.svg)](https://scan.coverity.com/projects/comcast-parodus)
[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/Comcast/parodus/blob/master/LICENSE)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=xmidt-org_parodus&metric=alert_status)](https://sonarcloud.io/dashboard?id=xmidt-org_parodus)
[![Language Grade: C/C++](https://img.shields.io/lgtm/grade/cpp/g/xmidt-org/parodus.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/xmidt-org/parodus/context:cpp)
[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/xmidt-org/parodus/blob/master/LICENSE)
[![GitHub release](https://img.shields.io/github/release/xmidt-org/parodus.svg)](CHANGELOG.md)
C implementation of the XMiDT client coordinator
XMiDT is a highly scalable, highly available, generic message routing system.
# Building and Testing Instructions
```
@@ -15,3 +26,85 @@ cmake ..
make
make test
```
# Command line Arguments needed to start parodus
```
- /hw-model -The hardware model name.
- /hw-serial-number -The serial number.
- /hw-manufacturer -The device manufacturer.
- /hw-mac -The MAC address used to manage the device.
- /hw-last-reboot-reason -The last known reboot reason.
- /fw-name -The firmware name.
- /boot-time -The boot time in unix time.
- /webpa-url -The URL that the WRP client should reach out to. (required). Must begin with 'https://' or 'http://'. May end with a port number. If no port specified, then 443 is assumed for https, 80 for http.
- /webpa-backoff-max -The maximum value of c in the binary backoff algorithm
- /webpa-ping-timeout -The maximum time to wait between pings before assuming the connection is broken.
- /webpa-interface-used -The device interface being used to connect to the cloud.
- /parodus-local-url -Parodus local server url (optional argument)
- /partner-id - Partner ID of broadband gateway (optional argument)
- /ssl-cert-path -Provide the certs for establishing secure connection (optional argument)
- /force-ipv4 -Forcefully connect parodus to ipv4 address (optional argument)
- /force-ipv6 -Forcefully connect parodus to ipv6 address (optional argument)
- /client-cert-path -MTLS client cert location to request auth token for establishing secure connection [absolute path where client cert is present] (optional argument)
- /token-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
# if ENABLE_SESHAT is enabled
- /seshat-url - The seshat server url
# if FEATURE_DNS_QUERY is enabled then below mentioned arguments are needed
- /acquire-jwt - this parameter (0 or 1) specifies whether there will be a dns lookup. If not, or if any problem occurs with the dns lookup, then webpa-url will be the target.
- /dns-txt-url - this parameter is used along with the hw_mac parameter to create the dns txt record id
- /jwt-algo -Allowed algorithm used for communication
- /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:
```
# Seshat & FEATURE_DNS_QUERY Enabled
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=https://somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --acquire-jwt=1 --dns-txt-url=somebody.net --jwt-public-key-file=webpa-rs256.pem --jwt-algo=RS256 --seshat-url=tcp://127.0.0.1:7777 --client-cert-path=/tmp/clientcert.mch --token-server-url=https://somebody.net:8080/token --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
# Seshat is not enabled
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=https://somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --acquire-jwt=1 --dns-txt-url=somebody.net --jwt-public-key-file=webpa-rs256.pem --jwt-algo=RS256 --client-cert-path=/tmp/clientcert.mch --token-server-url=https://somebody.net:8080/token --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
# When both Seshat & FEATURE_DNS_QUERY not Enabled
./parodus --hw-model=TGXXX --hw-serial-number=E8GBUEXXXXXXXXX --hw-manufacturer=ARRIS --hw-mac=14cfexxxxxxx --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_20170512115046sdy --boot-time=1494590301 --webpa-ping-timeout=180 --webpa-interface-used=eth0 --webpa-url=https://somebody.net:8080 --webpa-backoff-max=9 --parodus-local-url=tcp://127.0.0.1:6666 --partner-id=comcast --ssl-cert-path=/etc/ssl/certs/ca-certificates.crt --client-cert-path=/tmp/clientcert.mch --token-server-url=https://somebody.net:8080/token --force-ipv4 --crud-config-file=/tmp/parodus_cfg.json
```

File diff suppressed because it is too large Load Diff

View File

@@ -11,8 +11,18 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set(SOURCES main.c mutex.c networking.c nopoll_helpers.c nopoll_handlers.c ParodusInternal.c
string_helpers.c time.c config.c conn_interface.c connection.c spin_thread.c client_list.c service_alive.c upstream.c downstream.c thread_tasks.c partners_check.c)
set(SOURCES main.c mutex.c networking.c nopoll_helpers.c heartBeat.c nopoll_handlers.c
ParodusInternal.c string_helpers.c time.c config.c conn_interface.c
connection.c spin_thread.c client_list.c service_alive.c
upstream.c downstream.c thread_tasks.c partners_check.c token.c event_handler.c
crud_interface.c crud_tasks.c crud_internal.c close_retry.c auth_token.c privilege.c)
if (ENABLE_SESHAT)
set(SOURCES ${SOURCES} seshat_interface.c)
else()
set(SOURCES ${SOURCES} seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(parodus ${SOURCES})
@@ -20,9 +30,9 @@ target_link_libraries (parodus
${CMAKE_THREAD_LIBS_INIT}
-lwrp-c
-lmsgpackc
-lcurl
-ltrower-base64
-lnopoll
-llibseshat
-luuid
-lm
-lcimplog
@@ -30,7 +40,18 @@ target_link_libraries (parodus
-lcrypto
-lnanomsg
-lcjson
-lcjwt
-lpthread
-lrt
)
if (FEATURE_DNS_QUERY)
target_link_libraries (parodus -lucresolv -lresolv)
endif (FEATURE_DNS_QUERY)
if (ENABLE_SESHAT)
target_link_libraries (parodus -llibseshat)
endif (ENABLE_SESHAT)
install (TARGETS parodus DESTINATION bin)

View File

@@ -1,15 +1,35 @@
/**
* 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 ParodusInternal.c
*
* @description This file is used to manage internal functions of parodus
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
#include "config.h"
#include "connection.h"
bool interface_down_event = false;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t interface_down_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -72,6 +92,10 @@ char* getWebpaConveyHeader()
ParodusError("Failed to GET Reconnect reason value\n");
}
if(get_parodus_cfg()->boot_retry_wait > 0)
{
cJSON_AddNumberToObject(response, BOOT_RETRY_WAIT, get_parodus_cfg()->boot_retry_wait);
}
buffer = cJSON_PrintUnformatted(response);
ParodusInfo("X-WebPA-Convey Header: [%zd]%s\n", strlen(buffer), buffer);
@@ -97,6 +121,91 @@ char* getWebpaConveyHeader()
encodedData[j]='\0';
ParodusPrint("Encoded X-WebPA-Convey Header: [%zd]%s\n", strlen(encodedData), encodedData);
}
free(buffer);
cJSON_Delete(response);
return encodedData;
if( 0 < strlen(encodedData) ) {
return encodedData;
}
return NULL;
}
int readFromFile(const char *file_name, char **data)
{
FILE *fp;
int ch_count = 0;
fp = fopen(file_name, "r+");
if (fp == NULL)
{
ParodusError("Failed to open file %s (errno %d)\n", file_name, errno);
return 0;
}
fseek(fp, 0, SEEK_END);
ch_count = ftell(fp);
fseek(fp, 0, SEEK_SET);
*data = (char *) malloc(sizeof(char) * (ch_count + 1));
fread(*data, 1, ch_count,fp);
(*data)[ch_count] ='\0';
fclose(fp);
return 1;
}
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *diff)
{
if ((stop->tv_nsec - start->tv_nsec) < 0) {
diff->tv_sec = stop->tv_sec - start->tv_sec - 1;
diff->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000UL;
} else {
diff->tv_sec = stop->tv_sec - start->tv_sec;
diff->tv_nsec = stop->tv_nsec - start->tv_nsec;
}
return;
}
/*------------------------------------------------------------------------------*/
/* For interface_down_event Flag */
/*------------------------------------------------------------------------------*/
// Get value of interface_down_event
bool get_interface_down_event()
{
bool tmp = false;
pthread_mutex_lock (&interface_down_mut);
tmp = interface_down_event;
pthread_mutex_unlock (&interface_down_mut);
return tmp;
}
// Reset value of interface_down_event to false
void reset_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = false;
pthread_cond_signal(&interface_down_con);
pthread_mutex_unlock (&interface_down_mut);
}
// set value of interface_down_event to true
void set_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = true;
pthread_mutex_unlock (&interface_down_mut);
}
pthread_cond_t *get_interface_down_con(void)
{
return &interface_down_con;
}
pthread_mutex_t *get_interface_down_mut(void)
{
return &interface_down_mut;
}

View File

@@ -1,9 +1,24 @@
/**
* 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 ParodusInternal.h
*
* @description This file is used to manage internal functions of parodus
*
* Copyright (c) 2015 Comcast
*/
#ifndef _PARODUSINTERNAL_H_
#define _PARODUSINTERNAL_H_
@@ -34,8 +49,10 @@
/*----------------------------------------------------------------------------*/
/* 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
@@ -44,6 +61,12 @@ extern int numLoops;
#define FOREVER() numLoops--
#endif
// Return values for find_servers() in connection.c
#define FIND_SUCCESS 0
#define FIND_INVALID_DEFAULT -2
#define FIND_JWT_FAIL -1
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
@@ -56,12 +79,66 @@ typedef struct ParodusMsg__
struct ParodusMsg__ *next;
} ParodusMsg;
// Used in token.c to get jwt from dns server
typedef struct {
const char *rr_ptr;
int rr_len;
} rr_rec_t;
//------------ Used in comnection.c -----------------
typedef struct {
int allow_insecure;
char *server_addr; // must be freed
unsigned int port;
} server_t;
typedef struct {
server_t defaults; // from command line
server_t jwt; // from jwt endpoint claim
server_t redirect; // from redirect response to
// nopoll_conn_wait_until_connection_ready
} server_list_t;
//---- Used in connection.c for expire timer
typedef struct {
int running;
struct timespec start_time;
struct timespec end_time;
} expire_timer_t;
//--- Used in connection.c for backoff delay timer
typedef struct {
unsigned long start_time;
struct timespec ts;
int count;
int max_count;
int delay;
} backoff_timer_t;
//--- Used in connection.c for init_header_info
typedef struct {
char *conveyHeader; // Do not free
char *device_id; // Need to free
char *user_agent; // Need to free
} header_info_t;
// connection context which is defined in createNopollConnection
// and passed into functions keep_retrying_connect, connect_and_wait,
// wait_connection_ready, and nopoll_connect
typedef struct {
noPollCtx *nopoll_ctx;
server_list_t *server_list;
server_t *current_server;
header_info_t header_info;
char *extra_headers; // need to be freed
expire_timer_t connect_timer;
} create_connection_ctx_t;
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
extern bool LastReasonStatus;
extern bool g_shutdown;
extern ParodusMsg *ParodusMsgQ;
int numLoops;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
@@ -76,6 +153,33 @@ void parStrncpy(char *destStr, const char *srcStr, size_t destSize);
char* getWebpaConveyHeader();
void *CRUDHandlerTask();
void addCRUDmsgToQueue(wrp_msg_t *crudMsg);
int readFromFile(const char *file_name, char **data);
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result);
/*------------------------------------------------------------------------------*/
/* For interface_down_event Flag */
/*------------------------------------------------------------------------------*/
// Get value of interface_down_event
bool get_interface_down_event();
// Reset value of interface_down_event to false
void reset_interface_down_event();
// Set value of interface_down_event to true
void set_interface_down_event();
pthread_cond_t *get_interface_down_con();
pthread_mutex_t *get_interface_down_mut();
#ifdef __cplusplus
}
#endif

320
src/auth_token.c Normal file
View File

@@ -0,0 +1,320 @@
/**
* 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 "connection.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 256
#define CURL_TIMEOUT_SEC 25L
#define MAX_CURL_RETRY_COUNT 3
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
void createCurlheader(struct curl_slist *list, struct curl_slist **header_list);
long g_response_code;
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int getGlobalResponseCode()
{
return g_response_code;
}
/*
* @brief Initialize curl object with required options. create newToken using libcurl.
* @param[out] newToken auth token string obtained from JWT curl response
* @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;
double total;
struct token_data data;
data.size = 0;
data.data = newToken;
curl = curl_easy_init();
if(curl)
{
data.data[0] = '\0';
createCurlheader(list, &headers_list);
curl_easy_setopt(curl, CURLOPT_URL, get_parodus_cfg()->token_server_url);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT_SEC);
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, &g_response_code);
ParodusInfo("themis curl response %d http_code %d\n", res, g_response_code);
time_res = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total);
if(time_res == 0)
{
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(getGlobalResponseCode() == 200)
{
ParodusInfo("cURL success\n");
}
else
{
ParodusError("Failed response from auth token server %s\n", data.data);
curl_easy_cleanup(curl);
data.size = 0;
memset (data.data, 0, len);
return -1;
}
}
curl_easy_cleanup(curl);
}
else
{
ParodusError("curl init failure\n");
data.size = 0;
memset (data.data, 0, len);
return -1;
}
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] h the auth headers to populate
* @param[in] list temp curl header list
* @param[out] header_list output curl header list
*/
void createCurlheader(struct curl_slist *list, struct curl_slist **header_list)
{
char buf[MAX_BUF_SIZE];
char *uuid = NULL;
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Mac-Address: %s", get_parodus_cfg()->hw_mac);
ParodusPrint("mac_header formed %s\n", buf);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Serial-Number: %s", get_parodus_cfg()->hw_serial_number);
ParodusPrint("serial_header formed %s\n", buf);
list = curl_slist_append(list, buf);
uuid = generate_trans_uuid();
if(uuid !=NULL) {
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Uuid: %s", uuid);
ParodusInfo("uuid_header formed %s\n", buf);
list = curl_slist_append(list, buf);
free(uuid);
} else {
ParodusError("Failed to generate transaction_uuid\n");
}
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Partner-Id: %s", get_parodus_cfg()->partner_id);
ParodusInfo("partnerid_header formed %s\n", buf);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Hardware-Model: %s", get_parodus_cfg()->hw_model);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Hardware-Manufacturer: %s", get_parodus_cfg()->hw_manufacturer);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Firmware-Name: %s", get_parodus_cfg()->fw_name);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Protocol: %s", get_parodus_cfg()->webpa_protocol);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Interface-Used: %s", get_parodus_cfg()->webpa_interface_used);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Last-Reboot-Reason: %s", get_parodus_cfg()->hw_last_reboot_reason);
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Last-Reconnect-Reason: %s", get_global_reconnect_reason());
list = curl_slist_append(list, buf);
snprintf(buf, MAX_BUF_SIZE, "X-Midt-Boot-Retry-Wait: %d", get_parodus_cfg()->boot_retry_wait);
list = curl_slist_append(list, buf);
*header_list = list;
}

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

@@ -1,9 +1,24 @@
/**
* 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 client_list.h
*
* @description This file is used to manage registered clients
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
@@ -15,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 */
@@ -22,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;
@@ -37,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)
{
@@ -52,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
@@ -63,15 +91,15 @@ 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);
ParodusPrint("(*msg)->u.reg.service_name is %s\n", (*msg)->u.reg.service_name);
ParodusPrint("(*msg)->u.reg.url is %s\n", (*msg)->u.reg.url);
strncpy(new_node->service_name, (*msg)->u.reg.service_name, strlen((*msg)->u.reg.service_name)+1);
strncpy(new_node->url, (*msg)->u.reg.url, strlen((*msg)->u.reg.url)+1);
parStrncpy(new_node->service_name, (*msg)->u.reg.service_name, sizeof(new_node->service_name));
parStrncpy(new_node->url, (*msg)->u.reg.url, sizeof(new_node->url));
new_node->next=NULL;
if (g_head == NULL) //adding first client
@@ -196,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;
}
@@ -210,3 +248,70 @@ int deleteFromList(char* service_name)
ParodusError("Could not find the entry to delete from list\n");
return -1;
}
void deleteAllClients (void)
{
reg_list_item_t *next_node = NULL;
while (NULL != g_head)
{
next_node = g_head->next;
free (g_head);
g_head = next_node;
}
if (numOfClients > 0) {
ParodusInfo ("Deleted %d clients\n", numOfClients);
numOfClients = 0;
}
}
/*
*@dest : Client destination to send message
*@Msg: Msg to send it to client (No free done here), user responsibilites to free the msg
*@msgSize : Total size of the msg to send to client
*/
int sendMsgtoRegisteredClients(char *dest,const char **Msg,size_t msgSize)
{
int bytes =0;
reg_list_item_t *temp = NULL;
temp = get_global_node();
//Checking for individual clients & Sending msg to registered client
while (NULL != temp)
{
ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
// Sending message to registered clients
if( strcmp(dest, temp->service_name) == 0)
{
bytes = nn_send(temp->sock, *Msg, msgSize, 0);
release_global_node ();
ParodusInfo("sent downstream message to reg_client '%s'\n", temp->url);
ParodusPrint("downstream bytes sent:%d\n", bytes);
return 1;
}
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
release_global_node ();
return 0;
}
//To check client registration status with parodus.
int checkClientStatus(char *serviceName)
{
reg_list_item_t *temp = NULL;
temp = get_global_node();
while (NULL != temp)
{
ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
// Sending message to registered clients
if( strcmp(serviceName, temp->service_name) == 0)
{
release_global_node ();
return 1;
}
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
release_global_node ();
return 0;
}

View File

@@ -1,9 +1,24 @@
/**
* 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 client_list.h
*
* @description This file is used to manage registered clients
*
* Copyright (c) 2015 Comcast
*/
#ifndef _CLIENTLIST_H_
#define _CLIENTLIST_H_
@@ -15,6 +30,7 @@
typedef struct reg_list_item
{
int sock;
int endpoint;
char service_name[32];
char url[100];
struct reg_list_item *next;
@@ -35,9 +51,12 @@ 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);
int checkClientStatus();
#ifdef __cplusplus
}
#endif

56
src/close_retry.c Normal file
View File

@@ -0,0 +1,56 @@
/**
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file close_retry.c
*
* @description Functions required to manage connection close retry.
*
*/
#include "close_retry.h"
bool close_retry = false;
pthread_mutex_t close_mut=PTHREAD_MUTEX_INITIALIZER;
// Get value of close_retry
bool get_close_retry()
{
bool tmp = false;
pthread_mutex_lock (&close_mut);
tmp = close_retry;
pthread_mutex_unlock (&close_mut);
return tmp;
}
// Reset value of close_retry to false
void reset_close_retry()
{
pthread_mutex_lock (&close_mut);
close_retry = false;
pthread_mutex_unlock (&close_mut);
}
// set value of close_retry to true
void set_close_retry()
{
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
}

47
src/close_retry.h Normal file
View File

@@ -0,0 +1,47 @@
/**
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file close_retry.h
*
* @description Functions required to manage connection close retry.
*
*/
#ifndef _CLOSERETRY_H_
#define _CLOSERETRY_H_
#include <pthread.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// Get value of close_retry
bool get_close_retry();
// Reset value of close_retry to false
void reset_close_retry();
// Set value of close_retry to true
void set_close_retry();
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,20 +1,42 @@
/**
* @file config.h
* 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 config.c
*
* @description This file contains configuration details of parodus
*
* Copyright (c) 2015 Comcast
*/
#include <stdio.h>
#include <fcntl.h>
#include "config.h"
#include "ParodusInternal.h"
#include <cjwt/cjwt.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <uuid/uuid.h>
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
static ParodusCfg parodusCfg;
static unsigned int rsa_algorithms =
(1<<alg_rs256) | (1<<alg_rs384) | (1<<alg_rs512);
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -26,35 +48,362 @@ ParodusCfg *get_parodus_cfg(void)
void set_parodus_cfg(ParodusCfg *cfg)
{
parodusCfg = *cfg;
memcpy(&parodusCfg, cfg, sizeof(ParodusCfg));
}
void parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
void set_cloud_disconnect_reason(ParodusCfg *cfg, char *disconn_reason)
{
int c;
cfg->cloud_disconnect = strdup(disconn_reason);
}
void reset_cloud_disconnect_reason(ParodusCfg *cfg)
{
cfg->cloud_disconnect = NULL;
}
const char *get_tok (const char *src, int delim, char *result, int resultsize)
{
int i;
char c;
int endx = resultsize-1;
memset (result, 0, resultsize);
for (i=0; (c=src[i]) != 0; i++) {
if (c == delim)
break;
if (i < endx)
result[i] = c;
}
if (c == 0)
return NULL;
return src + i + 1;
}
// the algorithm mask indicates which algorithms are allowed
unsigned int get_algo_mask (const char *algo_str)
{
unsigned int mask = 0;
unsigned int mask_val;
#define BUFLEN 16
char tok[BUFLEN];
int alg_val;
while(NULL != algo_str)
{
algo_str = get_tok (algo_str, ':', tok, BUFLEN);
alg_val = cjwt_alg_str_to_enum (tok);
if ((alg_val < 0) || (alg_val >= num_algorithms)) {
ParodusError("Invalid jwt algorithm %s\n", tok);
return (unsigned int) (-1);
}
if (alg_val == alg_none) {
ParodusError("Disallowed jwt algorithm none\n");
return (unsigned int) (-1);
}
mask_val = (1<<alg_val);
#if !ALLOW_NON_RSA_ALG
if (0 == (mask_val & rsa_algorithms)) {
ParodusError("Disallowed non-rsa jwt algorithm %s\n", tok);
return (unsigned int) (-1);
}
#endif
mask |= mask_val;
}
return mask;
#undef BUFLEN
}
static int open_input_file (const char *fname)
{
int fd = open(fname, O_RDONLY);
if (fd<0)
{
ParodusError ("File %s open error\n", fname);
abort ();
}
return fd;
}
void read_key_from_file (const char *fname, char *buf, size_t buflen)
{
ssize_t nbytes;
int fd = open_input_file(fname);
nbytes = read(fd, buf, buflen);
if (nbytes < 0)
{
ParodusError ("Read file %s error\n", fname);
close(fd);
abort ();
}
close(fd);
ParodusInfo ("%d bytes read\n", nbytes);
}
// strips ':' characters
// verifies that there exactly 12 characters
int parse_mac_address (char *target, const char *arg)
{
int count = 0;
int i;
char c;
for (i=0; (c=arg[i]) != 0; i++) {
if (c !=':')
count++;
}
if (count != 12)
return -1; // bad mac address
for (i=0; (c=arg[i]) != 0; i++) {
if (c != ':')
*(target++) = c;
}
*target = 0; // terminating null
return 0;
}
int server_is_http (const char *full_url,
const char **server_ptr)
{
int http_match;
const char *ptr;
if (strncmp(full_url, "https://", 8) == 0) {
http_match = 0;
ptr = full_url + 8;
} else if (strncmp(full_url, "http://", 7) == 0) {
http_match = 1;
ptr = full_url + 7;
} else {
ParodusError ("Invalid url %s\n", full_url);
return -1;
}
if (NULL != server_ptr)
*server_ptr = ptr;
return http_match;
}
int parse_webpa_url__ (const char *full_url,
char *server_addr, int server_addr_buflen,
char *port_buf, int port_buflen)
{
const char *server_ptr;
char *port_val;
char *end_port;
size_t server_len;
int http_match;
char *closeBracket = NULL;
char *openBracket = NULL;
char *checkPort = NULL;
ParodusInfo ("full url: %s\n", full_url);
http_match = server_is_http (full_url, &server_ptr);
if (http_match < 0)
return http_match;
ParodusInfo ("server address copied from url\n");
parStrncpy (server_addr, server_ptr, server_addr_buflen);
server_len = strlen(server_addr);
// If there's a '/' on end, null it out
if ((server_len>0) && (server_addr[server_len-1] == '/'))
server_addr[server_len-1] = '\0';
openBracket = strchr(server_addr,'[');
if(openBracket != NULL){
//Remove [ from server address
char *remove = server_addr;
int i;
// Strings can overlap, so don't use strncpy()
remove++;
for( i = 0; i < server_addr_buflen; i++ ) {
server_addr[i] = remove[i];
}
closeBracket = strchr(server_addr,']');
if(closeBracket != NULL){
//Remove ] by making it as null
*closeBracket = '\0';
closeBracket++;
checkPort = strchr(closeBracket,':');
if (NULL == checkPort) {
if (http_match)
parStrncpy (port_buf, "80", port_buflen);
else
parStrncpy (port_buf, "443", port_buflen);
} else {
checkPort++;
end_port = strchr (checkPort, '/');
if (NULL != end_port)
*end_port = '\0'; // terminate port with null
parStrncpy (port_buf, checkPort, port_buflen);
}
}else{
ParodusError("Invalid url %s\n", full_url);
return -1;
}
}else if (strchr(server_addr,']') != NULL ){
ParodusError("Invalid url %s\n", full_url);
return -1;
}else{
// Look for ':'
port_val = strchr (server_addr, ':');
if (NULL == port_val) {
if (http_match)
parStrncpy (port_buf, "80", port_buflen);
else
parStrncpy (port_buf, "443", port_buflen);
end_port = strchr (server_addr, '/');
if (NULL != end_port) {
*end_port = '\0'; // terminate server address with null
}
} else {
*port_val = '\0'; // terminate server address with null
port_val++;
end_port = strchr (port_val, '/');
if (NULL != end_port)
*end_port = '\0'; // terminate port with null
parStrncpy (port_buf, port_val, port_buflen);
}
}
ParodusInfo ("server %s, port %s, http_match %d\n",
server_addr, port_buf, http_match);
return http_match;
}
unsigned int parse_num_arg (const char *arg, const char *arg_name)
{
unsigned int result = 0;
int i;
char c;
if (arg[0] == '\0') {
ParodusError ("Empty %s argument\n", arg_name);
return (unsigned int) -1;
}
for (i=0; '\0' != (c=arg[i]); i++)
{
if ((c<'0') || (c>'9')) {
ParodusError ("Non-numeric %s argument\n", arg_name);
return (unsigned int) -1;
}
result = (result*10) + c - '0';
}
return result;
}
int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port)
{
int allow_insecure;
unsigned int port_val;
int buflen = strlen (full_url) + 1;
char *url_buf = NULL;
char port_buf[8];
#define ERROR__(msg) \
ParodusError (msg); \
if (NULL != url_buf) \
free (url_buf);
*server_addr = NULL;
url_buf = (char *) malloc (buflen);
if (NULL == url_buf) {
ERROR__ ("parse_webpa_url allocatio n failed.\n")
return -1;
}
allow_insecure = parse_webpa_url__ (full_url,
url_buf, buflen, port_buf, 8);
if (allow_insecure < 0) {
ERROR__ ("parse_webpa_url invalid url\n")
return -1;
}
port_val = parse_num_arg (port_buf, "server port");
if (port_val == (unsigned int) -1) {
ERROR__ ("Invalid port in server url")
return -1;
}
if ((port_val == 0) || (port_val > 65535)) {
ERROR__ ("port value out of range in server url")
return -1;
}
*server_addr = url_buf;
*port = port_val;
return allow_insecure;
#undef ERROR__
}
int parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
{
static const struct option long_options[] = {
{"hw-model", required_argument, 0, 'm'},
{"hw-serial-number", required_argument, 0, 's'},
{"hw-manufacturer", required_argument, 0, 'f'},
{"hw-mac", required_argument, 0, 'd'},
{"hw-last-reboot-reason", required_argument, 0, 'r'},
{"fw-name", required_argument, 0, 'n'},
{"boot-time", required_argument, 0, 'b'},
{"webpa-url", required_argument, 0, 'u'},
{"webpa-ping-timeout", required_argument, 0, 't'},
{"webpa-backoff-max", required_argument, 0, 'o'},
{"webpa-interface-used", required_argument, 0, 'i'},
{"parodus-local-url", required_argument, 0, 'l'},
{"partner-id", required_argument, 0, 'p'},
#ifdef ENABLE_SESHAT
{"seshat-url", required_argument, 0, 'e'},
#endif
{"dns-txt-url", required_argument, 0, 'D'},
{"acquire-jwt", required_argument, 0, 'j'},
{"jwt-algo", required_argument, 0, 'a'},
{"jwt-public-key-file", required_argument, 0, 'k'},
{"ssl-cert-path", required_argument, 0, 'c'},
{"force-ipv4", no_argument, 0, '4'},
{"force-ipv6", no_argument, 0, '6'},
{"boot-time-retry-wait", required_argument, 0, 'w'},
{"client-cert-path", required_argument, 0, 'P'},
{"token-server-url", required_argument, 0, 'U'},
{"crud-config-file", required_argument, 0, 'C'},
{"connection-health-file", required_argument, 0, 'S'},
{"close-reason-file", required_argument, 0, 'R'},
{"mtls-client-key-path", required_argument, 0, 'K'},
{"mtls-client-cert-path", required_argument, 0,'M'},
{0, 0, 0, 0}
};
int c;
ParodusInfo("Parsing parodus command line arguments..\n");
if (NULL == cfg) {
ParodusError ("NULL cfg structure\n");
return -1;
}
cfg->flags = 0;
parStrncpy (cfg->webpa_url, "", sizeof(cfg->webpa_url));
cfg->acquire_jwt = 0;
cfg->jwt_algo = 0;
parStrncpy (cfg->jwt_key, "", sizeof(cfg->jwt_key));
cfg->crud_config_file = NULL;
cfg->connection_health_file = NULL;
cfg->close_reason_file = NULL;
cfg->client_cert_path = NULL;
cfg->token_server_url = NULL;
cfg->cloud_status = NULL;
cfg->cloud_disconnect = NULL;
optind = 1; /* We need this if parseCommandLine is called again */
while (1)
{
static struct option long_options[] = {
{"hw-model", required_argument, 0, 'm'},
{"hw-serial-number", required_argument, 0, 's'},
{"hw-manufacturer", required_argument, 0, 'f'},
{"hw-mac", required_argument, 0, 'd'},
{"hw-last-reboot-reason", required_argument, 0, 'r'},
{"fw-name", required_argument, 0, 'n'},
{"boot-time", required_argument, 0, 'b'},
{"webpa-url", required_argument, 0, 'u'},
{"webpa-ping-timeout", required_argument, 0, 't'},
{"webpa-backoff-max", required_argument, 0, 'o'},
{"webpa-inteface-used", required_argument, 0, 'i'},
{"parodus-local-url", required_argument, 0, 'l'},
{"partner-id", required_argument, 0, 'p'},
{"seshat-url", required_argument, 0, 'e'},
{0, 0, 0, 0}
};
/* 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:",long_options, &option_index);
c = getopt_long (argc, argv,
"m:s:f:d:r:n:b:u:t:o:i:l:p:e:D:j:a:k:c:T:w:J:46:C:S:R:K:M",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
@@ -78,18 +427,23 @@ void parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
break;
case 'd':
parStrncpy(cfg->hw_mac, optarg,sizeof(cfg->hw_mac));
ParodusInfo("hw_mac is %s\n",cfg->hw_mac);
if (parse_mac_address (cfg->hw_mac, optarg) == 0) {
ParodusInfo ("hw_mac is %s\n",cfg->hw_mac);
} else {
ParodusError ("Bad mac address %s\n", optarg);
return -1;
}
break;
#ifdef ENABLE_SESHAT
case 'e':
parStrncpy(cfg->seshat_url, optarg,sizeof(cfg->seshat_url));
ParodusInfo("seshat_url is %s\n",cfg->seshat_url);
break;
#endif
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':
@@ -98,50 +452,158 @@ void parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
break;
case 'b':
cfg->boot_time = atoi(optarg);
cfg->boot_time = parse_num_arg (optarg, "boot-time");
ParodusInfo("boot_time is %d\n",cfg->boot_time);
break;
case 'u':
parStrncpy(cfg->webpa_url, optarg,sizeof(cfg->webpa_url));
parStrncpy(cfg->webpa_url, optarg,sizeof(cfg->webpa_url));
if (server_is_http (cfg->webpa_url, NULL) < 0) {
ParodusError ("Bad webpa url %s\n", optarg);
return -1;
}
ParodusInfo("webpa_url is %s\n",cfg->webpa_url);
break;
case 't':
cfg->webpa_ping_timeout = atoi(optarg);
cfg->webpa_ping_timeout = parse_num_arg (optarg, "webpa-ping-timeout");
if (cfg->webpa_ping_timeout == (unsigned int) -1)
return -1;
ParodusInfo("webpa_ping_timeout is %d\n",cfg->webpa_ping_timeout);
break;
case 'o':
cfg->webpa_backoff_max = atoi(optarg);
cfg->webpa_backoff_max = parse_num_arg (optarg, "webpa-backoff-max");
if (cfg->webpa_backoff_max == (unsigned int) -1)
return -1;
ParodusInfo("webpa_backoff_max is %d\n",cfg->webpa_backoff_max);
break;
case 'i':
parStrncpy(cfg->webpa_interface_used, optarg,sizeof(cfg->webpa_interface_used));
ParodusInfo("webpa_inteface_used is %s\n",cfg->webpa_interface_used);
ParodusInfo("webpa_interface_used is %s\n",cfg->webpa_interface_used);
break;
case 'l':
parStrncpy(cfg->local_url, optarg,sizeof(cfg->local_url));
ParodusInfo("parodus local_url is %s\n",cfg->local_url);
break;
case 'D':
// like 'fabric' or 'test'
// this parameter is used, along with the hw_mac parameter
// to create the dns txt record id
parStrncpy(cfg->dns_txt_url, optarg,sizeof(cfg->dns_txt_url));
ParodusInfo("parodus dns-txt-url is %s\n",cfg->dns_txt_url);
break;
case 'j':
cfg->acquire_jwt = parse_num_arg (optarg, "acquire-jwt");
if (cfg->acquire_jwt == (unsigned int) -1)
return -1;
ParodusInfo("acquire jwt option is %d\n",cfg->acquire_jwt);
break;
case 'a':
// the command line argument is a list of allowed algoritms,
// separated by colons, like "RS256:RS512:none"
cfg->jwt_algo = get_algo_mask (optarg);
if (cfg->jwt_algo == (unsigned int) -1) {
return -1;
}
ParodusInfo("jwt_algo is %u\n",cfg->jwt_algo);
break;
case 'k':
read_key_from_file (optarg, cfg->jwt_key, sizeof(cfg->jwt_key));
ParodusInfo("jwt_key is %s\n",cfg->jwt_key);
break;
case 'p':
parStrncpy(cfg->partner_id, optarg,sizeof(cfg->partner_id));
ParodusInfo("partner_id is %s\n",cfg->partner_id);
break;
case 'c':
parStrncpy(cfg->cert_path, optarg,sizeof(cfg->cert_path));
ParodusInfo("cert_path is %s\n",cfg->cert_path);
break;
case '4':
ParodusInfo("Force IPv4\n");
cfg->flags |= FLAGS_IPV4_ONLY;
break;
case '6':
ParodusInfo("Force IPv6\n");
cfg->flags |= FLAGS_IPV6_ONLY;
break;
case 'w':
cfg->boot_retry_wait = parse_num_arg (optarg, "boot-time-retry-wait");
ParodusInfo("boot_retry_wait is %d\n",cfg->boot_retry_wait);
break;
case 'S':
cfg->connection_health_file = strdup(optarg);
ParodusInfo("connection_health_file is %s\n", cfg->connection_health_file);
break;
case 'R':
cfg->close_reason_file = strdup(optarg);
ParodusInfo("sigterm_close_reason_file is %s\n", cfg->close_reason_file);
break;
case 'C':
cfg->crud_config_file = strdup(optarg);
ParodusInfo("crud_config_file is %s\n", cfg->crud_config_file);
break;
case 'P':
cfg->client_cert_path = strdup(optarg);
ParodusInfo("client_cert_path is %s\n", cfg->client_cert_path);
break;
case 'U':
cfg->token_server_url = strdup(optarg);
ParodusInfo("token_server_url is %s\n", cfg->token_server_url);
break;
case 'K':
cfg->mtls_client_key_path = strdup(optarg);
ParodusInfo("mtls_client_key_path is %s\n", cfg->mtls_client_key_path);
break;
case 'M':
cfg->mtls_client_cert_path = strdup(optarg);
ParodusInfo("mtls_client_cert_path is %s\n", cfg->mtls_client_cert_path);
break;
case '?':
/* getopt_long already printed an error message. */
break;
default:
ParodusError("Enter Valid commands..\n");
abort ();
return -1;
}
}
if (0 == strlen (cfg->webpa_url)) {
ParodusError ("Missing webpa url argument\n");
return -1;
}
if (cfg->acquire_jwt) {
if (0 == cfg->jwt_algo) {
ParodusError ("Missing jwt algorithm argument\n");
return -1;
}
if ((0 != (cfg->jwt_algo & rsa_algorithms)) &&
(0 == strlen (cfg->jwt_key)) ) {
ParodusError ("Missing jwt public key file argument\n");
return -1;
}
}
ParodusPrint("argc is :%d\n", argc);
ParodusPrint("optind is :%d\n", optind);
@@ -153,6 +615,47 @@ void parseCommandLine(int argc,char **argv,ParodusCfg * cfg)
ParodusPrint ("%s ", argv[optind++]);
putchar ('\n');
}
return 0;
}
void setDefaultValuesToCfg(ParodusCfg *cfg)
{
if(cfg == NULL)
{
ParodusError("cfg is NULL\n");
return;
}
ParodusInfo("Setting default values to parodusCfg\n");
parStrncpy(cfg->local_url, PARODUS_UPSTREAM, sizeof(cfg->local_url));
cfg->acquire_jwt = 0;
parStrncpy(cfg->dns_txt_url, DNS_TXT_URL, sizeof(cfg->dns_txt_url));
parStrncpy(cfg->jwt_key, "\0", sizeof(cfg->jwt_key));
cfg->jwt_algo = 0;
parStrncpy(cfg->cert_path, "\0", sizeof(cfg->cert_path));
cfg->flags = 0;
parStrncpy(cfg->webpa_path_url, WEBPA_PATH_URL,sizeof(cfg->webpa_path_url));
snprintf(cfg->webpa_protocol, sizeof(cfg->webpa_protocol), "%s-%s", PROTOCOL_VALUE, GIT_COMMIT_TAG);
ParodusInfo(" cfg->webpa_protocol is %s\n", cfg->webpa_protocol);
parStrncpy(cfg->webpa_uuid, "1234567-345456546",sizeof(cfg->webpa_uuid));
ParodusPrint("cfg->webpa_uuid is :%s\n", cfg->webpa_uuid);
cfg->crud_config_file = NULL;
cfg->connection_health_file = NULL;
cfg->close_reason_file = NULL;
cfg->client_cert_path = NULL;
cfg->token_server_url = NULL;
cfg->cloud_status = CLOUD_STATUS_OFFLINE;
ParodusInfo("Default cloud_status is %s\n", cfg->cloud_status);
}
void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg)
@@ -163,99 +666,186 @@ void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg)
return;
}
ParodusCfg *pConfig =config;
if(strlen (pConfig->hw_model) !=0)
if(strlen (config->hw_model) !=0)
{
strncpy(cfg->hw_model, pConfig->hw_model,strlen(pConfig->hw_model)+1);
parStrncpy(cfg->hw_model, config->hw_model, sizeof(cfg->hw_model));
}
else
{
ParodusPrint("hw_model is NULL. read from tmp file\n");
}
if( strlen(pConfig->hw_serial_number) !=0)
if( strlen(config->hw_serial_number) !=0)
{
strncpy(cfg->hw_serial_number, pConfig->hw_serial_number,strlen(pConfig->hw_serial_number)+1);
parStrncpy(cfg->hw_serial_number, config->hw_serial_number, sizeof(cfg->hw_serial_number));
}
else
{
ParodusPrint("hw_serial_number is NULL. read from tmp file\n");
}
if(strlen(pConfig->hw_manufacturer) !=0)
if(strlen(config->hw_manufacturer) !=0)
{
strncpy(cfg->hw_manufacturer, pConfig->hw_manufacturer,strlen(pConfig->hw_manufacturer)+1);
parStrncpy(cfg->hw_manufacturer, config->hw_manufacturer,sizeof(cfg->hw_manufacturer));
}
else
{
ParodusPrint("hw_manufacturer is NULL. read from tmp file\n");
}
if(strlen(pConfig->hw_mac) !=0)
if(strlen(config->hw_mac) !=0)
{
strncpy(cfg->hw_mac, pConfig->hw_mac,strlen(pConfig->hw_mac)+1);
parStrncpy(cfg->hw_mac, config->hw_mac,sizeof(cfg->hw_mac));
}
else
{
ParodusPrint("hw_mac is NULL. read from tmp file\n");
}
if(strlen (pConfig->hw_last_reboot_reason) !=0)
if(strlen (config->hw_last_reboot_reason) !=0)
{
strncpy(cfg->hw_last_reboot_reason, pConfig->hw_last_reboot_reason,strlen(pConfig->hw_last_reboot_reason)+1);
parStrncpy(cfg->hw_last_reboot_reason, config->hw_last_reboot_reason,sizeof(cfg->hw_last_reboot_reason));
}
else
{
ParodusPrint("hw_last_reboot_reason is NULL. read from tmp file\n");
}
if(strlen(pConfig->fw_name) !=0)
if(strlen(config->fw_name) !=0)
{
strncpy(cfg->fw_name, pConfig->fw_name,strlen(pConfig->fw_name)+1);
parStrncpy(cfg->fw_name, config->fw_name,sizeof(cfg->fw_name));
}
else
{
ParodusPrint("fw_name is NULL. read from tmp file\n");
}
if( strlen(pConfig->webpa_url) !=0)
if( strlen(config->webpa_url) !=0)
{
strncpy(cfg->webpa_url, pConfig->webpa_url,strlen(pConfig->webpa_url)+1);
parStrncpy(cfg->webpa_url, config->webpa_url,sizeof(cfg->webpa_url));
}
else
{
ParodusPrint("webpa_url is NULL. read from tmp file\n");
}
if(strlen(pConfig->webpa_interface_used )!=0)
if(strlen(config->webpa_interface_used )!=0)
{
strncpy(cfg->webpa_interface_used, pConfig->webpa_interface_used,strlen(pConfig->webpa_interface_used)+1);
parStrncpy(cfg->webpa_interface_used, config->webpa_interface_used,sizeof(cfg->webpa_interface_used));
}
else
{
ParodusPrint("webpa_interface_used is NULL. read from tmp file\n");
}
if( strlen(pConfig->local_url) !=0)
if( strlen(config->local_url) !=0)
{
strncpy(cfg->local_url, pConfig->local_url,strlen(pConfig->local_url)+1);
parStrncpy(cfg->local_url, config->local_url,sizeof(cfg->local_url));
}
else
{
ParodusInfo("parodus local_url is NULL. adding default url\n");
strncpy(cfg->local_url, PARODUS_UPSTREAM, strlen(PARODUS_UPSTREAM)+1);
parStrncpy(cfg->local_url, PARODUS_UPSTREAM, sizeof(cfg->local_url));
}
if( strlen(pConfig->partner_id) !=0)
if( strlen(config->partner_id) !=0)
{
strncpy(cfg->partner_id, pConfig->partner_id,strlen(pConfig->partner_id)+1);
parStrncpy(cfg->partner_id, config->partner_id,sizeof(cfg->partner_id));
}
else
{
ParodusPrint("partner_id is NULL. read from tmp file\n");
}
cfg->boot_time = pConfig->boot_time;
cfg->secureFlag = 1;
cfg->webpa_ping_timeout = pConfig->webpa_ping_timeout;
cfg->webpa_backoff_max = pConfig->webpa_backoff_max;
strncpy(cfg->webpa_path_url, WEBPA_PATH_URL, strlen(WEBPA_PATH_URL)+1);
strncpy(cfg->webpa_protocol, WEBPA_PROTOCOL_VALUE, strlen(WEBPA_PROTOCOL_VALUE)+1);
strncpy(cfg->webpa_uuid, "1234567-345456546", strlen("1234567-345456546")+1);
#ifdef ENABLE_SESHAT
if( strlen(config->seshat_url) !=0)
{
parStrncpy(cfg->seshat_url, config->seshat_url,sizeof(cfg->seshat_url));
}
else
{
ParodusInfo("seshat_url is NULL. Read from tmp file\n");
}
#endif
cfg->acquire_jwt = config->acquire_jwt;
if( strlen(config->dns_txt_url) !=0)
{
parStrncpy(cfg->dns_txt_url, config->dns_txt_url, sizeof(cfg->dns_txt_url));
}
else
{
ParodusInfo("parodus dns-txt-url is NULL. adding default\n");
parStrncpy(cfg->dns_txt_url, DNS_TXT_URL, sizeof(cfg->dns_txt_url));
}
if(strlen(config->jwt_key )!=0)
{
parStrncpy(cfg->jwt_key, config->jwt_key,sizeof(cfg->jwt_key));
}
else
{
parStrncpy(cfg->jwt_key, "\0", sizeof(cfg->jwt_key));
ParodusPrint("jwt_key is NULL. set to empty\n");
}
cfg->jwt_algo = config->jwt_algo;
if(strlen(config->cert_path )!=0)
{
parStrncpy(cfg->cert_path, config->cert_path,sizeof(cfg->cert_path));
}
else
{
parStrncpy(cfg->cert_path, "\0", sizeof(cfg->cert_path));
ParodusPrint("cert_path is NULL. set to empty\n");
}
cfg->boot_time = config->boot_time;
cfg->webpa_ping_timeout = config->webpa_ping_timeout;
cfg->webpa_backoff_max = config->webpa_backoff_max;
parStrncpy(cfg->webpa_path_url, WEBPA_PATH_URL,sizeof(cfg->webpa_path_url));
snprintf(cfg->webpa_protocol, sizeof(cfg->webpa_protocol), "%s-%s", PROTOCOL_VALUE, GIT_COMMIT_TAG);
ParodusInfo("cfg->webpa_protocol is %s\n", cfg->webpa_protocol);
parStrncpy(cfg->webpa_uuid, "1234567-345456546",sizeof(cfg->webpa_uuid));
ParodusPrint("cfg->webpa_uuid is :%s\n", cfg->webpa_uuid);
if(config->connection_health_file != NULL)
{
cfg->connection_health_file = strdup(config->connection_health_file);
}
else
{
ParodusPrint("connection_health_file is NULL. set to empty\n");
}
if(config->close_reason_file != NULL)
{
cfg->close_reason_file = strdup(config->close_reason_file);
}
else
{
ParodusPrint("close_reason_file is NULL. set to empty\n");
}
if(config->crud_config_file != NULL)
{
cfg->crud_config_file = strdup(config->crud_config_file);
}
else
{
ParodusPrint("crud_config_file is NULL. set to empty\n");
}
if(config->client_cert_path != NULL)
{
cfg->client_cert_path = strdup(config->client_cert_path);
}
else
{
ParodusPrint("client_cert_path is NULL. set to empty\n");
}
if(config->token_server_url != NULL)
{
cfg->token_server_url = strdup(config->token_server_url);
}
else
{
ParodusPrint("token_server_url is NULL. set to empty\n");
}
}

View File

@@ -1,9 +1,24 @@
/**
* 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 config.h
*
* @description This file contains configuration details of parodus
*
* Copyright (c) 2015 Comcast
*/
#ifndef _CONFIG_H_
@@ -18,25 +33,37 @@ extern "C" {
/*----------------------------------------------------------------------------*/
/* WRP CRUD Model Macros */
#define HW_MODELNAME "hw-model"
#define HW_SERIALNUMBER "hw-serial-number"
#define HW_MANUFACTURER "hw-manufacturer"
#define HW_DEVICEMAC "hw-mac"
#define HW_LAST_REBOOT_REASON "hw-last-reboot-reason"
#define FIRMWARE_NAME "fw-name"
#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_UUID "webpa-uuid"
#define WEBPA_URL "webpa-url"
#define WEBPA_PING_TIMEOUT "webpa-ping-timeout"
#define WEBPA_BACKOFF_MAX "webpa-backoff-max"
#define PARTNER_ID "partner-id"
#define HW_MODELNAME "hw-model"
#define HW_SERIALNUMBER "hw-serial-number"
#define HW_MANUFACTURER "hw-manufacturer"
#define HW_DEVICEMAC "hw-mac"
#define HW_LAST_REBOOT_REASON "hw-last-reboot-reason"
#define FIRMWARE_NAME "fw-name"
#define BOOT_TIME "boot-time"
#define LAST_RECONNECT_REASON "webpa-last-reconnect-reason"
#define WEBPA_PROTOCOL "webpa-protocol"
#define WEBPA_INTERFACE "webpa-interface-used"
#define WEBPA_UUID "webpa-uuid"
#define WEBPA_URL "webpa-url"
#define WEBPA_PING_TIMEOUT "webpa-ping-timeout"
#define WEBPA_BACKOFF_MAX "webpa-backoff-max"
#define PARTNER_ID "partner-id"
#define CERT_PATH "ssl-cert-path"
#define CLOUD_STATUS "cloud-status"
#define CLOUD_DISCONNECT "cloud-disconnect"
#define CLOUD_STATUS_ONLINE "online"
#define CLOUD_STATUS_OFFLINE "offline"
#define CLOUD_DISCONNECT_REASON "disconnection-reason"
#define BOOT_RETRY_WAIT "boot-time-retry-wait"
#define WEBPA_PROTOCOL_VALUE "WebPA-1.6"
#define WEBPA_PATH_URL "/api/v2/device"
#define PARODUS_UPSTREAM "tcp://127.0.0.1:6666"
#define PROTOCOL_VALUE "PARODUS-2.0"
#define WEBPA_PATH_URL "/api/v2/device"
#define JWT_ALGORITHM "jwt-algo"
#define JWT_KEY "jwt-key"
#define DNS_TXT_URL "fabric"
#define PARODUS_UPSTREAM "tcp://127.0.0.1:6666"
#define ALLOW_NON_RSA_ALG false
/*----------------------------------------------------------------------------*/
/* Data Structures */
@@ -48,7 +75,7 @@ typedef struct
char hw_serial_number[64];
char hw_manufacturer[64];
char hw_mac[64];
char hw_last_reboot_reason[64];
char hw_last_reboot_reason[128];
char fw_name[64];
unsigned int boot_time;
unsigned int webpa_ping_timeout;
@@ -56,26 +83,76 @@ typedef struct
char webpa_path_url[124];
unsigned int webpa_backoff_max;
char webpa_interface_used[16];
char webpa_protocol[16];
char webpa_protocol[32];
char webpa_uuid[64];
unsigned int secureFlag;
unsigned int flags;
char local_url[124];
char partner_id[64];
#ifdef ENABLE_SESHAT
char seshat_url[128];
#endif
char dns_txt_url[64];
unsigned int acquire_jwt;
unsigned int jwt_algo; // bit mask set for each allowed algorithm
char jwt_key[4096]; // may be read in from a pem file
char cert_path[64];
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 *close_reason_file;
char *mtls_client_key_path;
char *mtls_client_cert_path;
char *crud_config_file;
char *cloud_status;
char *cloud_disconnect;
unsigned int boot_retry_wait;
} ParodusCfg;
#define FLAGS_IPV6_ONLY (1 << 0)
#define FLAGS_IPV4_ONLY (1 << 1)
#define FLAGS_IPV6_IPV4 (FLAGS_IPV6_ONLY | FLAGS_IPV4_ONLY)
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void loadParodusCfg(ParodusCfg * config,ParodusCfg *cfg);
void parseCommandLine(int argc,char **argv,ParodusCfg * cfg);
/**
* parse command line arguments and create config structure
* and return whether args are valid or not
*
* @param argc number of command line arguments
* @param argv command line argument lis
* @return 0 if OK
* or -1 if error
*/
int parseCommandLine(int argc,char **argv,ParodusCfg * cfg);
void setDefaultValuesToCfg(ParodusCfg *cfg);
// Accessor for the global config structure.
ParodusCfg *get_parodus_cfg(void);
void set_parodus_cfg(ParodusCfg *);
char *get_token_application(void) ;
void set_cloud_disconnect_reason(ParodusCfg *cfg, char *disconn_reason);
void reset_cloud_disconnect_reason(ParodusCfg *cfg);
/**
* parse a webpa url. Extract the server address, the port
* and return whether it's secure or not
*
* @param full_url full url
* @param server_addr ptr to a server address ptr
* will be NULL if invalid,
* otherwise will need to be freed
* @param port ptr to port variable
* @return 1 if insecure connection is allowed, 0 if not,
* or -1 if error
*/
int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port);
#ifdef __cplusplus
}
#endif

View File

@@ -1,9 +1,24 @@
/**
* 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 conn_interface.c
*
* @description This decribes interface to create WebSocket client connections.
*
* Copyright (c) 2015 Comcast
*/
#include "connection.h"
@@ -17,35 +32,59 @@
#include "mutex.h"
#include "spin_thread.h"
#include "service_alive.h"
#include <libseshat.h>
#include "seshat_interface.h"
#include "event_handler.h"
#include "crud_interface.h"
#include "heartBeat.h"
#include "close_retry.h"
#include <curl/curl.h>
#ifdef FEATURE_DNS_QUERY
#include <ucresolv_log.h>
#endif
#include <time.h>
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define HEARTBEAT_RETRY_SEC 30 /* Heartbeat (ping/pong) timeout in seconds */
#define CLOUD_RECONNECT_TIME 5 /* Cloud disconnect max time in minutes */
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool g_shutdown = false;
pthread_t upstream_tid;
pthread_t upstream_msg_tid;
pthread_t downstream_tid;
pthread_t svc_alive_tid;
pthread_t crud_tid;
bool close_retry = false;
bool LastReasonStatus = false;
volatile unsigned int heartBeatTimer = 0;
pthread_mutex_t close_mut=PTHREAD_MUTEX_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *result);
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
void createSocketConnection(void *config_in, void (* initKeypress)())
void createSocketConnection(void (* initKeypress)())
{
int intTimer=0;
ParodusCfg *tmpCfg = (ParodusCfg*)config_in;
//ParodusCfg *tmpCfg = (ParodusCfg*)config_in;
noPollCtx *ctx;
bool seshat_started;
server_list_t server_list;
bool seshat_registered = false;
int create_conn_rtn = 0;
unsigned int webpa_ping_timeout_ms = 1000 * get_parodus_cfg()->webpa_ping_timeout;
unsigned int heartBeatTimer = 0;
struct timespec start_svc_alive_timer;
loadParodusCfg(tmpCfg,get_parodus_cfg());
//loadParodusCfg(tmpCfg,get_parodus_cfg());
#ifdef FEATURE_DNS_QUERY
register_ucresolv_logger (__cimplog);
#endif
ParodusPrint("Configure nopoll thread handlers in Parodus\n");
nopoll_thread_handlers(&createMutex, &destroyMutex, &lockMutex, &unlockMutex);
ctx = nopoll_ctx_new();
@@ -58,75 +97,139 @@ void createSocketConnection(void *config_in, void (* initKeypress)())
nopoll_log_set_handler (ctx, __report_log, NULL);
#endif
createNopollConnection(ctx);
EventHandler();
set_server_list_null (&server_list);
create_conn_rtn = createNopollConnection(ctx, &server_list);
if(!create_conn_rtn)
{
ParodusError("Unrecovered error, terminating the process\n");
OnboardLog("Unrecovered error, terminating the process\n");
abort();
}
packMetaData();
UpStreamMsgQ = NULL;
StartThread(handle_upstream);
StartThread(processUpstreamMessage);
StartThread(handle_upstream, &upstream_tid);
StartThread(processUpstreamMessage, &upstream_msg_tid);
ParodusMsgQ = NULL;
StartThread(messageHandlerTask);
StartThread(serviceAliveTask);
StartThread(messageHandlerTask, &downstream_tid);
StartThread(serviceAliveTask, &svc_alive_tid);
StartThread(CRUDHandlerTask, &crud_tid);
if (NULL != initKeypress)
{
(* initKeypress) ();
}
/* Start seshat lib interface */
seshat_started = (0 == init_lib_seshat(get_parodus_cfg()->seshat_url));
if (false == seshat_started) {
ParodusPrint("init_lib_seshat() Failed, seshatlib not available!\n");
} else {
ParodusPrint("init_lib_seshat() seshatlib initialized! (url %s)\n",
get_parodus_cfg()->seshat_url);
}
seshat_registered = __registerWithSeshat();
clock_gettime(CLOCK_REALTIME, &start_svc_alive_timer);
do
{
nopoll_loop_wait(ctx, 5000000);
intTimer = intTimer + 5;
struct timespec start, stop, diff;
int time_taken_ms;
if(heartBeatTimer >= get_parodus_cfg()->webpa_ping_timeout)
clock_gettime(CLOCK_REALTIME, &start);
nopoll_loop_wait(ctx, 5000000);
clock_gettime(CLOCK_REALTIME, &stop);
timespec_diff(&start, &stop, &diff);
time_taken_ms = diff.tv_sec * 1000 + (diff.tv_nsec / 1000000);
// ParodusInfo("nopoll_loop_wait() time %d msec\n", time_taken_ms);
heartBeatTimer = get_heartBeatTimer();
if(heartBeatTimer >= webpa_ping_timeout_ms)
{
if(!close_retry)
ParodusInfo("heartBeatTimer %d webpa_ping_timeout_ms %d\n", heartBeatTimer, webpa_ping_timeout_ms);
if(!get_close_retry())
{
ParodusError("ping wait time > %d. Terminating the connection with WebPA server and retrying\n", get_parodus_cfg()->webpa_ping_timeout);
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");
LastReasonStatus = true;
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
set_global_reconnect_status(true);
// Invoke the ping status change event callback as "missed" ping
if(NULL != on_ping_status_change)
{
on_ping_status_change("missed");
}
set_close_retry();
}
else
{
ParodusPrint("heartBeatHandler - close_retry set to %d, hence resetting the heartBeatTimer\n",close_retry);
{
ParodusPrint("heartBeatHandler - close_retry set to %d, hence resetting the heartBeatTimer\n",get_close_retry());
}
heartBeatTimer = 0;
reset_heartBeatTimer();
}
else if(intTimer >= 30)
{
ParodusPrint("heartBeatTimer %d\n",heartBeatTimer);
heartBeatTimer += HEARTBEAT_RETRY_SEC;
intTimer = 0;
else {
increment_heartBeatTimer(time_taken_ms);
}
if(close_retry)
if( false == seshat_registered ) {
seshat_registered = __registerWithSeshat();
}
if (get_interface_down_event ())
if (0 != wait_while_interface_down ())
break;
if(get_close_retry())
{
ParodusInfo("close_retry is %d, hence closing the connection and retrying\n", close_retry);
close_and_unref_connection(get_global_conn());
ParodusInfo("close_retry is %d, hence closing the connection and retrying\n", get_close_retry());
close_and_unref_connection(get_global_conn(), false);
set_global_conn(NULL);
createNopollConnection(ctx);
}
} while(!close_retry);
close_and_unref_connection(get_global_conn());
if(get_parodus_cfg()->cloud_disconnect !=NULL)
{
ParodusPrint("get_parodus_cfg()->cloud_disconnect is %s\n", get_parodus_cfg()->cloud_disconnect);
set_cloud_disconnect_time(CLOUD_RECONNECT_TIME);
ParodusInfo("Waiting for %d minutes for reconnecting .. \n", get_cloud_disconnect_time());
sleep (get_cloud_disconnect_time() * 60);
ParodusInfo("cloud-disconnect reason reset after %d minutes\n", get_cloud_disconnect_time());
free(get_parodus_cfg()->cloud_disconnect);
reset_cloud_disconnect_reason(get_parodus_cfg());
}
createNopollConnection(ctx, &server_list);
}
} while(!get_close_retry() && !g_shutdown);
pthread_mutex_lock (get_global_svc_mut());
pthread_cond_signal (get_global_svc_con());
pthread_mutex_unlock (get_global_svc_mut());
pthread_mutex_lock (get_global_crud_mut());
pthread_cond_signal (get_global_crud_con());
pthread_mutex_unlock (get_global_crud_mut());
pthread_mutex_lock (&g_mutex);
pthread_cond_signal (&g_cond);
pthread_mutex_unlock (&g_mutex);
pthread_mutex_lock (get_global_nano_mut ());
pthread_cond_signal (get_global_nano_con());
pthread_mutex_unlock (get_global_nano_mut());
ParodusInfo ("joining threads\n");
JoinThread (svc_alive_tid);
JoinThread (upstream_tid);
JoinThread (downstream_tid);
JoinThread (upstream_msg_tid);
JoinThread (crud_tid);
deleteAllClients ();
ParodusInfo ("reconnect reason at close %s\n", get_global_reconnect_reason());
close_and_unref_connection(get_global_conn(), true);
nopoll_ctx_unref(ctx);
nopoll_cleanup_library();
if (seshat_started) {
shutdown_seshat_lib();
}
curl_global_cleanup();
}
void shutdownSocketConnection(char *reason) {
set_global_shutdown_reason (reason);
g_shutdown = true;
reset_interface_down_event ();
terminate_backoff_delay ();
}

View File

@@ -1,11 +1,25 @@
/**
* 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 conn_interface.h
*
* @description This header defines interface to create WebSocket client connections.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _CONN_INTERFACE_H_
#define _CONN_INTERFACE_H_
@@ -30,7 +44,8 @@ extern UpStreamMsg *UpStreamMsgQ;
* Loads the WebPA config file, if not provided by the caller,
* and creates the intial connection and manages the connection wait, close mechanisms.
*/
void createSocketConnection(void *config_in, void (* initKeypress)());
void createSocketConnection(void (* initKeypress)());
void shutdownSocketConnection(char *reason);
#ifdef __cplusplus
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,24 @@
/**
* 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 connection.h
*
* @description This header defines functions required to manage WebSocket client connections.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _CONNECTION_H_
@@ -18,28 +33,60 @@ extern "C" {
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
#define SHUTDOWN_REASON_PARODUS_STOP "parodus_stopping"
#define SHUTDOWN_REASON_SYSTEM_RESTART "system_restarting"
#define SHUTDOWN_REASON_SIGTERM "SIGTERM"
extern bool close_retry;
extern volatile unsigned int heartBeatTimer;
extern pthread_mutex_t close_mut;
/**
* parodusOnPingStatusChangeHandler - Function pointer
* Used to define callback function to do additional processing
* when websocket Ping status change event
* i.e. ping_miss or ping receive after miss
*/
typedef void (*parodusOnPingStatusChangeHandler) (char * status);
extern parodusOnPingStatusChangeHandler on_ping_status_change;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
int createNopollConnection(noPollCtx *);
void set_server_list_null (server_list_t *server_list);
int createNopollConnection(noPollCtx *, server_list_t *);
/**
* @brief Interface to terminate WebSocket client connections and clean up resources.
*/
void close_and_unref_connection(noPollConn *);
void close_and_unref_connection(noPollConn *conn, bool is_shutting_down);
noPollConn *get_global_conn(void);
void set_global_conn(noPollConn *);
char *get_global_shutdown_reason();
void set_global_shutdown_reason(char *reason);
char *get_global_reconnect_reason();
void set_global_reconnect_reason(char *reason);
bool get_global_reconnect_status();
void set_global_reconnect_status(bool status);
int get_cloud_disconnect_time();
void set_cloud_disconnect_time(int disconnTime);
/**
* @brief Interface to self heal connection in progress getting stuck
*/
void start_conn_in_progress (unsigned long start_time);
void stop_conn_in_progress (void);
// To Register parodusOnPingStatusChangeHandler Callback function
void registerParodusOnPingStatusChangeHandler(parodusOnPingStatusChangeHandler on_ping_status_change);
// To stop connection and wait duing interface down state
int wait_while_interface_down (void);
void terminate_backoff_delay (void);
#ifdef __cplusplus
}
#endif

187
src/crud_interface.c Normal file
View File

@@ -0,0 +1,187 @@
/**
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file crud_interface.c
*
* @description This file is used to manage incoming and outgoing CRUD messages.
*
*/
#include "ParodusInternal.h"
#include "crud_tasks.h"
#include "crud_interface.h"
#include "upstream.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
pthread_mutex_t crud_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t crud_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Internal variables */
/*----------------------------------------------------------------------------*/
CrudMsg *crudMsgQ = NULL;
/*----------------------------------------------------------------------------*/
/* External functions */
/*----------------------------------------------------------------------------*/
pthread_cond_t *get_global_crud_con(void)
{
return &crud_con;
}
pthread_mutex_t *get_global_crud_mut(void)
{
return &crud_mut;
}
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
CrudMsg * crudMessage;
crudMessage = (CrudMsg *)malloc(sizeof(CrudMsg));
if(crudMessage && crudMsg!=NULL)
{
crudMessage->msg = crudMsg;
crudMessage->next = NULL;
ParodusPrint("Inside addCRUDmsgToQueue : mutex lock in producer \n");
pthread_mutex_lock(&crud_mut);
if(crudMsgQ ==NULL)
{
crudMsgQ = crudMessage;
ParodusPrint("Producer added message\n");
pthread_cond_signal(&crud_con);
pthread_mutex_unlock(&crud_mut);
ParodusPrint("Inside addCRUDmsgToQueue : mutex unlock in producer \n");
}
else
{
CrudMsg *temp = crudMsgQ;
while(temp->next)
{
temp = temp->next;
}
temp->next = crudMessage;
pthread_mutex_unlock(&crud_mut);
}
}
else
{
ParodusError("Memory allocation failed for CRUD\n");
}
}
void *CRUDHandlerTask()
{
int ret = 0;
ssize_t resp_size = 0;
void *resp_bytes;
wrp_msg_t *crud_response = NULL;
while(FOREVER())
{
pthread_mutex_lock(&crud_mut);
ParodusPrint("Mutex lock in CRUD consumer thread\n");
if(crudMsgQ !=NULL)
{
CrudMsg *message = crudMsgQ;
crudMsgQ = crudMsgQ->next;
pthread_mutex_unlock(&crud_mut);
ParodusPrint("Mutex unlock in CRUD consumer thread\n");
ret = processCrudRequest(message->msg, &crud_response);
wrp_free_struct(message->msg);
free(message);
message = NULL;
if(ret == 0)
{
ParodusInfo("CRUD processed successfully\n");
}
else
{
ParodusError("Failure in CRUD request processing !!\n");
}
ParodusPrint("msgpack encode to send to upstream\n");
resp_size = wrp_struct_to( crud_response, WRP_BYTES, &resp_bytes );
ParodusPrint("Encoded CRUD resp_size :%lu\n", resp_size);
ParodusPrint("Adding CRUD response to upstreamQ\n");
addCRUDresponseToUpstreamQ(resp_bytes, resp_size);
wrp_free_struct(crud_response);
}
else
{
if (g_shutdown) {
pthread_mutex_unlock (&crud_mut);
break;
}
pthread_cond_wait(&crud_con, &crud_mut);
pthread_mutex_unlock (&crud_mut);
}
}
return 0;
}
//CRUD Producer adds the response into common UpStreamQ
void addCRUDresponseToUpstreamQ(void *response_bytes, ssize_t response_size)
{
UpStreamMsg *response;
response = (UpStreamMsg *)malloc(sizeof(UpStreamMsg));
if(response)
{
response->msg =(void *)response_bytes;
response->len =(int)response_size;
response->next=NULL;
pthread_mutex_lock (get_global_nano_mut());
ParodusPrint("Mutex lock in CRUD response producer\n");
if(get_global_UpStreamMsgQ() == NULL)
{
set_global_UpStreamMsgQ(response);
ParodusPrint("Producer added CRUD response to UpStreamQ\n");
pthread_cond_signal(get_global_nano_con());
pthread_mutex_unlock (get_global_nano_mut());
ParodusPrint("mutex unlock in CRUD response producer\n");
}
else
{
ParodusPrint("Producer adding CRUD response to UpStreamQ\n");
UpStreamMsg *temp = get_global_UpStreamMsgQ();
while(temp->next)
{
temp = temp->next;
}
temp->next = response;
pthread_mutex_unlock (get_global_nano_mut());
}
}
else
{
ParodusError("failure in allocation for CRUD response\n");
}
}

57
src/crud_interface.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 crud_interface.h
*
* @description This header defines functions required to manage CRUD messages.
*
*/
#ifndef _CRUD_INTERFACE_H_
#define _CRUD_INTERFACE_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
typedef struct CrudMsg__
{
wrp_msg_t *msg;
struct CrudMsg__ *next;
} CrudMsg;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
void addCRUDresponseToUpstreamQ(void *response_bytes, ssize_t response_size);
pthread_cond_t *get_global_crud_con(void);
pthread_mutex_t *get_global_crud_mut(void);
#ifdef __cplusplus
}
#endif
#endif /* _CRUD_INTERFACE_H_ */

1650
src/crud_internal.c Normal file

File diff suppressed because it is too large Load Diff

27
src/crud_internal.h Normal file
View File

@@ -0,0 +1,27 @@
/**
* Copyright 2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <wrp-c.h>
#include <stdlib.h>
int createObject( wrp_msg_t *reqMsg, wrp_msg_t **response );
int retrieveObject( wrp_msg_t *reqMsg, wrp_msg_t **response);
int updateObject( wrp_msg_t *reqMsg, wrp_msg_t **response);
int deleteObject(wrp_msg_t *reqMsg, wrp_msg_t **response);
int writeToJSON(char *data);
int readFromJSON(char **data);
int retrieveFromMemory(char *keyName, cJSON **jsonresponse);

109
src/crud_tasks.c Normal file
View File

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

31
src/crud_tasks.h Normal file
View File

@@ -0,0 +1,31 @@
/**
* Copyright 2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <wrp-c.h>
#include "ParodusInternal.h"
/**
* @brief processCrudRequest function to process CRUD operations.
*
* @note processCrudRequest function allocates memory for response,
* caller needs to free the response (resMsg) in both success and failure case.
* @param[in] decoded request in wrp_msg_t structure format
* @param[out] resulting wrp_msg_t structure as a response
* @return 0 in success case and -1 in error case
*/
int processCrudRequest(wrp_msg_t * reqMsg, wrp_msg_t **resMsg);

View File

@@ -1,9 +1,24 @@
/**
* 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 downstream.c
*
* @description This describes functions required to manage downstream messages.
*
* Copyright (c) 2015 Comcast
*/
#include "downstream.h"
@@ -11,7 +26,11 @@
#include "connection.h"
#include "partners_check.h"
#include "ParodusInternal.h"
#include "crud_interface.h"
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
static void createNewMsgForCRUD(wrp_msg_t *message, wrp_msg_t **crudMessage );
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -26,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;
@@ -42,7 +62,7 @@ void listenerOnMessage(void * msg, size_t msgSize)
recivedMsg = (const char *) msg;
ParodusInfo("Received msg from server:%s\n", recivedMsg);
ParodusInfo("Received msg from server\n");
if(recivedMsg!=NULL)
{
/*** Decoding downstream recivedMsg to check destination ***/
@@ -53,90 +73,297 @@ void listenerOnMessage(void * msg, size_t msgSize)
ParodusPrint("\nDecoded recivedMsg of size:%d\n", rv);
msgType = message->msg_type;
ParodusInfo("msgType received:%d\n", msgType);
if(message->msg_type == WRP_MSG_TYPE__REQ)
switch( message->msg_type )
{
ParodusPrint("numOfClients registered is %d\n", get_numOfClients());
int ret = validate_partner_id(message, NULL);
if(ret < 0)
case WRP_MSG_TYPE__AUTH:
{
response = cJSON_CreateObject();
cJSON_AddNumberToObject(response, "statusCode", 430);
cJSON_AddStringToObject(response, "message", "Invalid partner_id");
ParodusInfo("Authorization Status received with Status code :%d\n", message->u.auth.status);
break;
}
if((message->u.req.dest !=NULL) && (ret >= 0))
case WRP_MSG_TYPE__EVENT:
case WRP_MSG_TYPE__REQ:
case WRP_MSG_TYPE__CREATE:
case WRP_MSG_TYPE__UPDATE:
case WRP_MSG_TYPE__RETREIVE:
case WRP_MSG_TYPE__DELETE:
{
destVal = message->u.req.dest;
strtok(destVal , "/");
parStrncpy(dest,strtok(NULL , "/"), sizeof(dest));
ParodusInfo("Received downstream dest as :%s\n", dest);
temp = get_global_node();
//Checking for individual clients & Sending to each client
while (NULL != temp)
ParodusPrint("numOfClients registered is %d\n", get_numOfClients());
int ret = validate_partner_id(message, NULL);
if(ret < 0)
{
ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
// Sending message to registered clients
if( strcmp(dest, temp->service_name) == 0)
{
ParodusPrint("sending to nanomsg client %s\n", dest);
bytes = nn_send(temp->sock, recivedMsg, msgSize, 0);
ParodusInfo("sent downstream message '%s' to reg_client '%s'\n",recivedMsg,temp->url);
ParodusPrint("downstream bytes sent:%d\n", bytes);
destFlag =1;
break;
}
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
//if any unknown dest received sending error response to server
if(destFlag ==0)
{
ParodusError("Unknown dest:%s\n", dest);
response = cJSON_CreateObject();
cJSON_AddNumberToObject(response, "statusCode", 531);
cJSON_AddStringToObject(response, "message", "Service Unavailable");
}
}
cJSON_AddNumberToObject(response, "statusCode", 403);
cJSON_AddStringToObject(response, "message", "Invalid partner_id");
}
if(destFlag == 0 || ret < 0)
{
resp_msg = (wrp_msg_t *)malloc(sizeof(wrp_msg_t));
memset(resp_msg, 0, sizeof(wrp_msg_t));
destVal = strdup(((WRP_MSG_TYPE__EVENT == msgType) ? message->u.event.dest :
((WRP_MSG_TYPE__REQ == msgType) ? message->u.req.dest : message->u.crud.dest)));
resp_msg ->msg_type = msgType;
resp_msg ->u.req.source = message->u.req.dest;
resp_msg ->u.req.dest = message->u.req.source;
resp_msg ->u.req.transaction_uuid=message->u.req.transaction_uuid;
if(response != NULL)
if( (destVal != NULL) && (ret >= 0) )
{
str = cJSON_PrintUnformatted(response);
ParodusInfo("Payload Response: %s\n", str);
char *newDest = NULL;
char *tempDest = strtok(destVal , "/");
if(tempDest != NULL)
{
newDest = strtok(NULL , "/");
}
if(newDest != NULL)
{
parStrncpy(dest,newDest, sizeof(dest));
}
else
{
parStrncpy(dest,destVal, sizeof(dest));
}
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);
resp_msg ->u.req.payload = (void *)str;
resp_msg ->u.req.payload_size = strlen(str);
temp = get_global_node();
//Checking for individual clients & Sending to each client
ParodusPrint("msgpack encode\n");
resp_size = wrp_struct_to( resp_msg, WRP_BYTES, &resp_bytes );
if(resp_size > 0)
while (NULL != temp)
{
size = (size_t) resp_size;
sendUpstreamMsgToServer(&resp_bytes, size);
ParodusPrint("node is pointing to temp->service_name %s \n",temp->service_name);
// Sending message to registered clients
if( strcmp(dest, temp->service_name) == 0)
{
ParodusPrint("sending to nanomsg client %s\n", dest);
bytes = nn_send(temp->sock, recivedMsg, msgSize, 0);
ParodusInfo("sent downstream message to reg_client '%s'\n",temp->url);
ParodusPrint("downstream bytes sent:%d\n", bytes);
destFlag =1;
break;
}
ParodusPrint("checking the next item in the list\n");
temp= temp->next;
}
release_global_node ();
/* check Downstream dest for CRUD requests */
if(destFlag ==0 && strcmp("parodus", dest)==0)
{
ParodusPrint("Received CRUD request : dest : %s\n", dest);
if ((message->u.crud.source == NULL) || (message->u.crud.transaction_uuid == NULL))
{
ParodusError("Invalid request\n");
response = cJSON_CreateObject();
cJSON_AddNumberToObject(response, "statusCode", 400);
cJSON_AddStringToObject(response, "message", "Invalid Request");
ret = -1;
}
else
{
createNewMsgForCRUD(message, &crudMessage);
addCRUDmsgToQueue(crudMessage);
}
destFlag =1;
}
//if any unknown dest received sending error response to server
if(destFlag ==0)
{
ParodusError("Unknown dest:%s\n", dest);
response = cJSON_CreateObject();
cJSON_AddNumberToObject(response, "statusCode", 531);
cJSON_AddStringToObject(response, "message", "Service Unavailable");
}
free(str);
}
free(resp_msg);
if( (WRP_MSG_TYPE__EVENT != msgType) &&
((destFlag == 0) || (ret < 0)) )
{
resp_msg = (wrp_msg_t *)malloc(sizeof(wrp_msg_t));
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg ->msg_type = msgType;
if( WRP_MSG_TYPE__REQ == msgType )
{
resp_msg ->u.req.source = message->u.req.dest;
resp_msg ->u.req.dest = message->u.req.source;
resp_msg ->u.req.transaction_uuid=message->u.req.transaction_uuid;
}
else
{
resp_msg ->u.crud.source = message->u.crud.dest;
if(message->u.crud.source !=NULL)
{
resp_msg ->u.crud.dest = message->u.crud.source;
}
else
{
resp_msg ->u.crud.dest = "unknown";
}
resp_msg ->u.crud.transaction_uuid = message->u.crud.transaction_uuid;
resp_msg ->u.crud.path = message->u.crud.path;
}
if(response != NULL)
{
str = cJSON_PrintUnformatted(response);
ParodusInfo("Payload Response: %s\n", str);
if( WRP_MSG_TYPE__REQ == msgType )
{
resp_msg ->u.req.payload = (void *)str;
resp_msg ->u.req.payload_size = strlen(str);
}
else
{
resp_msg ->u.crud.payload = (void *)str;
resp_msg ->u.crud.payload_size = strlen(str);
}
ParodusPrint("msgpack encode\n");
resp_size = wrp_struct_to( resp_msg, WRP_BYTES, &resp_bytes );
if(resp_size > 0)
{
size = (size_t) resp_size;
sendUpstreamMsgToServer(&resp_bytes, size);
}
free(str);
cJSON_Delete(response);
free(resp_bytes);
resp_bytes = NULL;
}
free(resp_msg);
}
break;
}
case WRP_MSG_TYPE__SVC_REGISTRATION:
case WRP_MSG_TYPE__SVC_ALIVE:
case WRP_MSG_TYPE__UNKNOWN:
default:
break;
}
ParodusPrint("free for downstream decoded msg\n");
wrp_free_struct(message);
message = NULL;
}
else
{
ParodusError( "Failure in msgpack decoding for receivdMsg: rv is %d\n", rv );
}
ParodusPrint("free for downstream decoded msg\n");
wrp_free_struct(message);
}
}
/*----------------------------------------------------------------------------*/
/* Internal Functions */
/*----------------------------------------------------------------------------*/
/**
* @brief createNewMsgForCRUD function to create new message for processing CRUD requests
*
* @param[in] message The message received from server
* @param[out] crudMessage New message for processing CRUD requests
*/
static void createNewMsgForCRUD(wrp_msg_t *message, wrp_msg_t **crudMessage )
{
wrp_msg_t *msg;
msg = ( wrp_msg_t * ) malloc( sizeof( wrp_msg_t ) );
size_t i;
if(msg != NULL)
{
memset( msg, 0, sizeof( wrp_msg_t ) );
msg->msg_type = message->msg_type;
if(message->u.crud.source != NULL)
{
ParodusPrint("message->u.crud.source = %s\n",message->u.crud.source);
msg->u.crud.source = strdup(message->u.crud.source);
}
if(message->u.crud.dest!= NULL)
{
ParodusPrint("message->u.crud.dest = %s\n",message->u.crud.dest);
msg->u.crud.dest = strdup(message->u.crud.dest);
}
if(message->u.crud.transaction_uuid != NULL)
{
ParodusPrint("message->u.crud.transaction_uuid = %s\n",message->u.crud.transaction_uuid);
msg->u.crud.transaction_uuid = strdup(message->u.crud.transaction_uuid);
}
if(message->u.crud.partner_ids!= NULL && message->u.crud.partner_ids->count >0)
{
msg->u.crud.partner_ids = ( partners_t * ) malloc( sizeof( partners_t ) +
sizeof( char * ) * message->u.crud.partner_ids->count );
if(msg->u.crud.partner_ids != NULL)
{
msg->u.crud.partner_ids->count = message->u.crud.partner_ids->count;
for(i = 0; i<message->u.crud.partner_ids->count; i++)
{
ParodusPrint("message->u.crud.partner_ids->partner_ids[%d] = %s\n",i,message->u.crud.partner_ids->partner_ids[i]);
msg->u.crud.partner_ids->partner_ids[i] = strdup(message->u.crud.partner_ids->partner_ids[i]);
}
}
}
if(message->u.crud.headers!= NULL && message->u.crud.headers->count >0)
{
msg->u.crud.headers = ( headers_t * ) malloc( sizeof( headers_t ) +
sizeof( char * ) * message->u.crud.headers->count );
if(msg->u.crud.headers != NULL)
{
msg->u.crud.headers->count = message->u.crud.headers->count;
for(i = 0; i<message->u.crud.headers->count; i++)
{
ParodusPrint("message->u.crud.headers->headers[%d] = %s\n",i,message->u.crud.headers->headers[i]);
msg->u.crud.headers->headers[i] = strdup(message->u.crud.headers->headers[i]);
}
}
}
if(message->u.crud.metadata != NULL && message->u.crud.metadata->count > 0)
{
msg->u.crud.metadata = (data_t *) malloc( sizeof( data_t ) );
if(msg->u.crud.metadata != NULL)
{
memset( msg->u.crud.metadata, 0, sizeof( data_t ) );
msg->u.crud.metadata->count = message->u.crud.metadata->count;
msg->u.crud.metadata->data_items = ( struct data* )malloc( sizeof( struct data ) * ( message->u.crud.metadata->count ) );
for(i=0; i<message->u.crud.metadata->count; i++)
{
if(message->u.crud.metadata->data_items[i].name != NULL)
{
ParodusPrint("message->u.crud.metadata->data_items[%d].name : %s\n",i,message->u.crud.metadata->data_items[i].name);
msg->u.crud.metadata->data_items[i].name = strdup(message->u.crud.metadata->data_items[i].name);
}
if(message->u.crud.metadata->data_items[i].value != NULL)
{
ParodusPrint("message->u.crud.metadata->data_items[%d].value : %s\n",i,message->u.crud.metadata->data_items[i].value);
msg->u.crud.metadata->data_items[i].value = strdup(message->u.crud.metadata->data_items[i].value);
}
}
}
}
msg->u.crud.include_spans = message->u.crud.include_spans;
if(message->u.crud.content_type != NULL)
{
ParodusPrint("message->u.crud.content_type : %s\n",message->u.crud.content_type);
msg->u.crud.content_type = strdup(message->u.crud.content_type);
}
msg->u.crud.spans.spans = NULL; /* not supported */
msg->u.crud.spans.count = 0; /* not supported */
msg->u.crud.status = message->u.crud.status;
msg->u.crud.rdr = message->u.crud.rdr;
if(message->u.crud.payload != NULL)
{
ParodusPrint("message->u.crud.payload = %s\n", (char *)message->u.crud.payload);
msg->u.crud.payload = strdup((char *)message->u.crud.payload);
}
msg->u.crud.payload_size = message->u.crud.payload_size;
if(message->u.crud.path != NULL)
{
ParodusPrint("message->u.crud.path = %s\n", message->u.crud.path);
msg->u.crud.path = strdup(message->u.crud.path);
}
*crudMessage = msg;
}
}

View File

@@ -1,9 +1,24 @@
/**
* 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 downstream.h
*
* @description This header defines functions required to manage downstream messages.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _DOWNSTREAM_H_

26
src/event_handler.c Normal file
View File

@@ -0,0 +1,26 @@
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
* Copyright [2014] [Cisco Systems, Inc.]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* This is a stub file that will be overridden in a patch */
#include "event_handler.h"
void EventHandler()
{
}

21
src/event_handler.h Normal file
View File

@@ -0,0 +1,21 @@
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
* Copyright [2014] [Cisco Systems, Inc.]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
void EventHandler();
#define LOGGING_INTERVAL_SECS ( 60 * 60 )

77
src/heartBeat.c Normal file
View File

@@ -0,0 +1,77 @@
/**
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file heartBeat.c
*
* @description This decribes functions required to manage heartBeatTimer.
*
*/
#include "heartBeat.h"
#include <stdbool.h>
volatile unsigned int heartBeatTimer = 0;
volatile bool paused = false;
pthread_mutex_t heartBeat_mut=PTHREAD_MUTEX_INITIALIZER;
// Get value of heartBeatTimer
unsigned int get_heartBeatTimer()
{
unsigned int tmp = 0;
pthread_mutex_lock (&heartBeat_mut);
tmp = heartBeatTimer;
pthread_mutex_unlock (&heartBeat_mut);
return tmp;
}
// Reset value of heartBeatTimer to 0
void reset_heartBeatTimer()
{
pthread_mutex_lock (&heartBeat_mut);
heartBeatTimer = 0;
pthread_mutex_unlock (&heartBeat_mut);
}
// Increment value of heartBeatTimer to desired value
void increment_heartBeatTimer(unsigned int inc_time_ms)
{
pthread_mutex_lock (&heartBeat_mut);
if (!paused)
heartBeatTimer += inc_time_ms;
pthread_mutex_unlock (&heartBeat_mut);
}
// Pause heartBeatTimer, i.e. stop incrementing
void pause_heartBeatTimer()
{
pthread_mutex_lock (&heartBeat_mut);
heartBeatTimer = 0;
paused = true;
pthread_mutex_unlock (&heartBeat_mut);
}
// Resume heartBeatTimer, i.e. resume incrementing
void resume_heartBeatTimer()
{
pthread_mutex_lock (&heartBeat_mut);
paused = false;
pthread_mutex_unlock (&heartBeat_mut);
}

52
src/heartBeat.h Normal file
View File

@@ -0,0 +1,52 @@
/**
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* @file heartBeat.h
*
* @description This decribes functions required to manage heartBeatTimer.
*
*/
#ifndef _HEARBEAT_H_
#define _HEARBEAT_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
// Get value of heartBeatTimer
unsigned int get_heartBeatTimer();
// Reset value of heartBeatTimer to 0
void reset_heartBeatTimer();
// Increment value of heartBeatTimer to desired value
void increment_heartBeatTimer(unsigned int inc_time_ms);
// Pause heartBeatTimer, i.e. stop incrementing
void pause_heartBeatTimer();
// Resume heartBeatTimer, i.e. resume incrementing
void resume_heartBeatTimer();
#ifdef __cplusplus
}
#endif
#endif

View File

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

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

@@ -1,14 +1,31 @@
/**
* 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 nopoll_handlers.c
*
* @description This describes nopoll handler functions.
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
#include "nopoll_handlers.h"
#include "connection.h"
#include "heartBeat.h"
#include "close_retry.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -21,6 +38,7 @@
pthread_mutex_t g_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond=PTHREAD_COND_INITIALIZER;
ParodusMsg *ParodusMsgQ = NULL;
noPollMsg * previous_msg = NULL;
/*----------------------------------------------------------------------------*/
/* External Functions */
@@ -39,18 +57,43 @@ void listenerOnMessage_queue(noPollCtx * ctx, noPollConn * conn, noPollMsg * msg
UNUSED(ctx);
UNUSED(conn);
UNUSED(user_data);
noPollMsg * aux;
if (nopoll_msg_is_fragment (msg))
{
ParodusInfo("Found fragment, FIN = %d \n", nopoll_msg_is_final (msg));
aux = previous_msg;
previous_msg = nopoll_msg_join (previous_msg, msg);
nopoll_msg_unref (aux);
if (! nopoll_msg_is_final (msg)) {
ParodusInfo ("Found fragment that is not final..\n");
return;
}
ParodusInfo("Found final fragment *** \n");
}
ParodusMsg *message;
message = (ParodusMsg *)malloc(sizeof(ParodusMsg));
if(message)
{
message->msg = msg;
message->payload = (void *)nopoll_msg_get_payload (msg);
message->len = nopoll_msg_get_payload_size (msg);
message->next = NULL;
if(previous_msg)
{
message->msg = previous_msg;
message->payload = (void *)nopoll_msg_get_payload (previous_msg);
message->len = nopoll_msg_get_payload_size (previous_msg);
message->next = NULL;
}
else
{
message->msg = msg;
message->payload = (void *)nopoll_msg_get_payload (msg);
message->len = nopoll_msg_get_payload_size (msg);
message->next = NULL;
nopoll_msg_ref(msg);
}
pthread_mutex_lock (&g_mutex);
ParodusPrint("mutex lock in producer thread\n");
@@ -79,6 +122,7 @@ void listenerOnMessage_queue(noPollCtx * ctx, noPollConn * conn, noPollMsg * msg
//Memory allocation failed
ParodusError("Memory allocation is failed\n");
}
previous_msg = NULL;
ParodusPrint("*****Returned from listenerOnMessage_queue*****\n");
}
@@ -94,6 +138,7 @@ void listenerOnPingMessage (noPollCtx * ctx, noPollConn * conn, noPollMsg * msg,
{
UNUSED(ctx);
UNUSED(user_data);
UNUSED(conn);
noPollPtr payload = NULL;
payload = (noPollPtr ) nopoll_msg_get_payload(msg);
@@ -103,9 +148,7 @@ void listenerOnPingMessage (noPollCtx * ctx, noPollConn * conn, noPollMsg * msg,
ParodusInfo("Ping received with payload %s, opcode %d\n",(char *)payload, nopoll_msg_opcode(msg));
if (nopoll_msg_opcode(msg) == NOPOLL_PING_FRAME)
{
nopoll_conn_send_frame (conn, nopoll_true, nopoll_true, NOPOLL_PONG_FRAME, strlen(payload), payload, 0);
heartBeatTimer = 0;
ParodusPrint("Sent Pong frame and reset HeartBeat Timer\n");
reset_heartBeatTimer();
}
}
}
@@ -114,22 +157,35 @@ void listenerOnCloseMessage (noPollCtx * ctx, noPollConn * conn, noPollPtr user_
{
UNUSED(ctx);
UNUSED(conn);
UNUSED(user_data);
int closeStatus;
char * defaultReason = "SSL_Socket_Close";
ParodusPrint("listenerOnCloseMessage(): mutex lock in producer thread\n");
if((user_data != NULL) && (strstr(user_data, "SSL_Socket_Close") != NULL) && !LastReasonStatus)
closeStatus = nopoll_conn_get_close_status (conn);
if( closeStatus == 1006 && !get_global_reconnect_status())
{
set_global_reconnect_reason("Server_closed_connection");
LastReasonStatus = true;
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 ((user_data == NULL) && !LastReasonStatus)
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");
pthread_mutex_lock (&close_mut);
close_retry = true;
pthread_mutex_unlock (&close_mut);
ParodusPrint("listenerOnCloseMessage(): mutex unlock in producer thread\n");
}

View File

@@ -1,9 +1,24 @@
/**
* 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 nopoll_handlers.h
*
* @description This header defines nopoll handler functions.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _NOPOLL_HANDLERS_H_
@@ -21,9 +36,6 @@ extern "C" {
extern pthread_mutex_t g_mutex;
extern pthread_cond_t g_cond;
extern pthread_mutex_t close_mut;
extern volatile unsigned int heartBeatTimer;
extern bool close_retry;
/*----------------------------------------------------------------------------*/
/* Function Prototypes */

View File

@@ -1,15 +1,32 @@
/**
* 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 nopoll_helpers.c
*
* @description This file is used to manage incomming and outgoing messages.
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
#include "connection.h"
#include "nopoll_helpers.h"
#include "nopoll_handlers.h"
#include "time.h"
#include "config.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -18,6 +35,10 @@
#define MAX_SEND_SIZE (60 * 1024)
#define FLUSH_WAIT_TIME (2000000LL)
struct timespec connStuck_start,connStuck_end;
struct timespec *connStuck_startPtr = &connStuck_start;
struct timespec *connStuck_endPtr = &connStuck_end;
/*----------------------------------------------------------------------------*/
/* External functions */
/*----------------------------------------------------------------------------*/
@@ -29,26 +50,33 @@ void setMessageHandlers()
nopoll_conn_set_on_close(get_global_conn(), (noPollOnCloseHandler)listenerOnCloseMessage, NULL);
}
static int cloud_status_is_online (void)
{
const char *status = get_parodus_cfg()->cloud_status;
if (NULL == status)
return false;
return (strcmp (status, CLOUD_STATUS_ONLINE) == 0);
}
/** To send upstream msgs to server ***/
void sendMessage(noPollConn *conn, void *msg, size_t len)
{
int bytesWritten = 0;
ParodusInfo("sendMessage length %zu\n", len);
if(nopoll_conn_is_ok(conn) && nopoll_conn_is_ready(conn))
{
//bytesWritten = nopoll_conn_send_binary(conn, msg, len);
bytesWritten = sendResponse(conn, msg, len);
ParodusPrint("Number of bytes written: %d\n", bytesWritten);
if (bytesWritten != (int) len)
{
ParodusError("Failed to send bytes %zu, bytes written were=%d (errno=%d, %s)..\n", len, bytesWritten, errno, strerror(errno));
}
}
else
{
if (!cloud_status_is_online ()) {
ParodusError("Failed to send msg upstream as connection is not OK\n");
OnboardLog("Failed to send msg upstream as connection is not OK\n");
return;
}
ParodusInfo("sendMessage length %zu\n", len);
bytesWritten = sendResponse(conn, msg, len);
ParodusPrint("Number of bytes written: %d\n", bytesWritten);
if (bytesWritten != (int) len)
{
ParodusError("Failed to send bytes %zu, bytes written were=%d (errno=%d, %s)..\n", len, bytesWritten, errno, strerror(errno));
}
}
@@ -70,7 +98,7 @@ int sendResponse(noPollConn * conn, void * buffer, size_t length)
{
if (-1 == bytes_sent || (bytes_sent = nopoll_conn_flush_writes(conn, FLUSH_WAIT_TIME, bytes_sent)) != len_to_send)
{
ParodusPrint("sendResponse() Failed to send all the data\n");
ParodusError("sendResponse() Failed to send all the data\n");
cp = NULL;
break;
}
@@ -106,6 +134,7 @@ void __report_log (noPollCtx * ctx, noPollDebugLevel level, const char * log_msg
if (level == NOPOLL_LEVEL_CRITICAL)
{
ParodusError("%s\n", log_msg );
OnboardLog("%s\n", log_msg );
}
return;
}

View File

@@ -1,9 +1,24 @@
/**
* 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 nopoll_handlers.h
*
* @description This header defines functions to manage incomming and outgoing messages.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _NOPOLL_HELPERS_H_

View File

@@ -1,9 +1,24 @@
/**
* 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 parodus_log.h
*
* @description This header defines parodus log levels
*
* Copyright (c) 2015 Comcast
*/
#include <stdarg.h>
@@ -18,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

@@ -1,9 +1,24 @@
/**
* 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 partners_check.c
*
* @description This describes functions to validate partner_id.
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
@@ -24,85 +39,184 @@
/*----------------------------------------------------------------------------*/
/* External functions */
/*----------------------------------------------------------------------------*/
static void parse_partner_id(char *partnerId, partners_t **partnersList)
{
char *token;
int i = 0, j = 0, count = 0;
ParodusPrint("********* %s ********\n",__FUNCTION__);
while(partnerId[i] != '\0')
{
if(partnerId[i] == ',')
{
count++;
}
i++;
}
ParodusPrint("count = %d\n", count+1);
*partnersList = (partners_t *)malloc(sizeof(partners_t)+ sizeof( char * ) * (count+1));
memset(*partnersList, 0, sizeof(partners_t));
(*partnersList)->count = count+1;
while ((token = strsep(&partnerId, ",")) != NULL)
{
ParodusPrint("token=%s\n", token);
(*partnersList)->partner_ids[j] = strdup(token);
ParodusPrint("(*partnersList)->partner_ids[%d] = %s\n",j,(*partnersList)->partner_ids[j]);
j++;
}
}
int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
int matchFlag = 0, i = 0, count = 0;
size_t j = 0;
partners_t *partnersList = NULL;
char *partnerId = NULL;
ParodusPrint("********* %s ********\n",__FUNCTION__);
char *partnerId = get_parodus_cfg()->partner_id;
if(strlen(partnerId) <= 0)
char *temp = get_parodus_cfg()->partner_id;
ParodusPrint("temp = %s\n",temp);
if(temp[0] != '\0' && strlen(temp) > 0)
{
partnerId = strdup(temp);
}
ParodusPrint("partnerId = %s\n",partnerId);
if(partnerId != NULL)
{
parse_partner_id(partnerId, &partnersList);
ParodusPrint("partnersList->count = %lu\n", partnersList->count);
if(msg->msg_type == WRP_MSG_TYPE__EVENT)
{
if(msg->u.event.partner_ids != NULL)
{
count = (int) msg->u.event.partner_ids->count;
ParodusPrint("partner_ids count is %d\n",count);
for(i = 0; i < count; i++)
{
for(j = 0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j]) {
ParodusPrint("partnersList->partner_ids[%lu] = %s\n",j, partnersList->partner_ids[j]);
ParodusPrint("msg->u.event.partner_ids->partner_ids[%lu] = %s\n",i, msg->u.event.partner_ids->partner_ids[i]);
if(strcasecmp(partnersList->partner_ids[j], msg->u.event.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
else
ParodusError("partner Id in partnersList is NULL but count is not 0");
}
/* Commandline input partner_ids matched with partner_ids from request */
if(matchFlag == 1)
{
break;
}
}
/* Commandline input partner_ids not matching with partner_ids from request, appending to request partner_ids*/
if(matchFlag != 1)
{
(*partnerIds) = (partners_t *) malloc(sizeof(partners_t) + (sizeof(char *) * (count+partnersList->count)));
(*partnerIds)->count = count+partnersList->count;
for(i = 0; i < count; i++)
{
(*partnerIds)->partner_ids[i] = msg->u.event.partner_ids->partner_ids[i];
ParodusPrint("(*partnerIds)->partner_ids[%d] : %s\n",i,(*partnerIds)->partner_ids[i]);
}
i = 0;
for(j = count; j<(count+partnersList->count); j++)
{
(*partnerIds)->partner_ids[j] = (char *) malloc(sizeof(char) * 64);
parStrncpy((*partnerIds)->partner_ids[j], partnersList->partner_ids[i], 64);
ParodusPrint("(*partnerIds)->partner_ids[%lu] : %s\n",j,(*partnerIds)->partner_ids[j]);
i++;
}
}
}
else
{
ParodusPrint("partner_ids list is NULL\n");
(*partnerIds) = (partners_t *) malloc(sizeof(partners_t) + (sizeof(char *) * partnersList->count));
(*partnerIds)->count = partnersList->count;
i=0;
for(j = 0; j<partnersList->count; j++)
{
(*partnerIds)->partner_ids[j] = (char *) malloc(sizeof(char) * 64);
parStrncpy((*partnerIds)->partner_ids[j], partnersList->partner_ids[i], 64);
ParodusPrint("(*partnerIds)->partner_ids[%lu] : %s\n",j,(*partnerIds)->partner_ids[j]);
i++;
}
}
}
else if(msg->msg_type == WRP_MSG_TYPE__REQ)
{
if(msg->u.req.partner_ids != NULL)
{
count = (int) msg->u.req.partner_ids->count;
ParodusPrint("partner_ids count is %d\n",count);
for(i = 0; i < count; i++)
{
for(j = 0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
{
ParodusPrint("partnersList->partner_ids[%lu] = %s\n",j, partnersList->partner_ids[j]);
ParodusPrint("msg->u.req.partner_ids->partner_ids[%lu] = %s\n",i, msg->u.req.partner_ids->partner_ids[i]);
if(strcasecmp(partnersList->partner_ids[j], msg->u.req.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
else
ParodusError("partner Id in partnersList is NULL but count is not 0");
}
}
/* Commandline input partner_ids not matching with partner_ids from request, ignoring request*/
if(matchFlag != 1)
{
ParodusError("Invalid partner_id %s\n",temp);
OnboardLog("Invalid partner_id %s\n",temp);
if(partnersList != NULL)
{
for(j=0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
{
free(partnersList->partner_ids[j]);
}
}
free(partnersList);
}
free(partnerId);
return -1;
}
}
else
{
ParodusPrint("partner_ids list is NULL\n");
}
}
if(partnersList != NULL)
{
for(j=0; j<partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
{
free(partnersList->partner_ids[j]);
}
}
free(partnersList);
}
free(partnerId);
}
else
{
ParodusPrint("partner_id is not available to validate\n");
return 0;
}
if(msg->msg_type == WRP_MSG_TYPE__EVENT)
{
if(msg->u.event.partner_ids != NULL)
{
count = (int) msg->u.event.partner_ids->count;
ParodusPrint("partner_ids count is %d\n",count);
for(i = 0; i < count; i++)
{
if(strcmp(partnerId, msg->u.event.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
if(matchFlag != 1)
{
(*partnerIds) = (partners_t *) malloc(sizeof(partners_t));
(*partnerIds)->count = count+1;
for(i = 0; i < count; i++)
{
(*partnerIds)->partner_ids[i] = msg->u.event.partner_ids->partner_ids[i];
ParodusPrint("(*partnerIds)->partner_ids[%d] : %s\n",i,(*partnerIds)->partner_ids[i]);
}
(*partnerIds)->partner_ids[count] = (char *) malloc(sizeof(char) * 64);
strcpy((*partnerIds)->partner_ids[count], partnerId);
ParodusPrint("(*partnerIds)->partner_ids[%d] : %s\n",count,(*partnerIds)->partner_ids[count]);
}
}
else
{
ParodusPrint("partner_ids list is NULL\n");
(*partnerIds) = (partners_t *) malloc(sizeof(partners_t));
(*partnerIds)->count = 1;
(*partnerIds)->partner_ids[0] = (char *) malloc(sizeof(char) * 64);
strcpy((*partnerIds)->partner_ids[0], partnerId);
ParodusPrint("(*partnerIds)->partner_ids[0] : %s\n",(*partnerIds)->partner_ids[0]);
}
}
else if(msg->msg_type == WRP_MSG_TYPE__REQ)
{
if(msg->u.req.partner_ids != NULL)
{
count = (int) msg->u.req.partner_ids->count;
ParodusPrint("partner_ids count is %d\n",count);
for(i = 0; i < count; i++)
{
if(strcmp(partnerId, msg->u.req.partner_ids->partner_ids[i]) == 0)
{
ParodusInfo("partner_id match found\n");
matchFlag = 1;
break;
}
}
if(matchFlag != 1)
{
ParodusError("Invalid partner_id %s\n",partnerId);
return -1;
}
}
else
{
ParodusPrint("partner_ids list is NULL\n");
}
}
return 1;
}

View File

@@ -1,9 +1,24 @@
/**
* 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 partners_check.h
*
* @description This describes functions to validate partner_id.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _PARTNERS_CHECK_H_

6
src/privilege.c Normal file
View File

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

2
src/privilege.h Normal file
View File

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

View File

@@ -1,9 +1,24 @@
/**
* 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 service_alive.c
*
* @description This file is used to manage keep alive section
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
@@ -16,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.
*/
@@ -43,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)
{
@@ -67,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
@@ -76,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(70);
if (wait__ (50))
break;
}
}
free (svc_bytes);
}
return 0;
}

View File

@@ -1,14 +1,31 @@
/**
* 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 service_alive.h
*
* @description This file is used to manage keep alive section
*
* Copyright (c) 2015 Comcast
*/
#ifndef _SERVICE_ALIVE_H_
#define _SERVICE_ALIVE_H_
#include <pthread.h>
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
@@ -18,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
}

81
src/seshat_interface.c Normal file
View File

@@ -0,0 +1,81 @@
/**
* 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 seshat_interface.c
*
* @description This decribes interface to register seshat service.
*
*/
#include "seshat_interface.h"
#include "ParodusInternal.h"
#include "config.h"
#include <libseshat.h>
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define SESHAT_SERVICE_NAME "Parodus"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Internal Functions */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* External functions */
/*----------------------------------------------------------------------------*/
bool __registerWithSeshat()
{
char *seshat_url = get_parodus_cfg()->seshat_url;
char *parodus_url = get_parodus_cfg()->local_url;
char *discover_url = NULL;
bool rv = false;
if( 0 == init_lib_seshat(seshat_url) ) {
ParodusInfo("seshatlib initialized! (url %s)\n", seshat_url);
if( 0 == seshat_register(SESHAT_SERVICE_NAME, parodus_url) ) {
ParodusInfo("seshatlib registered! (url %s)\n", parodus_url);
discover_url = seshat_discover(SESHAT_SERVICE_NAME);
if( (NULL != discover_url) && (0 == strcmp(parodus_url, discover_url)) ) {
ParodusInfo("seshatlib discovered url = %s\n", discover_url);
rv = true;
} else {
ParodusError("seshatlib registration error (url %s)!", discover_url);
}
free(discover_url);
} else {
ParodusError("seshatlib not registered! (url %s)\n", parodus_url);
}
} else {
ParodusPrint("seshatlib not initialized! (url %s)\n", seshat_url);
}
shutdown_seshat_lib();
return rv;
}

54
src/seshat_interface.h Normal file
View File

@@ -0,0 +1,54 @@
/**
* 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 seshat_interface.h
*
* @description This header defines interface to register seshat service.
*
*/
#ifndef _SESHAT_INTERFACE_H_
#define _SESHAT_INTERFACE_H_
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/**
* @brief Helper function to register with seshat.
*
* @note return whether successfully registered.
*
* @return true when registered, false otherwise.
*/
bool __registerWithSeshat();
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,53 @@
/**
* 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 seshat_interface_stub.c
*
* @description This decribes interface to register seshat service
*
*/
#include "seshat_interface.h"
#include "ParodusInternal.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Internal Functions */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* External functions */
/*----------------------------------------------------------------------------*/
bool __registerWithSeshat()
{
ParodusInfo("libseshat disabled, Hence proceeding without registration\n");
return true;
}

View File

@@ -1,14 +1,28 @@
/**
* 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 spin_thread.c
*
* @description This file is used to define thread function
*
* Copyright (c) 2015 Comcast
*/
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "spin_thread.h"
#include "parodus_log.h"
@@ -16,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));
@@ -29,8 +43,13 @@ void StartThread(void *(*start_routine) (void *))
}
else
{
ParodusPrint("Thread created Successfully %d\n", (int ) threadId);
*threadId = __threadId;
ParodusPrint("Thread created Successfully %lu\n", (unsigned long) __threadId);
}
}
void JoinThread (pthread_t threadId)
{
pthread_join (threadId, NULL);
}

View File

@@ -1,14 +1,31 @@
/**
* 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 spin_thread.h
*
* @description This file is used to define thread function
*
* Copyright (c) 2015 Comcast
*/
#ifndef _SPIN_THREAD_H_
#define _SPIN_THREAD_H_
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
@@ -17,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

@@ -1,9 +1,24 @@
/**
* 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 thread_tasks.h
*
* @description This header defines thread functions.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _THREAD_TASKS_H_

548
src/token.c Normal file
View File

@@ -0,0 +1,548 @@
/**
* 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 token.c
*
* @description This file contains operations for using jwt token.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <netinet/in.h>
#ifdef FEATURE_DNS_QUERY
#include <ucresolv.h>
#endif
//#include <res_update.h>
#include <netdb.h>
#include <strings.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/param.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include <cjwt/cjwt.h>
#include "token.h"
#include "config.h"
#include "parodus_log.h"
#include "ParodusInternal.h"
#define JWT_MAXBUF 8192
#ifdef NS_MAXMSG
#if NS_MAXMSG > JWT_MAXBUF
#define NS_MAXBUF JWT_MAXBUF
#else
#define NS_MAXBUF NS_MAXMSG
#endif
#else
#define NS_MAXBUF JWT_MAXBUF
#endif
#define TXT_REC_ID_MAXSIZE 128
#define MAX_RR_RECS 10
#define SEQ_TABLE_SIZE (MAX_RR_RECS + 1)
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define ENDPOINT_NAME "endpoint"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
#ifdef FEATURE_DNS_QUERY
extern int __res_ninit(res_state statp);
extern void __res_nclose(res_state statp);
extern int __res_nquery(res_state statp,
const char *name, /* domain name */
int class, int type, /* class and type of query */
u_char *answer, /* buffer to put answer */
int anslen); /* size of answer buffer */
/*----------------------------------------------------------------------------*/
/* Internal functions */
/*----------------------------------------------------------------------------*/
static void show_times (time_t exp_time, time_t cur_time)
{
char exp_buf[30];
char cur_buf[30];
ctime_r (&exp_time, exp_buf);
exp_buf[strlen(exp_buf)-1] = 0;
ctime_r (&cur_time, cur_buf);
cur_buf[strlen(cur_buf)-1] = 0;
ParodusInfo ("Exp: %d %s, Current: %d %s\n",
(int)exp_time, exp_buf+4, (int)cur_time, cur_buf+4);
}
// returns 1 if insecure, 0 if secure, < 0 if error
int analyze_jwt (const cjwt_t *jwt, char **url_buf, unsigned int *port)
{
cJSON *claims = jwt->private_claims;
cJSON *endpoint = NULL;
time_t exp_time, cur_time;
int http_match;
if (!claims) {
ParodusError ("Private claims not found in jwt\n");
return TOKEN_ERR_INVALID_JWT_CONTENT;
}
endpoint = cJSON_GetObjectItem(claims, ENDPOINT_NAME);
if (!endpoint) {
ParodusError ("Endpoint claim not found in jwt\n");
return TOKEN_ERR_INVALID_JWT_CONTENT;
}
ParodusInfo ("JWT endpoint: %s\n", endpoint->valuestring);
exp_time = jwt->exp.tv_sec;
if (0 == exp_time) {
ParodusError ("exp not found in JWT payload\n");
return TOKEN_ERR_NO_EXPIRATION;
} else {
cur_time = time(NULL);
show_times (exp_time, cur_time);
if (exp_time < cur_time) {
ParodusError ("JWT has expired\n");
OnboardLog ("JWT has expired\n");
return TOKEN_ERR_JWT_EXPIRED;
}
}
http_match = parse_webpa_url (endpoint->valuestring,
url_buf, port);
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);
return http_match;
}
bool validate_algo(const cjwt_t *jwt)
{
// return true if jwt->header.alg is included in the set
// of allowed algorithms specified by cfg->jwt_algo
ParodusCfg *cfg = get_parodus_cfg();
int alg = jwt->header.alg;
int alg_mask;
if ((alg < 0) || (alg >= num_algorithms))
return false;
alg_mask = 1<<alg;
if ((alg_mask & cfg->jwt_algo) == 0) {
ParodusError ("Algorithm %d not allowed (mask %d)\n", alg, alg_mask);
return false;
}
return true;
}
int nquery(const char* dns_txt_record_id, u_char *nsbuf)
{
int len;
struct __res_state statp;
/* Initialize resolver */
memset (&statp, 0, sizeof(__res_state));
if (NULL == nsbuf) {
ParodusError ("nquery: nsbuf is NULL\n");
return (-1);
}
statp.options = RES_DEBUG;
if (__res_ninit(&statp) < 0) {
ParodusError ("res_ninit error: can't initialize statp.\n");
return (-1);
}
ParodusInfo ("nquery: domain : %s\n", dns_txt_record_id);
memset (nsbuf, 0, NS_MAXBUF);
len = __res_nquery(&statp, dns_txt_record_id, ns_c_in, ns_t_txt, nsbuf, NS_MAXBUF);
if (len < 0) {
if (0 != statp.res_h_errno) {
const char *msg = hstrerror (statp.res_h_errno);
ParodusError ("Error in res_nquery: %s\n", msg);
}
return len;
}
__res_nclose (&statp);
ParodusInfo ("nquery: nsbuf (1) 0x%lx\n", (unsigned long) nsbuf);
if (len >= NS_MAXBUF) {
ParodusError ("res_nquery error: ns buffer too small.\n");
return -1;
}
return len;
}
bool valid_b64_char (char c)
{
if ((c>='A') && (c<='Z'))
return true;
if ((c>='a') && (c<='z'))
return true;
if ((c>='0') && (c<='9'))
return true;
if ((c=='/') || (c=='+') || (c=='-') || (c=='_'))
return true;
return false;
}
static bool is_digit (char c)
{
return (bool) ((c>='0') && (c<='9'));
}
// strip quotes and newlines from rr rec
const char *strip_rr_data (const char *rr_ptr, int *rrlen)
{
int len = *rrlen;
const char *optr = rr_ptr;
char c;
if (len > 0) {
c = optr[0];
if (!is_digit(c)) {
optr++;
len--;
}
}
if (len > 0) {
if (!valid_b64_char (optr[len-1]))
len--;
}
if (len > 0) {
if (!valid_b64_char (optr[len-1]))
len--;
}
*rrlen = len;
return optr;
}
// return offset to seq number in record
// return -1 if not found, -2 if invalid fmt
int find_seq_num (const char *rr_ptr, int rrlen)
{
char c;
int i;
int digit_ct = 0;
for (i=0; i<rrlen; i++)
{
c = rr_ptr[i];
if (c == ':') {
if (digit_ct >= 2)
return i - 2;
else
return -2;
}
if (is_digit (c))
digit_ct++;
else
digit_ct = 0;
}
return -1;
}
// get seq num in rr rec
// return -1 if not formatted correctly
int get_rr_seq_num (const char *rr_ptr, int rrlen)
{
char c;
int lo, hi;
if (rrlen < 3)
return -1;
if (rr_ptr[2] != ':')
return -1;
c = rr_ptr[0];
if (is_digit (c))
hi = c - '0';
else
return -1;
c = rr_ptr[1];
if (is_digit (c))
lo = c - '0';
else
return -1;
return (10*hi) + lo;
}
// scan rr recs and build seq table using seq numbers in the recs
// return num_txt_recs
int get_rr_seq_table (ns_msg *msg_handle, int num_rr_recs, rr_rec_t *seq_table)
{
ns_rr rr;
const char *rr_ptr;
int seq_pos;
int rrlen;
int i, ret, seq_num;
int num_txt_recs = 0;
if (num_rr_recs > MAX_RR_RECS) {
ParodusError ("num rr recs (%d) to big, > %d\n", num_rr_recs, MAX_RR_RECS);
return -1;
}
// clear seq table
for (i=0; i<SEQ_TABLE_SIZE; i++)
{
seq_table[i].rr_ptr = NULL;
seq_table[i].rr_len = 0;
}
// extract and concatenate all the records in rr
for (i=0; i<num_rr_recs; i++) {
ret = ns_parserr(msg_handle, ns_s_an, i, &rr);
if (ret != 0) {
ParodusError ("query_dns: ns_parserr failed: %s\n", strerror (errno));
return ret;
}
if (ns_rr_type(rr) != ns_t_txt)
continue;
++num_txt_recs;
rr_ptr = (const char *)ns_rr_rdata(rr);
rrlen = ns_rr_rdlen(rr);
ParodusPrint ("Found rr rec type %d: %s\n", ns_t_txt, rr_ptr);
rr_ptr = strip_rr_data (rr_ptr, &rrlen);
seq_pos = find_seq_num (rr_ptr, rrlen);
if (seq_pos == -2) {
ParodusError ("Invalid seq number in rr record %d\n", i);
return -1;
}
if (seq_pos < 0) {
seq_num = 0;
} else {
rr_ptr += seq_pos;
rrlen -= seq_pos;
seq_num = get_rr_seq_num (rr_ptr, rrlen);
}
ParodusPrint ("Found seq num %d in rr rec %d\n", seq_num, i);
if (seq_num < 0) {
ParodusError ("Seq number not found in rr record %d\n", i);
return -1;
}
if (seq_num > num_rr_recs) {
ParodusError ("Invalid seq number (too big) in rr record %d\n", i);
return -1;
}
if (NULL != seq_table[seq_num].rr_ptr) {
ParodusError ("Duplicate rr record number %d\n", seq_num);
return -1;
}
if (seq_num != 0) {
rr_ptr += 3; // skip the seq number
rrlen -= 3;
}
seq_table[seq_num].rr_ptr = rr_ptr;
seq_table[seq_num].rr_len = rrlen;
}
if (NULL != seq_table[0].rr_ptr) {
// sequence-less record should not be used when there
// are multiple records
if (num_txt_recs > 1) {
ParodusError ("Seq number not found in rr record\n");
return -1;
}
// when there is only one record, use the sequence-less record
seq_table[1].rr_ptr = seq_table[0].rr_ptr;
seq_table[1].rr_len = seq_table[0].rr_len;
}
// check if we got them all
for (i=1; i<num_txt_recs; i++) {
if (NULL == seq_table[i].rr_ptr) {
ParodusError ("Missing rr record number %d\n", i+1);
return -1;
}
}
return num_txt_recs;
}
int assemble_jwt_from_dns (ns_msg *msg_handle, int num_rr_recs, char *jwt_ans)
{
// slot 0 in the seq table is for the sequence-less record that
// you get when there is only one record.
rr_rec_t seq_table[SEQ_TABLE_SIZE];
int i;
int num_txt_recs = get_rr_seq_table (msg_handle, num_rr_recs, seq_table);
if (num_txt_recs < 0)
return num_txt_recs;
ParodusPrint ("Found %d TXT records\n", num_txt_recs);
jwt_ans[0] = 0;
for (i=1; i<=num_txt_recs; i++)
strncat (jwt_ans, seq_table[i].rr_ptr, seq_table[i].rr_len);
return 0;
}
int query_dns(const char* dns_txt_record_id,char *jwt_ans)
{
u_char *nsbuf;
ns_msg msg_handle;
int ret;
int l = -1;
if( !dns_txt_record_id || !jwt_ans )
return l;
nsbuf = (u_char *) malloc (NS_MAXBUF);
ParodusInfo ("nsbuf (1) 0x%lx\n", (unsigned long) nsbuf);
if (NULL == nsbuf) {
ParodusError ("Unable to allocate nsbuf in query_dns\n");
return TOKEN_ERR_MEMORY_FAIL;
}
l = nquery(dns_txt_record_id,nsbuf);
if (l < 0) {
ParodusError("nquery returns error: l value is %d\n", l);
free (nsbuf);
return l;
}
ParodusInfo ("nsbuf (2) 0x%lx\n", (unsigned long) nsbuf);
/*--
memset((void *) &msg_handle, 0x5e, sizeof (ns_msg));
ParodusInfo ("nsbuf (3) 0x%lx\n", (unsigned long) nsbuf);
msg_handle._msg = nsbuf;
*/
ParodusInfo ("ns_initparse, msglen %d, nsbuf 0x%lx\n",
l, (unsigned long) nsbuf);
ret = ns_initparse((const u_char *) nsbuf, l, &msg_handle);
if (ret != 0) {
ParodusError ("ns_initparse failed\n");
free (nsbuf);
return ret;
}
ParodusInfo ("ns_msg_count\n");
l = ns_msg_count(msg_handle, ns_s_an);
ParodusInfo ("query_dns: ns_msg_count : %d\n",l);
jwt_ans[0] = 0;
ret = assemble_jwt_from_dns (&msg_handle, l, jwt_ans);
free (nsbuf);
if (ret == 0)
ParodusInfo ("query_dns JWT: %s\n", jwt_ans);
return ret;
}
static void get_dns_txt_record_id (char *buf)
{
ParodusCfg *cfg = get_parodus_cfg();
buf[0] = 0;
sprintf (buf, "%s.%s", cfg->hw_mac, cfg->dns_txt_url);
ParodusInfo("dns_txt_record_id %s\n", buf);
}
#endif
int allow_insecure_conn(char **server_addr, unsigned int *port)
{
#ifdef FEATURE_DNS_QUERY
int insecure=0, ret = -1;
char *jwt_token, *key;
cjwt_t *jwt = NULL;
char dns_txt_record_id[TXT_REC_ID_MAXSIZE];
jwt_token = malloc (NS_MAXBUF);
if (NULL == jwt_token) {
ParodusError ("Unable to allocate jwt_token in allow_insecure_conn\n");
insecure = TOKEN_ERR_MEMORY_FAIL;
goto end;
}
get_dns_txt_record_id (dns_txt_record_id);
ret = query_dns(dns_txt_record_id, jwt_token);
ParodusPrint("query_dns returns %d\n", ret);
if(ret){
ParodusError("Failed in DNS query\n");
if (ret == TOKEN_ERR_MEMORY_FAIL){
insecure = ret;
}
else{
insecure = TOKEN_ERR_QUERY_DNS_FAIL;
}
goto end;
}
//Decoding the jwt token
key = get_parodus_cfg()->jwt_key;
ret = cjwt_decode( jwt_token, 0, &jwt, ( const uint8_t * )key,strlen(key) );
if(ret) {
if (ret == ENOMEM) {
ParodusError ("Memory allocation failed in JWT decode\n");
} else {
ParodusError ("CJWT decode error\n");
}
insecure = TOKEN_ERR_JWT_DECODE_FAIL;
goto end;
}
ParodusPrint("Decoded CJWT successfully\n");
//validate algo from --jwt_algo
if( validate_algo(jwt) ) {
insecure = analyze_jwt (jwt, server_addr, port);
} else {
insecure = TOKEN_ERR_ALGO_NOT_ALLOWED;
}
if (insecure >= 0) {
char *claim_str = cJSON_Print (jwt->private_claims);
ParodusInfo ("JWT claims: %s\n", claim_str);
free (claim_str);
}
cjwt_destroy(&jwt);
end:
if (NULL != jwt_token)
free (jwt_token);
#else
(void) server_addr;
(void) port;
int insecure = TOKEN_NO_DNS_QUERY;
#endif
ParodusPrint ("Allow Insecure %d\n", insecure);
return insecure;
}

90
src/token.h Normal file
View File

@@ -0,0 +1,90 @@
/**
* 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 token.h
*
* @description This file contains apis and error codes for using jwt token.
*
*/
#ifndef _TOKEN_H_
#define _TOKEN_H_
/**
* @brief token error rtn codes
*
*/
typedef enum {
TOKEN_ERR_MEMORY_FAIL = -999,
TOKEN_ERR_QUERY_DNS_FAIL = -101,
TOKEN_ERR_JWT_DECODE_FAIL = -102,
TOKEN_ERR_ALGO_NOT_ALLOWED = -103,
TOKEN_ERR_INVALID_JWT_CONTENT = -104,
TOKEN_ERR_NO_EXPIRATION = -105,
TOKEN_ERR_JWT_EXPIRED = -106,
TOKEN_ERR_BAD_ENDPOINT = -107,
TOKEN_NO_DNS_QUERY = -1
} token_error_t;
/**
Connection Logic:
----- Criteria -----
Feature FeatureDnsQuery enabled
QueryGood Dns query succeeds, jwt decodes and is valid and unexpired
Endpt starts Endpoint specified in the jwt starts with http:// or https://
Config Secflag secureFlag in config is set. Currently always set.
----- Actions -----
Default Securely connect to the default URL, specified
in the config
Secure Securely connect to the endpoint given in the jwt
Insecure Insecurely connect to the endpoint given in the jwt
----- Logic Table -----
Feature Query Endpt Config Action
Good Claim SecFlag
No Default
Yes No Default
Yes Yes https Secure
Yes Yes http False Insecure
Yes Yes http True Default
*/
/**
* query the dns server, obtain a jwt, determine if insecure
* connections can be allowed.
*
* @param server_addr ptr to buffer ptr containing endpoint value found in JWT
* will be NULL if invalid, otherwise needs to be freed
* @param port ptr to variable receiving the port number
* @return 1 if insecure connection is allowed, 0 if not,
* or one of the error codes given above.
*/
int allow_insecure_conn (char **server_addr, unsigned int *port);
#endif

52
src/token_stub.c Normal file
View File

@@ -0,0 +1,52 @@
/**
* 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 token_stub.c
*
* @description This file contains operations for using jwt token.
*
*/
#include "token.h"
#include "parodus_log.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Internal functions */
/*----------------------------------------------------------------------------*/
int allow_insecure_conn(void)
{
ParodusInfo("CJWT is disabled, Hence proceeding without validation\n");
return 1;
}

View File

@@ -1,9 +1,24 @@
/**
* 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 upstream.c
*
* @description This describes functions required to manage upstream messages.
*
* Copyright (c) 2015 Comcast
*/
#include "ParodusInternal.h"
@@ -13,12 +28,13 @@
#include "connection.h"
#include "client_list.h"
#include "nopoll_helpers.h"
#include "close_retry.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
#define METADATA_COUNT 12
#define PARODUS_SERVICE_NAME "parodus"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
@@ -33,6 +49,26 @@ pthread_mutex_t nano_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t nano_con=PTHREAD_COND_INITIALIZER;
UpStreamMsg * get_global_UpStreamMsgQ(void)
{
return UpStreamMsgQ;
}
void set_global_UpStreamMsgQ(UpStreamMsg * UpStreamQ)
{
UpStreamMsgQ = UpStreamQ;
}
pthread_cond_t *get_global_nano_con(void)
{
return &nano_con;
}
pthread_mutex_t *get_global_nano_mut(void)
{
return &nano_mut;
}
/*----------------------------------------------------------------------------*/
/* Internal Functions */
/*----------------------------------------------------------------------------*/
@@ -93,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)
@@ -101,12 +143,19 @@ 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);
ParodusInfo ("Upstream message received from nanomsg client: \"%s\"\n", (char*)buf);
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));
if(message)
@@ -141,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
@@ -156,12 +215,15 @@ void *processUpstreamMessage()
{
int rv=-1, rc = -1;
int msgType;
wrp_msg_t *msg;
void *appendData, *bytes;
size_t encodedSize;
wrp_msg_t *msg,*retrieve_msg = NULL;
void *bytes;
reg_list_item_t *temp = NULL;
int matchFlag = 0;
int status = -1;
char *device_id = NULL;
size_t device_id_len = 0;
size_t parodus_len;
int ret = -1;
while(FOREVER())
{
@@ -182,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");
strncpy(temp->url,msg->u.reg.url, strlen(msg->u.reg.url)+1);
if(nn_shutdown(temp->sock, 0) < 0)
parStrncpy(temp->url,msg->u.reg.url, sizeof(temp->url));
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)
@@ -218,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)
@@ -249,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\n");
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)
@@ -275,52 +346,146 @@ void *processUpstreamMessage()
sendUpstreamMsgToServer(&bytes, size);
}
free(eventMsg);
free(bytes);
bytes = NULL;
}
else
{
sendUpstreamMsgToServer(&message->msg, message->len);
}
if(partnersList != NULL)
{
for(j=0; j<(int)partnersList->count; j++)
{
if(NULL != partnersList->partner_ids[j])
{
free(partnersList->partner_ids[j]);
}
}
free(partnersList);
}
partnersList = NULL;
}
else
{
//Sending to server for msgTypes 3, 5, 6, 7, 8.
ParodusInfo(" Received upstream data with MsgType: %d\n", msgType);
//Appending metadata with packed msg received from client
if(metaPackSize > 0)
{
ParodusPrint("Appending received msg with metadata\n");
encodedSize = appendEncodedData( &appendData, message->msg, message->len, metadataPack, metaPackSize );
ParodusPrint("encodedSize after appending :%zu\n", encodedSize);
ParodusPrint("metadata appended upstream msg %s\n", (char *)appendData);
ParodusInfo("Sending metadata appended upstream msg to server\n");
sendMessage(get_global_conn(),appendData, encodedSize);
free( appendData);
appendData =NULL;
}
else
{
ParodusError("Failed to send upstream as metadata packing is not successful\n");
}
}
}
//Sending to server for msgTypes 3, 5, 6, 7, 8.
if( WRP_MSG_TYPE__REQ == msgType )
{
ParodusInfo(" Received upstream data with MsgType: %d dest: '%s' transaction_uuid: %s\n", msgType, msg->u.req.dest, msg->u.req.transaction_uuid );
sendUpstreamMsgToServer(&message->msg, message->len);
}
else
{
ParodusInfo(" Received upstream data with MsgType: %d dest: '%s' transaction_uuid: %s status: %d\n",msgType, msg->u.crud.dest, msg->u.crud.transaction_uuid, msg->u.crud.status );
if(WRP_MSG_TYPE__RETREIVE == msgType)
{
ret = getDeviceId(&device_id, &device_id_len);
if(ret == 0)
{
ParodusPrint("device_id %s device_id_len %lu\n", device_id, device_id_len);
/* Match dest based on device_id. Check dest start with: "mac:112233445xxx" ? */
if( 0 == strncasecmp(device_id, msg->u.crud.dest, device_id_len-1) )
{
/* For this device. */
parodus_len = strlen( PARODUS_SERVICE_NAME );
if( 0 == strncmp(PARODUS_SERVICE_NAME, &msg->u.crud.dest[device_id_len], parodus_len-1) )
{
/* For Parodus CRUD queue. */
ParodusInfo("Create RetrieveMsg and add to parodus CRUD queue\n");
createUpstreamRetrieveMsg(msg, &retrieve_msg);
addCRUDmsgToQueue(retrieve_msg);
}
else
{
/* For nanomsg clients. */
getServiceNameAndSendResponse(msg, &message->msg, message->len);
}
}
else
{
/* Not for this device. Send upstream */
ParodusInfo("sendUpstreamMsgToServer \n");
sendUpstreamMsgToServer(&message->msg, message->len);
}
if(device_id != NULL)
{
free(device_id);
device_id = NULL;
}
}
else
{
ParodusError("Failed to get device_id\n");
}
}
else if((WRP_MSG_TYPE__UPDATE == msgType) || (WRP_MSG_TYPE__DELETE == msgType))
{
ParodusPrint("UPDATE/DELETE request\n");
ret = getDeviceId(&device_id, &device_id_len);
if(ret == 0)
{
ParodusPrint("device_id %s device_id_len %lu\n", device_id, device_id_len);
/* Match dest based on device_id. Check dest start with: "mac:112233445xxx" ? */
if( 0 == strncasecmp(device_id, msg->u.crud.dest, device_id_len-1) )
{
/* For this device. For nanomsg clients.*/
getServiceNameAndSendResponse(msg, &message->msg, message->len);
}
else
{
/* Not for this device. Send upstream */
ParodusInfo("sendUpstreamMsgToServer \n");
sendUpstreamMsgToServer(&message->msg, message->len);
}
if(device_id != NULL)
{
free(device_id);
device_id = NULL;
}
}
else
{
ParodusError("Failed to get device_id\n");
}
}
else if (WRP_MSG_TYPE__SVC_ALIVE != msgType) {
/* Don't reply to service alive message */
sendUpstreamMsgToServer(&message->msg, message->len);
}
}
}
}
else
{
ParodusError("Error in msgpack decoding for upstream\n");
}
ParodusPrint("Free for upstream decoded msg\n");
wrp_free_struct(msg);
msg = NULL;
if(nn_freemsg (message->msg) < 0)
{
ParodusError ("Failed to free msg\n");
//nn_freemsg should not be done for parodus/tags/ CRUD requests as it is not received through nanomsg.
if ((msg && (msg->u.crud.source !=NULL) && wrp_does_service_match("parodus", msg->u.crud.source) == 0))
{
free(message->msg);
}
else
{
if(nn_freemsg (message->msg) < 0)
{
ParodusError ("Failed to free msg\n");
}
}
ParodusPrint("Free for upstream decoded msg\n");
if (msg) {
wrp_free_struct(msg);
}
free(message);
message = NULL;
msg = NULL;
free(message);
message = NULL;
}
else
{
if (g_shutdown) {
pthread_mutex_unlock (&nano_mut);
break;
}
ParodusPrint("Before pthread cond wait in consumer thread\n");
pthread_cond_wait(&nano_con, &nano_mut);
pthread_mutex_unlock (&nano_mut);
@@ -330,11 +495,112 @@ void *processUpstreamMessage()
return NULL;
}
/**
* @brief getDeviceId function to create deviceId in the format "mac:112233445xxx"
*
* @param[out] device_id in the format "mac:112233445xxx"
* @param[out] total size of device_id
*/
int getDeviceId(char **device_id, size_t *device_id_len)
{
char *deviceID = NULL;
size_t len;
if((get_parodus_cfg()->hw_mac !=NULL) && (strlen(get_parodus_cfg()->hw_mac)!=0))
{
len = strlen(get_parodus_cfg()->hw_mac) + 5;
deviceID = (char *) malloc(sizeof(char)*64);
if(deviceID != NULL)
{
snprintf(deviceID, len, "mac:%s", get_parodus_cfg()->hw_mac);
*device_id = deviceID;
*device_id_len = len;
}
else
{
ParodusError("device_id allocation failed\n");
return -1;
}
}
else
{
ParodusError("device mac is NULL\n");
return -1;
}
return 0;
}
/**
* @brief createUpstreamRetrieveMsg function to create new message for processing Retrieve requests
*
* @param[in] message The upstream message received from cloud or internal clients
* @param[out] retrieve_msg New message for processing Retrieve requests
*/
void createUpstreamRetrieveMsg(wrp_msg_t *message, wrp_msg_t **retrieve_msg)
{
wrp_msg_t *msg;
msg = ( wrp_msg_t * ) malloc( sizeof( wrp_msg_t ) );
if(msg != NULL)
{
memset(msg, 0, sizeof(wrp_msg_t));
msg->msg_type = message->msg_type;
if(message->u.crud.transaction_uuid != NULL)
{
msg->u.crud.transaction_uuid = strdup(message->u.crud.transaction_uuid);
}
if(message->u.crud.source !=NULL)
{
msg->u.crud.source = strdup(message->u.crud.source);
}
if(message->u.crud.dest != NULL)
{
msg->u.crud.dest = strdup(message->u.crud.dest);
}
*retrieve_msg = msg;
}
}
/**
* @brief getServiceNameAndSendResponse function to fetch client service name and to send msg to it.
*
* @param[in] msg The decoded message to fetch client service name from its dest field
* @param[in] msg_bytes The encoded upstream msg to be sent to client
* @param[in] msg_size Total size of the msg to send to client
*/
void getServiceNameAndSendResponse(wrp_msg_t *msg, void **msg_bytes, size_t msg_size)
{
char *serviceName = NULL;
int sendStatus =-1;
serviceName = wrp_get_msg_element(WRP_ID_ELEMENT__SERVICE, msg, DEST);
if ( serviceName != NULL)
{
sendStatus=sendMsgtoRegisteredClients(serviceName,(const char **)msg_bytes, msg_size);
if(sendStatus ==1)
{
ParodusInfo("Send upstreamMsg successfully to registered client %s\n", serviceName);
}
else
{
ParodusError("Failed to send upstreamMsg to registered client %s\n", serviceName);
}
free(serviceName);
serviceName = NULL;
}
else
{
ParodusError("serviceName is NULL,not sending retrieve response to client\n");
}
}
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
{
void *appendData;
size_t encodedSize;
bool close_retry = false;
//appending response with metadata
if(metaPackSize > 0)
{
@@ -343,8 +609,19 @@ void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
ParodusPrint("encodedSize after appending :%zu\n", encodedSize);
ParodusInfo("Sending response to server\n");
sendMessage(get_global_conn(),appendData, encodedSize);
close_retry = get_close_retry();
/* send response when connection retry is not in progress. Also during cloud_disconnect UPDATE request. Here, close_retry becomes 1 hence check is added to send disconnect response to server. */
//TODO: Upstream and downstream messages in queue should be handled and queue should be empty before parodus forcefully disconnect from cloud.
if(!close_retry || (get_parodus_cfg()->cloud_disconnect !=NULL))
{
sendMessage(get_global_conn(),appendData, encodedSize);
}
else
{
ParodusInfo("close_retry is %d, unable to send response as connection retry is in progress\n", close_retry);
OnboardLog("close_retry is %d, unable to send response as connection retry is in progress\n", close_retry);
}
free(appendData);
appendData =NULL;
}

View File

@@ -1,18 +1,35 @@
/**
* 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 upstream.h
*
* @description This header defines functions required to manage upstream messages.
*
* Copyright (c) 2015 Comcast
*/
#ifndef _UPSTREAM_H_
#define _UPSTREAM_H_
#include <pthread.h>
#include <wrp-c.h>
#ifdef __cplusplus
extern "C" {
#endif
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
@@ -30,8 +47,14 @@ typedef struct UpStreamMsg__
void packMetaData();
void *handle_upstream();
void *processUpstreamMessage();
int getDeviceId(char **device_id, size_t *device_id_len);
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size);
void getServiceNameAndSendResponse(wrp_msg_t *msg, void **msg_bytes, size_t msg_size);
void createUpstreamRetrieveMsg(wrp_msg_t *message, wrp_msg_t **retrieve_msg);
void set_global_UpStreamMsgQ(UpStreamMsg * UpStreamQ);
UpStreamMsg * get_global_UpStreamMsgQ(void);
pthread_cond_t *get_global_nano_con(void);
pthread_mutex_t *get_global_nano_mut(void);
#ifdef __cplusplus
}

View File

@@ -1,4 +1,4 @@
# Copyright 2016 Comcast Cable Communications Management, LLC
# Copyright 2016 Comcast Cable Communications Management, LLCD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -16,205 +16,373 @@ set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -W -g -fprofile-arcs -ftest-coverage
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DTEST ")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -W -g -fprofile-arcs -ftest-coverage -O0")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage -O0")
set (PARODUS_COMMON_SRC ../src/string_helpers.c ../src/mutex.c ../src/time.c ../src/config.c ../src/spin_thread.c)
set (PARODUS_COMMON_LIBS gcov -lcunit -lcimplog -llibseshat -lwrp-c -luuid -lpthread -lm -lmsgpackc -lcjson -ltrower-base64 -lnopoll -lnanomsg -Wl,--no-as-needed -lrt)
set (PARODUS_COMMON_SRC ../src/string_helpers.c ../src/mutex.c
../src/time.c ../src/config.c ../src/spin_thread.c
../src/event_handler.c ../src/token.c)
set (PARODUS_COMMON_LIBS gcov -lcunit -lcimplog -lwrp-c
-luuid -lmsgpackc -lnopoll -lnanomsg -lpthread
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
if (ENABLE_SESHAT)
set (PARODUS_COMMON_LIBS -llibseshat ${PARODUS_COMMON_LIBS})
endif (ENABLE_SESHAT)
if (FEATURE_DNS_QUERY)
set (PARODUS_COMMON_LIBS ${PARODUS_COMMON_LIBS} -lucresolv -lresolv)
endif (FEATURE_DNS_QUERY)
if(NOT DISABLE_VALGRIND)
set (MEMORY_CHECK valgrind --leak-check=full --show-reachable=yes -v)
endif ()
link_directories ( ${LIBRARY_DIR} )
#-------------------------------------------------------------------------------
# test_heartBeatTimer
#-------------------------------------------------------------------------------
add_test(NAME test_heartBeatTimer COMMAND ${MEMORY_CHECK} ./test_heartBeatTimer)
add_executable(test_heartBeatTimer test_heartBeatTimer.c ../src/heartBeat.c)
target_link_libraries (test_heartBeatTimer ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_close_retry
#-------------------------------------------------------------------------------
add_test(NAME test_close_retry COMMAND ${MEMORY_CHECK} ./test_close_retry)
add_executable(test_close_retry test_close_retry.c ../src/close_retry.c)
target_link_libraries (test_close_retry ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_mutex
#-------------------------------------------------------------------------------
add_test(NAME test_mutex COMMAND test_mutex)
add_test(NAME test_mutex COMMAND ${MEMORY_CHECK} ./test_mutex)
add_executable(test_mutex test_mutex.c ../src/mutex.c)
target_link_libraries (test_mutex ${PARODUS_COMMON_LIBS} -lcmocka)
#-------------------------------------------------------------------------------
# test_networking
#-------------------------------------------------------------------------------
add_test(NAME test_networking COMMAND test_networking)
add_test(NAME test_networking COMMAND ${MEMORY_CHECK} ./test_networking)
add_executable(test_networking test_networking.c ../src/networking.c)
target_link_libraries (test_networking ${PARODUS_COMMON_LIBS})
#-------------------------------------------------------------------------------
# test_nopoll_helpers
#-------------------------------------------------------------------------------
add_test(NAME test_nopoll_helpers COMMAND test_nopoll_helpers)
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)
target_link_libraries (libpd_test
cunit
-llibparodus
-lwrp-c
-llibseshat
-luuid
-lmsgpackc
-ltrower-base64
-lnanomsg
-lcimplog
-lm
-lpthread
-lrt)
#-------------------------------------------------------------------------------
# test_time
#-------------------------------------------------------------------------------
add_test(NAME test_time COMMAND test_time)
add_test(NAME test_time COMMAND ${MEMORY_CHECK} ./test_time)
add_executable(test_time test_time.c ../src/time.c)
target_link_libraries (test_time ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_spin_thread error
#-------------------------------------------------------------------------------
add_test(NAME test_spin_thread_e COMMAND test_spin_thread_e)
add_test(NAME test_spin_thread_e COMMAND ${MEMORY_CHECK} ./test_spin_thread_e)
add_executable(test_spin_thread_e test_spin_thread_e.c ../src/spin_thread.c)
target_link_libraries (test_spin_thread_e ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_spin_thread success
#-------------------------------------------------------------------------------
add_test(NAME test_spin_thread_s COMMAND test_spin_thread_s)
add_executable(test_spin_thread_s test_spin_thread_s.c ../src/spin_thread.c)
target_link_libraries (test_spin_thread_s ${PARODUS_COMMON_LIBS} )
# add_test(NAME test_spin_thread_s COMMAND ${MEMORY_CHECK} ./test_spin_thread_s)
# add_executable(test_spin_thread_s test_spin_thread_s.c ../src/spin_thread.c)
# target_link_libraries (test_spin_thread_s ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_string_helpers
#-------------------------------------------------------------------------------
add_test(NAME test_string_helpers COMMAND test_string_helpers)
add_executable(test_string_helpers test_string_helpers.c ../src/string_helpers.c)
target_link_libraries (test_string_helpers ${PARODUS_COMMON_LIBS} )
# add_test(NAME test_string_helpers COMMAND ${MEMORY_CHECK} ./test_string_helpers)
# add_executable(test_string_helpers test_string_helpers.c ../src/string_helpers.c)
# target_link_libraries (test_string_helpers ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_nopoll_handlers
#-------------------------------------------------------------------------------
add_test(NAME test_nopoll_handlers COMMAND test_nopoll_handlers)
add_executable(test_nopoll_handlers test_nopoll_handlers.c ../src/nopoll_handlers.c)
add_test(NAME test_nopoll_handlers COMMAND ${MEMORY_CHECK} ./test_nopoll_handlers)
add_executable(test_nopoll_handlers test_nopoll_handlers.c ../src/nopoll_handlers.c ../src/heartBeat.c ../src/close_retry.c)
target_link_libraries (test_nopoll_handlers -lnopoll -lcunit -lcimplog -Wl,--no-as-needed -lrt -lpthread -lm)
#-------------------------------------------------------------------------------
# test_nopoll_handlers_fragment
#-------------------------------------------------------------------------------
add_test(NAME test_nopoll_handlers_fragment COMMAND ${MEMORY_CHECK} ./test_nopoll_handlers_fragment)
add_executable(test_nopoll_handlers_fragment test_nopoll_handlers_fragment.c ../src/nopoll_handlers.c ../src/heartBeat.c ../src/close_retry.c)
target_link_libraries (test_nopoll_handlers_fragment -lnopoll -lcunit -lcimplog -Wl,--no-as-needed -lrt -lpthread -lm -lcmocka)
#-------------------------------------------------------------------------------
# test_connection
#-------------------------------------------------------------------------------
add_test(NAME test_connection COMMAND test_connection)
add_executable(test_connection test_connection.c ../src/connection.c ${PARODUS_COMMON_SRC})
target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka)
add_test(NAME test_connection COMMAND ${MEMORY_CHECK} ./test_connection)
set (CONN_SRC ../src/connection.c
../src/string_helpers.c ../src/mutex.c ../src/time.c
../src/config.c ../src/auth_token.c ../src/spin_thread.c ../src/heartBeat.c ../src/close_retry.c)
#set(CONN_SRC ../src/connection.c ${PARODUS_COMMON_SRC})
add_executable(test_connection test_connection.c ${CONN_SRC})
target_link_libraries (test_connection ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_connection - function createNopollConnection
#-------------------------------------------------------------------------------
add_test(NAME test_createConnection COMMAND test_createConnection)
add_executable(test_createConnection test_createConnection.c ../src/connection.c ../src/string_helpers.c ../src/config.c)
target_link_libraries (test_createConnection ${PARODUS_COMMON_LIBS} -lcmocka)
#add_test(NAME test_createConnection COMMAND ${MEMORY_CHECK} ./test_createConnection)
#add_executable(test_createConnection test_createConnection.c ../src/connection.c ../src/string_helpers.c ../src/config.c)
#target_link_libraries (test_createConnection ${PARODUS_COMMON_LIBS} -lcmocka)
#add_executable(test_createConnection test_createConnection.c ../src/connection.c ../src/string_helpers.c ../src/config.c ../src/heartBeat.c)
#target_link_libraries (test_createConnection ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} -lcmocka )
#target_link_libraries (test_createConnection ${PARODUS_COMMON_LIBS} -lcmocka )
#-------------------------------------------------------------------------------
# test_client_list
#-------------------------------------------------------------------------------
add_test(NAME test_client_list COMMAND 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})
add_test(NAME test_client_list COMMAND ${MEMORY_CHECK} ./test_client_list)
#add_executable(test_client_list test_client_list.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/downstream.c ../src/connection.c ../src/nopoll_handlers.c ../src/ParodusInternal.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS})
set(CLIST_SRC test_client_list.c ../src/client_list.c ../src/auth_token.c
../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
../src/partners_check.c ../src/crud_interface.c ../src/crud_tasks.c ../src/crud_internal.c ${PARODUS_COMMON_SRC})
if (ENABLE_SESHAT)
set(CLIST_SRC ${CLIST_SRC} ../src/seshat_interface.c)
else()
set(CLIST_SRC ${CLIST_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_client_list ${CLIST_SRC})
#target_link_libraries (test_client_list ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS})
target_link_libraries (test_client_list ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_service_alive
#-------------------------------------------------------------------------------
add_test(NAME test_service_alive COMMAND 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})
add_test(NAME test_service_alive COMMAND ${MEMORY_CHECK} ./test_service_alive)
#add_executable(test_service_alive test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ${PARODUS_COMMON_SRC})
#target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS})
set(SVA_SRC test_service_alive.c ../src/client_list.c ../src/service_alive.c ../src/auth_token.c ../src/upstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/downstream.c ../src/thread_tasks.c ../src/conn_interface.c ../src/partners_check.c ../src/heartBeat.c ../src/close_retry.c ${PARODUS_COMMON_SRC})
if (ENABLE_SESHAT)
set(SVA_SRC ${SVA_SRC} ../src/seshat_interface.c)
else()
set(SVA_SRC ${SVA_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_service_alive ${SVA_SRC})
#target_link_libraries (test_service_alive ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS})
target_link_libraries (test_service_alive ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_config
#-------------------------------------------------------------------------------
add_test(NAME test_config COMMAND test_config)
add_executable(test_config test_config.c ../src/config.c ../src/string_helpers.c)
target_link_libraries (test_config -lcmocka -lm -Wl,--no-as-needed -lrt -lcimplog)
add_test(NAME test_config COMMAND ${MEMORY_CHECK} ./test_config)
add_executable(test_config test_config.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_config -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_auth_token
#-------------------------------------------------------------------------------
add_test(NAME test_auth_token COMMAND ${MEMORY_CHECK} ./test_auth_token)
add_executable(test_auth_token test_auth_token.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_auth_token -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_auth_token_more
#-------------------------------------------------------------------------------
add_test(NAME test_auth_token_more COMMAND ${MEMORY_CHECK} ./test_auth_token_more)
add_executable(test_auth_token_more test_auth_token_more.c ../src/config.c ../src/auth_token.c ../src/string_helpers.c)
target_link_libraries (test_auth_token_more -lcmocka
-Wl,--no-as-needed -lcimplog
-lcjson -lcjwt -ltrower-base64 -lssl -lcrypto -lrt -lm -lcurl -luuid
)
#-------------------------------------------------------------------------------
# test_crud_interface
#-------------------------------------------------------------------------------
add_test(NAME test_crud_interface COMMAND ${MEMORY_CHECK} ./test_crud_interface)
add_executable(test_crud_interface test_crud_interface.c ../src/crud_interface.c ../src/ParodusInternal.c)
target_link_libraries (test_crud_interface -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_crud_tasks
#-------------------------------------------------------------------------------
add_test(NAME test_crud_tasks COMMAND ${MEMORY_CHECK} ./test_crud_tasks)
add_executable(test_crud_tasks test_crud_tasks.c ../src/crud_tasks.c )
target_link_libraries (test_crud_tasks -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_crud_internal
#-------------------------------------------------------------------------------
add_test(NAME test_crud_internal COMMAND ${MEMORY_CHECK} ./test_crud_internal)
add_executable(test_crud_internal test_crud_internal.c ../src/config.c ../src/close_retry.c
../src/ParodusInternal.c ../src/string_helpers.c ../src/crud_internal.c ../src/client_list.c)
target_link_libraries (test_crud_internal -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_upstream
#-------------------------------------------------------------------------------
add_test(NAME test_upstream COMMAND test_upstream)
add_executable(test_upstream test_upstream.c ../src/upstream.c)
target_link_libraries (test_upstream -lcmocka ${PARODUS_COMMON_LIBS} )
add_test(NAME test_upstream COMMAND ${MEMORY_CHECK} ./test_upstream)
add_executable(test_upstream test_upstream.c ../src/upstream.c ../src/close_retry.c ../src/string_helpers.c)
target_link_libraries (test_upstream -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm -lnanomsg)
#-------------------------------------------------------------------------------
# test_upstream_sock
#-------------------------------------------------------------------------------
add_test(NAME test_upstream_sock COMMAND ${MEMORY_CHECK} ./test_upstream_sock)
add_executable(test_upstream_sock test_upstream_sock.c ../src/upstream.c
../src/client_list.c ../src/close_retry.c ../src/string_helpers.c)
target_link_libraries (test_upstream_sock -lcmocka gcov -lcunit -lcimplog
-lwrp-c -luuid -lpthread -lmsgpackc -lnopoll -lnanomsg
-Wl,--no-as-needed -lcjson -lcjwt -ltrower-base64
-lssl -lcrypto -lrt -lm)
#-------------------------------------------------------------------------------
# test_downstream
#-------------------------------------------------------------------------------
add_test(NAME test_downstream COMMAND 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
#-------------------------------------------------------------------------------
add_test(NAME test_downstream_more COMMAND ${MEMORY_CHECK} ./test_downstream_more)
add_executable(test_downstream_more test_downstream_more.c ../src/downstream.c ../src/string_helpers.c)
target_link_libraries (test_downstream_more -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_thread_tasks
#-------------------------------------------------------------------------------
add_test(NAME test_thread_tasks COMMAND test_thread_tasks)
add_test(NAME test_thread_tasks COMMAND ${MEMORY_CHECK} ./test_thread_tasks)
add_executable(test_thread_tasks test_thread_tasks.c ../src/thread_tasks.c)
target_link_libraries (test_thread_tasks -lcmocka ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# test_conn_interface
#-------------------------------------------------------------------------------
add_test(NAME test_conn_interface COMMAND test_conn_interface)
add_executable(test_conn_interface test_conn_interface.c ../src/conn_interface.c ../src/config.c ../src/string_helpers.c ../src/mutex.c)
target_link_libraries (test_conn_interface -lcmocka ${PARODUS_COMMON_LIBS} )
add_test(NAME test_conn_interface COMMAND ${MEMORY_CHECK} ./test_conn_interface)
set(CONIFC_SRC test_conn_interface.c
../src/crud_interface.c ../src/crud_tasks.c ../src/crud_internal.c
../src/conn_interface.c
../src/config.c
../src/token.c
../src/string_helpers.c
../src/mutex.c
../src/heartBeat.c
../src/close_retry.c
../src/event_handler.c
../src/client_list.c
)
if (ENABLE_SESHAT)
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface.c)
else()
set(CONIFC_SRC ${CONIFC_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_conn_interface ${CONIFC_SRC})
target_link_libraries (test_conn_interface -lcmocka ${PARODUS_COMMON_LIBS} -lcurl -luuid )
#-------------------------------------------------------------------------------
# test_ParodusInternal
#-------------------------------------------------------------------------------
add_test(NAME test_ParodusInternal COMMAND 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
#-------------------------------------------------------------------------------
add_test(NAME test_partners_check COMMAND test_partners_check)
add_executable(test_partners_check test_partners_check.c ../src/partners_check.c)
target_link_libraries (test_partners_check -lcmocka -lwrp-c -llibseshat ${PARODUS_COMMON_LIBS})
add_test(NAME test_partners_check COMMAND ${MEMORY_CHECK} ./test_partners_check)
add_executable(test_partners_check test_partners_check.c ../src/partners_check.c ../src/string_helpers.c)
target_link_libraries (test_partners_check -lcmocka ${PARODUS_COMMON_LIBS} -lwrp-c)
#-------------------------------------------------------------------------------
# test_token - token.c tests
#-------------------------------------------------------------------------------
add_test(NAME test_token COMMAND ${MEMORY_CHECK} ./test_token)
set(TOKEN_SRC ../src/conn_interface.c ../src/config.c
../src/connection.c ../src/spin_thread.c
../src/service_alive.c ../src/client_list.c
../src/nopoll_handlers.c ../src/nopoll_helpers.c
../src/partners_check.c ../src/ParodusInternal.c
../src/upstream.c ../src/downstream.c
../src/networking.c ../src/auth_token.c
../src/thread_tasks.c ../src/time.c
../src/string_helpers.c ../src/mutex.c
../src/token.c ../src/heartBeat.c
../src/close_retry.c ../src/event_handler.c
)
if (ENABLE_SESHAT)
set(TOKEN_SRC ${TOKEN_SRC} ../src/seshat_interface.c)
else()
set(TOKEN_SRC ${TOKEN_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
if (FEATURE_DNS_QUERY)
set(TOKEN_SRC test_token.c ${TOKEN_SRC})
else()
set(TOKEN_SRC test_token_stub.c ${TOKEN_SRC})
endif (FEATURE_DNS_QUERY)
add_executable(test_token ${TOKEN_SRC} )
#target_link_libraries (test_token ${PARODUS_COMMON_LIBS} ${PARODUS_JWT_LIBS} -lcmocka )
target_link_libraries (test_token ${PARODUS_COMMON_LIBS} -lcmocka -lcurl -luuid)
#-------------------------------------------------------------------------------
# test_seshat_interface - registerWithSeshat
#-------------------------------------------------------------------------------
add_test(NAME test_seshat_interface COMMAND ${MEMORY_CHECK} ./test_seshat_interface)
if (ENABLE_SESHAT)
set(SESHIFC_SRC test_seshat_interface.c ../src/seshat_interface.c ../src/string_helpers.c)
else()
set(SESHIFC_SRC test_seshat_interface_stub.c ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(test_seshat_interface ${SESHIFC_SRC})
target_link_libraries (test_seshat_interface -lcmocka ${PARODUS_COMMON_LIBS} -lwrp-c)
if (INTEGRATION_TESTING)
#-------------------------------------------------------------------------------
# simple_connection test
#-------------------------------------------------------------------------------
add_test(NAME simple_connection COMMAND simple_connection)
add_executable(simple_connection simple_connection.c ${PARODUS_COMMON_SRC}
../src/upstream.c
../src/conn_interface.c
../src/thread_tasks.c
../src/downstream.c
../src/networking.c
../src/nopoll_helpers.c
../src/nopoll_handlers.c
../src/connection.c
../src/ParodusInternal.c
../src/client_list.c
../src/partners_check.c
../src/service_alive.c)
target_link_libraries (simple_connection ${PARODUS_COMMON_LIBS})
add_test(NAME simple_connection COMMAND ${MEMORY_CHECK} ./simple_connection)
set(SIMCON_SRC simple_connection.c ${PARODUS_COMMON_SRC} ../src/upstream.c ../src/conn_interface.c
../src/thread_tasks.c ../src/downstream.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/connection.c ../src/ParodusInternal.c ../src/client_list.c ../src/partners_check.c ../src/service_alive.c)
if (ENABLE_SESHAT)
set(SIMCON_SRC ${SIMCON_SRC} ../src/seshat_interface.c)
else()
set(SIMCON_SRC ${SIMCON_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(simple_connection ${SIMCON_SRC})
target_link_libraries (simple_connection ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} )
#-------------------------------------------------------------------------------
# simple test
#-------------------------------------------------------------------------------
add_test(NAME simple COMMAND simple)
add_executable(simple simple.c
../src/upstream.c
../src/conn_interface.c
../src/downstream.c
../src/thread_tasks.c
../src/networking.c
../src/nopoll_helpers.c
../src/nopoll_handlers.c
../src/string_helpers.c
../src/mutex.c
../src/time.c
../src/config.c
../src/connection.c
../src/ParodusInternal.c
../src/spin_thread.c
../src/client_list.c
../src/partners_check.c
../src/service_alive.c)
add_test(NAME simple COMMAND ${MEMORY_CHECK} ./simple)
set(SIMPLE_SRC simple.c ../src/upstream.c ../src/conn_interface.c ../src/downstream.c ../src/thread_tasks.c ../src/networking.c ../src/nopoll_helpers.c ../src/nopoll_handlers.c ../src/string_helpers.c ../src/mutex.c ../src/time.c
../src/config.c ../src/connection.c ../src/ParodusInternal.c ../src/spin_thread.c ../src/client_list.c ../src/partners_check.c ../src/service_alive.c)
if (ENABLE_SESHAT)
set(SIMPLE_SRC ${SIMPLE_SRC} ../src/seshat_interface.c)
else()
set(SIMPLE_SRC ${SIMPLE_SRC} ../src/seshat_interface_stub.c)
endif (ENABLE_SESHAT)
add_executable(simple ${SIMPLE_SRC})
target_link_libraries (simple ${PARODUS_COMMON_LIBS} gcov -lnopoll -lnanomsg )
target_link_libraries (simple ${PARODUS_CONN_LIBS} ${PARODUS_COMMON_LIBS} gcov -lnopoll )
endif (INTEGRATION_TESTING)

28
tests/key4.pem Normal file
View File

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

View File

@@ -1,402 +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>
#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;
strcpy (buf, str);
return buf;
}
void insert_number_into_buf (char *buf, unsigned num)
{
char *pos = strrchr (buf, '#');
if (NULL == pos)
return;
while (true) {
*pos = (num%10) + '0';
num /= 10;
if (pos <= buf)
break;
pos--;
if (*pos != '#')
break;
}
}
int send_event_msg (const char *src, const char *dest,
const char *payload, unsigned event_num)
{
int rtn = 0;
char *payload_buf;
wrp_msg_t *new_msg;
#ifndef SEND_EVENT_MSGS
return 0;
#endif
new_msg = malloc (sizeof (wrp_msg_t));
if (NULL == new_msg)
return -1;
printf ("Making event msg\n");
new_msg->msg_type = WRP_MSG_TYPE__EVENT;
new_msg->u.event.source = new_str (src);
new_msg->u.event.dest = new_str (dest);
new_msg->u.event.headers = NULL;
new_msg->u.event.metadata = NULL;
payload_buf = new_str (payload);
insert_number_into_buf (payload_buf, event_num);
new_msg->u.event.payload = (void*) payload_buf;
new_msg->u.event.payload_size = strlen (payload) + 1;
printf ("Sending event msg %u\n", event_num);
rtn = libparodus_send (test_instance, new_msg);
//printf ("Freeing event msg\n");
wrp_free_struct (new_msg);
//printf ("Freed event msg\n");
return rtn;
}
int send_event_msgs (unsigned *msg_num, unsigned *event_num, int count)
{
int i;
unsigned msg_num_mod;
#ifndef SEND_EVENT_MSGS
return 0;
#endif
if (NULL != msg_num) {
(*msg_num)++;
msg_num_mod = (*msg_num) % 3;
if (msg_num_mod != 0)
return 0;
}
for (i=0; i<count; i++) {
(*event_num)++;
if (send_event_msg ("---LIBPARODUS---", "---ParodusService---",
"---EventMessagePayload####", *event_num) != 0)
return -1;
}
return 0;
}
int get_msg_num (const char *msg)
{
int num = -1;
bool found_pound = false;
int i;
char c;
for (i=0; (c=msg[i]) != 0; i++)
{
if (!found_pound) {
if (c == '#')
found_pound = true;
continue;
}
if ((c>='0') && (c<='9')) {
if (num == -1)
num = c - '0';
else
num = 10*num + (c - '0');
}
}
return num;
}
static int flush_queue_count = 0;
void qfree (void * msg)
{
flush_queue_count++;
free (msg);
}
void delay_ms(unsigned int secs, unsigned int msecs)
{
struct timespec ts;
ts.tv_sec = (time_t) secs;
ts.tv_nsec = (long) msecs * 1000000L;
nanosleep (&ts, NULL);
}
void dbg_log_err (const char *fmt, ...)
{
char errbuf[100];
va_list arg_ptr;
va_start(arg_ptr, fmt);
vprintf(fmt, arg_ptr);
va_end(arg_ptr);
printf ("LIBPD_TEST: %s\n", strerror_r (errno, errbuf, 100));
}
void wait_auth_received (void)
{
if (!is_auth_received ()) {
printf ("Waiting for auth received\n");
sleep(1);
}
if (!is_auth_received ()) {
printf ("Waiting for auth received\n");
sleep(1);
}
CU_ASSERT (is_auth_received ());
}
void test_send_only (void)
{
unsigned event_num = 0;
libpd_cfg_t cfg = {.service_name = service_name,
.receive = false, .keepalive_timeout_secs = 0};
CU_ASSERT (libparodus_init (&test_instance, &cfg) == 0);
CU_ASSERT (send_event_msgs (NULL, &event_num, 10) == 0);
CU_ASSERT (libparodus_shutdown (&test_instance) == 0);
}
void test_1(void)
{
unsigned msgs_received_count = 0;
int rtn;
wrp_msg_t *wrp_msg;
unsigned event_num = 0;
unsigned msg_num = 0;
libpd_cfg_t cfg = {.service_name = service_name,
.receive = true, .keepalive_timeout_secs = 0};
if (no_mock_send_only_test) {
test_send_only ();
return;
}
cfg.parodus_url = GOOD_PARODUS_URL;
cfg.client_url = GOOD_CLIENT_URL;
CU_ASSERT (libparodus_init (&test_instance, &cfg) == 0);
printf ("LIBPD_TEST: libparodus_init successful\n");
initEndKeypressHandler ();
wait_auth_received ();
printf ("LIBPD_TEST: starting msg receive loop\n");
while (true) {
rtn = libparodus_receive (test_instance, &wrp_msg, 2000);
if (rtn == 1) {
printf ("LIBPD_TEST: Timed out waiting for msg\n");
if (msgs_received_count > 0)
if (send_event_msgs (&msg_num, &event_num, 5) != 0)
break;
continue;
}
if (rtn != 0)
break;
show_wrp_msg (wrp_msg);
msgs_received_count++;
if (wrp_msg->msg_type == WRP_MSG_TYPE__REQ)
send_reply (wrp_msg);
wrp_free_struct (wrp_msg);
if (send_event_msgs (&msg_num, &event_num, 5) != 0)
break;
}
printf ("Messages received %u\n", msgs_received_count);
CU_ASSERT (libparodus_shutdown (&test_instance) == 0);
}
/*
* @brief To initiate end keypress handler
*/
static void initEndKeypressHandler()
{
int err = 0;
err = pthread_create(&endKeypressThreadId, NULL, endKeypressHandlerTask, NULL);
if (err != 0)
{
libpd_log (LEVEL_ERROR, "Error creating End Keypress Handler thread\n");
}
else
{
printf ("End Keypress handler Thread created successfully\n");
printf ("\n--->> Press <Enter> to shutdown the test. ---\n");
}
}
/*
* @brief To handle End Keypress
*/
static void *endKeypressHandlerTask()
{
char inbuf[10];
memset(inbuf, 0, 10);
while (true) {
fgets (inbuf, 10, stdin);
if ((inbuf[0] != '\n') && (inbuf[0] != '\0')) {
printf ("endKeyPressHandler exiting\n");
break;
}
}
libparodus_close_receiver (test_instance);
return NULL;
}
void add_suites( CU_pSuite *suite )
{
*suite = CU_add_suite( "libparodus tests", NULL, NULL );
CU_add_test( *suite, "Test 1", test_1 );
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( int argc, char **argv __attribute__((unused)) )
{
unsigned rv = 1;
CU_pSuite suite = NULL;
if (argc > 1) {
const char *arg = argv[1];
if ((arg[0] == 's') || (arg[0] == 'S'))
no_mock_send_only_test = true;
}
if( CUE_SUCCESS == CU_initialize_registry() ) {
add_suites( &suite );
if( NULL != suite ) {
CU_basic_set_mode( CU_BRM_VERBOSE );
CU_basic_run_tests();
printf( "\n" );
CU_basic_show_failures( CU_get_failure_list() );
printf( "\n\n" );
rv = CU_get_number_of_tests_failed();
}
CU_cleanup_registry();
}
if( 0 != rv ) {
return 1;
}
return 0;
}

104
tests/mock_event_handler.c Normal file
View File

@@ -0,0 +1,104 @@
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2016 RDK Management
* Copyright [2014] [Cisco Systems, Inc.]
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* This is a test version of event_handler.c that can be used
* to simulate interface down, interface up event
* You overwrite event_handler.c in the src diectory with this
* version. It will generate interface down / interface up events
* at random intervals between 60 secs and 124 secs
*/
#include "parodus_log.h"
#include "event_handler.h"
#include "connection.h"
#include "config.h"
#include "heartBeat.h"
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "time.h"
#include "close_retry.h"
extern bool g_shutdown;
static pthread_t sysevent_tid;
static void start_interface_down (void)
{
set_interface_down_event();
ParodusInfo("Interface_down_event is set\n");
pause_heartBeatTimer();
}
static void end_interface_down (void)
{
reset_interface_down_event();
ParodusInfo("Interface_down_event is reset\n");
resume_heartBeatTimer();
set_close_retry();
}
// waits from 60 to 124 secs
int wait_random (const char *msg)
{
#define HALF_SEC 500000l
long delay = (random() >> 5) + 60000000l;
long secs, usecs;
struct timeval timeout;
secs = delay / 1000000;
usecs = delay % 1000000;
ParodusInfo ("Waiting %ld secs %ld usecs for %s\n", secs, usecs, msg);
while (!g_shutdown) {
timeout.tv_sec = 0;
if (delay <= HALF_SEC) {
timeout.tv_usec = delay;
select (0, NULL, NULL, NULL, &timeout);
return 0;
}
timeout.tv_usec = HALF_SEC;
delay -= HALF_SEC;
select (0, NULL, NULL, NULL, &timeout);
}
return -1;
}
static void *parodus_sysevent_handler (void *data)
{
while (!g_shutdown) {
if (wait_random ("interface down") != 0)
break;
start_interface_down ();
wait_random ("interface up");
end_interface_down ();
}
ParodusInfo ("Exiting event handler\n");
return data;
}
void EventHandler()
{
ParodusInfo ("RAND_MAX is %ld (0x%lx)\n", RAND_MAX, RAND_MAX);
srandom (getpid());
pthread_create(&sysevent_tid, NULL, parodus_sysevent_handler, NULL);
}

3
tests/parodus_cmd.sh Executable file
View File

@@ -0,0 +1,3 @@
sudo ./parodus --hw-model=TG1682 --hw-serial-number=Fer23u948590 --hw-manufacturer=ARRISGroup,Inc. --hw-mac=aabb33ddeeff --hw-last-reboot-reason=unknown --fw-name=TG1682_DEV_master_2016000000sdy --boot-time=123589 --webpa-ping-timeout=180 --webpa-backoff-max=0 --webpa-interface-used=p7p1 --webpa-url=https://example.net:8080 --acquire-jwt=1 --jwt-algo=RS256 --jwt-public-key-file=../../tests/webpa-rs256.pem --dns-txt-url=example.net

9
tests/pubkey4.pem Normal file
View File

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

1
tests/return_failure.bsh Executable file
View File

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

1
tests/return_ser_mac.bsh Executable file
View File

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

1
tests/return_success.bsh Executable file
View File

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

View File

@@ -1,712 +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 <stdarg.h>
#include <CUnit/Basic.h>
#include <stdbool.h>
#include <assert.h>
#include <nopoll.h>
//#include <nanomsg/bus.h>
#include "../src/ParodusInternal.h"
#include "../src/config.h"
#include "../src/nopoll_helpers.h"
#include "../src/downstream.h"
#include "../src/upstream.h"
#include<errno.h>
/* Nanomsg related Macros */
#define ENDPOINT "tcp://127.0.0.1:6666"
#define CLIENT1_URL "tcp://127.0.0.1:6667"
#define CLIENT2_URL "tcp://127.0.0.1:6668"
#define CLIENT3_URL "tcp://127.0.0.1:6669"
#define HTTP_CUSTOM_HEADER_COUNT 4
static void send_nanomsg_upstream(void **buf, int size);
void *handle_testsuites();
headers_t headers = { 2, {"Header 1", "Header 2"}};
void test_nanomsg_client_registration1()
{
/*****Test svc registation for nanomsg client1 ***/
ParodusInfo("test_nanomsg_client_registration1\n");
const wrp_msg_t reg = { .msg_type = WRP_MSG_TYPE__SVC_REGISTRATION,
.u.reg.service_name = "iot",
.u.reg.url = CLIENT1_URL};
void *bytes;
int size =0;
int rv1, rc;
wrp_msg_t *msg1;
int sock, bind;
int byte =0;
int t=25000;
// msgpack encode
ParodusPrint("msgpack encode\n");
size = wrp_struct_to( &reg, WRP_BYTES, &bytes );
/*** Enable this to decode and verify upstream registration msg **/
/***
rv = wrp_to_struct(bytes, size, WRP_BYTES, &message);
ParodusPrint("decoded msgType:%d\n", message->msg_type);
ParodusPrint("decoded service_name:%s\n", message->u.reg.service_name);
ParodusPrint("decoded dest:%s\n", message->u.reg.url);
wrp_free_struct(message);
***/
//nanomsg socket
sock = nn_socket (AF_SP, NN_PUSH);
int connect = nn_connect (sock, ENDPOINT);
CU_ASSERT(connect >= 0);
rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_SNDTIMEO, &t, sizeof(t));
CU_ASSERT(rc >= 0);
byte = nn_send (sock, bytes, size, 0);
ParodusInfo("----->Expected byte to be sent:%d\n", size);
ParodusInfo("----->actual byte sent:%d\n", byte);
ParodusInfo("Nanomsg client1 - Testing Upstream Registration msg send\n");
CU_ASSERT_EQUAL( byte, size );
//************************************************************
int sock1 = nn_socket (AF_SP, NN_PULL);
byte = 0;
bind = nn_bind(sock1, reg.u.reg.url);
CU_ASSERT(bind >= 0);
void *buf = NULL;
rc = nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
CU_ASSERT(rc >= 0);
ParodusPrint("Client 1 waiting for acknowledgement \n");
byte = nn_recv(sock1, &buf, NN_MSG, 0);
ParodusInfo("Data Received for client 1 : %s \n", (char * )buf);
rv1 = wrp_to_struct((void *)buf, byte, WRP_BYTES, &msg1);
CU_ASSERT_EQUAL( rv1, byte );
ParodusPrint("msg1->msg_type for client 1 = %d \n", msg1->msg_type);
ParodusPrint("msg1->status for client 1 = %d \n", msg1->u.auth.status);
CU_ASSERT_EQUAL(msg1->msg_type, 2);
CU_ASSERT_EQUAL(msg1->u.auth.status, 200);
rc = nn_freemsg(buf);
CU_ASSERT(rc == 0);
free(bytes);
wrp_free_struct(msg1);
rc = nn_shutdown(sock1, bind);
CU_ASSERT(rc == 0);
}
void test_nanomsg_client_registration2()
{
/*****Test svc registation for upstream - nanomsg client2 ***/
ParodusInfo("test_nanomsg_client_registration2\n");
const wrp_msg_t reg = { .msg_type = WRP_MSG_TYPE__SVC_REGISTRATION,
.u.reg.service_name = "iot2",
.u.reg.url = CLIENT2_URL};
void *bytes;
int size;
int rv1, rc;
wrp_msg_t *msg1;
int sock, bind;
int byte =0;
int t=28000;
// msgpack encode
ParodusPrint("msgpack encode\n");
size = wrp_struct_to( &reg, WRP_BYTES, &bytes );
/*** Enable this to decode and verify packed upstream registration msg **/
/**
rv = wrp_to_struct(bytes, size, WRP_BYTES, &message);
ParodusPrint("decoded msgType:%d\n", message->msg_type);
ParodusPrint("decoded service_name:%s\n", message->u.reg.service_name);
ParodusPrint("decoded dest:%s\n", message->u.reg.url);
wrp_free_struct(message);
***/
//nanomsg socket
sock = nn_socket (AF_SP, NN_PUSH);
int connect = nn_connect (sock, ENDPOINT);
CU_ASSERT( connect >= 0);
rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_SNDTIMEO, &t, sizeof(t));
CU_ASSERT(rc >= 0);
byte = nn_send (sock, bytes, size,0);
ParodusInfo("----->Expected byte to be sent:%d\n", size);
ParodusInfo("----->actual byte sent:%d\n", byte);
ParodusInfo("Nanomsg client2 - Testing Upstream Registration msg send\n");
CU_ASSERT_EQUAL( byte, size );
int sock1 = nn_socket (AF_SP, NN_PULL);
byte = 0;
bind = nn_bind(sock1, reg.u.reg.url);
CU_ASSERT(bind >= 0);
void *buf1 = NULL;
rc = nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
CU_ASSERT(rc >= 0);
ParodusPrint("Client 2 waiting for acknowledgement \n");
byte = nn_recv(sock1, &buf1, NN_MSG, 0);
ParodusInfo("Data Received : %s \n", (char * )buf1);
rv1 = wrp_to_struct((void *)buf1, byte, WRP_BYTES, &msg1);
CU_ASSERT_EQUAL( rv1, byte );
ParodusPrint("msg1->msg_type for client 2 = %d \n", msg1->msg_type);
ParodusPrint("msg1->status for client 2 = %d \n", msg1->u.auth.status);
CU_ASSERT_EQUAL(msg1->msg_type, 2);
CU_ASSERT_EQUAL(msg1->u.auth.status, 200);
rc = nn_freemsg(buf1);
CU_ASSERT(rc == 0);
free(bytes);
wrp_free_struct(msg1);
rc = nn_shutdown(sock1, bind);
CU_ASSERT(rc == 0);
}
void test_nanomsg_client_registration3()
{
/*****Test svc registation for upstream - nanomsg client2 ***/
ParodusInfo("test_nanomsg_client_registration3\n");
const wrp_msg_t reg = { .msg_type = WRP_MSG_TYPE__SVC_REGISTRATION,
.u.reg.service_name = "iot",
.u.reg.url = CLIENT3_URL};
void *bytes;
int size;
int rv1, rc;
wrp_msg_t *msg1;
int sock;
int byte =0;
int t=35000;
// msgpack encode
ParodusPrint("msgpack encode\n");
size = wrp_struct_to( &reg, WRP_BYTES, &bytes );
/*** Enable this to decode and verify packed upstream registration msg **/
/**
rv = wrp_to_struct(bytes, size, WRP_BYTES, &message);
ParodusPrint("decoded msgType:%d\n", message->msg_type);
ParodusPrint("decoded service_name:%s\n", message->u.reg.service_name);
ParodusPrint("decoded dest:%s\n", message->u.reg.url);
wrp_free_struct(message);
***/
//nanomsg socket
sock = nn_socket (AF_SP, NN_PUSH);
int connect = nn_connect (sock, ENDPOINT);
CU_ASSERT(connect >= 0);
rc = nn_setsockopt(sock, NN_SOL_SOCKET, NN_SNDTIMEO, &t, sizeof(t));
CU_ASSERT(rc >= 0);
byte = nn_send (sock, bytes, size,0);
ParodusInfo("----->Expected byte to be sent:%d\n", size);
ParodusInfo("----->actual byte sent:%d\n", byte);
ParodusInfo("Nanomsg client3 - Testing Upstream Registration msg send\n");
CU_ASSERT_EQUAL( byte, size );
int sock1 = nn_socket (AF_SP, NN_PULL);
byte = 0;
int bind = nn_bind(sock1, reg.u.reg.url);
CU_ASSERT(bind >= 0);
ParodusPrint("Need to close this bind %d \n", bind);
void *buf2 = NULL;
rc = nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
CU_ASSERT(rc >= 0);
ParodusPrint("Client 3 is waiting for acknowledgement \n");
byte = nn_recv(sock1, &buf2, NN_MSG, 0);
ParodusInfo("Data Received : %s \n", (char * )buf2);
rv1 = wrp_to_struct((void *)buf2, byte, WRP_BYTES, &msg1);
CU_ASSERT_EQUAL( rv1, byte );
ParodusPrint("msg1->msg_type for client 3 = %d \n", msg1->msg_type);
ParodusPrint("msg1->status for client 3 = %d \n", msg1->u.auth.status);
CU_ASSERT_EQUAL(msg1->msg_type, 2);
CU_ASSERT_EQUAL(msg1->u.auth.status, 200);
rc = nn_freemsg(buf2);
CU_ASSERT(rc == 0);
free(bytes);
wrp_free_struct(msg1);
rc = nn_shutdown(sock1, bind);
CU_ASSERT(rc == 0);
}
void test_nanomsg_downstream_success()
{
ParodusInfo("test_nanomsg_downstream_success\n");
int sock;
int bit=0, rc;
wrp_msg_t *message;
void *buf =NULL;
char* destVal = NULL;
// char dest[32] = {'\0'};
char *dest = NULL;
//char *temp_ptr;
int bind = -1;
const wrp_msg_t msg = { .msg_type = WRP_MSG_TYPE__SVC_REGISTRATION,
.u.reg.service_name = "iot",
.u.reg.url = CLIENT3_URL};
sock = nn_socket (AF_SP, NN_PULL);
while(bind == -1)
{
bind = nn_bind(sock, msg.u.reg.url);
sleep(3);
}
ParodusPrint("Bind returns = %d \n", bind);
ParodusPrint("***** Nanomsg client3 in Receiving mode in %s *****\n", msg.u.reg.url);
bit = nn_recv (sock, &buf, NN_MSG, 0);
ParodusInfo ("----->Received downstream request from server to client3 : \"%s\"\n", (char *)buf);
ParodusPrint("Received %d bytes\n", bit);
CU_ASSERT(bit >= 0);
//Decode and verify downstream request has received by correct registered client
wrp_to_struct(buf, bit, WRP_BYTES, &message);
destVal = message->u.req.dest;
dest = strtok(destVal , "/");
//temp_ptr = strtok(destVal , "/");
// ParodusPrint("temp_ptr = %s \n", temp_ptr);
strcpy(dest,strtok(NULL , "/"));
ParodusInfo("------>decoded dest:%s\n", dest);
CU_ASSERT_STRING_EQUAL( msg.u.reg.service_name, dest );
wrp_free_struct(message);
//To send nanomsg client response upstream
send_nanomsg_upstream(&buf, bit);
rc = nn_freemsg(buf);
CU_ASSERT(rc == 0);
rc = nn_shutdown(sock, bind);
CU_ASSERT(rc == 0);
//Need to wait for parodus to finish it's task.
sleep(10);
}
void test_nanomsg_downstream_failure()
{
int sock, bind, rc;
int bit =0;
char *buf =NULL;
ParodusError("test_nanomsg_downstream_failure\n");
sleep(60);
sock = nn_socket (AF_SP, NN_PULL);
bind = nn_bind (sock, CLIENT3_URL);
CU_ASSERT(bind >= 0);
ParodusPrint("***** Nanomsg client3 in Receiving mode *****\n");
bit = nn_recv (sock, &buf, NN_MSG, 0);
ParodusInfo ("Received downstream request from server for client3 : \"%s\"\n", buf);
CU_ASSERT(bit >= 0);
rc = nn_freemsg(buf);
CU_ASSERT(rc == 0);
rc = nn_shutdown(sock, bind);
CU_ASSERT(rc == 0);
}
void test_checkHostIp()
{
int ret;
ParodusPrint("**********************************Calling check_host_ip \n");
ret = checkHostIp("fabric.webpa.comcast.net");
ParodusPrint("------------------> Ret = %d \n", ret);
CU_ASSERT_EQUAL(ret, 0);
}
void test_sendMessage()
{
noPollConnOpts * opts;
noPollCtx *ctx = NULL;
noPollConn *conn = NULL;
ParodusPrint("**********************************Calling sendMessage \n");
const char * headerNames[HTTP_CUSTOM_HEADER_COUNT] = {"X-WebPA-Device-Name","X-WebPA-Device-Protocols","User-Agent", "X-WebPA-Convey"};
const char * headerValues[HTTP_CUSTOM_HEADER_COUNT];
headerValues[0] = "123567892366";
headerValues[1] = "wrp-0.11,getset-0.1";
headerValues[2] = "WebPA-1.6 (TG1682_DEV_master_2016000000sdy;TG1682/ARRISGroup,Inc.;)";
headerValues[3] = "zacbvfxcvglodfjdigjkdshuihgkvn";
int headerCount = HTTP_CUSTOM_HEADER_COUNT;
//ctx = nopoll_ctx_new();
opts = nopoll_conn_opts_new ();
nopoll_conn_opts_ssl_peer_verify (opts, nopoll_false);
nopoll_conn_opts_set_ssl_protocol (opts, NOPOLL_METHOD_TLSV1_2);
conn = nopoll_conn_tls_new(ctx, opts, "fabric.webpa.comcast.net", "8080", NULL, "/api/v2/device", NULL, NULL, "eth0",
headerNames, headerValues, headerCount);
/*while(conn == NULL)
{
opts = nopoll_conn_opts_new ();
nopoll_conn_opts_ssl_peer_verify (opts, nopoll_false);
nopoll_conn_opts_set_ssl_protocol (opts, NOPOLL_METHOD_TLSV1_2);
conn = nopoll_conn_tls_new(ctx, opts, "fabric.webpa.comcast.net", 8080, NULL, "/api/v2/device", NULL, NULL, "eth0",
headerNames, headerValues, headerCount);
}*/
ParodusPrint("Sending conn as %p \n", conn);
sendMessage(conn, "hello", 6);
}
void test_parseCommandLine()
{
int argc =11;
char * command[15]={'\0'};
command[0] = "parodus";
command[1] = "--hw-model=TG1682";
command[2] = "--hw-serial-number=Fer23u948590";
command[3] = "--hw-manufacturer=ARRISGroup,Inc.";
command[4] = "--hw-mac=123567892366";
command[5] = "--hw-last-reboot-reason=unknown";
command[6] = "--fw-name=TG1682_DEV_master_2016000000sdy";
command[7] = "--webpa-ping-time=180";
command[8] = "--webpa-inteface-used=eth0";
command[9] = "--webpa-url=fabric.webpa.comcast.net";
command[10] = "--webpa-backoff-max=0";
ParodusCfg parodusCfg;
memset(&parodusCfg,0,sizeof(parodusCfg));
ParodusPrint("call parseCommand\n");
parseCommandLine(argc,command,&parodusCfg);
ParodusPrint("parodusCfg.webpa_ping_timeout is %d\n", parodusCfg.webpa_ping_timeout);
ParodusPrint("parodusCfg.webpa_backoff_max is %d\n", parodusCfg.webpa_backoff_max);
CU_ASSERT_STRING_EQUAL( parodusCfg.hw_model, "TG1682");
CU_ASSERT_STRING_EQUAL( parodusCfg.hw_serial_number, "Fer23u948590");
CU_ASSERT_STRING_EQUAL( parodusCfg.hw_manufacturer, "ARRISGroup,Inc.");
CU_ASSERT_STRING_EQUAL( parodusCfg.hw_mac, "123567892366");
CU_ASSERT_STRING_EQUAL( parodusCfg.hw_last_reboot_reason, "unknown");
CU_ASSERT_STRING_EQUAL( parodusCfg.fw_name, "TG1682_DEV_master_2016000000sdy");
CU_ASSERT( parodusCfg.webpa_ping_timeout==180);
CU_ASSERT_STRING_EQUAL( parodusCfg.webpa_interface_used, "eth0");
CU_ASSERT_STRING_EQUAL( parodusCfg.webpa_url, "fabric.webpa.comcast.net");
CU_ASSERT( parodusCfg.webpa_backoff_max==0);
}
void test_loadParodusCfg()
{
ParodusPrint("Calling test_loadParodusCfg \n");
//ParodusCfg parodusCfg, tmpcfg;
ParodusCfg tmpcfg;
ParodusCfg *Cfg;
Cfg = (ParodusCfg*)malloc(sizeof(ParodusCfg));
strcpy(Cfg->hw_model, "TG1682");
strcpy(Cfg->hw_serial_number, "Fer23u948590");
strcpy(Cfg->hw_manufacturer , "ARRISGroup,Inc.");
strcpy(Cfg->hw_mac , "123567892366");
memset(&tmpcfg,0,sizeof(tmpcfg));
loadParodusCfg(Cfg,&tmpcfg);
ParodusInfo("tmpcfg.hw_model = %s, tmpcfg.hw_serial_number = %s, tmpcfg.hw_manufacturer = %s, tmpcfg.hw_mac = %s, \n", tmpcfg.hw_model,tmpcfg.hw_serial_number, tmpcfg.hw_manufacturer, tmpcfg.hw_mac);
CU_ASSERT_STRING_EQUAL( tmpcfg.hw_model, "TG1682");
CU_ASSERT_STRING_EQUAL( tmpcfg.hw_serial_number, "Fer23u948590");
CU_ASSERT_STRING_EQUAL( tmpcfg.hw_manufacturer, "ARRISGroup,Inc.");
CU_ASSERT_STRING_EQUAL( tmpcfg.hw_mac, "123567892366");
}
void add_suites( CU_pSuite *suite )
{
ParodusInfo("--------Start of Test Cases Execution ---------\n");
*suite = CU_add_suite( "tests", NULL, NULL );
CU_add_test( *suite, "Test 1", test_nanomsg_client_registration1 );
CU_add_test( *suite, "Test 2", test_nanomsg_client_registration2 );
CU_add_test( *suite, "Test 3", test_nanomsg_client_registration3 );
CU_add_test( *suite, "Test 4", test_nanomsg_downstream_success );
//CU_add_test( *suite, "Test 5", test_nanomsg_downstream_failure );
ParodusInfo("-------------Integration testing is completed-----------\n");
ParodusInfo("******************************************************************\n");
//sleep(10);
ParodusInfo("-------------Start of Unit Test Cases Execution---------\n");
CU_add_test( *suite, "UnitTest 1", test_parseCommandLine );
CU_add_test( *suite, "UnitTest 2", test_checkHostIp );
CU_add_test( *suite, "UnitTest 3", test_sendMessage );
CU_add_test( *suite, "UnitTest 4", test_loadParodusCfg );
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( void )
{
pid_t pid, pid1;
char value[512] = {'\0'};
char* data =NULL;
int status;
char commandUrl[255];
pid_t curl_pid;
char * command[] = {"parodus","--hw-model=TG1682", "--hw-serial-number=Fer23u948590","--hw-manufacturer=ARRISGroup,Inc.","--hw-mac=123567892366","--hw-last-reboot-reason=unknown","--fw-name=TG1682_DEV_master_2016000000sdy","--boot-time=10","--webpa-ping-time=180","--webpa-inteface-used=eth0","--webpa-url=fabric-cd.webpa.comcast.net","--webpa-backoff-max=9", NULL};
//int size = sizeof(command)/sizeof(command[0]);
//int i;
//ParodusInfo("commad: ");
//for(i=0;i<size-1;i++)
//ParodusInfo("command:%s",command);
ParodusInfo("Starting parodus process \n");
const char *s = getenv("WEBPA_AUTH_HEADER");
sprintf(commandUrl, "curl -i -H \"Authorization:Basic %s\" -H \"Accept: application/json\" -w %%{time_total} -k \"https://api-cd.webpa.comcast.net:8090/api/v2/device/mac:123567892366/iot?names=Device.DeviceInfo.Webpa.X_COMCAST-COM_SyncProtocolVersion\"", s);
ParodusPrint("---------------------->>>>Executing system(commandUrl)\n");
curl_pid = getpid();
ParodusPrint("child process execution with curl_pid:%d\n", curl_pid);
pid = fork();
if (pid == -1)
{
ParodusError("fork was unsuccessful for pid (errno=%d, %s)\n",errno, strerror(errno));
return -1;
}
else if (pid == 0)
{
int err;
ParodusPrint("child process created for parodus\n");
pid = getpid();
ParodusPrint("child process execution with pid:%d\n", pid);
err = execv("../src/parodus", command);
if(errno == 2)
{
err = execv("./src/parodus", command);
}
ParodusError("err is %d, errno is %d\n",err, errno);
}
else if (pid > 0)
{
int link[2];
sleep(5);
//Starting test suites execution in new thread
ParodusPrint("Creating new thread for test suite execution\n");
pthread_t testId;
int err1 = 0;
err1 = pthread_create(&testId,NULL,handle_testsuites,(void *)&pid);
if(err1 != 0)
ParodusError("Error creating test suite thread %s\n",strerror(err1));
else
ParodusPrint("test suite thread created successfully\n");
if (pipe(link)==-1)
{
ParodusError("Failed to create pipe\n");
}
else
ParodusPrint("Created pipe to read curl output\n");
pid1 = fork();
if (pid1 == -1)
{
ParodusError("fork was unsuccessful for pid1 (errno=%d, %s)\n",errno, strerror(errno));
return -1;
}
else if(pid1 == 0)
{
while(NULL == fopen("/tmp/parodus_ready", "r"))
{
sleep(5);
}
dup2 (link[1], STDOUT_FILENO);
close(link[0]);
close(link[1]);
sleep(40);
system(commandUrl);
ParodusInfo("\n----Executed first Curl request for downstream ------- \n");
}
else if(pid1 > 0)
{
//wait fro child process to finish and read from pipe
waitpid(pid1, &status, 0);
//reading from pipe
ParodusPrint("parent process...:%d\n", pid1);
close(link[1]);
int nbytes = read(link[0], value, sizeof(value));
ParodusPrint("Read %d \n", nbytes);
if ((data = strstr(value, "message:Success")) !=NULL)
{
ParodusInfo("curl success\n");
}
else
{
ParodusError("curl failure..\n");
}
while(1);
}
}
return 0;
}
void *handle_testsuites(void* pid)
{
unsigned rv = 1;
CU_pSuite suite = NULL;
pid_t pid_parodus = *((int *)pid);
ParodusPrint("Starting handle_testsuites thread\n");
sleep(25);
if( CUE_SUCCESS == CU_initialize_registry() )
{
add_suites( &suite );
if( NULL != suite )
{
CU_basic_set_mode( CU_BRM_VERBOSE );
CU_basic_run_tests();
ParodusPrint( "\n" );
CU_basic_show_failures( CU_get_failure_list() );
ParodusPrint( "\n\n" );
rv = CU_get_number_of_tests_failed();
}
CU_cleanup_registry();
}
kill(pid_parodus, SIGKILL);
ParodusInfo("parodus process with pid %d is stopped\n", pid_parodus);
if( 0 != rv )
{
_exit(-1);
}
_exit(0);
}
static void send_nanomsg_upstream(void **buf, int size)
{
/**** To send nanomsg response to server ****/
int rv;
void *bytes;
int resp_size;
int sock;
int byte;
wrp_msg_t *message;
ParodusInfo("Decoding downstream request received from server\n");
rv = wrp_to_struct(*buf, size, WRP_BYTES, &message);
ParodusPrint("after downstream req decode:%d\n", rv);
/**** Preparing Nanomsg client response ****/
wrp_msg_t resp_m;
resp_m.msg_type = WRP_MSG_TYPE__REQ;
ParodusPrint("resp_m.msg_type:%d\n", resp_m.msg_type);
resp_m.u.req.source = message->u.req.dest;
ParodusPrint("------resp_m.u.req.source is:%s\n", resp_m.u.req.source);
resp_m.u.req.dest = message->u.req.source;
ParodusPrint("------resp_m.u.req.dest is:%s\n", resp_m.u.req.dest);
resp_m.u.req.transaction_uuid = message->u.req.transaction_uuid;
ParodusPrint("------resp_m.u.req.transaction_uuid is:%s\n", resp_m.u.req.transaction_uuid);
resp_m.u.req.headers = NULL;
resp_m.u.req.payload = "{statusCode:200,message:Success}";
ParodusPrint("------resp_m.u.req.payload is:%s\n", (char *)resp_m.u.req.payload);
resp_m.u.req.payload_size = strlen(resp_m.u.req.payload);
resp_m.u.req.metadata = NULL;
resp_m.u.req.include_spans = false;
resp_m.u.req.spans.spans = NULL;
resp_m.u.req.spans.count = 0;
ParodusPrint("Encoding downstream response\n");
resp_size = wrp_struct_to( &resp_m, WRP_BYTES, &bytes );
/*** Enable this to verify downstream response by decoding ***/
/***
wrp_msg_t *message1;
rv = wrp_to_struct(bytes, resp_size, WRP_BYTES, &message1);
ParodusPrint("after downstream response decode:%d\n", rv);
ParodusPrint("downstream response decoded msgType:%d\n", message1->msg_type);
ParodusPrint("downstream response decoded source:%s\n", message1->u.req.source);
ParodusPrint("downstream response decoded dest:%s\n", message1->u.req.dest);
ParodusPrint("downstream response decoded transaction_uuid:%s\n", message1->u.req.transaction_uuid);
ParodusPrint("downstream response decoded payload:%s\n", (char*)message1->u.req.payload);
wrp_free_struct(message1);
***/
/**** Nanomsg client sending msgs ****/
sock = nn_socket (AF_SP, NN_PUSH);
int connect = nn_connect (sock, ENDPOINT);
CU_ASSERT(connect >= 0);
sleep(1);
ParodusInfo("nanomsg client sending response upstream\n");
byte = nn_send (sock, bytes, resp_size,0);
ParodusInfo("----->Expected byte to be sent:%d\n", resp_size);
ParodusInfo("----->actual byte sent:%d\n", byte);
CU_ASSERT(byte==resp_size );
wrp_free_struct(message);
free(bytes);
ParodusPrint("---- End of send_nanomsg_upstream ----\n");
}

View File

@@ -59,45 +59,45 @@ void test_set_global_conn()
set_global_conn(conn);
CU_ASSERT(conn == get_global_conn());
close_and_unref_connection(get_global_conn());
free(opts);
}
void test_set_parodus_cfg()
{
ParodusCfg *cfg;
ParodusCfg cfg;
cfg = (ParodusCfg*)malloc(sizeof(ParodusCfg));
strcpy(cfg->hw_model, "TG1682");
strcpy(cfg->hw_serial_number, "Fer23u948590");
strcpy(cfg->hw_manufacturer , "ARRISGroup,Inc.");
strcpy(cfg->hw_mac , "123567892366");
strcpy(cfg->hw_last_reboot_reason , "unknown");
strcpy(cfg->fw_name , "2.364s2");
strcpy(cfg->webpa_path_url , "/api/v2/device");
strcpy(cfg->webpa_url , "fabric-cd.webpa.comcast.net");
strcpy(cfg->webpa_interface_used , "eth0");
strcpy(cfg->webpa_protocol , "WebPA-1.6");
strcpy(cfg->webpa_uuid , "1234567-345456546");
cfg->secureFlag = 1;
cfg->boot_time = 423457;
cfg->webpa_ping_timeout = 30;
cfg->webpa_backoff_max = 255;
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.hw_last_reboot_reason , "unknown", sizeof(cfg.hw_last_reboot_reason));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_path_url , "/api/v2/device", sizeof(cfg.webpa_path_url));
parStrncpy(cfg.webpa_url , "fabric-cd.webpa.comcast.net", sizeof(cfg.webpa_url));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
parStrncpy(cfg.webpa_uuid , "1234567-345456546", sizeof(cfg.webpa_uuid));
cfg.secureFlag = 1;
cfg.boot_time = 423457;
cfg.webpa_ping_timeout = 30;
cfg.webpa_backoff_max = 255;
set_parodus_cfg(cfg);
set_parodus_cfg(&cfg);
CU_ASSERT_STRING_EQUAL(cfg->hw_model, get_parodus_cfg()->hw_model);
CU_ASSERT_STRING_EQUAL(cfg->webpa_uuid, get_parodus_cfg()->webpa_uuid);
CU_ASSERT_STRING_EQUAL(cfg->hw_serial_number, get_parodus_cfg()->hw_serial_number);
CU_ASSERT_STRING_EQUAL(cfg->hw_manufacturer , get_parodus_cfg()->hw_manufacturer);
CU_ASSERT_STRING_EQUAL(cfg->hw_mac, get_parodus_cfg()->hw_mac);
CU_ASSERT_STRING_EQUAL(cfg->hw_last_reboot_reason,get_parodus_cfg()->hw_last_reboot_reason);
CU_ASSERT_STRING_EQUAL(cfg->fw_name,get_parodus_cfg()->fw_name);
CU_ASSERT_STRING_EQUAL(cfg->webpa_url, get_parodus_cfg()->webpa_url);
CU_ASSERT_STRING_EQUAL(cfg->webpa_interface_used , get_parodus_cfg()->webpa_interface_used);
CU_ASSERT_STRING_EQUAL(cfg->webpa_protocol, get_parodus_cfg()->webpa_protocol);
CU_ASSERT_EQUAL(cfg->boot_time, get_parodus_cfg()->boot_time);
CU_ASSERT_EQUAL(cfg->webpa_ping_timeout, get_parodus_cfg()->webpa_ping_timeout);
CU_ASSERT_EQUAL(cfg->webpa_backoff_max, get_parodus_cfg()->webpa_backoff_max);
CU_ASSERT_EQUAL(cfg->secureFlag, get_parodus_cfg()->secureFlag);
CU_ASSERT_STRING_EQUAL(cfg.hw_model, get_parodus_cfg()->hw_model);
CU_ASSERT_STRING_EQUAL(cfg.webpa_uuid, get_parodus_cfg()->webpa_uuid);
CU_ASSERT_STRING_EQUAL(cfg.hw_serial_number, get_parodus_cfg()->hw_serial_number);
CU_ASSERT_STRING_EQUAL(cfg.hw_manufacturer , get_parodus_cfg()->hw_manufacturer);
CU_ASSERT_STRING_EQUAL(cfg.hw_mac, get_parodus_cfg()->hw_mac);
CU_ASSERT_STRING_EQUAL(cfg.hw_last_reboot_reason,get_parodus_cfg()->hw_last_reboot_reason);
CU_ASSERT_STRING_EQUAL(cfg.fw_name,get_parodus_cfg()->fw_name);
CU_ASSERT_STRING_EQUAL(cfg.webpa_url, get_parodus_cfg()->webpa_url);
CU_ASSERT_STRING_EQUAL(cfg.webpa_interface_used , get_parodus_cfg()->webpa_interface_used);
CU_ASSERT_STRING_EQUAL(cfg.webpa_protocol, get_parodus_cfg()->webpa_protocol);
CU_ASSERT_EQUAL(cfg.boot_time, get_parodus_cfg()->boot_time);
CU_ASSERT_EQUAL(cfg.webpa_ping_timeout, get_parodus_cfg()->webpa_ping_timeout);
CU_ASSERT_EQUAL(cfg.webpa_backoff_max, get_parodus_cfg()->webpa_backoff_max);
CU_ASSERT_EQUAL(cfg.secureFlag, get_parodus_cfg()->secureFlag);
}
void test_getWebpaConveyHeader()
@@ -117,6 +117,7 @@ void test_getWebpaConveyHeader()
CU_ASSERT_STRING_EQUAL(get_parodus_cfg()->webpa_protocol, cJSON_GetObjectItem(payload, WEBPA_PROTOCOL)->valuestring);
CU_ASSERT_EQUAL((int)get_parodus_cfg()->boot_time, cJSON_GetObjectItem(payload, BOOT_TIME)->valueint);
cJSON_Delete(payload);
}
void test_createSecureConnection()
@@ -175,7 +176,7 @@ void test_WebpaConveyHeaderWithNullValues()
CU_ASSERT_PTR_NULL(cJSON_GetObjectItem(payload, FIRMWARE_NAME));
CU_ASSERT_PTR_NULL(cJSON_GetObjectItem(payload, WEBPA_INTERFACE));
free(cfg);
cJSON_Delete(payload);
}
void add_suites( CU_pSuite *suite )

View File

@@ -39,7 +39,7 @@ bool LastReasonStatus;
nopoll_bool nopoll_base64_encode(const char *content,int length,char *output, int *output_size)
{
UNUSED(content); UNUSED(length); UNUSED(output_size);
strcpy(output, "AWYFUJHUDUDKJDDRDKUIIKORE\nSFJLIRRSHLOUTDESTDJJITTESLOIUHJGDRS\nGIUY&%WSJ");
parStrncpy(output, "AWYFUJHUDUDKJDDRDKUIIKORE\nSFJLIRRSHLOUTDESTDJJITTESLOIUHJGDRS\nGIUY&%WSJ", (size_t) *output_size);
function_called();
return (nopoll_bool)(intptr_t)mock();
}
@@ -56,19 +56,19 @@ char *get_global_reconnect_reason()
void test_getWebpaConveyHeader()
{
ParodusCfg cfg;
strcpy(cfg.hw_model, "TG1682");
strcpy(cfg.hw_serial_number, "Fer23u948590");
strcpy(cfg.hw_manufacturer , "ARRISGroup,Inc.");
strcpy(cfg.hw_mac , "123567892366");
strcpy(cfg.hw_last_reboot_reason , "unknown");
strcpy(cfg.fw_name , "2.364s2");
strcpy(cfg.webpa_path_url , "/api/v2/device");
strcpy(cfg.webpa_url , "localhost");
strcpy(cfg.webpa_interface_used , "eth0");
strcpy(cfg.webpa_protocol , "WebPA-1.6");
strcpy(cfg.webpa_uuid , "1234567-345456546");
cfg.secureFlag = 1;
memset(&cfg, 0, sizeof(ParodusCfg));
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.hw_last_reboot_reason , "unknown", sizeof(cfg.hw_last_reboot_reason));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_path_url , "/api/v2/device", sizeof(cfg.webpa_path_url));
parStrncpy(cfg.webpa_url , "localhost", sizeof(cfg.webpa_url));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
parStrncpy(cfg.webpa_uuid , "1234567-345456546", sizeof(cfg.webpa_uuid));
cfg.flags = 0;
cfg.boot_time = 423457;
cfg.webpa_ping_timeout = 30;
cfg.webpa_backoff_max = 255;
@@ -95,6 +95,38 @@ void err_getWebpaConveyHeader()
getWebpaConveyHeader();
}
/*
* Test function to verify timespec_diff function
* Verifys when the time diff is positive ie stop time > start time
*/
void test_timespec_diff()
{
struct timespec start, stop, diff;
int time_taken_ms;
clock_gettime(CLOCK_REALTIME, &start);
sleep(1);
clock_gettime(CLOCK_REALTIME, &stop);
timespec_diff(&start, &stop, &diff);
time_taken_ms = diff.tv_sec * 1000 + (diff.tv_nsec / 1000000);
assert_true(time_taken_ms >= 0);
}
/*
* Test function to verify timespec_diff function
* Verifys when the time diff is negative ie stop time < start time
*/
void test_timespec_diff1()
{
struct timespec start, stop, diff;
int time_taken_ms;
clock_gettime(CLOCK_REALTIME, &start);
sleep(1);
clock_gettime(CLOCK_REALTIME, &stop);
timespec_diff(&stop, &start, &diff);
time_taken_ms = diff.tv_sec * 1000 + (diff.tv_nsec / 1000000);
assert_true(time_taken_ms <= 0);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -103,6 +135,8 @@ int main(void)
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_getWebpaConveyHeader),
cmocka_unit_test(err_getWebpaConveyHeader),
cmocka_unit_test(test_timespec_diff),
cmocka_unit_test(test_timespec_diff1),
};
return cmocka_run_group_tests(tests, NULL, NULL);

435
tests/test_auth_token.c Normal file
View File

@@ -0,0 +1,435 @@
/**
* 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;
}
extern int g_response_code;
void setGlobalResponseCode (int response_code)
{
g_response_code = response_code;
}
int curl_easy_getinfo(CURL *curl, CURLINFO CURLINFO_RESPONSE_CODE, long response_code)
{
UNUSED(curl);
UNUSED(CURLINFO_RESPONSE_CODE);
if (0 != g_response_code)
{
response_code= g_response_code;
ParodusInfo("response_code is %ld\n", response_code);
}
function_called();
return (int) mock();
}
char* get_global_reconnect_reason()
{
return "none";
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
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;
setGlobalResponseCode(200);
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;
setGlobalResponseCode(200);
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);
}
void test_requestNewAuthToken_non200 ()
{
char token[1024];
ParodusCfg cfg;
int output;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
test_data.size = 0;
test_data.data = token;
setGlobalResponseCode(404);
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
output = requestNewAuthToken (token, sizeof(token), 1);
assert_int_equal (output, -1);
assert_string_equal (token, "");
ParodusInfo("requestNewAuthToken output: %d token empty len: %lu\n", output, strlen(token));
free(cfg.token_server_url);
}
void test_getAuthTokenFailure_non200 ()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
cfg.token_server_url = strdup("https://dev.comcast.net/token");
cfg.client_cert_path = strdup("testcert");
parStrncpy(cfg.cert_path , "/etc/ssl/certs/ca-certificates.crt", sizeof(cfg.cert_path));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
set_parodus_cfg(&cfg);
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_perform, 0);
expect_function_calls (curl_easy_perform, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
will_return (curl_easy_getinfo, 0);
expect_function_calls (curl_easy_getinfo, 1);
setGlobalResponseCode(504);
getAuthToken(&cfg);
assert_string_equal( cfg.webpa_auth_token, "");
free(cfg.client_cert_path);
free(cfg.token_server_url);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
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),
cmocka_unit_test(test_requestNewAuthToken_non200),
cmocka_unit_test(test_getAuthTokenFailure_non200)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

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

View File

@@ -26,9 +26,14 @@
#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();
int numLoops;
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -58,7 +63,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,8 +78,9 @@ 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");
}
@@ -86,13 +92,23 @@ static void *client_rcv_task()
int byte =0;
int rv1=0;
int t=25000;
int rc = -1;
int bind;
wrp_msg_t *msg1;
int sock1 = nn_socket (AF_SP, NN_PULL);
nn_bind(sock1, TEST_CLIENT1_URL);
bind = nn_bind(sock1, TEST_CLIENT1_URL);
if(bind < 0)
{
ParodusError("Unable to bind socket (errno=%d, %s)\n",errno, strerror(errno));
}
void *buf = NULL;
nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
rc = nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
if(rc < 0)
{
ParodusError ("Unable to set socket timeout (errno=%d, %s)\n",errno, strerror(errno));
}
ParodusPrint("Client 1 waiting for acknowledgement \n");
byte = nn_recv(sock1, &buf, NN_MSG, 0);
@@ -118,13 +134,23 @@ static void *client2_rcv_task()
int byte =0;
int rv1=0;
int t=25000;
int rc = -1;
int bind;
wrp_msg_t *msg1;
int sock1 = nn_socket (AF_SP, NN_PULL);
nn_bind(sock1, TEST_CLIENT2_URL);
bind = nn_bind(sock1, TEST_CLIENT2_URL);
if(bind < 0)
{
ParodusError("Unable to bind socket (errno=%d, %s)\n",errno, strerror(errno));
}
void *buf = NULL;
nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
rc = nn_setsockopt(sock1, NN_SOL_SOCKET, NN_RCVTIMEO, &t, sizeof(t));
if(rc < 0)
{
ParodusError ("Unable to set socket timeout (errno=%d, %s)\n",errno, strerror(errno));
}
ParodusPrint("Client 2 waiting for acknowledgement \n");
byte = nn_recv(sock1, &buf, NN_MSG, 0);
@@ -168,7 +194,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);
@@ -185,8 +211,9 @@ 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");
}

93
tests/test_close_retry.c Normal file
View File

@@ -0,0 +1,93 @@
/**
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <pthread.h>
#include "../src/close_retry.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_close_retry() {
/* get close_retry initial value */
bool close_retry =false;
close_retry = get_close_retry();
ParodusInfo("close_retry initial value is: %d\n", close_retry);
assert_int_equal(close_retry, 0);
/* set close_retry value and check whether its returning modified value or not*/
set_close_retry();
close_retry = get_close_retry();
ParodusInfo("close_retry modified to: %d\n", close_retry);
assert_int_equal(close_retry,1);
/* reset close_retry */
reset_close_retry();
close_retry = get_close_retry();
ParodusInfo("close_retry reset to: %d\n", close_retry);
assert_int_equal(close_retry,0);
}
void *test_mutex_set_close_retry() {
set_close_retry();
return NULL;
}
void *test_mutex_reset_close_retry() {
reset_close_retry();
return NULL;
}
void test_mutex_close_retry() {
bool close_retry;
pthread_t thread[3];
pthread_create(&thread[0], NULL, test_mutex_set_close_retry, NULL);
pthread_create(&thread[1], NULL, test_mutex_set_close_retry, NULL);
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
/* After execution of threads check the value of close_retry */
close_retry = get_close_retry();
ParodusInfo("Threads execution is completed, close_retry is: %d\n", close_retry);
assert_int_equal(close_retry, 1);
pthread_create(&thread[2], NULL, test_mutex_reset_close_retry, NULL);
pthread_join(thread[2], NULL);
close_retry = get_close_retry();
ParodusInfo("close_retry reset to: %d\n", close_retry);
assert_int_equal(close_retry, 0);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_close_retry),
cmocka_unit_test(test_mutex_close_retry)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -25,42 +25,76 @@
#include <CUnit/Basic.h>
#include "../src/config.h"
#include "../src/auth_token.h"
#include "../src/ParodusInternal.h"
#define K_argc 15
extern int parse_mac_address (char *target, const char *arg);
extern int server_is_http (const char *full_url,
const char **server_ptr);
extern int parse_webpa_url__(const char *full_url,
char *server_addr, int server_addr_buflen,
char *port_buf, int port_buflen);
extern int parse_webpa_url (const char *full_url,
char **server_addr, unsigned int *port);
extern unsigned int get_algo_mask (const char *algo_str);
extern unsigned int parse_num_arg (const char *arg, const char *arg_name);
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void create_token_script(char *fname)
{
char command[128] = {'\0'};
FILE *fp = fopen(fname, "w");
assert_non_null(fp);
fprintf(fp, "%s", "printf secure-token-$1-$2");
fclose(fp);
sprintf(command, "chmod +x %s",fname);
system(command);
}
char* get_global_reconnect_reason()
{
return "none";
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_setParodusConfig()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
strcpy(cfg.hw_model, "TG1682");
strcpy(cfg.hw_serial_number, "Fer23u948590");
strcpy(cfg.hw_manufacturer , "ARRISGroup,Inc.");
strcpy(cfg.hw_mac , "123567892366");
strcpy(cfg.hw_last_reboot_reason , "unknown");
strcpy(cfg.fw_name , "2.364s2");
strcpy(cfg.webpa_path_url , "/v1");
strcpy(cfg.webpa_url , "localhost");
strcpy(cfg.webpa_interface_used , "eth0");
strcpy(cfg.webpa_protocol , "WebPA-1.6");
strcpy(cfg.webpa_uuid , "1234567-345456546");
strcpy(cfg.partner_id , "comcast");
strcpy(cfg.seshat_url, "ipc://tmp/seshat_service.url");
cfg.secureFlag = 1;
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.hw_last_reboot_reason , "unknown", sizeof(cfg.hw_last_reboot_reason));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_path_url , "/v1", sizeof(cfg.webpa_path_url));
parStrncpy(cfg.webpa_url , "http://127.0.0.1", sizeof(cfg.webpa_url));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
parStrncpy(cfg.webpa_uuid , "1234567-345456546", sizeof(cfg.webpa_uuid));
parStrncpy(cfg.partner_id , "mycom", sizeof(cfg.partner_id));
#ifdef ENABLE_SESHAT
parStrncpy(cfg.seshat_url, "ipc://tmp/seshat_service.url", sizeof(cfg.seshat_url));
#endif
cfg.flags = 0;
cfg.boot_time = 423457;
cfg.webpa_ping_timeout = 30;
cfg.webpa_backoff_max = 255;
set_parodus_cfg(&cfg);
ParodusCfg *temp = get_parodus_cfg();
#ifdef FEATURE_DNS_QUERY
cfg.acquire_jwt = 1;
parStrncpy(cfg.dns_txt_url, "test",sizeof(cfg.dns_txt_url));
cfg.jwt_algo = 1025;
parStrncpy(cfg.jwt_key, "key.txt",sizeof(cfg.jwt_key));
#endif
cfg.crud_config_file = strdup("parodus_cfg.json");
set_parodus_cfg(&cfg);
ParodusCfg *temp = get_parodus_cfg();
assert_string_equal(cfg.hw_model, temp->hw_model);
assert_string_equal(cfg.hw_serial_number, temp->hw_serial_number);
@@ -73,13 +107,22 @@ void test_setParodusConfig()
assert_string_equal(cfg.webpa_protocol, temp->webpa_protocol);
assert_string_equal(cfg.webpa_uuid, temp->webpa_uuid);
assert_string_equal(cfg.partner_id, temp->partner_id);
#ifdef ENABLE_SESHAT
assert_string_equal(cfg.seshat_url, temp->seshat_url);
assert_int_equal((int) cfg.secureFlag, (int) temp->secureFlag);
#endif
assert_int_equal((int) cfg.flags, (int) temp->flags);
assert_int_equal((int) cfg.boot_time, (int) temp->boot_time);
assert_int_equal((int) cfg.webpa_ping_timeout, (int) temp->webpa_ping_timeout);
assert_int_equal((int) cfg.webpa_backoff_max, (int) temp->webpa_backoff_max);
#ifdef FEATURE_DNS_QUERY
assert_int_equal( (int) cfg.acquire_jwt, (int) temp->acquire_jwt);
assert_string_equal(cfg.dns_txt_url, temp->dns_txt_url);
assert_int_equal( (int) cfg.jwt_algo, (int) temp->jwt_algo);
assert_string_equal(cfg.jwt_key, temp->jwt_key);
#endif
assert_string_equal(cfg.crud_config_file, temp->crud_config_file);
free(cfg.crud_config_file);
}
void test_getParodusConfig()
@@ -87,7 +130,7 @@ void test_getParodusConfig()
ParodusCfg cfg;
memset(&cfg,0,sizeof(cfg));
strcpy(cfg.hw_model, "TG1682133");
parStrncpy(cfg.hw_model, "TG1682133",sizeof(cfg.hw_model));
set_parodus_cfg(&cfg);
ParodusCfg *temp = get_parodus_cfg();
@@ -95,33 +138,82 @@ void test_getParodusConfig()
assert_string_equal(cfg.hw_model, temp->hw_model);
}
static int open_output_file (const char *fname)
{
int fd = open(fname, O_WRONLY | O_CREAT, 0666);
if (fd<0)
{
ParodusError ("File %s open error\n", fname);
abort ();
}
return fd;
}
void write_key_to_file (const char *fname, const char *buf)
{
ssize_t nbytes;
ssize_t buflen = strlen (buf);
int fd = open_output_file(fname);
nbytes = write(fd, buf, buflen);
if (nbytes < 0)
{
ParodusError ("Write file %s error\n", fname);
close(fd);
abort ();
}
close(fd);
ParodusInfo ("%d bytes written\n", nbytes);
}
void test_parseCommandLine()
{
int argc =K_argc;
char * command[argc+1];
int i = 0;
char expectedToken[1280] = {'\0'};
#ifdef FEATURE_DNS_QUERY
const char *jwt_key = "AGdyuwyhwl2ow2ydsoioiygkshwdthuwd";
#endif
command[i++] = "parodus";
command[i++] = "--hw-model=TG1682";
command[i++] = "--hw-serial-number=Fer23u948590";
command[i++] = "--hw-manufacturer=ARRISGroup,Inc.";
command[i++] = "--hw-mac=123567892366";
command[i++] = "--hw-last-reboot-reason=unknown";
command[i++] = "--fw-name=TG1682_DEV_master_2016000000sdy";
command[i++] = "--webpa-ping-time=180";
command[i++] = "--webpa-inteface-used=br0";
command[i++] = "--webpa-url=localhost";
command[i++] = "--webpa-backoff-max=0";
command[i++] = "--boot-time=1234";
command[i++] = "--parodus-local-url=tcp://127.0.0.1:6666";
command[i++] = "--partner-id=cox";
command[i++] = "--seshat-url=ipc://127.0.0.1:7777";
command[i] = '\0';
char *command[] = {"parodus",
"--hw-model=TG1682",
"--hw-serial-number=Fer23u948590",
"--hw-manufacturer=ARRISGroup,Inc.",
"--hw-mac=123567892366",
"--hw-last-reboot-reason=unknown",
"--fw-name=TG1682_DEV_master_2016000000sdy",
"--webpa-ping-timeout=180",
"--webpa-interface-used=br0",
"--webpa-url=http://127.0.0.1",
"--webpa-backoff-max=0",
"--boot-time=1234",
"--parodus-local-url=tcp://127.0.0.1:6666",
"--partner-id=cox",
#ifdef ENABLE_SESHAT
"--seshat-url=ipc://127.0.0.1:7777",
#endif
"--force-ipv4",
"--force-ipv6",
"--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",
"--jwt-public-key-file=../../tests/jwt_key.tst",
"--jwt-algo=RS256",
#endif
"--crud-config-file=parodus_cfg.json",
NULL
};
int argc = (sizeof (command) / sizeof (char *)) - 1;
ParodusCfg parodusCfg;
memset(&parodusCfg,0,sizeof(parodusCfg));
parseCommandLine(argc,command,&parodusCfg);
#ifdef FEATURE_DNS_QUERY
write_key_to_file ("../../tests/jwt_key.tst", jwt_key);
#endif
create_token_script("/tmp/token.sh");
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), 0);
assert_string_equal( parodusCfg.hw_model, "TG1682");
assert_string_equal( parodusCfg.hw_serial_number, "Fer23u948590");
@@ -130,57 +222,120 @@ 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, "localhost");
assert_string_equal( parodusCfg.webpa_url, "http://127.0.0.1");
assert_int_equal( (int) parodusCfg.webpa_backoff_max,0);
assert_int_equal( (int) parodusCfg.boot_time,1234);
assert_string_equal( parodusCfg.local_url,"tcp://127.0.0.1:6666");
assert_string_equal( parodusCfg.partner_id,"cox");
#ifdef ENABLE_SESHAT
assert_string_equal( parodusCfg.seshat_url, "ipc://127.0.0.1:7777");
#endif
assert_int_equal( (int) parodusCfg.flags, FLAGS_IPV6_ONLY|FLAGS_IPV4_ONLY);
set_parodus_cfg(&parodusCfg);
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");
}
void test_parseCommandLineNull()
{
parseCommandLine(0,NULL,NULL);
assert_int_equal (parseCommandLine(0,NULL,NULL), -1);
}
void err_parseCommandLine()
{
int argc =K_argc;
char * command[20]={'\0'};
command[0] = "parodus";
command[1] = "--hw-model=TG1682";
command[12] = "webpa";
int argc;
char *command[] = {"parodus",
"--hw-model=TG1682",
"--hw-serial-number=Fer23u948590",
"-Z",
"--nosuch",
"--hw-mac=123567892366",
"webpa",
NULL
};
ParodusCfg parodusCfg;
memset(&parodusCfg,0,sizeof(parodusCfg));
parseCommandLine(argc,command,&parodusCfg);
assert_string_equal( parodusCfg.hw_model, "");
assert_string_equal( parodusCfg.hw_serial_number, "");
argc = (sizeof (command) / sizeof (char *)) - 1;
// Missing webpa_url
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
// Bad webpa_url
command[5] = "--webpa-url=127.0.0.1";
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
// Bad mac address
command[5] = "--hw-mac=1235678923";
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
command[5] = "--webpa-ping-timeout=123x";
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
command[5] = "--webpa-backoff-max=";
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
command[5] = "--boot-time=12x";
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
#ifdef FEATURE_DNS_QUERY
command[5] = "--webpa-url=https://127.0.0.1";
command[3] = "--acquire-jwt=1";
command[4] = "--dns-txt-url=mydns.mycom.net";
// missing algo
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
command[4] = "--jwt-algo=none:RS256";
// disallowed alogrithm none
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
command[4] = "--jwt-algo=RS256";
// missing jwt public key file
assert_int_equal (parseCommandLine(argc,command,&parodusCfg), -1);
#endif
}
void test_loadParodusCfg()
{
ParodusCfg tmpcfg;
ParodusCfg *Cfg;
ParodusCfg *Cfg = NULL;
char protocol[32] = {'\0'};
Cfg = (ParodusCfg*)malloc(sizeof(ParodusCfg));
memset(Cfg, 0, sizeof(ParodusCfg));
strcpy(Cfg->hw_model, "TG1682");
strcpy(Cfg->hw_serial_number, "Fer23u948590");
strcpy(Cfg->hw_manufacturer , "ARRISGroup,Inc.");
strcpy(Cfg->hw_mac , "123567892366");
strcpy(Cfg->hw_last_reboot_reason , "unknown");
strcpy(Cfg->fw_name , "2.364s2");
strcpy(Cfg->webpa_path_url , "/v1");
strcpy(Cfg->webpa_url , "localhost");
strcpy(Cfg->webpa_interface_used , "eth0");
strcpy(Cfg->webpa_protocol , "WebPA-1.6");
strcpy(Cfg->local_url , "tcp://10.0.0.1:6000");
strcpy(Cfg->partner_id , "shaw");
parStrncpy(Cfg->hw_model, "TG1682", sizeof(Cfg->hw_model));
parStrncpy(Cfg->hw_serial_number, "Fer23u948590", sizeof(Cfg->hw_serial_number));
parStrncpy(Cfg->hw_manufacturer , "ARRISGroup,Inc.", sizeof(Cfg->hw_manufacturer));
parStrncpy(Cfg->hw_mac , "123567892366", sizeof(Cfg->hw_mac));
parStrncpy(Cfg->hw_last_reboot_reason , "unknown", sizeof(Cfg->hw_last_reboot_reason));
parStrncpy(Cfg->fw_name , "2.364s2", sizeof(Cfg->fw_name));
parStrncpy(Cfg->webpa_path_url , "/v1", sizeof(Cfg->webpa_path_url));
parStrncpy(Cfg->webpa_url , "http://127.0.0.1", sizeof(Cfg->webpa_url));
parStrncpy(Cfg->webpa_interface_used , "eth0", sizeof(Cfg->webpa_interface_used));
snprintf(protocol, sizeof(protocol), "%s-%s", PROTOCOL_VALUE, GIT_COMMIT_TAG);
parStrncpy(Cfg->webpa_protocol , protocol, sizeof(Cfg->webpa_protocol));
parStrncpy(Cfg->local_url , "tcp://10.0.0.1:6000", sizeof(Cfg->local_url));
parStrncpy(Cfg->partner_id , "shaw", sizeof(Cfg->partner_id));
#ifdef FEATURE_DNS_QUERY
Cfg->acquire_jwt = 1;
parStrncpy(Cfg->dns_txt_url, "mydns",sizeof(Cfg->dns_txt_url));
Cfg->jwt_algo = 1025;
parStrncpy(Cfg->jwt_key, "AGdyuwyhwl2ow2ydsoioiygkshwdthuwd",sizeof(Cfg->jwt_key));
#endif
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);
@@ -190,6 +345,28 @@ void test_loadParodusCfg()
assert_string_equal( tmpcfg.hw_mac, "123567892366");
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.cert_path, "/etc/ssl.crt");
#ifdef ENABLE_SESHAT
assert_string_equal(tmpcfg.seshat_url, "ipc://tmp/seshat_service.url");
#endif
assert_string_equal(tmpcfg.crud_config_file, "parodus_cfg.json");
free(tmpcfg.client_cert_path);
free(tmpcfg.token_server_url);
free(tmpcfg.crud_config_file);
free(Cfg->crud_config_file);
free(Cfg->client_cert_path);
free(Cfg->token_server_url);
free(Cfg);
}
@@ -206,12 +383,11 @@ void test_loadParodusCfgNull()
assert_string_equal(temp.hw_model, "");
assert_string_equal(temp.hw_serial_number, "");
assert_string_equal(temp.hw_manufacturer, "");
assert_int_equal( (int) temp.secureFlag,1);
assert_int_equal( (int) temp.flags,0);
assert_string_equal( temp.webpa_path_url, WEBPA_PATH_URL);
assert_string_equal( temp.webpa_protocol, WEBPA_PROTOCOL_VALUE);
assert_string_equal( temp.webpa_uuid,"1234567-345456546");
assert_string_equal( temp.local_url, PARODUS_UPSTREAM);
assert_null(temp.crud_config_file);
free(cfg);
}
@@ -221,6 +397,184 @@ void err_loadParodusCfg()
loadParodusCfg(NULL,&cfg);
}
void test_parodusGitVersion()
{
FILE *fp;
char version[32] = {'\0'};
char *command = "git describe --tags --always";
int n;
size_t len;
fp = popen(command,"r");
while(fgets(version, 32, fp) !=NULL)
{
len = strlen(version);
if (len > 0 && version[len-1] == '\n')
{
version[--len] = '\0';
}
}
pclose(fp);
printf ("version: %s\n", version);
printf ("GIT_COMMIT_TAG: %s\n", GIT_COMMIT_TAG);
n = strcmp( version, GIT_COMMIT_TAG);
assert_int_equal(n, 0);
}
void test_setDefaultValuesToCfg()
{
ParodusCfg *cfg = (ParodusCfg *) malloc(sizeof(ParodusCfg));
memset(cfg,0,sizeof(ParodusCfg));
setDefaultValuesToCfg(cfg);
assert_string_equal( cfg->local_url, PARODUS_UPSTREAM);
#ifdef FEATURE_DNS_QUERY
assert_int_equal(cfg->acquire_jwt, 0);
assert_string_equal(cfg->dns_txt_url, DNS_TXT_URL);
assert_string_equal(cfg->jwt_key, "\0");
assert_int_equal( (int)cfg->jwt_algo, 0);
#endif
assert_string_equal(cfg->cert_path, "\0");
assert_int_equal((int)cfg->flags, 0);
assert_string_equal(cfg->webpa_path_url, WEBPA_PATH_URL);
assert_string_equal(cfg->webpa_uuid, "1234567-345456546");
assert_string_equal(cfg->cloud_status, CLOUD_STATUS_OFFLINE);
free(cfg);
}
void err_setDefaultValuesToCfg()
{
setDefaultValuesToCfg(NULL);
}
void test_parse_num_arg ()
{
assert_int_equal (parse_num_arg ("1234", "1234"), 1234);
assert_int_equal (parse_num_arg ("1", "1"), 1);
assert_int_equal (parse_num_arg ("0", "0"), 0);
assert_true (parse_num_arg ("", "empty arg") == (unsigned int) -1);
assert_true (parse_num_arg ("0x", "non-num arg") == (unsigned int) -1);
}
void test_parse_mac_address ()
{
char result[14];
assert_int_equal (parse_mac_address (result, "aabbccddeeff"), 0);
assert_string_equal (result, "aabbccddeeff");
assert_int_equal (parse_mac_address (result, "aa:bb:cc:dd:ee:ff"), 0);
assert_string_equal (result, "aabbccddeeff");
assert_int_equal (parse_mac_address (result, "aabbccddeeff0"), -1);
assert_int_equal (parse_mac_address (result, "aa:bb:c:dd:ee:ff:00"), -1);
assert_int_equal (parse_mac_address (result, ""), -1);
}
void test_server_is_http ()
{
const char *server_ptr;
assert_int_equal (server_is_http ("https://127.0.0.1", &server_ptr), 0);
assert_string_equal (server_ptr, "127.0.0.1");
assert_int_equal (server_is_http ("http://127.0.0.1", &server_ptr), 1);
assert_string_equal (server_ptr, "127.0.0.1");
assert_int_equal (server_is_http ("127.0.0.1", &server_ptr), -1);
}
void test_parse_webpa_url__ ()
{
char addr_buf[80];
char port_buf[8];
assert_int_equal (parse_webpa_url__ ("mydns.mycom.net:8080",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("https://mydns.mycom.net:8080",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("https://mydns.mycom.net/",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (port_buf, "443");
assert_int_equal (parse_webpa_url__ ("https://mydns.mycom.net/api/v2/",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (port_buf, "443");
assert_int_equal (parse_webpa_url__ ("http://mydns.mycom.net:8080",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("http://mydns.mycom.net",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "mydns.mycom.net");
assert_string_equal (port_buf, "80");
assert_int_equal (parse_webpa_url__ ("https://[2001:558:fc18:2:f816:3eff:fe7f:6efa]:8080",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("https://[2001:558:fc18:2:f816:3eff:fe7f:6efa]",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "443");
assert_int_equal (parse_webpa_url__ ("http://[2001:558:fc18:2:f816:3eff:fe7f:6efa]:8080",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "8080");
assert_int_equal (parse_webpa_url__ ("http://[2001:558:fc18:2:f816:3eff:fe7f:6efa]",
addr_buf, 80, port_buf, 8), 1);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "80");
assert_int_equal (parse_webpa_url__ ("http://2001:558:fc18:2:f816:3eff:fe7f:6efa]",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("http://[2001:558:fc18:2:f816:3eff:fe7f:6efa",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("[2001:558:fc18:2:f816:3eff:fe7f:6efa",
addr_buf, 80, port_buf, 8), -1);
assert_int_equal (parse_webpa_url__ ("https://[2001:558:fc18:2:f816:3eff:fe7f:6efa]:8080/api/v2/",
addr_buf, 80, port_buf, 8), 0);
assert_string_equal (addr_buf, "2001:558:fc18:2:f816:3eff:fe7f:6efa");
assert_string_equal (port_buf, "8080");
}
void test_parse_webpa_url ()
{
char *addr;
unsigned int port;
assert_int_equal (parse_webpa_url ("mydns.mycom.net:8080",
&addr, &port), -1);
assert_int_equal (parse_webpa_url ("https://mydns.mycom.net:8080",
&addr, &port), 0);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 8080);
free (addr);
assert_int_equal (parse_webpa_url ("https://mydns.mycom.net/",
&addr, &port), 0);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 443);
free (addr);
assert_int_equal (parse_webpa_url ("http://mydns.mycom.net:8080",
&addr, &port), 1);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 8080);
free (addr);
assert_int_equal (parse_webpa_url ("http://mydns.mycom.net",
&addr, &port), 1);
assert_string_equal (addr, "mydns.mycom.net");
assert_int_equal (port, 80);
free(addr);
}
void test_get_algo_mask ()
{
assert_true (get_algo_mask ("RS256:RS512") == 5120);
assert_true (get_algo_mask ("none:RS256") == (unsigned int) -1);
assert_true (get_algo_mask ("nosuch") == (unsigned int) -1);
#if ALLOW_NON_RSA_ALG
assert_true (get_algo_mask ("ES256:RS256") == 1026);
#else
assert_true (get_algo_mask ("ES256:RS256") == (unsigned int) -1);
#endif
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -233,9 +587,18 @@ int main(void)
cmocka_unit_test(test_loadParodusCfg),
cmocka_unit_test(test_loadParodusCfgNull),
cmocka_unit_test(err_loadParodusCfg),
cmocka_unit_test(test_parse_num_arg),
cmocka_unit_test(test_parse_mac_address),
cmocka_unit_test(test_get_algo_mask),
cmocka_unit_test(test_server_is_http),
cmocka_unit_test(test_parse_webpa_url__),
cmocka_unit_test(test_parse_webpa_url),
cmocka_unit_test(test_parseCommandLine),
cmocka_unit_test(test_parseCommandLineNull),
cmocka_unit_test(err_parseCommandLine),
//cmocka_unit_test(test_parodusGitVersion),
cmocka_unit_test(test_setDefaultValuesToCfg),
cmocka_unit_test(err_setDefaultValuesToCfg),
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -27,20 +27,41 @@
#include "../src/conn_interface.h"
#include "../src/connection.h"
#include "../src/config.h"
#include "../src/heartBeat.h"
#include "../src/close_retry.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
static char *reconnect_reason = "webpa_process_starts";
UpStreamMsg *UpStreamMsgQ;
ParodusMsg *ParodusMsgQ;
extern bool close_retry;
extern volatile unsigned int heartBeatTimer;
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;
int numLoops;
parodusOnPingStatusChangeHandler on_ping_status_change;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
int createNopollConnection(noPollCtx *ctx)
void set_server_list_null (server_list_t *server_list)
{
UNUSED(ctx);
UNUSED(server_list);
}
int find_servers (server_list_t *server_list)
{
UNUSED(server_list);
return FIND_SUCCESS;
}
int createNopollConnection(noPollCtx *ctx, server_list_t *server_list)
{
UNUSED(ctx); UNUSED(server_list);
function_called();
return (int) mock();
}
@@ -66,12 +87,70 @@ noPollMutexUnlock mutex_unlock
UNUSED(mutex_create); UNUSED(mutex_destroy); UNUSED(mutex_lock); UNUSED(mutex_unlock);
function_called();
}
char *get_global_reconnect_reason()
{
return reconnect_reason;
}
char *get_global_shutdown_reason()
{
return SHUTDOWN_REASON_PARODUS_STOP;
}
void set_global_shutdown_reason(char *reason)
{
UNUSED(reason);
}
void start_conn_in_progress (unsigned long start_time)
{
UNUSED(start_time);
}
void stop_conn_in_progress (void)
{
}
void reset_interface_down_event (void)
{
}
bool get_interface_down_event (void)
{
return false;
}
void set_interface_down_event (void)
{
}
int wait_while_interface_down (void)
{
return 0;
}
void terminate_backoff_delay (void)
{
}
void packMetaData()
{
function_called();
}
int get_cloud_disconnect_time(void)
{
function_called();
return (int) (intptr_t)mock();
}
void set_cloud_disconnect_time(int Time)
{
UNUSED(Time);
function_called();
}
void *handle_upstream()
{
@@ -88,9 +167,9 @@ void *messageHandlerTask()
return NULL;
}
void *serviceAliveTask()
int serviceAliveTask()
{
return NULL;
return 0;
}
int nopoll_loop_wait(noPollCtx * ctx,long timeout)
@@ -106,12 +185,25 @@ void set_global_reconnect_reason(char *reason)
function_called();
}
void close_and_unref_connection(noPollConn *conn)
void set_global_reconnect_status(bool status)
{
UNUSED(conn);
(void)status;
function_called();
}
void close_and_unref_connection(noPollConn *conn, bool is_shutting_down)
{
UNUSED(conn); UNUSED(is_shutting_down);
function_called();
}
int readFromFile(const char *file_name, char **data)
{
UNUSED(file_name);
*data = strdup ("parodus_stopping");
return 1;
}
void nopoll_cleanup_library ()
{
function_called();
@@ -135,12 +227,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();
@@ -150,6 +248,51 @@ void initKeypress()
{
function_called();
}
UpStreamMsg * get_global_UpStreamMsgQ(void)
{
return UpStreamMsgQ;
}
void set_global_UpStreamMsgQ(UpStreamMsg * UpStreamQ)
{
UpStreamMsgQ = UpStreamQ;
}
pthread_cond_t *get_global_nano_con(void)
{
return &nano_con;
}
pthread_mutex_t *get_global_nano_mut(void)
{
return &nano_mut;
}
pthread_cond_t *get_global_svc_con(void)
{
return &svc_con;
}
pthread_mutex_t *get_global_svc_mut(void)
{
return &svc_mut;
}
/*
* Mock func to calculate time diff between start and stop time
* This timespec_diff retuns 1 sec as diff time
*/
void timespec_diff(struct timespec *start, struct timespec *stop,
struct timespec *diff)
{
UNUSED(start);
UNUSED(stop);
diff->tv_sec = 1;
diff->tv_nsec = 1000;
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -159,8 +302,7 @@ void test_createSocketConnection()
noPollCtx *ctx;
ParodusCfg cfg;
memset(&cfg,0,sizeof(ParodusCfg));
close_retry = false;
reset_close_retry();
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)&ctx);
@@ -170,13 +312,14 @@ void test_createSocketConnection()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 4);
expect_function_calls(StartThread, 5);
expect_function_call(initKeypress);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
expect_function_call(set_global_reconnect_reason);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(set_global_reconnect_status);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(set_global_conn);
@@ -187,7 +330,7 @@ void test_createSocketConnection()
expect_function_call(close_and_unref_connection);
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(&cfg,initKeypress);
createSocketConnection(initKeypress);
}
void test_createSocketConnection1()
@@ -195,7 +338,7 @@ void test_createSocketConnection1()
noPollCtx *ctx;
ParodusCfg cfg;
memset(&cfg,0, sizeof(ParodusCfg));
close_retry = true;
set_close_retry();
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)&ctx);
@@ -205,7 +348,7 @@ void test_createSocketConnection1()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 4);
expect_function_calls(StartThread, 5);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
@@ -220,29 +363,31 @@ void test_createSocketConnection1()
expect_function_call(close_and_unref_connection);
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(&cfg,NULL);
createSocketConnection(NULL);
}
void test_createSocketConnection2()
void test_PingMissIntervalTime()
{
noPollCtx *ctx;
ParodusCfg cfg;
memset(&cfg,0,sizeof(ParodusCfg));
strcpy(cfg.hw_model, "TG1682");
strcpy(cfg.hw_serial_number, "Fer23u948590");
strcpy(cfg.hw_manufacturer , "ARRISGroup,Inc.");
strcpy(cfg.hw_mac , "123567892366");
strcpy(cfg.hw_last_reboot_reason , "unknown");
strcpy(cfg.fw_name , "2.364s2");
strcpy(cfg.webpa_path_url , "/v1");
strcpy(cfg.webpa_url , "localhost");
strcpy(cfg.webpa_interface_used , "eth0");
strcpy(cfg.webpa_protocol , "WebPA-1.6");
strcpy(cfg.webpa_uuid , "1234567-345456546");
cfg.webpa_ping_timeout = 1;
parStrncpy(cfg.hw_model, "TG1682", sizeof(cfg.hw_model));
parStrncpy(cfg.hw_serial_number, "Fer23u948590", sizeof(cfg.hw_serial_number));
parStrncpy(cfg.hw_manufacturer , "ARRISGroup,Inc.", sizeof(cfg.hw_manufacturer));
parStrncpy(cfg.hw_mac , "123567892366", sizeof(cfg.hw_mac));
parStrncpy(cfg.hw_last_reboot_reason , "unknown", sizeof(cfg.hw_last_reboot_reason));
parStrncpy(cfg.fw_name , "2.364s2", sizeof(cfg.fw_name));
parStrncpy(cfg.webpa_path_url , "/v1", sizeof(cfg.webpa_path_url));
parStrncpy(cfg.webpa_url , "localhost", sizeof(cfg.webpa_url));
parStrncpy(cfg.webpa_interface_used , "eth0", sizeof(cfg.webpa_interface_used));
parStrncpy(cfg.webpa_protocol , "WebPA-1.6", sizeof(cfg.webpa_protocol));
parStrncpy(cfg.webpa_uuid , "1234567-345456546", sizeof(cfg.webpa_uuid));
//Max ping timeout is 6 sec
cfg.webpa_ping_timeout = 6;
set_parodus_cfg(&cfg);
close_retry = false;
reset_close_retry();
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)&ctx);
@@ -252,7 +397,8 @@ void test_createSocketConnection2()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 4);
expect_function_calls(StartThread, 5);
//Increment ping interval time to 1 sec for each nopoll_loop_wait call
will_return(nopoll_loop_wait, 1);
will_return(nopoll_loop_wait, 1);
will_return(nopoll_loop_wait, 1);
@@ -261,9 +407,10 @@ void test_createSocketConnection2()
will_return(nopoll_loop_wait, 1);
will_return(nopoll_loop_wait, 1);
expect_function_calls(nopoll_loop_wait, 7);
//Expecting Ping miss after 6 sec
expect_function_call(set_global_reconnect_reason);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(set_global_reconnect_status);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(set_global_conn);
@@ -274,13 +421,14 @@ void test_createSocketConnection2()
expect_function_call(close_and_unref_connection);
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(&cfg,NULL);
createSocketConnection(NULL);
}
void err_createSocketConnection()
{
close_retry = true;
heartBeatTimer = 0;
set_close_retry();
reset_heartBeatTimer();
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)NULL);
@@ -290,7 +438,7 @@ void err_createSocketConnection()
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 4);
expect_function_calls(StartThread, 5);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
@@ -305,7 +453,54 @@ void err_createSocketConnection()
expect_function_call(close_and_unref_connection);
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(NULL,NULL);
createSocketConnection(NULL);
}
void test_createSocketConnection_cloud_disconn()
{
ParodusCfg cfg;
memset(&cfg,0,sizeof(ParodusCfg));
cfg.cloud_disconnect = strdup("XPC");
set_parodus_cfg(&cfg);
set_close_retry();
reset_heartBeatTimer();
expect_function_call(nopoll_thread_handlers);
will_return(nopoll_ctx_new, (intptr_t)NULL);
expect_function_call(nopoll_ctx_new);
expect_function_call(nopoll_log_set_handler);
will_return(createNopollConnection, nopoll_true);
expect_function_call(createNopollConnection);
expect_function_call(packMetaData);
expect_function_calls(StartThread, 5);
will_return(nopoll_loop_wait, 1);
expect_function_call(nopoll_loop_wait);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(set_global_conn);
expect_function_call(set_cloud_disconnect_time);
will_return(get_cloud_disconnect_time, 0);
expect_function_call(get_cloud_disconnect_time);
will_return(get_cloud_disconnect_time, 0);
expect_function_call(get_cloud_disconnect_time);
will_return(get_cloud_disconnect_time, 0);
expect_function_call(get_cloud_disconnect_time);
will_return(createNopollConnection, nopoll_true);
expect_function_call(createNopollConnection);
will_return(get_global_conn, (intptr_t)NULL);
expect_function_call(get_global_conn);
expect_function_call(close_and_unref_connection);
expect_function_call(nopoll_ctx_unref);
expect_function_call(nopoll_cleanup_library);
createSocketConnection(NULL);
}
/*----------------------------------------------------------------------------*/
@@ -317,8 +512,9 @@ int main(void)
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_createSocketConnection),
cmocka_unit_test(test_createSocketConnection1),
cmocka_unit_test(test_createSocketConnection2),
cmocka_unit_test(test_PingMissIntervalTime),
cmocka_unit_test(err_createSocketConnection),
cmocka_unit_test(test_createSocketConnection_cloud_disconn)
};
return cmocka_run_group_tests(tests, NULL, NULL);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

397
tests/test_crud_interface.c Normal file
View File

@@ -0,0 +1,397 @@
/**
* Copyright 2010-2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <malloc.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <string.h>
#include <unistd.h>
#include <wrp-c.h>
#include "../src/crud_interface.h"
#include "../src/config.h"
#include "../src/client_list.h"
#include "../src/ParodusInternal.h"
#include "../src/partners_check.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool g_shutdown = false;
extern CrudMsg *crudMsgQ;
int numLoops = 1;
wrp_msg_t *temp = NULL;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
char * get_global_UpStreamMsgQ(void)
{
function_called();
return (char *)mock();
}
int set_global_UpStreamMsgQ(void)
{
function_called();
return (int)mock();
}
int get_global_nano_con(void)
{
function_called();
return (int)mock();
}
int get_global_nano_mut(void)
{
function_called();
return (int)mock();
}
char *get_global_reconnect_reason()
{
function_called();
return (char *)(intptr_t)mock();
}
ParodusCfg *get_parodus_cfg(void)
{
function_called();
return (ParodusCfg*) (intptr_t)mock();
}
int pthread_mutex_lock(pthread_mutex_t *restrict mutex)
{
UNUSED(mutex);
function_called();
return (int)mock();
}
int pthread_mutex_unlock(pthread_mutex_t *restrict mutex)
{
UNUSED(mutex);
function_called();
return (int)mock();
}
int pthread_cond_signal(pthread_cond_t *restrict cond)
{
UNUSED(cond);
function_called();
return (int)mock();
}
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)
{
UNUSED(cond); UNUSED(mutex);
function_called();
return (int)mock();
}
int processCrudRequest(wrp_msg_t *reqMsg, wrp_msg_t **responseMsg )
{
UNUSED(reqMsg);
wrp_msg_t *resp_msg = NULL;
resp_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg->msg_type = 5;
resp_msg->u.crud.transaction_uuid = strdup("1234");
resp_msg->u.crud.source = strdup("tag-update");
resp_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
*responseMsg = resp_msg;
function_called();
return (int)mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_addCRUDmsgToQueue()
{
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
crudMsgQ = (CrudMsg *)malloc(sizeof(CrudMsg));
crudMsgQ->msg = crud_msg;
crudMsgQ->next = (CrudMsg *) malloc(sizeof(CrudMsg));
crudMsgQ->next->msg = crud_msg;
crudMsgQ->next->next = NULL;
addCRUDmsgToQueue(crud_msg);
free(crudMsgQ->next);
free(crudMsgQ);
crudMsgQ = NULL;
wrp_free_struct(crud_msg);
}
void test_addCRUDmsgToQueueNULL()
{
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
addCRUDmsgToQueue(crud_msg);
free(crudMsgQ->next);
free(crudMsgQ);
crudMsgQ = NULL;
wrp_free_struct(crud_msg);
}
void err_CRUDHandlerTask()
{
numLoops = 1;
crudMsgQ = NULL;
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_cond_wait, 0);
expect_function_call(pthread_cond_wait);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
CRUDHandlerTask();
}
void test_CRUDHandlerTask()
{
numLoops = 1;
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
crudMsgQ = (CrudMsg *)malloc(sizeof(CrudMsg));
crudMsgQ->msg = crud_msg;
crudMsgQ->next = NULL;
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
will_return(processCrudRequest, 0);
expect_function_call(processCrudRequest);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(get_global_UpStreamMsgQ, NULL);
expect_function_call(get_global_UpStreamMsgQ);
will_return(set_global_UpStreamMsgQ, 0);
expect_function_call(set_global_UpStreamMsgQ);
will_return(get_global_nano_con, 0);
expect_function_call(get_global_nano_con);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
CRUDHandlerTask();
free(crudMsgQ);
}
void test_CRUDHandlerTaskFailure()
{
numLoops = 1;
wrp_msg_t *crud_msg = NULL;
crud_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(crud_msg, 0, sizeof(wrp_msg_t));
crud_msg->msg_type = 5;
crud_msg->u.crud.transaction_uuid = strdup("bd4ad2d1-5c9c-486f-8e25-52c242b38f71");
crud_msg->u.crud.source = strdup("tag-update");
crud_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
crudMsgQ = (CrudMsg *)malloc(sizeof(CrudMsg));
crudMsgQ->msg = crud_msg;
crudMsgQ->next = NULL;
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
will_return(processCrudRequest, -1);
expect_function_call(processCrudRequest);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(get_global_UpStreamMsgQ, 0);
expect_function_call(get_global_UpStreamMsgQ);
will_return(set_global_UpStreamMsgQ, 0);
expect_function_call(set_global_UpStreamMsgQ);
will_return(get_global_nano_con, 0);
expect_function_call(get_global_nano_con);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
CRUDHandlerTask();
free(crudMsgQ);
}
void test_addCRUDresponseToUpstreamQ()
{
numLoops = 1;
ssize_t resp_size = 0;
void *resp_bytes;
wrp_msg_t *resp_msg = NULL;
resp_msg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(resp_msg, 0, sizeof(wrp_msg_t));
resp_msg->msg_type = 5;
resp_msg->u.crud.transaction_uuid = strdup("1234");
resp_msg->u.crud.source = strdup("tag-update");
resp_msg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
resp_size = wrp_struct_to( resp_msg, WRP_BYTES, &resp_bytes );
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_lock, 0);
expect_function_call(pthread_mutex_lock);
will_return(get_global_UpStreamMsgQ, 0);
expect_function_call(get_global_UpStreamMsgQ);
will_return(set_global_UpStreamMsgQ, 0);
expect_function_call(set_global_UpStreamMsgQ);
will_return(get_global_nano_con, 0);
expect_function_call(get_global_nano_con);
will_return(pthread_cond_signal, 0);
expect_function_call(pthread_cond_signal);
will_return(get_global_nano_mut, 0);
expect_function_call(get_global_nano_mut);
will_return(pthread_mutex_unlock, 0);
expect_function_call(pthread_mutex_unlock);
addCRUDresponseToUpstreamQ(resp_bytes, resp_size);
wrp_free_struct(resp_msg);
}
void test_addCRUDmsgToQueueAllocation()
{
addCRUDmsgToQueue(NULL);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_addCRUDmsgToQueueNULL),
cmocka_unit_test(test_addCRUDmsgToQueue),
cmocka_unit_test(test_addCRUDmsgToQueueAllocation),
cmocka_unit_test(err_CRUDHandlerTask),
cmocka_unit_test(test_CRUDHandlerTask),
cmocka_unit_test(test_CRUDHandlerTaskFailure),
cmocka_unit_test(test_addCRUDresponseToUpstreamQ)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

3029
tests/test_crud_internal.c Normal file

File diff suppressed because it is too large Load Diff

283
tests/test_crud_tasks.c Normal file
View File

@@ -0,0 +1,283 @@
/**
* Copyright 2010-2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <malloc.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <string.h>
#include <unistd.h>
#include <wrp-c.h>
#include "../src/crud_tasks.h"
#include "../src/config.h"
#include "../src/client_list.h"
#include "../src/ParodusInternal.h"
#include "../src/partners_check.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
wrp_msg_t *response = NULL;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
cJSON * cJSON_Parse(const char *payload)
{
UNUSED(payload);
function_called();
return (cJSON *) mock();
}
int createObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
int retrieveObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
int updateObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
int deleteObject(wrp_msg_t *reqMsg , wrp_msg_t **response)
{
UNUSED(reqMsg); UNUSED(response);
function_called();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_processCrudRequestCreate()
{
int ret = -1;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 5;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(createObject, 0);
expect_function_call(createObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestCreateFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 5;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(createObject, -1);
expect_function_call(createObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestRetrieve()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 6;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(retrieveObject, 0);
expect_function_call(retrieveObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestRetrieveFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 6;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(retrieveObject, -1);
expect_function_call(retrieveObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestUpdate()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 7;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(updateObject, 0);
expect_function_call(updateObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestUpdateFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 7;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(updateObject, -1);
expect_function_call(updateObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestDelete()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 8;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(deleteObject, 0);
expect_function_call(deleteObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestDeleteFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 8;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
will_return(deleteObject, -1);
expect_function_call(deleteObject);
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, -1);
wrp_free_struct(reqMsg);
}
void test_processCrudRequestFailure()
{
int ret = -2;
wrp_msg_t *reqMsg = NULL;
reqMsg = ( wrp_msg_t *)malloc( sizeof( wrp_msg_t ) );
memset(reqMsg, 0, sizeof(wrp_msg_t));
reqMsg->msg_type = 3;
reqMsg->u.crud.transaction_uuid = strdup("1234");
reqMsg->u.crud.source = strdup("tag-update");
reqMsg->u.crud.dest = strdup("mac:14xxx/parodus/tags");
ret = processCrudRequest(reqMsg, &response);
assert_int_equal(ret, 0);
wrp_free_struct(reqMsg);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_processCrudRequestCreate),
cmocka_unit_test(test_processCrudRequestCreateFailure),
cmocka_unit_test(test_processCrudRequestRetrieve),
cmocka_unit_test(test_processCrudRequestRetrieveFailure),
cmocka_unit_test(test_processCrudRequestUpdate),
cmocka_unit_test(test_processCrudRequestUpdateFailure),
cmocka_unit_test(test_processCrudRequestDelete),
cmocka_unit_test(test_processCrudRequestDeleteFailure),
cmocka_unit_test(test_processCrudRequestFailure),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -21,6 +21,7 @@
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <wrp-c.h>
#include "../src/downstream.h"
#include "../src/ParodusInternal.h"
@@ -32,9 +33,16 @@
ParodusMsg *ParodusMsgQ;
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
int crud_test = 0;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
UNUSED(crudMsg) ;
function_called();
}
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
{
UNUSED(resp_bytes); UNUSED(resp_size);
@@ -53,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 )
{
@@ -60,13 +72,22 @@ ssize_t wrp_to_struct( const void *bytes, const size_t length,
function_called();
*msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
memset(*msg, 0, sizeof(wrp_msg_t));
(*msg)->msg_type = WRP_MSG_TYPE__REQ;
(*msg)->u.req.dest = (char *) malloc(sizeof(char) *100);
(*msg)->u.req.partner_ids = (partners_t *) malloc(sizeof(partners_t));
(*msg)->u.req.partner_ids->count = 1;
(*msg)->u.req.partner_ids->partner_ids[0] = (char *) malloc(sizeof(char) *64);
strcpy((*msg)->u.req.dest,"mac:1122334455/iot");
strcpy((*msg)->u.req.partner_ids->partner_ids[0],"comcast");
(*msg)->msg_type = WRP_MSG_TYPE__REQ;
(*msg)->u.req.dest = (char *) malloc(sizeof(char) *100);
(*msg)->u.req.partner_ids = (partners_t *) malloc(sizeof(partners_t));
(*msg)->u.req.partner_ids->count = 1;
(*msg)->u.req.partner_ids->partner_ids[0] = (char *) malloc(sizeof(char) *64);
parStrncpy((*msg)->u.req.dest,"mac:1122334455/iot", 100);
parStrncpy((*msg)->u.req.partner_ids->partner_ids[0],"comcast", 64);
if(crud_test)
{
(*msg)->msg_type = WRP_MSG_TYPE__CREATE;
parStrncpy((*msg)->u.crud.dest,"mac:1122334455/parodus", 100);
(*msg)->u.crud.source = (char *) malloc(sizeof(char) *40);
parStrncpy ((*msg)->u.crud.source, "tag-update", 40);
(*msg)->u.crud.transaction_uuid = (char *) malloc(sizeof(char) *40);
parStrncpy ((*msg)->u.crud.transaction_uuid, "1234", 40);
}
return (ssize_t) mock();
}
@@ -93,8 +114,8 @@ void test_listenerOnMessage()
expect_function_calls(wrp_to_struct, 1);
reg_list_item_t *head = (reg_list_item_t *) malloc(sizeof(reg_list_item_t));
memset(head, 0, sizeof(reg_list_item_t));
strcpy(head->service_name, "iot");
strcpy(head->url, "tcp://10.0.0.1:6600");
parStrncpy(head->service_name, "iot", sizeof(head->service_name));
parStrncpy(head->url, "tcp://10.0.0.1:6600", sizeof(head->url));
will_return(get_numOfClients, 1);
expect_function_call(get_numOfClients);
@@ -116,19 +137,19 @@ void test_listenerOnMessageMultipleClients()
reg_list_item_t *head2 = (reg_list_item_t *) malloc(sizeof(reg_list_item_t));
memset(head2, 0, sizeof(reg_list_item_t));
strcpy(head2->service_name, "iot");
strcpy(head2->url, "tcp://10.0.0.1:6622");
parStrncpy(head2->service_name, "iot", sizeof(head2->service_name));
parStrncpy(head2->url, "tcp://10.0.0.1:6622", sizeof(head2->url));
reg_list_item_t *head1 = (reg_list_item_t *) malloc(sizeof(reg_list_item_t));
memset(head1, 0, sizeof(reg_list_item_t));
strcpy(head1->service_name, "lmlite");
strcpy(head1->url, "tcp://10.0.0.1:6611");
parStrncpy(head1->service_name, "lmlite", sizeof(head1->service_name));
parStrncpy(head1->url, "tcp://10.0.0.1:6611", sizeof(head1->url));
head1->next = head2;
reg_list_item_t *head = (reg_list_item_t *) malloc(sizeof(reg_list_item_t));
memset(head, 0, sizeof(reg_list_item_t));
strcpy(head->service_name, "config");
strcpy(head->url, "tcp://10.0.0.1:6600");
parStrncpy(head->service_name, "config", sizeof(head->service_name));
parStrncpy(head->url, "tcp://10.0.0.1:6600", sizeof(head->url));
head->next = head1;
will_return(get_numOfClients, 3);
@@ -189,6 +210,23 @@ void err_listenerOnMessageAllNull()
listenerOnMessage(NULL, 0);
}
void test_listenerOnMessageCRUD()
{
crud_test = 1;
will_return(wrp_to_struct, 2);
expect_function_calls(wrp_to_struct, 1);
will_return(get_numOfClients, 0);
expect_function_call(get_numOfClients);
will_return(validate_partner_id, 0);
expect_function_call(validate_partner_id);
will_return(get_global_node, (intptr_t)NULL);
expect_function_call(get_global_node);
expect_function_call(addCRUDmsgToQueue);
listenerOnMessage("Hello", 6);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
@@ -202,6 +240,7 @@ int main(void)
cmocka_unit_test(err_listenerOnMessageServiceUnavailable),
cmocka_unit_test(err_listenerOnMessageInvalidPartnerId),
cmocka_unit_test(err_listenerOnMessageAllNull),
cmocka_unit_test(test_listenerOnMessageCRUD),
};
return cmocka_run_group_tests(tests, NULL, NULL);

View File

@@ -0,0 +1,325 @@
/**
* Copyright 2017 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <wrp-c.h>
#include <CUnit/Basic.h>
#include "../src/downstream.h"
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
typedef struct {
wrp_msg_t s;
wrp_msg_t r;
} test_t;
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
static test_t tests[] = {
{
.s.msg_type = WRP_MSG_TYPE__CREATE,
.s.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.s.u.crud.source = "fake-server1",
.s.u.crud.dest = "fake-client1/iot",
.s.u.crud.partner_ids = NULL,
.s.u.crud.headers = NULL,
.s.u.crud.metadata = NULL,
.s.u.crud.include_spans = false,
.s.u.crud.spans.spans = NULL,
.s.u.crud.spans.count = 0,
.s.u.crud.path = "Some path",
.s.u.crud.payload = "Some binary",
.s.u.crud.payload_size = 11,
.r.msg_type = WRP_MSG_TYPE__CREATE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client1/iot",
.r.u.crud.dest = "fake-server1",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
.r.u.crud.metadata = NULL,
.r.u.crud.include_spans = false,
.r.u.crud.spans.spans = NULL,
.r.u.crud.spans.count = 0,
.r.u.crud.path = "Some path",
.r.u.crud.payload = "{\"statusCode\":531,\"message\":\"Service Unavailable\"}",
.r.u.crud.payload_size = 50,
},
{
.s.msg_type = WRP_MSG_TYPE__RETREIVE,
.s.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.s.u.crud.source = "fake-server2",
.s.u.crud.dest = "fake-client2/iot",
.s.u.crud.partner_ids = NULL,
.s.u.crud.headers = NULL,
.s.u.crud.metadata = NULL,
.s.u.crud.include_spans = false,
.s.u.crud.spans.spans = NULL,
.s.u.crud.spans.count = 0,
.s.u.crud.path = "Some path",
.s.u.crud.payload = NULL,
.s.u.crud.payload_size = 0,
.r.msg_type = WRP_MSG_TYPE__RETREIVE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client2/iot",
.r.u.crud.dest = "fake-server2",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
.r.u.crud.metadata = NULL,
.r.u.crud.include_spans = false,
.r.u.crud.spans.spans = NULL,
.r.u.crud.spans.count = 0,
.r.u.crud.path = "Some path",
.r.u.crud.payload = "{\"statusCode\":531,\"message\":\"Service Unavailable\"}",
.r.u.crud.payload_size = 50,
},
{
.s.msg_type = WRP_MSG_TYPE__UPDATE,
.s.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.s.u.crud.source = "fake-server3",
.s.u.crud.dest = "fake-client3/iot",
.s.u.crud.partner_ids = NULL,
.s.u.crud.headers = NULL,
.s.u.crud.metadata = NULL,
.s.u.crud.include_spans = false,
.s.u.crud.spans.spans = NULL,
.s.u.crud.spans.count = 0,
.s.u.crud.path = "Some path",
.s.u.crud.payload = NULL,
.s.u.crud.payload_size = 0,
.r.msg_type = WRP_MSG_TYPE__UPDATE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client3/iot",
.r.u.crud.dest = "fake-server3",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
.r.u.crud.metadata = NULL,
.r.u.crud.include_spans = false,
.r.u.crud.spans.spans = NULL,
.r.u.crud.spans.count = 0,
.r.u.crud.path = "Some path",
.r.u.crud.payload = "{\"statusCode\":531,\"message\":\"Service Unavailable\"}",
.r.u.crud.payload_size = 50,
},
{
.s.msg_type = WRP_MSG_TYPE__DELETE,
.s.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.s.u.crud.source = "fake-server4",
.s.u.crud.dest = "fake-client4/iot",
.s.u.crud.partner_ids = NULL,
.s.u.crud.headers = NULL,
.s.u.crud.metadata = NULL,
.s.u.crud.include_spans = false,
.s.u.crud.spans.spans = NULL,
.s.u.crud.spans.count = 0,
.s.u.crud.path = "Some path",
.s.u.crud.payload = NULL,
.s.u.crud.payload_size = 0,
.r.msg_type = WRP_MSG_TYPE__DELETE,
.r.u.crud.transaction_uuid = "c2bb1f16-09c8-11e7-93ae-92361f002671",
.r.u.crud.source = "fake-client4/iot",
.r.u.crud.dest = "fake-server4",
.r.u.crud.partner_ids = NULL,
.r.u.crud.headers = NULL,
.r.u.crud.metadata = NULL,
.r.u.crud.include_spans = false,
.r.u.crud.spans.spans = NULL,
.r.u.crud.spans.count = 0,
.r.u.crud.path = "Some path",
.r.u.crud.payload = "{\"statusCode\":531,\"message\":\"Service Unavailable\"}",
.r.u.crud.payload_size = 50,
},
{
.s.msg_type = WRP_MSG_TYPE__EVENT,
.s.u.event.source = "fake-server5",
.s.u.event.dest = "fake-client5/iot",
.s.u.event.partner_ids = NULL,
.s.u.event.headers = NULL,
.s.u.event.metadata = NULL,
.s.u.event.payload = NULL,
.s.u.event.payload_size = 0,
.r = {0},
},
};
static uint8_t i;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void addCRUDmsgToQueue(wrp_msg_t *crudMsg)
{
(void)crudMsg;
return;
}
int validate_partner_id(wrp_msg_t *msg, partners_t **partnerIds)
{
(void) msg; (void) partnerIds;
return 1;
}
ssize_t wrp_to_struct( const void *bytes, const size_t length, const enum wrp_format fmt,
wrp_msg_t **msg )
{
(void) bytes; (void) length; (void) fmt;
*msg = (wrp_msg_t*) malloc(sizeof(wrp_msg_t));
(*msg)->msg_type = tests[i].s.msg_type;
if( WRP_MSG_TYPE__EVENT == tests[i].s.msg_type ) {
(*msg)->u.event.source = strdup(tests[i].s.u.event.source);
(*msg)->u.event.dest = strdup(tests[i].s.u.event.dest);
}
else
{
(*msg)->u.crud.source = strdup(tests[i].s.u.crud.source);
(*msg)->u.crud.dest = strdup(tests[i].s.u.crud.dest);
(*msg)->u.crud.transaction_uuid = strdup(tests[i].s.u.crud.transaction_uuid);
(*msg)->u.crud.path = strdup(tests[i].s.u.crud.path);
}
return (ssize_t) sizeof(tests[i].s);
}
ssize_t wrp_struct_to( const wrp_msg_t *msg, const enum wrp_format fmt, void **bytes )
{
(void) fmt;
*bytes = malloc(1);
CU_ASSERT(WRP_MSG_TYPE__EVENT != msg->msg_type);
CU_ASSERT(tests[i].r.msg_type == msg->msg_type);
CU_ASSERT_STRING_EQUAL(tests[i].r.u.crud.transaction_uuid, msg->u.crud.transaction_uuid);
printf("tests[%d].r.u.crud.source = %s, msg->u.crud.source = %s\n", i, tests[i].r.u.crud.source, msg->u.crud.source);
CU_ASSERT_STRING_EQUAL(tests[i].r.u.crud.source, msg->u.crud.source);
CU_ASSERT_STRING_EQUAL(tests[i].r.u.crud.dest, msg->u.crud.dest);
CU_ASSERT_STRING_EQUAL(tests[i].r.u.crud.path, msg->u.crud.path);
CU_ASSERT(tests[i].r.u.crud.payload_size == msg->u.crud.payload_size);
CU_ASSERT(0 == memcmp(tests[i].r.u.crud.payload, msg->u.crud.payload, msg->u.crud.payload_size));
return 1;
}
void sendUpstreamMsgToServer(void **resp_bytes, size_t resp_size)
{
(void) resp_bytes; (void) resp_size;
}
int get_numOfClients()
{
return 0;
}
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 ) {
if( NULL != msg->u.event.source) {
free(msg->u.event.source);
}
if( NULL != msg->u.event.dest) {
free(msg->u.event.dest);
}
}
else
{
if( NULL != msg->u.crud.source) {
free(msg->u.crud.source);
}
if( NULL != msg->u.crud.dest) {
free(msg->u.crud.dest);
}
if( NULL != msg->u.crud.transaction_uuid) {
free(msg->u.crud.transaction_uuid);
}
if( NULL != msg->u.crud.path) {
free(msg->u.crud.path);
}
}
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_listenerOnMessage()
{
size_t t_size = sizeof(tests)/sizeof(test_t);
void *msg = malloc(1);
for( i = 0; i < t_size; i++ ) {
listenerOnMessage(msg, 0);
}
free(msg);
}
void add_suites( CU_pSuite *suite )
{
printf("--------Start of Test Cases Execution ---------\n");
*suite = CU_add_suite( "tests", NULL, NULL );
CU_add_test( *suite, "Test 1", test_listenerOnMessage );
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( void )
{
unsigned rv = 1;
CU_pSuite suite = NULL;
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();
}
return rv;
}

View File

@@ -0,0 +1,94 @@
/**
* Copyright 2018 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <pthread.h>
#include "../src/heartBeat.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_heartBeatTimer() {
/* get heartBeat timer's initial value */
unsigned int heartBeatTimer =5;
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer initial vaule is: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 0);
/* increment heartbeat timer value and check whether its returning modified value or not*/
unsigned int inc_time_ms =5;
increment_heartBeatTimer(inc_time_ms);
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer incremented to: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer,5);
/* reset heartBeat timer to 0 */
reset_heartBeatTimer();
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer reset to: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer,0);
}
void *test_mutexIncrementTimer() {
unsigned int inc_time_ms =5;
increment_heartBeatTimer(inc_time_ms);
return NULL;
}
void *test_mutexResetTimer() {
reset_heartBeatTimer();
return NULL;
}
void test_mutexHeartBeatTimer() {
unsigned int heartBeatTimer;
pthread_t thread[3];
pthread_create(&thread[0], NULL, test_mutexIncrementTimer, NULL);
pthread_create(&thread[1], NULL, test_mutexIncrementTimer, NULL);
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
/* After execution of both the threads check the value of timer */
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("Threads execution is completed, heartBeatTimer is: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 10);
pthread_create(&thread[2], NULL, test_mutexResetTimer, NULL);
pthread_join(thread[2], NULL);
heartBeatTimer = get_heartBeatTimer();
ParodusInfo("heartBeatTimer reset to: %d\n", heartBeatTimer);
assert_int_equal(heartBeatTimer, 0);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_heartBeatTimer),
cmocka_unit_test(test_mutexHeartBeatTimer),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -54,9 +54,7 @@ void* a(void *in)
lockMutex(data->mutex);
data->number++;
sleep(1);
data->number++;
sleep(1);
data->number++;
unlockMutex(data->mutex);
@@ -69,9 +67,7 @@ void* b(void *in)
lockMutex(data->mutex);
data->number+=10;
sleep(1);
data->number+=10;
sleep(1);
data->number+=10;
unlockMutex(data->mutex);
@@ -100,15 +96,16 @@ void test_Mutex()
void err_mutex()
{
noPollPtr mutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
noPollPtr mutex = &mtx;
will_return(pthread_mutex_destroy, -1);
destroyMutex(mutex);
will_return(pthread_mutex_init, -1);
mutex = createMutex();
free(mutex);
destroyMutex(mutex);
}
void err_mutexNull()

View File

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

View File

@@ -21,16 +21,18 @@
#include <nopoll_private.h>
#include <pthread.h>
#include "../src/ParodusInternal.h"
#include "../src/nopoll_handlers.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
volatile unsigned int heartBeatTimer;
bool LastReasonStatus;
pthread_mutex_t close_mut;
bool close_retry;
bool interface_down_event = false;
int closeReason = 0;
pthread_mutex_t interface_down_mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t interface_down_con=PTHREAD_COND_INITIALIZER;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -40,6 +42,34 @@ void set_global_reconnect_reason(char *reason)
(void) reason;
}
bool get_global_reconnect_status()
{
return LastReasonStatus;
}
void set_interface_down_event()
{
interface_down_event = true;
}
void reset_interface_down_event()
{
pthread_mutex_lock (&interface_down_mut);
interface_down_event = false;
pthread_cond_signal(&interface_down_con);
pthread_mutex_unlock (&interface_down_mut);
}
bool get_interface_down_event()
{
return interface_down_event;
}
void set_global_reconnect_status(bool status)
{
(void) status ;
}
const unsigned char *nopoll_msg_get_payload(noPollMsg *msg)
{
if( NULL != msg ) {
@@ -59,12 +89,27 @@ noPollOpCode nopoll_msg_opcode (noPollMsg * msg)
return NOPOLL_UNKNOWN_OP_CODE;
}
nopoll_bool nopoll_msg_is_fragment(noPollMsg *msg)
{
(void) msg;
return nopoll_false;
}
int nopoll_msg_get_payload_size(noPollMsg *msg)
{
(void) msg;
return 1;
}
int nopoll_conn_get_close_status (noPollConn * conn)
{
(void) conn;
if(closeReason)
return 1006;
else
return 0;
}
int nopoll_conn_send_frame (noPollConn * conn, nopoll_bool fin, nopoll_bool masked,
noPollOpCode op_code, long length, noPollPtr content, long sleep_in_header)
@@ -116,16 +161,16 @@ void *a1(void *in)
char str[] = "SSL_Socket_Close";
(void) in;
LastReasonStatus = false;
set_global_reconnect_status(false);
listenerOnCloseMessage(NULL, NULL, NULL);
LastReasonStatus = false;
set_global_reconnect_status(false);
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
LastReasonStatus = true;
set_global_reconnect_status(true);
listenerOnCloseMessage(NULL, NULL, NULL);
LastReasonStatus = true;
closeReason = 1;
set_global_reconnect_status(true);
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
pthread_exit(0);
@@ -153,6 +198,30 @@ void test_listenerOnPingMessage()
listenerOnPingMessage(NULL, NULL, NULL, NULL);
}
void test_getInterfaceDownEvent()
{
set_interface_down_event();
CU_ASSERT_TRUE(get_interface_down_event());
}
void test_interfaceDownEvent()
{
char str[] = "SSL_Socket_Close";
set_global_reconnect_status(true);
set_interface_down_event();
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
}
void test_noInterfaceDownEvent()
{
char str[] = "SSL_Socket_Close";
set_global_reconnect_status(true);
reset_interface_down_event();
listenerOnCloseMessage(NULL, NULL, (noPollPtr) str);
}
void add_suites( CU_pSuite *suite )
{
ParodusInfo("--------Start of Test Cases Execution ---------\n");
@@ -160,6 +229,9 @@ void add_suites( CU_pSuite *suite )
CU_add_test( *suite, "Test 1", test_listenerOnMessage_queue );
CU_add_test( *suite, "Test 2", test_listenerOnCloseMessage );
CU_add_test( *suite, "Test 3", test_listenerOnPingMessage );
CU_add_test( *suite, "Test 4", test_getInterfaceDownEvent );
CU_add_test( *suite, "Test 5", test_interfaceDownEvent );
CU_add_test( *suite, "Test 6", test_noInterfaceDownEvent );
}
/*----------------------------------------------------------------------------*/

View File

@@ -0,0 +1,140 @@
/**
* Copyright 2010-2016 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>
#include <CUnit/Basic.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
#include <nopoll_private.h>
#include <pthread.h>
#include "../src/nopoll_handlers.h"
#include "../src/parodus_log.h"
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
bool LastReasonStatus;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
void set_global_reconnect_reason(char *reason)
{
(void) reason;
}
bool get_global_reconnect_status()
{
return LastReasonStatus;
}
bool get_interface_down_event()
{
return false;
}
void set_global_reconnect_status(bool status)
{
(void) status ;
}
nopoll_bool nopoll_msg_is_fragment(noPollMsg *msg)
{
(void)msg;
function_called();
return (nopoll_bool) mock();
}
nopoll_bool nopoll_msg_is_final(noPollMsg *msg)
{
(void)msg;
function_called();
return (nopoll_bool) mock();
}
const unsigned char *nopoll_msg_get_payload(noPollMsg *msg)
{
(void)msg;
function_called();
return (const unsigned char *) mock();
}
int nopoll_msg_get_payload_size(noPollMsg *msg)
{
(void) msg;
function_called ();
return (int) mock();
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
void test_listenerOnMessage_queue_fragment()
{
noPollMsg *msg, *msg1;
msg = nopoll_msg_new ();
//1st Fragment
msg->payload_size = strlen("hello");
msg->payload = nopoll_new (char, msg->payload_size + 1);
will_return(nopoll_msg_is_fragment, nopoll_true);
expect_function_call(nopoll_msg_is_fragment);
will_return(nopoll_msg_is_final, nopoll_false);
will_return(nopoll_msg_is_final, nopoll_false);
expect_function_calls(nopoll_msg_is_final, 2);
listenerOnMessage_queue(NULL, NULL, msg, NULL);
//2nd fragment/final message
msg1 = nopoll_msg_new ();
msg1->payload_size = strlen("world");
msg1->payload = nopoll_new (char, msg->payload_size + 1);
will_return(nopoll_msg_is_fragment, nopoll_true);
expect_function_call(nopoll_msg_is_fragment);
will_return(nopoll_msg_is_final, nopoll_true);
will_return(nopoll_msg_is_final, nopoll_true);
expect_function_calls(nopoll_msg_is_final, 2);
will_return(nopoll_msg_get_payload, (intptr_t)"helloworld");
expect_function_call(nopoll_msg_get_payload);
will_return(nopoll_msg_get_payload_size, 10);
expect_function_call(nopoll_msg_get_payload_size);
listenerOnMessage_queue(NULL, NULL, msg1, NULL);
//release the message
nopoll_msg_unref(msg);
nopoll_msg_unref(msg1);
}
/*----------------------------------------------------------------------------*/
/* External Functions */
/*----------------------------------------------------------------------------*/
int main( void )
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_listenerOnMessage_queue_fragment),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -16,12 +16,14 @@
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <setjmp.h>
#include <cmocka.h>
#include <nopoll.h>
#include "../src/parodus_log.h"
#include "../src/nopoll_helpers.h"
#include "../src/config.h"
/*----------------------------------------------------------------------------*/
/* Macros */
@@ -31,7 +33,9 @@
/*----------------------------------------------------------------------------*/
/* File Scoped Variables */
/*----------------------------------------------------------------------------*/
static noPollConn *conn;
static noPollConn *conn = NULL;
static ParodusCfg cfg;
/*----------------------------------------------------------------------------*/
/* Mocks */
/*----------------------------------------------------------------------------*/
@@ -53,6 +57,12 @@ nopoll_bool nopoll_conn_is_ready( noPollConn *conn )
return (nopoll_bool)mock();
}
ParodusCfg *get_parodus_cfg(void)
{
function_called();
return &cfg;
}
int __nopoll_conn_send_common (noPollConn * conn, const char * content, long length, nopoll_bool has_fin, long sleep_in_header, noPollOpCode frame_type)
{
UNUSED(has_fin); UNUSED(sleep_in_header); UNUSED(frame_type); UNUSED(content);
@@ -96,6 +106,31 @@ void listenerOnCloseMessage (noPollCtx * ctx, noPollConn * conn, noPollPtr user_
UNUSED(ctx); UNUSED(conn); UNUSED(user_data);
}
void getCurrentTime(struct timespec *timer)
{
(void) timer;
function_called();
}
long timeValDiff(struct timespec *starttime, struct timespec *finishtime)
{
(void) starttime; (void) finishtime;
function_called();
return (long) mock();
}
int kill(pid_t pid, int sig)
{
UNUSED(pid); UNUSED(sig);
function_called();
return (int) mock();
}
bool get_interface_down_event()
{
return false;
}
/*----------------------------------------------------------------------------*/
/* Tests */
/*----------------------------------------------------------------------------*/
@@ -186,13 +221,8 @@ void test_sendMessage()
{
int len = strlen("Hello Parodus!");
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)conn);
will_return(nopoll_conn_is_ok, nopoll_true);
expect_function_call(nopoll_conn_is_ok);
expect_value(nopoll_conn_is_ready, (intptr_t)conn, (intptr_t)conn);
will_return(nopoll_conn_is_ready, nopoll_true);
expect_function_call(nopoll_conn_is_ready);
cfg.cloud_status = CLOUD_STATUS_ONLINE;
expect_function_calls (get_parodus_cfg, 1);
expect_value(__nopoll_conn_send_common, (intptr_t)conn, (intptr_t)conn);
expect_value(__nopoll_conn_send_common, length, len);
@@ -202,18 +232,23 @@ void test_sendMessage()
sendMessage(conn, "Hello Parodus!", len);
}
void test_sendMessageOffline()
{
int len = strlen("Hello Parodus!");
cfg.cloud_status = CLOUD_STATUS_OFFLINE;
expect_function_calls (get_parodus_cfg, 1);
sendMessage(conn, "Hello Parodus!", len);
}
void err_sendMessage()
{
int len = strlen("Hello Parodus!");
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)conn);
will_return(nopoll_conn_is_ok, nopoll_true);
expect_function_call(nopoll_conn_is_ok);
expect_value(nopoll_conn_is_ready, (intptr_t)conn, (intptr_t)conn);
will_return(nopoll_conn_is_ready, nopoll_true);
expect_function_call(nopoll_conn_is_ready);
cfg.cloud_status = CLOUD_STATUS_ONLINE;
expect_function_calls (get_parodus_cfg, 1);
expect_value(__nopoll_conn_send_common, (intptr_t)conn,(intptr_t) conn);
expect_value(__nopoll_conn_send_common, length, len);
will_return(__nopoll_conn_send_common, len-2);
@@ -231,10 +266,14 @@ void err_sendMessageConnNull()
{
int len = strlen("Hello Parodus!");
expect_value(nopoll_conn_is_ok, (intptr_t)conn, (intptr_t)NULL);
will_return(nopoll_conn_is_ok, nopoll_false);
expect_function_call(nopoll_conn_is_ok);
cfg.cloud_status = CLOUD_STATUS_ONLINE;
expect_function_calls (get_parodus_cfg, 1);
expect_value(__nopoll_conn_send_common, (intptr_t)conn, NULL);
expect_value(__nopoll_conn_send_common, length, len);
will_return(__nopoll_conn_send_common, len);
expect_function_calls(__nopoll_conn_send_common, 1);
sendMessage(NULL, "Hello Parodus!", len);
}
@@ -258,6 +297,7 @@ int main(void)
cmocka_unit_test(err_sendResponseFlushWrites),
cmocka_unit_test(err_sendResponseConnNull),
cmocka_unit_test(test_sendMessage),
cmocka_unit_test(test_sendMessageOffline),
cmocka_unit_test(err_sendMessage),
cmocka_unit_test(err_sendMessageConnNull),
cmocka_unit_test(test_reportLog),

View File

@@ -43,7 +43,7 @@ ParodusCfg *get_parodus_cfg(void)
void test_validate_partner_id_for_req()
{
static partners_t partner_ids = {1,{"comcast"}};
static partners_t partner_ids = {3,{"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;
@@ -51,12 +51,32 @@ void test_validate_partner_id_for_req()
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
strcpy(cfg.partner_id, "comcast");
parStrncpy(cfg.partner_id, "shaw,bar,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);
assert_int_equal(ret, 1);
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()
@@ -67,12 +87,13 @@ void test_validate_partner_id_for_req_listNULL()
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
strcpy(cfg.partner_id, "comcast");
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);
assert_int_equal(ret, 1);
free(msg);
}
void test_validate_partner_id_for_req_withoutId()
@@ -87,7 +108,8 @@ void test_validate_partner_id_for_req_withoutId()
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, 0);
assert_int_equal(ret, 0);
free(msg);
}
void err_validate_partner_id_for_req()
@@ -100,17 +122,18 @@ void err_validate_partner_id_for_req()
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
strcpy(cfg.partner_id, "comcast");
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);
assert_int_equal(ret, -1);
free(msg);
}
void test_validate_partner_id_for_event()
{
static partners_t partner_ids = {1,{"comcast"}};
static partners_t partner_ids = {4,{"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__EVENT;
@@ -118,14 +141,38 @@ void test_validate_partner_id_for_event()
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
strcpy(cfg.partner_id, "comcast");
parStrncpy(cfg.partner_id, "abc,*,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);
assert_int_equal(ret, 1);
free(list);
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()
@@ -136,7 +183,7 @@ void test_validate_partner_id_for_event_listNULL()
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
strcpy(cfg.partner_id, "comcast");
parStrncpy(cfg.partner_id, "comcast", sizeof(cfg.partner_id));
will_return(get_parodus_cfg, (intptr_t)&cfg);
expect_function_call(get_parodus_cfg);
@@ -145,6 +192,13 @@ void test_validate_partner_id_for_event_listNULL()
assert_int_equal(ret, 1);
assert_int_equal(list->count, 1);
assert_string_equal(list->partner_ids[0], "comcast");
int i;
for(i = 0; i< (int) list->count; i++)
{
free(list->partner_ids[i]);
}
free(list);
free(msg);
}
void err_validate_partner_id_for_event()
@@ -159,20 +213,25 @@ void err_validate_partner_id_for_event()
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, 0);
assert_int_equal(ret, 0);
free(msg);
}
void test_validate_partner_id_for_event_withoutId()
{
static partners_t partner_ids = {1,{"shaw"}};
partners_t *partner_ids = (partners_t *) malloc(sizeof(partners_t));
partner_ids->count = 1;
partner_ids->partner_ids[0] = (char *) malloc(sizeof(char)*64);
parStrncpy(partner_ids->partner_ids[0], "shaw", 64);
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;
msg->u.event.partner_ids = partner_ids;
ParodusCfg cfg;
memset(&cfg, 0, sizeof(ParodusCfg));
strcpy(cfg.partner_id, "comcast");
parStrncpy(cfg.partner_id, "comcast", sizeof(cfg.partner_id));
will_return(get_parodus_cfg, (intptr_t)&cfg);
expect_function_call(get_parodus_cfg);
@@ -182,6 +241,14 @@ void test_validate_partner_id_for_event_withoutId()
assert_int_equal(list->count, 2);
assert_string_equal(list->partner_ids[0], "shaw");
assert_string_equal(list->partner_ids[1], "comcast");
int i;
for(i = 0; i< (int) list->count; i++)
{
free(list->partner_ids[i]);
}
free(list);
free(msg);
free(partner_ids);
}
/*----------------------------------------------------------------------------*/
@@ -192,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),

Some files were not shown because too many files have changed in this diff Show More