libcgi2.sh 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #! /bin/bash -E
  2. # (internal) routine to store POST data
  3. function cgi_get_POST_vars() {
  4. # save POST variables (only first time this is called)
  5. [ -z "$QUERY_STRING_POST" \
  6. -a "$REQUEST_METHOD" = "POST" -a ! -z "$CONTENT_LENGTH" ] && \
  7. read -N $CONTENT_LENGTH QUERY_STRING_POST
  8. if [ "${CONTENT_TYPE}" != "application/x-www-form-urlencoded" ]; then
  9. # might work with regular parsing below..
  10. return
  11. elif [ "${CONTENT_TYPE}" != "multipart/form-data" ]; then
  12. # cant handle..
  13. return
  14. fi
  15. return
  16. }
  17. # (internal) routine to decode urlencoded strings
  18. function cgi_decodevar() {
  19. [ $# -ne 1 ] && return
  20. local v t h
  21. # replace all + with whitespace and append %%
  22. t="${1//+/ }%%"
  23. while [ ${#t} -gt 0 -a "${t}" != "%" ]; do
  24. v="${v}${t%%\%*}" # digest up to the first %
  25. t="${t#*%}" # remove digested part
  26. # decode if there is anything to decode and if not at end of string
  27. if [ ${#t} -gt 0 -a "${t}" != "%" ]; then
  28. h=${t:0:2} # save first two chars
  29. t="${t:2}" # remove these
  30. v="${v}"`echo -e \\\\x${h}` # convert hex to special char
  31. fi
  32. done
  33. # return decoded string
  34. echo "${v}"
  35. return
  36. }
  37. # routine to get variables from http requests
  38. # usage: cgi_getvars method varname1 [.. varnameN]
  39. # method is either GET or POST or BOTH
  40. # the magic varible name ALL gets everything
  41. function cgi_getvars() {
  42. [ $# -lt 2 ] && return
  43. local q="" p k v s
  44. # get query
  45. case $1 in
  46. GET)
  47. [ ! -z "${QUERY_STRING}" ] && q="${QUERY_STRING}&"
  48. ;;
  49. POST)
  50. cgi_get_POST_vars
  51. [ ! -z "${QUERY_STRING_POST}" ] && q="${QUERY_STRING_POST}&"
  52. ;;
  53. BOTH)
  54. [ ! -z "${QUERY_STRING}" ] && q="${QUERY_STRING}&"
  55. cgi_get_POST_vars
  56. [ ! -z "${QUERY_STRING_POST}" ] && q="${q}${QUERY_STRING_POST}&"
  57. ;;
  58. esac
  59. shift
  60. s=" $* "
  61. # parse the query data
  62. p="${q%%?*}" # get first part of query string
  63. while [ ! -z "$q" ]; do
  64. q="${q#$p&*}" # strip first part from query string
  65. k="${q%%=*}" # get the key (variable name) from it
  66. v="${q#*=}" # get the value from it
  67. v="${v%%&*}" # get the value from it
  68. q="${q#$k=$v}" # strip first part from query string
  69. # decode and evaluate var if requested
  70. [ "$1" = "ALL" -o "${s/ $k /}" != "$s" ] && \
  71. eval "$k=\"$(cgi_decodevar $v | sed 's/[\"\\]/\\&/g')\""
  72. done
  73. return
  74. }