Wanna see this logo while booting your 2.6 kernel? Click here!

25.04.2006 14:29

Uploading binary files in bash cgi script


Today I fixed the issue with my thinclients were I was unable to upload binary files (e.g. tar.gz) to my thinclient installation.

It's not very beautiful, but it works (I'm open for better solutions, so please send me e-mail if you know about a better solution to do this).
if [ "$REQUEST_METHOD" = "POST" ]; then
  TMPOUT=/tmp/fwupdate
  cat >$TMPOUT

  # Get the line count
  LINES=$(wc -l $TMPOUT | cut -d ' ' -f 1)

  # Remove the first four lines
  tail -$((LINES - 4)) $TMPOUT >$TMPOUT.1

  # Remove the last line
  head -$((LINES - 5)) $TMPOUT.1 >$TMPOUT

  # Copy everything but the new last line to a temporary file
  head -$((LINES - 6)) $TMPOUT >$TMPOUT.1

  # Copy the new last line but remove trailing \r\n
  tail -1 $TMPOUT | perl -p -i -e 's/\r\n$//' >>$TMPOUT.1
fi


This is necessary, because busybox's webserver (and maybe all others too) write four lines of content information at the beginning of the generated file and one line at the end as well as making a new line in the last line of the binary file causes the end of the last line to contain "\r\n" which is also subject to strip.

In my testings, I tried ten different binary files and always got the same md5sums after uploading, which means that this little shell script is likely to work.