From 5fd8b22b8c55a8bdd9002fc8474595637cfde9ef Mon Sep 17 00:00:00 2001 From: Matthias Kruk Date: Tue, 15 Jun 2021 09:21:48 +0900 Subject: [PATCH] include/ipc: Simplify IPC endpoint API The current API of the ipc module expects the user to create an ipc_msg and send that using the ipc_endpoint_send() function, however there is nothing useful that can be done with an ipc_msg besides sending it, so it makes no sense to have the user create the ipc_msg themselves. Further, the ipc_endpoint_recv() function will return any received ipc_msg to the user, including invalid or unauthenticated messages. This commit changes the IPC endpoint API so that the user can pass the data they intend to send right to ipc_endpoint_send() without having to call ipc_msg_new(). Since ipc_msg_new() is not intended to be used by the user directly, it is removed from the public API of the ipc module. Further, the ipc_endpoint_recv() function is modified to return only valid, authenticated messages to the caller. --- include/ipc.sh | 66 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 57 insertions(+), 9 deletions(-) diff --git a/include/ipc.sh b/include/ipc.sh index a48e8c1..c289a91 100644 --- a/include/ipc.sh +++ b/include/ipc.sh @@ -209,7 +209,7 @@ EOF return 0 } -ipc_msg_new() { +_ipc_msg_new() { local source="$1" local destination="$2" local data_raw="$3" @@ -410,10 +410,17 @@ _ipc_endpoint_get() { } ipc_endpoint_send() { - local endpoint="$1" - local msg="$2" + local source="$1" + local destination="$2" + local data="$3" + + local msg + + if ! msg=$(_ipc_msg_new "$source" "$destination" "$data"); then + return 1 + fi - if ! _ipc_endpoint_put "$endpoint" "$msg"; then + if ! _ipc_endpoint_put "$destination" "$msg"; then return 1 fi @@ -424,12 +431,53 @@ ipc_endpoint_recv() { local endpoint="$1" local -i timeout="$2" - local msg + local -i start - if ! msg=$(_ipc_endpoint_get "$endpoint" "$timeout"); then - return 1 + if (( $# < 2 )); then + timeout=-1 fi - echo "$msg" - return 0 + if ! start=$(date +"%s"); then + return 2 + fi + + while true; do + local msg + local -i elapsed + local -i remaining + + remaining="$timeout" + + if (( timeout > 0 )); then + local now + + if ! now=$(date +"%s"); then + return 2 + fi + + elapsed=$((now - start)) + remaining=$((timeout - elapsed)) + + # Remaining must not be negative because _ipc_endpoint_get() takes + # that to mean "block (possibly forever) until a message arrives" + if (( remaining < 0 )); then + remaining=0 + fi + fi + + if msg=$(_ipc_endpoint_get "$endpoint" "$remaining"); then + if _ipc_msg_validate "$msg"; then + echo "$msg" + return 0 + fi + + log_info "Dropping invalid message on $endpoint" + fi + + if (( remaining == 0 )); then + break + fi + done + + return 1 } -- 2.47.3