plugin-echo.sh (2019B)
1 #!/bin/sh 2 # A linkd plugin in POSIX shell: RESP over stdin/stdout. 3 # 4 # Exists to prove a plugin needs no C, no library and no linking -- and to give 5 # the test suite something to drive. It logs what it receives to 6 # $PLUGIN_LOG so tests can assert on the commands linkd actually sent. 7 # 8 # Only the subset of RESP linkd sends is parsed: arrays of bulk strings. 9 10 LOG="${PLUGIN_LOG:-/dev/null}" 11 HARDWARE="${PLUGIN_HARDWARE:-1}" 12 FAIL_VERB="${PLUGIN_FAIL_VERB:-}" 13 14 # RESP replies. printf with \r\n; the protocol is CRLF-delimited. 15 ok() { printf '+OK\r\n'; } 16 err() { printf -- '-ERR %s\r\n' "$1"; } 17 bulk() { printf '$%s\r\n%s\r\n' "${#1}" "$1"; } 18 19 array() { 20 printf '*%s\r\n' "$#" 21 for a in "$@"; do printf '$%s\r\n%s\r\n' "${#a}" "$a"; done 22 } 23 24 # Read one RESP array into $ARGV (newline-separated). Returns 1 at EOF. 25 read_command() { 26 ARGV='' 27 read -r line || return 1 28 line=${line%$(printf '\r')} 29 case "$line" in 30 '*'*) count=${line#\*} ;; 31 *) return 1 ;; 32 esac 33 34 i=0 35 while [ "$i" -lt "$count" ]; do 36 read -r hdr || return 1 # $<len> 37 read -r val || return 1 # payload 38 val=${val%$(printf '\r')} 39 ARGV="${ARGV}${val} 40 " 41 i=$((i + 1)) 42 done 43 return 0 44 } 45 46 while read_command; do 47 verb=$(printf '%s' "$ARGV" | sed -n '1p' | tr '[:lower:]' '[:upper:]') 48 sub=$(printf '%s' "$ARGV" | sed -n '2p' | tr '[:lower:]' '[:upper:]') 49 printf '%s' "$ARGV" | tr '\n' ' ' | sed 's/ *$//' >> "$LOG" 50 printf '\n' >> "$LOG" 51 52 if [ -n "$FAIL_VERB" ] && [ "$verb" = "$FAIL_VERB" ]; then 53 err "deliberate failure" 54 continue 55 fi 56 57 case "$verb" in 58 COMMAND) array PORT RIF NEIGH ROUTE RESYNC CONFIG INFO ;; 59 INFO) bulk "# Server 60 name:echo 61 version:0.1.0 62 63 # Stats 64 hardware_detected:${HARDWARE} 65 " ;; 66 CONFIG) 67 case "$sub" in 68 LIST) array echo-setting echo-other ;; 69 SET) ok ;; 70 *) err "unknown CONFIG subcommand" ;; 71 esac 72 ;; 73 PORT|RIF|NEIGH|ROUTE|RESYNC) ok ;; 74 AUTH) ok ;; 75 *) err "unknown command $verb" ;; 76 esac 77 done