#!/usr/bin/perl -w
# tristan+perl@ethereal.net 21jan2006
#
# strips everything up to and including first \r\n\r\n from file(s);
# useful in conjunction with tcpflow for capturing raw binary streams
# from HTTP request/response bodies

use strict;
use IO::File;
use File::Temp;

my $bufsize = 4096;

while (my $file = shift @ARGV) {
  my $in = IO::File->new($file, O_RDONLY) || die;

  $file =~ m|.*/|;
  my $out = File::Temp->new(TEMPLATE => ".$0.XXXXX",
                            DIR => (defined $& ? $& : '.')) || die;

  my $seenhead = 0;
  my $buf = '';

  while ($in->read($buf, $bufsize, length $buf)) {
    if ($seenhead) {
      $out->write($buf) || die;
      $buf = '';
    } elsif ($buf =~ s/\r\n\r\n//) {
      print "$file: byte 0 to " .
            ($in->tell - length($buf) + length($`)) . " stripped\n";
      $seenhead = 1;
      $out->write($') || die;
      $buf = '';
    } else {
      $buf =~ /([\r\n]+)$/;
      $buf = $1;
    }
  }

  if ($seenhead) {
    rename($out, $file) || die;
    $out->unlink_on_destroy(0);
  } else {
    warn "$file: no header found\n";
  }
}
