4 # A collection of posix shell functions for writing CGI scripts.
6 # Copyright 2017 - 2023 Paul Hänsch
8 # Permission to use, copy, modify, and/or distribute this software for any
9 # purpose with or without fee is hereby granted, provided that the above
10 # copyright notice and this permission notice appear in all copies.
12 # THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
15 # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
18 # IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 [ -n "$include_cgilite" ] && return 0
21 # guard set after webserver part
23 # ksh and zsh workaround
24 # set -o posix # ksh, not portable
25 setopt -o OCTAL_ZEROES 2>&-
27 # Integrated webserver request timeout
30 # General environment variables
31 # $_EXEC - directory containing application itself
32 # $_DATA - direcotry where application data may be stored
33 # $_BASE - optional prefix for http path, e.g. "/myapp"
35 # Programmers should take care to use those variables throughout the
37 # Variables may be set via CLI argument, in environment, or left as default.
39 for cgilite_arg in "$@"; do case $cgilite_arg in
40 --exec=*) _EXEC="${cgilite_arg#*=}";;
41 --data=*) _DATA="${cgilite_arg#*=}";;
42 --base=*) _BASE="${cgilite_arg#*=}";;
46 _EXEC="${_EXEC:-${0%/*}}"
48 _EXEC="${_EXEC%/}" _DATA="${_DATA%/}" _BASE="${_BASE%/}"
50 export _EXEC _DATA _BASE
52 # Carriage Return and Line Break characters for convenience
60 # read from stdin if no arguments are provided
62 [ $# -eq 0 ] && str="$(cat)" || str="$*"
64 seg=${str%%/*}; str="${str#*/}"
66 ..) out="${out%/}"; out="${out%/*}/";;
67 .|'') out="${out%/}/";;
68 *) out="${out%/}/${seg}";;
70 [ "$seg" = "$str" ] && break
72 [ "${str}" -a "${out}" ] && printf %s "$out" || printf %s/ "${out%/}"
76 local pfx="$1" in="$2" out
77 # Print out Data encoded as Hex
80 # pfx - required, prefix for a hex tupel, e.g. "\x", "%" "\", may be empty
81 # in - required, string to be decoded
83 # anything that does not constitute a tupel of valid Hex numerals
84 # will be copied to the output literally
87 [ "$pfx" ] || case $in in
88 [0-9a-fA-F][0-9a-fA-F]*):;;
89 ?*) out="${out}${in%%"${in#?}"}"
90 in="${in#?}"; continue;;
94 "$pfx"[0-9a-fA-F][0-9a-fA-F]*) in="${in#"${pfx}"}";;
95 \\*) in="${in#?}"; out="${out}\\\\"; continue;;
96 %*) in="${in#?}"; out="${out}%%"; continue;;
97 *) att="${in%%"${pfx}"*}"; att="${att%%%*}"; att="${att%%\\*}"
98 out="${out}${att}"; in="${in#"${att}"}"; continue;;
101 # Hex escapes for printf (e.g. \x41) are not portable
102 # The portable way for Hex output is transforming Hex to Octal
105 [0123]?*) out="${out}\\0";;
106 [4567]?*) out="${out}\\1";;
107 [89aAbB]?*) out="${out}\\2";;
108 [c-fC-F]?*) out="${out}\\3";;
111 [048cC][0-7]*) out="${out}0";;
112 [048cC][89a-fA-F]*) out="${out}1";;
113 [159dD][0-7]*) out="${out}2";;
114 [159dD][89a-fA-F]*) out="${out}3";;
115 [26aAeE][0-7]*) out="${out}4";;
116 [26aAeE][89a-fA-F]*) out="${out}5";;
117 [37bBfF][0-7]*) out="${out}6";;
118 [37bBfF][89a-fA-F]*) out="${out}7";;
121 ?[08]*) out="${out}0";;
122 ?[19]*) out="${out}1";;
123 ?[2aA]*) out="${out}2";;
124 ?[3bB]*) out="${out}3";;
125 ?[4cC]*) out="${out}4";;
126 ?[5dD]*) out="${out}5";;
127 ?[6eE]*) out="${out}6";;
128 ?[7fF]*) out="${out}7";;
136 if [ -z "$REQUEST_METHOD" ]; then
137 # no webserver variables means we are running via inetd / ncat
138 # so use builtin web server
140 # Use env from inetd as webserver variables
141 REMOTE_ADDR="${TCPREMOTEIP}"
142 SERVER_NAME="${TCPLOCALIP}"
143 SERVER_PORT="${TCPLOCALPORT}"
145 # Wait 2 seconds for request or kill connection through watchdog.
146 # Once Request is received the watchdog will be suspended (killed).
147 # At the end of the loop the watchdog will be restarted to enable
148 # timeout for the subsequent request.
150 (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
151 while read REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL; do
152 unset PATH_INFO QUERY_STRING cgilite_headers CONTENT_LENGTH CONTENT_TYPE
154 [ "${SERVER_PROTOCOL#HTTP/1.[01]${CR}}" ] && break
155 kill $cgilite_watchdog
157 SERVER_PROTOCOL="${SERVER_PROTOCOL%${CR}}"
158 PATH_INFO="$(HEX_DECODE % "${REQUEST_URI%\?*}" |PATH)"
159 [ "${REQUEST_URI}" = "${REQUEST_URI#*\?}" ] \
161 || QUERY_STRING="${REQUEST_URI#*\?}"
163 hl="${hl%${CR}}"; [ "$hl" ] || break
165 'Content-Length: '*) CONTENT_LENGTH="${hl#*: }";;
166 'Content-Type: '*) CONTENT_TYPE="${hl#*: }";;
168 cgilite_headers="${cgilite_headers}${hl}${BR}"
171 export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
172 PATH_INFO QUERY_STRING CONTENT_TYPE CONTENT_LENGTH cgilite_headers
174 # Try to serve multiple requests, provided that script serves a
175 # Content-Length header.
176 # Without Content-Length header, connection will terminate after
179 cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}${BR}";
180 . "$0" | while read -r l; do case $l in
182 cgilite_status="${l#Status: }";;
185 cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
187 cgilite_cl="${l}${BR}";;
188 $CR) printf '%s %s\r\n%s%s\r\n' \
189 'HTTP/1.1' "${cgilite_status%${CR}}" \
190 "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
192 [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
193 *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
194 esac; done || exit 0;
195 (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
197 kill $cgilite_watchdog
203 if [ "${REQUEST_METHOD}" = POST -a "${CONTENT_LENGTH:-0}" -gt 0 -a \
204 "${CONTENT_TYPE}" = "application/x-www-form-urlencoded" ]; then
205 cgilite_post="$(head -c "$CONTENT_LENGTH")"
208 PATH_INFO="$(PATH "/${PATH_INFO#${_BASE}}")"
210 debug(){ [ $# -gt 0 ] && printf '%s\n' "$@" >&2 || tee -a /dev/stderr; }
211 [ "${DEBUG+x}" ] && env >&2
213 # general helper functions, see GET, POST, and REF below
217 | grep -oE '&'"$2"'=[^&]*' \
222 local str="&$1" name="$2" cnt="${3:-1}"
223 while [ $cnt -gt 0 ]; do
224 [ "${str}" = "${str#*&${name}=}" ] && return 1
225 str="${str#*&${name}=}"
228 HEX_DECODE % "$(printf %s "${str%%&*}" |tr + \ )"
233 while [ "${str#*&}" != "${str}" ]; do
235 printf '%s\n' "${str%%=*}"
240 # Read arguments from GET, POST, or the query string of the referrer (REF).
244 # where n is number for the Nth occurence of a variable and defaults to 1
247 # -> returns number of ocurences
249 # -> returns list of available varnames
251 GET(){ cgilite_value "${QUERY_STRING}" "$@"; }
252 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
253 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
255 POST(){ cgilite_value "${cgilite_post}" "$@"; }
256 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
257 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
259 REF(){ cgilite_value "${HTTP_REFERER#*\?}" "$@"; }
260 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
261 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
264 # Read value of header line. Use this instead of
265 # referencing HTTP_* environment variables.
266 if [ -n "${cgilite_headers+x}" ]; then
267 local str="${BR}${cgilite_headers}"
268 [ "${str}" = "${str#*${BR}${1}: }" ] && return 1
269 str="${str#*${BR}${1}: }"
270 printf %s "${str%%${BR}*}"
272 local var="HTTP_$(printf %s "$1" |tr a-z- A-Z_)"
273 eval "[ \"\$$var\" ] && printf %s \"\$$var\" || return 1"
274 # eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
279 # Read value of cookie
282 | grep -oE '(^|; ?)'"$1"'=[^;]*' \
283 | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
288 # Escape HTML cahracters
289 # Also escape [, ], and \n for use in html-sh
291 [ $# -eq 0 ] && str="$(cat)" || str="$*"
292 while [ "$str" ]; do case $str in
293 \&*) out="${out}&"; str="${str#?}";;
294 \<*) out="${out}<"; str="${str#?}";;
295 \>*) out="${out}>"; str="${str#?}";;
296 \"*) out="${out}""; str="${str#?}";;
297 \'*) out="${out}'"; str="${str#?}";;
298 \[*) out="${out}["; str="${str#?}";;
299 \]*) out="${out}]"; str="${str#?}";;
300 "${CR}"*) out="${out}
"; str="${str#?}";;
301 "${BR}"*) out="${out}
"; str="${str#?}";;
302 *) out="${out}${str%%[]&<>\"\'${CR}${BR}[]*}"; str="${str#"${str%%[]&<>\"\'${CR}${BR}[]*}"}";;
308 # Escape pathes, so they can be used in link tags and HTTP Headers
310 [ $# -eq 0 ] && str="$(cat)" || str="$*"
311 while [ "$str" ]; do case $str in
312 \&*) out="${out}%26"; str="${str#?}";;
313 \"*) out="${out}%22"; str="${str#?}";;
314 \'*) out="${out}%27"; str="${str#?}";;
315 \`*) out="${out}%60"; str="${str#?}";;
316 \?*) out="${out}%3F"; str="${str#?}";;
317 \#*) out="${out}%23"; str="${str#?}";;
318 \[*) out="${out}%5B"; str="${str#?}";;
319 \]*) out="${out}%5D"; str="${str#?}";;
320 \ *) out="${out}%20"; str="${str#?}";;
321 " "*) out="${out}%09"; str="${str#?}";;
322 "${CR}"*) out="${out}%0D"; str="${str#?}";;
323 "${BR}"*) out="${out}%0A"; str="${str#?}";;
324 %*) out="${out}%25"; str="${str#?}";;
325 *) out="${out}${str%%[]&\"\'\?# ${CR}${BR}%[]*}"; str="${str#"${str%%[]&\"\'\?# ${CR}${BR}%[]*}"}";;
331 # Param: session | +seconds | [date]
333 # Param: Path= | Domain= | Secure
336 ''|0|session) expire='';;
337 [+-][0-9]*) expire="$(date -R -d @$(($(date +%s) + $1)))";;
338 *) expire="$(date -R -d "$1")";;
342 printf 'Set-Cookie: %s; HttpOnly; SameSite=Lax' "$cookie"
343 [ -n "$expire" ] && printf '; Expires=%s' "${expire%+????}${expire:+GMT}"
344 [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
349 # Trigger redirct and terminate script
350 printf '%s: %s\r\n' \
351 Status "303 See Other" \