]> git.plutz.net Git - cgilite/blob - static.sh
cgi conformant 404s
[cgilite] / static.sh
1 #!/bin/zsh
2
3 # Copyright 2016 Paul Hänsch
4 #
5 # This file is part of shcgi.
6
7 # shcgi 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 # shcgi 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 shcgi.  If not, see <http://www.gnu.org/licenses/>. 
19
20
21 unset length date file suffix
22 file="$1"
23 date="$(stat -Lc %Y "$file")"
24
25 # allow overriding magic file recognition
26 # don't use this if `file` returns type correctly
27 declare -A suffix
28 suffix[css]="text/css"
29
30 [ -n "$HTTP_IF_MODIFIED_SINCE" ] && cachedate="$(date -d "$HTTP_IF_MODIFIED_SINCE" +%s)"
31
32 if printf '%s' "${HTTP_RANGE}" |grep -qE '^bytes=[0-9]+-[0-9]*\r?$'; then
33   _range="${HTTP_RANGE#bytes=}"
34   _bstart="${_range%-*}"
35   _bend="${_range#*-}"
36 fi
37
38 if ! [ -f "$file" ] || [ -x "$file" ] || ! grep -qm1 '' "$file" ; then
39   printf 'Status:403 Forbidden\r\n\r\n'
40 elif [ "$date" = "$cachedate" ]; then
41   printf 'Status:304 Not Modified\r\n'
42   printf 'Last-Modified: %s\r\n\r\n' "$(date -Rd "@$date")"
43 elif [ "$_bstart" -gt 0 ] ; then
44   length="$(stat -Lc %s "$file")"
45   magic="${suffix[${file##*.}]:-$(file -bi "$file")}"
46
47   printf 'Status:206 Partial Content\r\n'
48   printf 'Last-Modified: %s\r\n' "$(date -Rd "@$date")"
49   printf 'Content-Type: %s\r\n' "${magic:-all/all}"
50   printf 'Content-Range: bytes %i-%i/%i\r\n' $_bstart $(($length - 1)) $length |debug
51   printf 'Content-Length: %i\r\n' $(($length - $_bstart))
52   printf '\r\n'
53
54   tail -c+"$(($_bstart + 1))" "$file"
55 else
56   length="$(stat -Lc %s "$file")"
57   magic="${suffix[${file##*.}]:-$(file -bi "$file")}"
58
59   printf 'Accept-Ranges: bytes\r\n'
60   printf 'Last-Modified: %s\r\n' "$(date -Rd "@$date")"
61   printf 'Content-Type: %s\r\n' "${magic:-all/all}"
62   printf 'Content-Length: %i\r\n' "$length"
63   printf '\r\n'
64
65   cat "$file"
66 fi
67