From Capacious Elephant, 1 Year ago, written in Lua.
Embed
  1. local multipart_string_beginning = 'multipart/form-data; boundary='
  2.  
  3. local function log(str)
  4.   ngx.log(ngx.STDERR, str)
  5. end
  6.  
  7. local function starts_with(str, start)
  8.   return str:sub(1, #start) == start
  9. end
  10.  
  11. local function ends_with(str, ending)
  12.   return ending == "" or str:sub(-#ending) == ending
  13. end
  14.  
  15. local function extract_boundary(str)
  16.   return str:sub(#multipart_string_beginning + 1)
  17. end
  18.  
  19. ngx.req.read_body()
  20. local body = ngx.req.get_body_data()
  21. if not body then
  22.   ngx.var.request_body_md5 = 'empty'
  23.   log('empty body')
  24.   return
  25. end
  26. local content_type = ngx.req.get_headers()['Content-Type']
  27. if not starts_with(content_type, multipart_string_beginning) then
  28.   ngx.var.request_body_md5 = ngx.now() + math.random()
  29.   log('wrong content type: ' .. content_type)
  30.   return
  31. end
  32. local boundary = extract_boundary(content_type)
  33. local boundary_start = '--' .. boundary .. '\r\n'
  34. local boundary_end = '\r\n' .. '--' .. boundary .. '--'
  35. local boundary_start_find = body:find(boundary_start)
  36. local boundary_end_find = body:find(boundary_end)
  37. if not boundary_start_find == 1 or boundary_end_find < (#body - (#boundary_end + 2)) then
  38.   ngx.var.request_body_md5 = ngx.md5(body)
  39.   log('boundary not found in body')
  40.   return
  41. end
  42. body = body:sub(#boundary_start + boundary_start_find, boundary_end_find)
  43. ngx.var.request_body_md5 = ngx.md5(body)
  44. log('md5sum: ' .. ngx.var.request_body_md5)