# FHTTP Kit by Xianur0
# Copyright (C) 2011 Oscar García López (http://hackingtelevision.blogspot.com) 
#  
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#   
#    xianur0.null@gmail.com
#    http://hackingtelevision.blogspot.com/

package tools;

sub urlencode {
	my ($url) = @_;
	$url =~ s/([^\w\d])/sprintf("%%%02X", ord($1))/seg;
	return $url;
}

sub tohex {
	my ($texto) = @_;
	my $auxiliar;
	@Hex = unpack("H*", $texto);
	$hex = "@Hex\n";
	my $len = length($hex);
	my $start = 0;
	$auxiliar = "";
	while ($start < $len) {
		$auxiliar .= "%".substr($hex,$start,2);
		$start += 2;
	}
	$auxiliar =~ s/\%$//;
	$auxiliar =~ s/(\r|\n)//g;
	return $auxiliar;
}

sub realpath {
	$cadena = $_[0];
	my $parametros = "";
	if(($cadena =~ /^([^\?]+)\?(.*)$/)) {
		($cadena,$parametros) = ($1,$2);
	}
	my @paths = split(/\//,$cadena);
	my $contador = 0;
	my @pathsvalidos = ();
	my $retornosfaltantes = 0;
	foreach $path (@paths) {
		if($path ne "..") {
			if($path ne ""){
				push(@pathsvalidos,$path);
				$contador++;
			}
		} else {
			if($contador <= 0) {
				$retornosfaltantes++;
			} else {
				pop(@pathsvalidos);
			}
			$contador-- if($contador > 0);
		}
	}
	my $nurl = join('/',@pathsvalidos);
	$nurl = "/".$nurl if($nurl !~/^(\/|\?)/);
	$nurl .= $parametros;
	return ($nurl,$retornosfaltantes);
}

sub maketunnel {
	my ($servidor,$host,$puerto,$debug,$version) = @_;
	$version = 1 if($version eq "");
	die("No se especifico un socket valido!\n") if(!$servidor);
	my $payloadconexion = "CONNECT ".$host.":".$puerto." HTTP/1.".$version."\r\n".
	"Host: ".$host.(($puerto eq "80") ? (":".$puerto) : "")."\r\n\r\n";
	print $servidor $payloadconexion;
	print $payloadconexion if($debug > 1);
	my $conteol = 0;
	my $estatustunnel = <$servidor>;
	$estatustunnel =~ s/[\r\n]+//g;
	if($estatustunnel =~ /HTTP\/1\.(0|1) 200/){
		READPAYLOAD: while(my $lpayload = <$servidor>) {
			if($lpayload =~ /^[\r\n]*$/) {
				last READPAYLOAD;
			}
		}
		print "[-] Tunnel creado correctamente: ".$estatustunnel."\n" if($debug != 0);
		return 1;
	}
	close($servidor) if($servidor);
	if($estatustunnel =~ /404/) {
		return 2;
	}
	print "[x] No se puede crear el tunnel: ".$estatustunnel."!\n" if($debug != 0);
	return 0;
}

sub encodeuri {
	my $uri = tohex($_[0]);
	$uri =~ s/%25/%/ig;
	$uri =~ s/%2f/\//ig;
	$uri =~ s/%3f/?/ig;
	return $uri;
}

sub encodeparam {
	my $param = $_[0];
	$param =~ s/^(\r?\n)//g;
	my @parametro = split(/&/,$param);
	if($#parametro > 0){
		$param = "";
		foreach $parame (@parametro) {
			if($parame =~ /^([^=]+?)=(.*)$/) {
				($nombre, $valor) = ($1,$2);
			} else {
				$nombre = $param;
			}
			if($valor ne "") {
				$param .= join "",tohex(toascii($nombre)),"=",tohex(toascii($valor)),"&";
				}
			else {
				$param .= join "",tohex(toascii($nombre)),"&";
			}
		}
		$param =~ s/&$//g;
		$param =~ s/&=//g;
		$param =~ s/=&/&/g;
	}
	return $param;
}

sub leerrequest {
	my $socket = $_[0];
	my $concrlf = 0;
	my ($todo,$postdata) = ("","");
	BLOQUE: while(my $linea = <$socket>) {
		$todo .= $linea;
		if($linea =~ /^[\r\n]*$/) {
			last BLOQUE;
		}
	}
	my ($porleer) = ($todo =~ /\r?\nContent-Length:[\s\t]+(\d+)/i);
	sysread($socket,$postdata,$porleer);
	my %retorno = ();
	$retorno{"request"} = $todo;
	$retorno{"postdata"} = $postdata;
	return %retorno;
}

sub toascii {
	my $cadena = $_[0];
	$cadena =~ tr/+/ /;
	$cadena =~ s/%([a-fA-F0-9]{2,2})/chr(hex($1))/eg;
	return $cadena;
}


sub gunzip{
	return 0;
}

if(&main::mods("IO::Uncompress::Inflate") != 1){
	sub inflate{
		return 0;
	}
}

sub descomprimirgzip {
	my ($cadena) = @_;
	my $tmp2;
	print "Descomprimiendo Gzip...\n";
	use if(&main::mods("IO::Uncompress::Gunzip") == 1), IO::Uncompress::Gunzip=>qw(gunzip $GunzipError);
	gunzip \$cadena => \$tmp2 or return $cadena;
	print "Exitoso!\n";
	return $tmp2;
}
sub descomprimirdeflate {
	my ($cadena) = @_;
	my $tmp2;
	print "Descomprimiendo deflate...\n";
	use if(&main::mods("IO::Uncompress::Inflate") == 1), IO::Uncompress::Inflate=>qw(inflate $InflateError);
	inflate \$cadena => \$tmp2 or return $cadena;
	return $tmp2;
}

sub geturls {
	my ($html,$proto,$host,$path) = @_;
	my @propiedades = ($html =~ /<(a|img|iframe|script|link)\s+([^>]+)/g);
	my %urls;
	foreach $cadena (@propiedades) {
		if($cadena =~ /(href|src)\s*=\s*("|')/){
			my ($propiedad,$cstring) = ($1,$2);
			my $regex = "(href|src)\s*=\s*".$cstring."([^".$cstring."]+)".$cstring;
			my ($propiedad,$url) = ($cadena =~ /$regex/);
			my $parametros;
			if($url =~ /^([^\?]+)\?(.+)$/){
				($url,$parametros) = ($1,$2);
				$parametros = "?".$parametros;
			}
			if($url =~ /^\// && $proto ne "" && $host ne "") {
				($url,$faltantes) = realpath($url);
				$url = $proto."://".$host.$url;
			} elsif($url !~ /^(https?|ftp):\/\//) {
				my $part;
				if($url =~ /(#.*)/) {
					$part = $1;
					$url =~ s/#.*//;
				}
				$url =~ s/\/\.?\//\//g;
				my (@dirs) = split(/\//,$path);
				my $ndirs = 0;
				foreach $dir (@dirs) {
					$ndirs++ if($dir ne "");
				}
				my ($tproto,$thost) = ($url =~ /^https?:\/\/([^\/]+)/);
				if($ndirs < 0 || $url !~ /\/\.\.\//) {
					my $nrpath = $path.$url;
					$nrpath =~ s/\/\//\//g;
					$url = (($proto ne "" && $host ne "") ? ($proto."://".$host) : "").$nrpath.$part;
				} else {
					my ($rpath,$rfaltantes) = realpath($url);
					if($rfaltantes == 0) {
						my $nrpath = $path.$rpath;
						$nrpath =~ s/\/\//\//g;
						$url = (($proto ne "" && $host ne "") ? ($proto."://".$host) : "").$nrpath.$part;
					} else {
						if($rfaltantes >= $ndirs) {
							$url = (($proto ne "" && $host ne "") ? $proto."://".$host : "").$rpath.$part;
						} else {
							my $i = 0;
							VUELTAS: for(;$i<$rfaltantes;$i++) {
								if($dirs[$i] ne "") {
									pop(@dirs);
									$ndirs--;
									last VUELTAS if($ndirs == 0);
								} else {
									$rfaltantes++;
								}
							}
							my $npath = join('/',@dirs);
							$npath = "/".$npath if($npath !~ /^\//);
							my $nrpath = $npath.$rpath;
							$nrpath =~ s/\/\///g;
							$url = (($proto ne "" && $host ne "") ? $proto."://".$host : "").$nrpath.$part;
						}
					}
				}
			}
			$url .= $parametros;
			if($urls{$url} <= 0){
				$urls{$url}++;
			}
		}
	}
	return %urls;
}

sub cookies {
	my ($tmpcookie,%acookies) = @_;
	$tmpcookies =~ s/^[\n\s\r]+//g;
	return if($tmpcookie eq "");
	my @cookies = split(/\r?\n/,$tmpcookie);
	foreach $cookie (@cookies) {
		$cookie =~ s/^\s*([^;]+);(.+)$/$1/;
		my ($cookiename,$cookieval) = ($cookie =~ /^([^=]+)=(.+)$/);
		$acookies{$cookiename} = $cookieval;
	}
	return %acookies;
}

sub getcookies {
	my %acookies = shift;
	my $retorno = "";
	while(($nombre, $valor) = each(%acookies)){
		$retorno .= $nombre."=".$valor."; ";
	}
	$retorno =~ s/;\s+$//g;
	return $retorno;
}

sub parseurl {
	my $url = $_[0];
	my ($proto,$host,$path) = ($url =~ /^(https?):\/\/([^\/]+)(.*)/);
	my $hostheader = $host;
	my $puerto = ($proto eq "http") ? 80 : 443;
	$path =~ s/\/\//\//g;
	$path = "/".$path if($path eq "" || $path !~ /^\//);
	if($host =~ /^([^:]+):(\d+)$/) {
		$host = $1;
		$puerto = $2;
	}
	elsif($puerto eq 443 && $proto eq "https") {
		$host = $host.":https";
	}
	$path =~s/#.*//;
	return ($proto,$host,$hostheader,$path,$puerto);
}

sub dechunk {
	my ($html) = @_;
	$html =~ s/((\r\n)*)$//;
	$html =~ s/^((\r\n)*)//;
	my $size = 1;
	my $sizehex = 0;
	my $salida = "";
	INFINITO: while(1) {
		if($html =~ /^([0-9A-Fa-f]+)/) {
			$sizehex = $1;
		} else {
			print "Error de de-chunk!\n";
			last INFINITO;
		}
		if(hex($sizehex) == 0 || length($html) == 0) {
			last INFINITO;
		}
		$html = substr($html,length($sizehex));
		$html =~ s/^(\r?\n)+//;
		$salida .= substr($html,0,hex($sizehex));
		$html = substr($html,hex($sizehex));
		$html =~ s/^(\r?\n)+//;
	}
	return $salida;
}

sub dateparser {
	my $date = $_[0];
	$date =~ s/^\s+//;
	my ($dia,$mes,$anio,$hora) = ($date =~ /^\w+,\s+(\d+)\s+(\w+)\s+(\d+)\s+([^\s]+)\s+\w+$/);
	my ($horas,$minutos,$segundos) = split(/:/,$hora);
	$segt1 = ($horas * 60)*60;
	$segt1 += $minutos * 60;
	$segt1 += $segundos;
	return ($dia,$mes,$anio,$hora,$horas,$minutos,$segundos,$segt1);
}

1;
