]> git.plutz.net Git - clickslide/commitdiff
functions for logging and session handling
authorPaul Hänsch <paul@plutz.net>
Sun, 18 Nov 2018 19:30:00 +0000 (20:30 +0100)
committerPaul Hänsch <paul@plutz.net>
Sun, 18 Nov 2018 19:30:00 +0000 (20:30 +0100)
logging.sh [new file with mode: 0755]
session.sh [new file with mode: 0755]

diff --git a/logging.sh b/logging.sh
new file mode 100755 (executable)
index 0000000..f10ea4c
--- /dev/null
@@ -0,0 +1,29 @@
+#!/bin/sh
+
+# LOGLEVEL 1: Crash condition
+# LOGLEVEL 2: Unexpected condition
+# LOGLEVEL 3: Failed action (i.e. due to config error)
+# LOGLEVEL 4: Debug
+
+[ -n "$include_logging" ] && return 0
+include_logging="$0"
+
+LOGLEVEL="${LOGLEVEL:-3}"
+LOGFILE="${LOGFILE:-/dev/stderr}"
+
+logmsg(){
+  if [ "${1:-3}" -le "$LOGLEVEL" ]; then
+    [ "$#" -gt 1 ] \
+    && printf %s\\n "$*" >>"${LOGFILE}" \
+    || tee -a "${LOGFILE}"
+  fi
+}
+
+
+die(){
+  [ "$#" -gt 0 ] && logmsg 1 "$@"
+  exit 1
+}
+panic(){ logmsg 2 "$@"; }
+error(){ logmsg 3 "$@"; }
+debug(){ logmsg 4 "$@"; }
diff --git a/session.sh b/session.sh
new file mode 100755 (executable)
index 0000000..2769328
--- /dev/null
@@ -0,0 +1,68 @@
+#!/bin/sh
+
+[ -n "$include_session" ] && return 0
+include_session="$0"
+
+server_key(){
+  IDFILE="${IDFILE:-${_DATA:-.}/serverkey}"
+  if ! grep -m1 -xE '.{512}' "$IDFILE"; then
+    dd count=1 bs=512 if=/dev/urandom \
+    | tee "$IDFILE"
+  fi 2>&-
+}
+
+slopecode(){
+  # 6-Bit Code that retains sort order of input data, while beeing safe to use
+  # in ascii transmissions, unix file names, HTTP URLs, and HTML attributes
+
+  uuencode -m - | sed '
+    1d;$d; 
+    y;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/;0123456789:=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz;
+  '
+}
+
+randomid(){
+  dd bs=12 count=1 if=/dev/urandom \
+  | slopecode 2>&-
+}
+
+timeid(){
+  d=$(($(date +%s) % 4294967296))
+  { printf "$(
+      printf \\%o \
+        $((d / 16777216 % 256)) \
+        $((d / 65536 % 256)) \
+        $((d / 256 % 256)) \
+        $((d % 256))
+    )"
+    dd bs=8 count=1 if=/dev/urandom
+  } | slopecode 2>&-
+}
+
+checkid(){ grep -m 1 -xE '[0-9a-zA-Z:_]{16}'; }
+
+update_session(){
+  local session sid time sig serverkey checksig
+
+  IFS=- read -r sid time sig <<-END
+       $(COOKIE session)
+       END
+  serverkey="$(server_key)"
+  
+  checksig="$(printf %s "$sid" "$time" "$serverkey" | sha256sum)"
+  checksig="${checksig%% *}"
+  d=$(date +%s)
+  
+  if [ "$checksig" != "$sig" -o "$time" -lt "$d" ] 2>&-; then
+    sid="$(randomid)"
+  fi
+
+  time=$(( $(date +%s) + 7200 ))
+  sig="$(printf %s "$sid" "$time" "$serverkey" |sha256sum)"
+  sig="${sig%% *}"
+  printf %s\\n "${sid}-${time}-${sig}"
+}
+
+SESSION_ID="$(update_session)"
+SET_COOKIE 0 "session=$SESSION_ID"
+SESSION_ID="${SESSION_ID%%-*}"