post.sh 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #!/bin/bash
  2. ## SuperGlue project | http://superglue.it | 2014 | GPLv3
  3. ## http://git.superglue.it/superglue/serverside/edit/master/common/rootFS/www/lib/post.sh
  4. ## author: Danja Vasiliev <danja@k0a1a.net>
  5. ##
  6. ## post.sh - all POST requests are redirected to this script.
  7. ##
  8. ## examples:
  9. ## text: curl --data-urlencode '<html><title>' http://host/file.html
  10. ## image: curl --form "userimage=@file.png" -H "Expect:" http://host/file.png
  11. ## command: curl --data-urlencode 'ls' http://host/cmd
  12. ##
  13. ## returns: 200 (+ output of operation) on success
  14. ## 406 (+ error message in debug mode) on error
  15. ## no globbing, for safety
  16. set -o noglob
  17. ## some path variables
  18. _WWW='/www'
  19. _HTDOCS="${_WWW}/htdocs"
  20. _TMP="${_WWW}/tmp"
  21. _LOG="${_TMP}/post.log"
  22. ## _DEBUG=0 no logging at all
  23. ## _DEBUG=1 writes to $_LOG file
  24. ## _DEBUG=2 adds [verbose].. to HTTP response. Can be triggered via 'Content-Type' header option
  25. ## eg: "Content-Type:application/octet-stream; verbose=1"
  26. _DEBUG=1
  27. #### FUNCTIONS
  28. ## logging
  29. logThis() {
  30. [[ $_DEBUG -gt 0 ]] || return 0
  31. [[ $_ERR -gt 0 ]] && _TYPE='E:' || _TYPE='I:' ## Info or Error indication
  32. local _TIME=$(printf '%(%d.%m.%Y %H:%M:%S)T' -1)
  33. printf '%b\n' "$_TIME $_TYPE ${1} " >> $_LOG
  34. [[ $_DEBUG -gt 1 ]] && printf '%b\n' "[verbose] $_TYPE ${1}"
  35. return 0
  36. }
  37. ## inject function execution trace to global _OUT
  38. wTf() {
  39. local _WTF="$(printf '%s -> ' '| trace: '${FUNCNAME[*]:1})"
  40. _OUT="$_OUT $_WTF"
  41. }
  42. ## urldecode
  43. urlDecode() {
  44. local encoded="${1//+/ }"
  45. printf '%b' "${encoded//%/\x}"
  46. }
  47. ## http response
  48. headerPrint() {
  49. case ${1} in
  50. 200) printf '%b' 'HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\n\n';;
  51. 405) printf '%b' 'HTTP/1.1 405 Method Not Allowed\n\n';;
  52. 406) printf '%b' 'HTTP/1.1 406 Not Acceptable\n\n';;
  53. esac
  54. return 0
  55. }
  56. ## takes exit code variable $? and optional "message" string.
  57. ## exit code 0 simply falls through. when local message
  58. ## is not provided tries to assign global $_OUT.
  59. ##
  60. ## eg: errorCheck $? "bad zombie"
  61. ##
  62. ## produces HTTP 406 header, $_OUT message, triggers logThis()
  63. ## and exits the main loop with exit >= 1.
  64. errorCheck() {
  65. _ERR=${1} ## exit code
  66. [[ $_ERR -gt 0 ]] || return 0
  67. local _MSG=${2}
  68. ## if $_OUT is present cut it down to one line
  69. ## otherwise assign message from the invokation arguments
  70. [[ $_OUT ]] && _OUT="${_OUT%%$'\n'*}" || { _OUT=${_MSG:='unknown error occured'}; wTf; }
  71. [[ -e $_POST_TMP ]] && rm -f $_POST_TMP
  72. headerPrint '406'
  73. logThis "${_OUT}";
  74. exit $_ERR
  75. }
  76. ## urlencoded POST dispatcher
  77. postUrlenc() {
  78. ## decode stream
  79. _POST=$(urlDecode "$(< $_POST_TMP)") ## decode global $_POST
  80. case "${_REQUEST_URI}" in
  81. \/cmd) postCmd ;; ## handle /cmd POST
  82. *) postHtml ;; ## handle html POST
  83. esac
  84. }
  85. ## handle /cmd POST
  86. postCmd() {
  87. local _CMD=( ${_POST} ) ## convert POST to array
  88. [[ ${#_CMD[@]} -lt 5 ]] || errorCheck '1' "'${_CMD[*]}': too many arguments"
  89. local _EXE="${_CMD[0]}" ## first member is command
  90. local _ARG="${_CMD[@]:1}" ## the rest is arguments
  91. ## note unquoted regex
  92. [[ ! "$_ARG" =~ (\.\.|^/| /) ]] || errorCheck '1' "'$_ARG': illegal path"
  93. ## 'ls' replacement function
  94. lss() {
  95. _D='\t' ## do we want a customizable delimiter?
  96. while getopts 'la' _OPT; do
  97. case $_OPT in
  98. l) local _LNG="$_D%F$_D%s$_D%y$_D%U$_D%G$_D%a" ;;
  99. a) shopt -s dotglob
  100. esac
  101. done
  102. shift $((OPTIND-1)) ## removing used args
  103. [[ -z "${@}" ]] && _PT="./*" ## list ./* if called with no args
  104. [[ -d "${@}" ]] && _PT="/*" ## add /* to directories
  105. ## if error occures return 0
  106. stat --printf "%n$_LNG\n" -- "${@%%/}"$_PT 2>/dev/null || _ERR=0
  107. return $_ERR
  108. }
  109. case "$_EXE" in
  110. ls|lss) _EXE="lss"; _ARG="${_ARG}" ;; ## no error is returned
  111. cp) _ARG="${_ARG}" ;;
  112. rm) _ARG="${_ARG}" ;; ## add recursive option if you need
  113. mv) _ARG="${_ARG}" ;;
  114. mkdir) _ARG="${_ARG}" ;;
  115. log) _EXE="tail"; _ARG="${_ARG} ${_LOG}" ;;
  116. wget) _ARG="-q ${_ARG/ */} -O ${_ARG/* /}" ;; ## quiet
  117. *) errorCheck '1' "'$_EXE': bad command" ;;
  118. esac
  119. ## toggle globbing
  120. set +o noglob
  121. _OUT=$($_EXE $_ARG 2>&1)
  122. _ERR=$?
  123. ## toggle globbing
  124. set -o noglob
  125. logThis "$_EXE $_ARG"
  126. errorCheck $_ERR
  127. }
  128. ## handle html POST
  129. postHtml() {
  130. ## save POST to file
  131. _OUT=$( (printf '%b' "${_POST}" > "${_HTDOCS}${_REQUEST_URI}") 2>&1)
  132. _ERR=$?
  133. errorCheck $_ERR
  134. }
  135. ## octet POST dispatcher
  136. postOctet() {
  137. ## get 'data:' header length
  138. local IFS=','; read -d',' -r _DH < $_POST_TMP
  139. case "${_ENC}" in
  140. base64) postBase64Enc;;
  141. binary) postBinary ;;
  142. *) postGuessEnc ;; ## handle data POST
  143. esac
  144. }
  145. ## to be converted into a proper data-type detection function
  146. postGuessEnc() {
  147. shopt -s nocasematch
  148. local _DTP="^.*\;([[:alnum:]].+)$" ## data-type header pattern
  149. ## look for encoding in the data header
  150. [[ "${_DH}" =~ ${_DTP} ]] && _ENC="${BASH_REMATCH[1]}"
  151. logThis "'$_ENC:' encoding is the best guess";
  152. shopt -u nocasematch
  153. case "$_ENC" in
  154. base64) postBase64Enc ;;
  155. ## binary) _ERR=1 ;;
  156. ## json) _ERR=1 ;;
  157. ## quoted-printable) _ERR=1 ;;
  158. *) _ERR=1; _OUT="'${_ENC:='unknown'}' encoding, unknown POST failed";;
  159. esac
  160. errorCheck $_ERR
  161. }
  162. ## handle base64 post
  163. postBase64Enc() {
  164. logThis "'${_ENC}:' decoding stream"
  165. _DL=${#_DH} ## get data-header length
  166. [[ $_DL -lt 10 ]] && { _DL=23; _SKP=0; } || { let _DL+=1; _SKP=1; } ## '23' - what?!
  167. ## the line below seems to be the best solution for the time being
  168. ## dd 'ibs' and 'iflags' seem not to work on OpenWRT - investigate as it might be very useful
  169. _OUT=$( dd if=${_POST_TMP} bs=${_DL} skip=${_SKP} | base64 -d > "${_HTDOCS}${_REQUEST_URI}" 2>&1)
  170. _ERR=$?
  171. errorCheck $_ERR
  172. }
  173. postBinary() {
  174. logThis "'binary': decoding stream"
  175. ## it is unclear what will be necessary to do here
  176. _OUT=$( dd if="${_POST_TMP}" of="${_HTDOCS}${_REQUEST_URI}" 2>&1 )
  177. _ERR=$?
  178. errorCheck $_ERR
  179. }
  180. postMpart() {
  181. logThis "'multipart': decoding stream"
  182. local _BND=$(findPostOpt 'boundary')
  183. ## bash is binary unsafe and eats away precious lines
  184. ## thus using gawk
  185. function cutFile() {
  186. gawk -v "want=$1" -v "bnd=$_BND" '
  187. BEGIN { RS="\r\n"; ORS="\r\n" }
  188. # reset based on boundaries
  189. $0 == "--"bnd"" { st=1; next; }
  190. $0 == "--"bnd"--" { st=0; next; }
  191. $0 == "--"bnd"--\r" { st=0; next; }
  192. # search for wanted file
  193. st == 1 && $0 ~ "^Content-Disposition:.* name=\""want"\"" { st=2; next; }
  194. st == 1 && $0 == "" { st=9; next; }
  195. # wait for newline, then start printing
  196. st == 2 && $0 == "" { st=3; next; }
  197. st == 3 { print $0 }
  198. ' 2>&1
  199. }
  200. cutFile 'userimage' < "${_POST_TMP}" > "${_HTDOCS}${_REQUEST_URI}"
  201. _ERR=$?
  202. errorCheck $_ERR
  203. }
  204. ## find arbitrary option supplied in Content-Type header
  205. ## eg: "Content-Type:application/octet-stream; verbose=1"
  206. findPostOpt() {
  207. for i in "${CONTENT_TYPE[@]:1}"; do
  208. case "${i/=*}" in
  209. "$1") printf '%b' "${i/*=}" ;;
  210. esac
  211. done
  212. return 0
  213. }
  214. ## sanitize by backslashing all expandable symbols
  215. escapeStr() {
  216. printf "%q" "${*}"
  217. }
  218. ## brutally replace unwanted characters
  219. cleanFname() {
  220. shopt -s extglob
  221. local _STR="${*}"
  222. echo -n "${_STR//[^[:alnum:]._\-\/\\]/_}"
  223. shopt -u extglob
  224. }
  225. #### MAIN LOOP
  226. ## timing
  227. ## TODO: remove it
  228. ## run once here and once at the end
  229. read t z < /proc/uptime
  230. ## check if we are in $_HTDOCS directory
  231. cd $_HTDOCS || errorCheck $? 'htdocs unavailable'
  232. [[ ${PWD} == ${_HTDOCS} ]] || errorCheck $? 'htdocs misconfigured'
  233. [[ $CONTENT_LENGTH -gt 0 ]] || errorCheck $? 'content length zero'
  234. ## URI is considered as a file dest to work with
  235. ## add 'index.html' to default and empty request uri
  236. _REQUEST_URI="${REQUEST_URI/%\///index.html}"
  237. _REQUEST_URI="$(urlDecode $_REQUEST_URI)"
  238. _PATH="${_REQUEST_URI%/*}"
  239. CONTENT_TYPE=( ${CONTENT_TYPE} )
  240. _CONTENT_TYPE="${CONTENT_TYPE[0]/;}"
  241. _ENC="${HTTP_CONTENT_ENCODING}"
  242. #logThis "Len: $CONTENT_LENGTH Ctype: $CONTENT_TYPE Enc: $_CONTENT_ENCODING"
  243. ## check for 'verbose' option in POST
  244. findPostOpt 'verbose' || { _DEBUG=2; logThis 'verbose mode is requested'; }
  245. _POST_TMP=$(mktemp -p $_TMP) ## make tmp POST file
  246. cat > $_POST_TMP ## cautiously storing entire POST in a file
  247. ## dispatching POST
  248. case "${_CONTENT_TYPE}" in
  249. application\/x-www-form-urlencoded) postUrlenc ;;
  250. application\/octet-stream) postOctet ;;
  251. multipart/form-data) postMpart ;;
  252. *) _ERR=1; _OUT='this is not a post' ;;
  253. esac
  254. [[ -e $_POST_TMP ]] && rm -f $_POST_TMP
  255. ## make sure we are good
  256. errorCheck $_ERR
  257. [[ -z $_OUT ]] || _OUT="${_OUT}\n"
  258. headerPrint '200' ## on success
  259. printf '%b' "${_OUT}"
  260. logThis 'OK 200'
  261. read d z < /proc/uptime
  262. logThis $((${d/./}-${t/./}))"/100s"
  263. exit 0