]> git.plutz.net Git - cgilite/blob - storage.sh
10a802950465c813001a3aa27f95f2f4a22dd1b7
[cgilite] / storage.sh
1 #!/bin/sh
2
3 # Copyright 2018, 2019 Paul Hänsch
4 #
5 # This is a file format helper, part of CGIlite.
6
7 # CGIlite is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # CGIlite is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with CGIlite.  If not, see <http://www.gnu.org/licenses/>. 
19
20 [ -n "$include_storage" ] && return 0
21 include_storage="$0"
22
23 LOCK(){
24   local lock timeout block
25   lock="${1}.lock"
26   timeout="${2-20}"
27   if [ \! -w "${lock%/*}" ] || [ -e "$lock" -a \! -d "$lock" ]; then
28     printf 'Impossible to get lock: %s\n' "$lock" >&2
29     return 1
30   fi
31
32   while ! mkdir "$lock" 2>&-; do
33     block="$(cat "$lock/pid" || printf 1)"
34     if ! { ps -eo pid |grep -qwF "$block"; }; then
35       printf 'Overriding stale lock: %s\n' "$lock" >&2
36       break
37     fi
38     if [ $timeout -le 0 ]; then
39       printf 'Timeout while trying to get lock: %s\n' "$lock" >&2
40       return 1
41     fi
42     timeout=$((timeout - 1))
43     sleep 1
44   done
45   printf '%i\n' $$ >"${lock}/pid"
46   return 0
47 }
48
49 RELEASE(){
50   local lock
51   lock="${1}.lock"
52   if [ "$(cat "$lock/pid")" = "$$" ]; then
53     rm "$lock/pid"
54     if ! rmdir "$lock"; then
55       printf 'Cannot remove tainted lock: %s\n' "$lock" >&2
56       printf '%i\n' $$ >"${lock}/pid"
57       return 1
58     fi
59     return 0
60   else
61     printf 'Refusing to release foreign lock: %s\n' "$lock" >&2
62     return 1
63   fi
64 }
65
66 STRING='
67   s;\\;\\\\;g;
68   s;\n;\\n;g;
69   s;\t;\\t;g;
70   s;\r;\\r;g;
71   s;\+;\\+;g;
72   s; ;+;g;
73 '
74
75 STRING(){
76   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
77   | sed -E ':X; $!{N;bX;}'"$STRING"
78 }
79
80 UNSTRING='
81   :UNSTRING_X
82   s;((^|[^\\])(\\\\)*)\\n;\1\n;g;
83   s;((^|[^\\])(\\\\)*)\\t;\1\t;g;
84   s;((^|[^\\])(\\\\)*)\\r;\1\r;g;
85   s;((^|[^\\])(\\\\)*)\+;\1 ;g;
86   tUNSTRING_X;
87   s;((^|[^\\])(\\\\)*)\\\+;\1+;g;
88   s;\\\\;\\;g;
89 '
90 UNSTRING(){
91   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
92   | sed -E "$UNSTRING"
93 }