summaryrefslogtreecommitdiffstats
path: root/krebs/5pkgs/simple/htgen-cyberlocker/src/htgen-cyberlocker
blob: 6c3ed6552eb17bea724a5c903064a008fab655b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
delete_response() {
  jq -n -r \
  --arg server "$Server" \
  '
    [ "HTTP/1.1 204 OK\r"
    , "Connection: close\r"
    , "Server: \($server)\r"
    , "\r"
    ][]
  '
}

file_response() {(
  type=$(file -ib "$1")
  size=$(wc -c < "$1")
  jq -n -r \
  --arg type "$type" \
  --arg size "$size" \
  --arg server "$Server" \
  '
    [ "HTTP/1.1 200 OK\r"
    , "Connection: close\r"
    , "Content-Length: \($size)\r"
    , "Content-Type: \($type)\r"
    , "Server: \($server)\r"
    , "\r"
    ][]
  '
  cat "$1"
)}

read_uri() {
  jq -cn --arg uri "$1" '
    $uri |
    capture("^((?<scheme>[^:]*):)?(//(?<authority>[^/]*))?(?<path>[^?#]*)([?](?<query>[^#]*))?([#](?<fragment>.*))?$") |
    . + {
      query: (.query | if . != null then
        split("&") |
        map(split("=") | {key:.[0],value:.[1]}) |
        from_entries
      else . end)
    }
  '
}

uri=$(read_uri "$Request_URI")
path=$(jq -nr --argjson uri "$uri" '$uri.path')

case "$Method $path" in
  'POST /'*|'PUT /'*)
    content=$(mktemp -t htgen.$$.content.XXXXXXXX)
    trap "rm $content >&2" EXIT

    head -c $req_content_length > $content

    item=$STATEDIR/items/$(echo "$path" | jq -rR @uri)

    mkdir -v -p $STATEDIR/items >&2
    cp -v $content $item >&2

    scheme=${req_x_forwarded_proto-http}
    link=$scheme://$req_host/$path

  ;;
  'GET /'*)
    item=$STATEDIR/items/$(echo "$path" | jq -rR @uri)
    if [ -e "$item" ]; then
      file_response "$item"
      exit
    fi
  ;;
  'DELETE /'*)
    item=$STATEDIR/items/$(echo "$path" | jq -rR @uri)
    if [ -e "$item" ]; then
      rm "$item"
      delete_response
      exit
    fi
esac