post.sh 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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="/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. ## get data from argv=data pair in POST request
  77. ## (any 4 character arg in the beginning of string is matched)
  78. postGetData() {
  79. _POST="${_POST##????'='}"
  80. }
  81. ## urlencoded POST dispatcher
  82. postUrlenc() {
  83. ## decode stream
  84. _POST=$(urlDecode "$(< $_POST_TMP)") ## decode global $_POST
  85. postGetData
  86. case "${_REQUEST_URI}" in
  87. \/cmd) postCmd ;; ## handle /cmd POST
  88. *) postHtml ;; ## handle html POST
  89. esac
  90. }
  91. ## handle /cmd POST
  92. postCmd() {
  93. local _CMD=( ${_POST} ) ## convert POST to array
  94. [[ ${#_CMD[@]} -lt 5 ]] || errorCheck '1' "'${_CMD[*]}': too many arguments"
  95. local _EXE="${_CMD[0]}" ## first member is command
  96. local _ARG="${_CMD[@]:1}" ## the rest is arguments
  97. ## note unquoted regex
  98. [[ ! "$_ARG" =~ (\.\.|^/| /) ]] || errorCheck '1' "'$_ARG': illegal path"
  99. ## 'ls' replacement function
  100. lss() {
  101. _D='\t' ## do we want a customizable delimiter?
  102. while getopts 'la' _OPT; do
  103. case $_OPT in
  104. l) local _LNG="$_D%F$_D%s$_D%y$_D%U$_D%G$_D%a" ;;
  105. a) shopt -s dotglob
  106. esac
  107. done
  108. shift $((OPTIND-1)) ## removing used args
  109. [[ -z "${@}" ]] && _PT="./*" ## list ./* if called with no args
  110. [[ -d "${@}" ]] && _PT="/*" ## add /* to directories
  111. ## if error occures return 0
  112. stat --printf "%n$_LNG\n" -- "${@%%/}"$_PT 2>/dev/null || _ERR=0
  113. return $_ERR
  114. }
  115. case "$_EXE" in
  116. ls|lss) _EXE="lss"; _ARG="${_ARG}" ;; ## no error is returned
  117. cp) _ARG="${_ARG}" ;;
  118. rm) _ARG="${_ARG}" ;; ## add recursive option if you need
  119. mv) _ARG="${_ARG}" ;;
  120. mkdir) _ARG="${_ARG}" ;;
  121. log) _EXE="tail"; _ARG="${_ARG} ${_LOG}" ;;
  122. wget) _ARG="-q ${_ARG/ */} -O ${_ARG/* /}" ;; ## quiet
  123. *) errorCheck '1' "'$_EXE': bad command" ;;
  124. esac
  125. ## toggle globbing
  126. set +o noglob
  127. _OUT=$($_EXE $_ARG 2>&1)
  128. _ERR=$?
  129. ## toggle globbing
  130. set -o noglob
  131. logThis "$_EXE $_ARG"
  132. errorCheck $_ERR
  133. }
  134. ## handle html POST
  135. postHtml() {
  136. ## save POST to file
  137. _OUT=$( (printf '%b' "${_POST}" > "${_HTDOCS}${_REQUEST_URI}") 2>&1)
  138. _ERR=$?
  139. errorCheck $_ERR
  140. }
  141. ## octet POST dispatcher
  142. postOctet() {
  143. ## get 'data:' header length
  144. local IFS=','; read -d',' -r _DH < $_POST_TMP
  145. case "${_ENC}" in
  146. base64) postBase64Enc;;
  147. binary) postBinary ;;
  148. *) postGuessEnc ;; ## handle data POST
  149. esac
  150. }
  151. ## to be converted into a proper data-type detection function
  152. postGuessEnc() {
  153. shopt -s nocasematch
  154. local _DTP="^.*\;([[:alnum:]].+)$" ## data-type header pattern
  155. ## look for encoding in the data header
  156. [[ "${_DH}" =~ ${_DTP} ]] && _ENC="${BASH_REMATCH[1]}"
  157. logThis "'$_ENC:' encoding is the best guess";
  158. shopt -u nocasematch
  159. case "$_ENC" in
  160. base64) postBase64Enc ;;
  161. ## binary) _ERR=1 ;;
  162. ## json) _ERR=1 ;;
  163. ## quoted-printable) _ERR=1 ;;
  164. *) _ERR=1; _OUT="'${_ENC:='unknown'}' encoding, unknown POST failed";;
  165. esac
  166. errorCheck $_ERR
  167. }
  168. ## handle base64 post
  169. postBase64Enc() {
  170. logThis "'${_ENC}:' decoding stream"
  171. _DL=${#_DH} ## get data-header length
  172. [[ $_DL -lt 10 ]] && { _DL=23; _SKP=0; } || { let _DL+=1; _SKP=1; } ## '23' - what?!
  173. ## the line below seems to be the best solution for the time being
  174. ## dd 'ibs' and 'iflags' seem not to work on OpenWRT - investigate as it might be very useful
  175. _OUT=$( dd if=${_POST_TMP} bs=${_DL} skip=${_SKP} | base64 -d > "${_HTDOCS}${_REQUEST_URI}" 2>&1)
  176. _ERR=$?
  177. errorCheck $_ERR
  178. }
  179. postBinary() {
  180. logThis "'binary': decoding stream"
  181. ## it is unclear what will be necessary to do here
  182. _OUT=$( dd if="${_POST_TMP}" of="${_HTDOCS}${_REQUEST_URI}" 2>&1 )
  183. _ERR=$?
  184. errorCheck $_ERR
  185. }
  186. postMpart() {
  187. logThis "'multipart': decoding stream"
  188. local _BND=$(findPostOpt 'boundary')
  189. ## bash is binary unsafe and eats away precious lines
  190. ## thus using gawk
  191. function cutFile() {
  192. gawk -v "want=$1" -v "bnd=$_BND" '
  193. BEGIN { RS="\r\n"; ORS="\r\n" }
  194. # reset based on boundaries
  195. $0 == "--"bnd"" { st=1; next; }
  196. $0 == "--"bnd"--" { st=0; next; }
  197. $0 == "--"bnd"--\r" { st=0; next; }
  198. # search for wanted file
  199. st == 1 && $0 ~ "^Content-Disposition:.* name=\""want"\"" { st=2; next; }
  200. st == 1 && $0 == "" { st=9; next; }
  201. # wait for newline, then start printing
  202. st == 2 && $0 == "" { st=3; next; }
  203. st == 3 { print $0 }
  204. ' 2>&1
  205. }
  206. cutFile 'userimage' < "${_POST_TMP}" > "${_HTDOCS}${_REQUEST_URI}"
  207. _ERR=$?
  208. errorCheck $_ERR
  209. }
  210. ## find arbitrary option supplied in Content-Type header
  211. ## eg: "Content-Type:application/octet-stream; verbose=1"
  212. findPostOpt() {
  213. for i in "${CONTENT_TYPE[@]:1}"; do
  214. case "${i/=*}" in
  215. "$1") printf '%b' "${i/*=}" ;;
  216. esac
  217. done
  218. return 0
  219. }
  220. ## sanitize by backslashing all expandable symbols
  221. escapeStr() {
  222. printf "%q" "${*}"
  223. }
  224. ## brutally replace unwanted characters
  225. cleanFname() {
  226. shopt -s extglob
  227. local _STR="${*}"
  228. echo -n "${_STR//[^[:alnum:]._\-\/\\]/_}"
  229. shopt -u extglob
  230. }
  231. #### MAIN LOOP
  232. ## timing
  233. ## TODO: remove it
  234. ## run once here and once at the end
  235. read t z < /proc/uptime
  236. ## check if we are in $_HTDOCS directory
  237. cd $_HTDOCS || errorCheck $? 'htdocs unavailable'
  238. [[ ${PWD} == ${_HTDOCS} ]] || errorCheck $? 'htdocs misconfigured'
  239. [[ $CONTENT_LENGTH -gt 0 ]] || errorCheck $? 'content length zero'
  240. ## URI is considered as a file dest to work with
  241. ## add 'index.html' to default and empty request uri
  242. _REQUEST_URI="${REQUEST_URI/%\///index.html}"
  243. _REQUEST_URI="$(urlDecode $_REQUEST_URI)"
  244. _PATH="${_REQUEST_URI%/*}"
  245. CONTENT_TYPE=( ${CONTENT_TYPE} )
  246. _CONTENT_TYPE="${CONTENT_TYPE[0]/;}"
  247. _ENC="${HTTP_CONTENT_ENCODING}"
  248. #logThis "Len: $CONTENT_LENGTH Ctype: $CONTENT_TYPE Enc: $_CONTENT_ENCODING"
  249. ## check for 'verbose' option in POST
  250. findPostOpt 'verbose' || { _DEBUG=2; logThis 'verbose mode is requested'; }
  251. _POST_TMP=$(mktemp -p $_TMP) ## make tmp POST file
  252. cat > $_POST_TMP ## cautiously storing entire POST in a file
  253. ## dispatching POST
  254. case "${_CONTENT_TYPE}" in
  255. application\/x-www-form-urlencoded) postUrlenc ;;
  256. application\/octet-stream) postOctet ;;
  257. multipart/form-data) postMpart ;;
  258. *) _ERR=1; _OUT='this is not a post' ;;
  259. esac
  260. [[ -e $_POST_TMP ]] && rm -f $_POST_TMP
  261. ## make sure we are good
  262. errorCheck $_ERR
  263. [[ -z $_OUT ]] || _OUT="${_OUT}\n"
  264. headerPrint '200' ## on success
  265. printf '%b' "${_OUT}"
  266. logThis 'OK 200'
  267. read d z < /proc/uptime
  268. logThis $((${d/./}-${t/./}))"/100s"
  269. exit 0