dreadlock-ng.sh - dreadlock-ng - Remote locking daemon with a funny name. HTML git clone git://bitreich.org/dreadlock-ng git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65d7roiv6bfj7d652fid.onion/dreadlock-ng DIR Log DIR Files DIR Refs DIR Tags DIR README DIR LICENSE --- dreadlock-ng.sh (2176B) --- 1 #!/bin/bash 2 # 3 # Copy me, if you can. 4 # by 20h 5 # 6 7 #set -x 8 9 lockbasepath="/tmp/dreadlock-ng" 10 if [ $# -gt 0 ]; 11 then 12 lockbasepath="$1" 13 fi 14 15 mkdir -p "${lockbasepath}" 16 17 declare -A locks=() 18 19 function unlock_on_disconnect() { 20 for lockfd in ${locks[@]}; 21 do 22 flock -u "${lockfd}" 2>/dev/null 23 done 24 for lockname in ${!locks[@]}; 25 do 26 [ -e "${lockbasepath}/${lockname}" ] && rm -f "${lockbasepath}/${lockname}"; 27 done 28 } 29 30 trap unlock_on_disconnect EXIT 31 trap unlock_on_disconnect 1 32 trap unlock_on_disconnect 2 33 trap unlock_on_disconnect 3 34 trap unlock_on_disconnect 6 35 trap unlock_on_disconnect 9 36 trap unlock_on_disconnect 15 37 38 while read -r line; 39 do 40 case "${line}" in 41 "lock "*) 42 lockname="$(printf "%s\n" "${line}" | tr -d $'\r' | cut -d' ' -f 2)" 43 if [ -z "${lockname}" ]; 44 then 45 printf "e no lock name specified\r\n" 46 exit 1; 47 fi 48 if [[ "${lockname}" =~ [^a-zA-Z0-9] ]]; 49 then 50 printf "e lock name must be alphanumeric\r\n" 51 exit 1 52 fi 53 timeoutms="$(printf "%s\n" "${line}" | tr -d $'\r' | cut -d' ' -f 3)" 54 if [ -z "${timeoutms}" ]; 55 then 56 printf "e no timeout specified\r\n" 57 exit 1; 58 fi 59 if [[ "${timeoutms}" =~ [^0-9] ]]; 60 then 61 printf "e timeout must be numeric\r\n" 62 exit 1 63 fi 64 timeouts="$(units -t "${timeoutms}ms" "s" 2>/dev/null)" 65 case "${timeouts}" in 66 0*) 67 # flock(1) needs at least one second. 68 timeouts=1 69 ;; 70 esac 71 72 lockpath="${lockbasepath}/${lockname}" 73 touch "${lockpath}" 74 exec {fd}<>"${lockpath}" 75 flock -x -w "${timeouts}" "${fd}" 76 if [ $? -gt 0 ]; 77 then 78 printf "t timeout\r\n" 79 exit 1 80 fi 81 locks[${lockname}]+="${fd}" 82 printf "l locked\r\n" 83 ;; 84 "unlock "*) 85 lockname="$(printf "%s\n" "${line}" | tr -d $'\r' | cut -d' ' -f 2)" 86 if [ -z "${lockname}" ]; 87 then 88 printf "e no lock name specified\r\n" 89 exit 1; 90 fi 91 if [[ "${lockname}" =~ [^a-zA-Z0-9] ]]; 92 then 93 printf "e lock name must be alphanumeric\r\n" 94 exit 1 95 fi 96 97 lockfd=${locks[${lockname}]} 98 if [ -z "${lockfd}" ]; 99 then 100 printf "e unknown lock\r\n" 101 exit 1 102 fi 103 104 flock -u "${lockfd}" 105 if [ $? -gt 1 ]; 106 then 107 printf "e unlock error\r\n" 108 exit 1 109 fi 110 printf "u unlocked\r\n" 111 ;; 112 *) 113 exit 1; 114 esac 115 done 116 117 exit 0 118