pproxy - прокси на PHP

Discussion in 'Избранное' started by bons, 24 Nov 2008.

  1. HIVER

    HIVER Member

    Joined:
    28 Oct 2008
    Messages:
    36
    Likes Received:
    18
    Reputations:
    0
    Чего-то в нем нехватало, на мой взгляд, добавил нормальные цепочки и ротатор с файла:)

    Серверная часть.
    Code:
    <?php
    
    //$secret = 'secret';
    
    if (isset($_POST["transfer"]) && $_POST["transfer"] != "")
    	{
    	if(isset($secret) && ($_POST['secret'] != $secret))exit;
    	$transfer_hosts = explode("::", base64_decode($_POST["transfer"]));
    	$next_host = array_shift($transfer_hosts);
    	$postfields = array(
    						"query" => $_POST['query'],
    						"host" => $_POST['host'],
    						"secret" => $_POST['secret']
    						);
    	if ($transfer_hosts[0] != "") $postfields["transfer"] = base64_encode(implode("::", $transfer_hosts));
    	$ch = curl_init($next_host);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_POST, 1);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
    	curl_setopt($ch, CURLOPT_HEADER, 0);
    	$result = curl_exec($ch);
    	curl_close($ch);
    	echo $result;
    	} else {
    	if(isset($_POST['query']) && isset($_POST['host']))
    		{
    		if(isset($secret) && ($_POST['secret'] != $secret))exit;
    		header('Content-type: application/octet-stream');
    		@set_time_limit(0);
    		$query = base64_decode(str_replace(" ", "+", $_POST['query']));
    		list($host, $port) = explode(':', base64_decode(str_replace(" ", "+", $_POST['host'])));
    		if(!$port)$port = 80;
    		$ip = gethostbyname($host);
    		if($fp = @fsockopen($ip, $port, $errno, $errstr, 20))
    			{
    			fwrite($fp, $query);        
    			while(!feof($fp))
    				{
    				$answer = fread($fp, 1024);
    				echo $answer;
    				}
    			fclose($fp);
    			}
    		exit;
    		}
    	}
    ?> 
    
    

    Локальная часть с генерацией рандомно распределенной цепочки:
    Code:
    use HTTP::Daemon;
    use MIME::Base64 ();
    use Getopt::Long;
    use POSIX ":sys_wait_h";
    use strict;
    
    my $user_agent = 'Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4';
    
    my $errheader = "HTTP/1.1 200 OK\x0D\x0AContent-Type: text/plain\x0D\x0A\x0D\x0A";
    my $errmsg1 = $errheader . 'Could not connect to server';
    my $errmsg2 = $errheader . 'Could not connect to pproxy';
    
    my ($pproxyhost, $pproxyport, $pproxyurl);
    my ($tunnelhost, $tunnelport);
    my ($pproxy, $pproxyfile, @pproxylist, $bindport, $tunnel, $secret);
    my ($destaddr, $destport, $desturl);
    
    #Вывод справки
    Usage() if @ARGV==0;
    
    #Задание опций
    GetOptions(
             "px=s"		=> \$pproxy,
             "bp=s" 	=> \$bindport,
             "tpx=s"	=> \$tunnel,
             "pwd=s"	=> \$secret,
    		 "pf=s"		=> \$pproxyfile
         );
    die "need pproxy.php url or pproxy.php url filelist" unless $pproxy || $pproxyfile;
    
    
    #Получение параметров
    $pproxyfile =~ /(.+)/;
    
    if ($pproxyfile) 
    	{
    	open(file, "proxies.txt");
    	@pproxylist = <file>;
    	} else {
    	$pproxy =~ /http:\/\/([\w\.\-]+)(:\d*)?\/(.+)/;
    	$pproxyhost = $1; $pproxyport = substr($2, 1); $pproxyurl = '/' . $3;
    	}
    
    defined($pproxyport) || ($pproxyport = 80);
    defined($bindport) || ($bindport = 8008);
    
    if(defined($tunnel))
    {
    	$tunnel =~ /http:\/\/([\w\.\-]+):(\d*)?/;
    	$tunnelhost = $1; $tunnelport = $2;
    
    	$destaddr = $tunnelhost;
    	$destport = $tunnelport;
    	$desturl = $pproxy;
    
    	print "# tunnelhost = $tunnelhost\n";
    	print "# tunnelport = $tunnelport\n";
    }else{
    	if (!$pproxyfile)
    		{
    		$destaddr = $pproxyhost;
    		$desturl = $pproxyurl;
    		}
    		$destport = $pproxyport;
    }
    
    if (!$pproxyfile)
    	{
    	print "# pproxyhost = $pproxyhost\n";
    	print "# pproxyport = $pproxyport\n";
    	print "# pproxyurl = $pproxyurl\n";
    	} else {
    	print "# pproxyfile = $pproxyfile\n";
    	}
    	
    print "# bindport = $bindport\n\n";
    
    $|=1;
    my %children;
    my $slave;
    
    #Прием подключений
    my $master = HTTP::Daemon->new(	LocalPort => $bindport,
    				LocalAddr => 'localhost', 
    				Reuse=>1)
    || die "Can't start server ($@)";
    &MainProc($slave) while $slave = $master->accept;
    
    sub MainProc
    {
    		my $conn = shift;
    
    		#Прием HTTP-запроса
    		my $request = $conn->get_request();
    		
    		#Ответвление процесса(потока)
    		my $pid = fork();
    		unless(defined($pid))
    		{
    			print "# Erorr couldn't fork\n";
    			close $conn;
    			return;
    		}
    
    		if($pid)
    		{
    			close $conn;
    			$children{$pid}++;
    			foreach(keys %children )
    			{
    				my $kid = waitpid($_, &WNOHANG);
    				delete $children{$_} if($kid == -1 || $kid == $_);
    			}
    			return;
    		}
    
    		#Преобразование HTTP заголовка
    		$request -> remove_header('Proxy-Connection');
    		$request -> remove_header('Keep-Alive');
    		$request -> header(Connection=>'close');
    		my $host = $request -> header('Host');
    		my $http = $request -> as_string();
    		my $head_end = index ($http, "\x0A\x0A") + 2;
    		my $head = substr ($http, 0, $head_end);
    		my $post = substr ($http, $head_end);
    		$head =~ s/\x0A/\x0D\x0A/g;
    		$http = $head . $post;
    		$http =~ s/http:\/\/$host//;
    		my $time_start = time;
    		
    		#Отправка запроса прокси и прием результата
    		my $lastaddr = SendToPProxy(	MIME::Base64::encode($host),
    				MIME::Base64::encode($http),
    				$conn
    					);
    
    		my $time_end = time;
    		
    		#Лог
    		print &TranslateTimeHour($time_end), "   ", $host, " <- ", $lastaddr,
    			" (", &TranslateTime($time_end - $time_start),
    			")\n";
    
    		close $conn;
    		exit;
    }
    
    sub SendToPProxy
    {
    	my $dest_host = shift;
    	my $query_content = shift;
    	my $clientsock = shift;
    	my (@destaddr, $desturl, $proxytransfer, $desthost);
    	
    	if ($pproxyfile)
    		{
    		
    		my @pproxylist_shuffled = @pproxylist;
    		shuffle(\@pproxylist_shuffled);
    		chomp(@pproxylist_shuffled);
    		my $desthost = shift(@pproxylist_shuffled);
    		my @destaddr = split("//", $desthost);
    		my @destaddrhost = (@destaddr[0] != "http:") ? split("/", @destaddr[0]) : split("/", @destaddr[1]);
    		$destaddr = shift(@destaddrhost);
    		$proxytransfer = MIME::Base64::encode(join("::", @pproxylist_shuffled));
    		$desturl = $desthost;
    		}
    		
    	my $proxysock = IO::Socket::INET->new(Proto=>'tcp',PeerAddr=>$destaddr,PeerPort=>$destport);
    
    	unless($proxysock)
    		{
    		syswrite($clientsock, $errmsg2, length($errmsg2));
    		return; 
    		}
    	
    	my $post_query;
    	#print "[!] <= $destaddr\n";
    	$post_query = 'secret=' . $secret . '&' if defined($secret);
    	$post_query .= 'transfer=' . $proxytransfer . '&' if defined($pproxyfile);
    	$post_query .= 'host=' . $dest_host . '&query=' . $query_content;
    	
    	my $postlen = length($post_query);
    
    	my $request = "POST $desturl HTTP/1.0\x0D\x0A".
    			"Host: $pproxyhost:$pproxyport\x0D\x0A".
    			"Accept: */*\x0D\x0A".
    			"Content-Type: application/x-www-form-urlencoded\x0D\x0A".
    			"Content-Length: $postlen\x0D\x0A".
    			"User-Agent: $user_agent\x0D\x0A".
    			"Connection: close\x0D\x0A\x0D\x0A" . $post_query;
    	
    	syswrite($proxysock, $request, length($request));
    	my ($result, $buffer, $response);
    	my $contentstart = -1;
    	my $count = 0;
    	while(1)
    	{
    		$result = sysread($proxysock, $buffer, 1024);
    		last if !defined($result) || !$result;
    
    		if($contentstart == -1)
    		{
    			$response .= $buffer;
    			last if length($response)>65535;
    			$contentstart = index($response,"\x0D\x0A\x0D\x0A");
    			next if $contentstart == -1;
    			$buffer = substr($response, $contentstart+4);
    		}
    		$count += length($buffer);
    		syswrite($clientsock, $buffer, length($buffer));
    	}
    	syswrite($clientsock, $errmsg1, length($errmsg1)) if $count == 0;
    	close $proxysock;
    	return $destaddr;
    }
    
    sub TranslateTime
    {
    	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(shift);
    	return sprintf "%02u:%02u", $min, $sec;
    }
    
    sub TranslateTimeHour
    {
    	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(shift);
    	return sprintf "%02u:%02u:%02u", $hour, $min, $sec;
    }
    
    sub shuffle
    	{
        my $deck = shift;    # $deck — ссылка на массив
        my $i = @$deck;
        while (--$i) {
            my $j = int rand ($i+1);
            @$deck[$i,$j] = @$deck[$j,$i];
            }
    	}
    
    sub Usage
    {
    	print "Usage: $0 -px proxy_url [-bp bindport] [-tpx tunnel_proxy] [-pwd secret] [-pf proxy filelist]\n";
    	print "Example: $0 -px http://site.com/proxy/proxy.php -bp 8080\n";
    	print "         $0 -px http://site.com/proxy/proxy.php -pwd pproxypass\n";
    	print "         $0 -px http://site.com/proxy/proxy.php -tpx http://localhost:8118\n";
    	print "         $0 -pf proxies.txt -bp 8080 -pwd pproxypass\n";
    	print "\nDefault bind port - 8008\n";
    	exit;
    }
    
    Либо с рандомной ротацией:
    Code:
    use HTTP::Daemon;
    use MIME::Base64 ();
    use Getopt::Long;
    use POSIX ":sys_wait_h";
    use strict;
    
    my $user_agent = 'Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4';
    
    my $errheader = "HTTP/1.1 200 OK\x0D\x0AContent-Type: text/plain\x0D\x0A\x0D\x0A";
    my $errmsg1 = $errheader . 'Could not connect to server';
    my $errmsg2 = $errheader . 'Could not connect to pproxy';
    
    my ($pproxyhost, $pproxyport, $pproxyurl);
    my ($tunnelhost, $tunnelport);
    my ($pproxy, $pproxyfile, @pproxylist, $bindport, $tunnel, $secret);
    my ($destaddr, $destport, $desturl);
    
    #Вывод справки
    Usage() if @ARGV==0;
    
    #Задание опций
    GetOptions(
             "px=s"		=> \$pproxy,
             "bp=s" 	=> \$bindport,
             "tpx=s"	=> \$tunnel,
             "pwd=s"	=> \$secret,
    		 "pf=s"		=> \$pproxyfile
         );
    die "need pproxy.php url or pproxy.php url filelist" unless $pproxy || $pproxyfile;
    
    
    #Получение параметров
    $pproxyfile =~ /(.+)/;
    
    if ($pproxyfile) 
    	{
    	open(file, "proxies.txt");
    	@pproxylist = <file>;
    	} else {
    	$pproxy =~ /http:\/\/([\w\.\-]+)(:\d*)?\/(.+)/;
    	$pproxyhost = $1; $pproxyport = substr($2, 1); $pproxyurl = '/' . $3;
    	}
    
    defined($pproxyport) || ($pproxyport = 80);
    defined($bindport) || ($bindport = 8008);
    
    if(defined($tunnel))
    {
    	$tunnel =~ /http:\/\/([\w\.\-]+):(\d*)?/;
    	$tunnelhost = $1; $tunnelport = $2;
    
    	$destaddr = $tunnelhost;
    	$destport = $tunnelport;
    	$desturl = $pproxy;
    
    	print "# tunnelhost = $tunnelhost\n";
    	print "# tunnelport = $tunnelport\n";
    }else{
    	if (!$pproxyfile)
    		{
    		$destaddr = $pproxyhost;
    		$desturl = $pproxyurl;
    		}
    		$destport = $pproxyport;
    }
    
    if (!$pproxyfile)
    	{
    	print "# pproxyhost = $pproxyhost\n";
    	print "# pproxyport = $pproxyport\n";
    	print "# pproxyurl = $pproxyurl\n";
    	} else {
    	print "# pproxyfile = $pproxyfile\n";
    	}
    	
    print "# bindport = $bindport\n\n";
    
    $|=1;
    my %children;
    my $slave;
    
    #Прием подключений
    my $master = HTTP::Daemon->new(	LocalPort => $bindport,
    				LocalAddr => 'localhost', 
    				Reuse=>1)
    || die "Can't start server ($@)";
    &MainProc($slave) while $slave = $master->accept;
    
    sub MainProc
    {
    		my $conn = shift;
    
    		#Прием HTTP-запроса
    		my $request = $conn->get_request();
    		
    		#Ответвление процесса(потока)
    		my $pid = fork();
    		unless(defined($pid))
    		{
    			print "# Erorr couldn't fork\n";
    			close $conn;
    			return;
    		}
    
    		if($pid)
    		{
    			close $conn;
    			$children{$pid}++;
    			foreach(keys %children )
    			{
    				my $kid = waitpid($_, &WNOHANG);
    				delete $children{$_} if($kid == -1 || $kid == $_);
    			}
    			return;
    		}
    
    		#Преобразование HTTP заголовка
    		$request -> remove_header('Proxy-Connection');
    		$request -> remove_header('Keep-Alive');
    		$request -> header(Connection=>'close');
    		my $host = $request -> header('Host');
    		my $http = $request -> as_string();
    		my $head_end = index ($http, "\x0A\x0A") + 2;
    		my $head = substr ($http, 0, $head_end);
    		my $post = substr ($http, $head_end);
    		$head =~ s/\x0A/\x0D\x0A/g;
    		$http = $head . $post;
    		$http =~ s/http:\/\/$host//;
    		my $time_start = time;
    		
    		#Отправка запроса прокси и прием результата
    		my $lastaddr = SendToPProxy(	MIME::Base64::encode($host),
    				MIME::Base64::encode($http),
    				$conn
    					);
    
    		my $time_end = time;
    		
    		#Лог
    		print &TranslateTimeHour($time_end), "   ", $host, " <- ", $lastaddr,
    			" (", &TranslateTime($time_end - $time_start),
    			")\n";
    
    		close $conn;
    		exit;
    }
    
    sub SendToPProxy
    {
    	my $dest_host = shift;
    	my $query_content = shift;
    	my $clientsock = shift;
    	my (@destaddr, $desturl, $proxytransfer, $desthost);
    	
    	if ($pproxyfile)
    		{
    		
    		my @pproxylist_shuffled = @pproxylist;
    		shuffle(\@pproxylist_shuffled);
    		chomp(@pproxylist_shuffled);
    		my $desthost = shift(@pproxylist_shuffled);
    		my @destaddr = split("//", $desthost);
    		my @destaddrhost = (@destaddr[0] != "http:") ? split("/", @destaddr[0]) : split("/", @destaddr[1]);
    		$destaddr = shift(@destaddrhost);
    		$proxytransfer = MIME::Base64::encode(join("::", @pproxylist_shuffled));
    		$desturl = $desthost;
    		}
    		
    	my $proxysock = IO::Socket::INET->new(Proto=>'tcp',PeerAddr=>$destaddr,PeerPort=>$destport);
    
    	unless($proxysock)
    		{
    		syswrite($clientsock, $errmsg2, length($errmsg2));
    		return; 
    		}
    	
    	my $post_query;
    	#print "[!] <= $destaddr\n";
    	$post_query = 'secret=' . $secret . '&' if defined($secret);
    	#$post_query .= 'transfer=' . $proxytransfer . '&' if defined($pproxyfile);
    	$post_query .= 'host=' . $dest_host . '&query=' . $query_content;
    	
    	my $postlen = length($post_query);
    
    	my $request = "POST $desturl HTTP/1.0\x0D\x0A".
    			"Host: $pproxyhost:$pproxyport\x0D\x0A".
    			"Accept: */*\x0D\x0A".
    			"Content-Type: application/x-www-form-urlencoded\x0D\x0A".
    			"Content-Length: $postlen\x0D\x0A".
    			"User-Agent: $user_agent\x0D\x0A".
    			"Connection: close\x0D\x0A\x0D\x0A" . $post_query;
    	
    	syswrite($proxysock, $request, length($request));
    	my ($result, $buffer, $response);
    	my $contentstart = -1;
    	my $count = 0;
    	while(1)
    	{
    		$result = sysread($proxysock, $buffer, 1024);
    		last if !defined($result) || !$result;
    
    		if($contentstart == -1)
    		{
    			$response .= $buffer;
    			last if length($response)>65535;
    			$contentstart = index($response,"\x0D\x0A\x0D\x0A");
    			next if $contentstart == -1;
    			$buffer = substr($response, $contentstart+4);
    		}
    		$count += length($buffer);
    		syswrite($clientsock, $buffer, length($buffer));
    	}
    	syswrite($clientsock, $errmsg1, length($errmsg1)) if $count == 0;
    	close $proxysock;
    	return $destaddr;
    }
    
    sub TranslateTime
    {
    	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(shift);
    	return sprintf "%02u:%02u", $min, $sec;
    }
    
    sub TranslateTimeHour
    {
    	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(shift);
    	return sprintf "%02u:%02u:%02u", $hour, $min, $sec;
    }
    
    sub shuffle
    	{
        my $deck = shift;    # $deck — ссылка на массив
        my $i = @$deck;
        while (--$i) {
            my $j = int rand ($i+1);
            @$deck[$i,$j] = @$deck[$j,$i];
            }
    	}
    
    sub Usage
    {
    	print "Usage: $0 -px proxy_url [-bp bindport] [-tpx tunnel_proxy] [-pwd secret] [-pf proxy filelist]\n";
    	print "Example: $0 -px http://site.com/proxy/proxy.php -bp 8080\n";
    	print "         $0 -px http://site.com/proxy/proxy.php -pwd pproxypass\n";
    	print "         $0 -px http://site.com/proxy/proxy.php -tpx http://localhost:8118\n";
    	print "         $0 -pf proxies.txt -bp 8080 -pwd pproxypass\n";
    	print "\nDefault bind port - 8008\n";
    	exit;
    }
    
     
  2. Phoenixy

    Phoenixy Member

    Joined:
    28 Mar 2009
    Messages:
    0
    Likes Received:
    13
    Reputations:
    0
    а вот например когда я пользуюсь wi-fi и ммне нужно другой ип поставить как сделать
     
    1 person likes this.
  3. djekxa

    djekxa Member

    Joined:
    20 Nov 2008
    Messages:
    0
    Likes Received:
    40
    Reputations:
    7
    юзать виртуалку либо дед
     
    6 people like this.
  4. bons

    bons Elder - Старейшина

    Joined:
    20 Dec 2007
    Messages:
    286
    Likes Received:
    121
    Reputations:
    21
    по поводу сокс-версии, думаю без помощи я не справлюсь. Недоработанная версия здесь: http://forum.antichat.ru/showthread.php?p=1214063
    Большая просьба всем кто имеет знания в этой области посмотреть и исправить ошибки
     
    1 person likes this.
  5. InFlame

    InFlame Banned

    Joined:
    27 Oct 2008
    Messages:
    207
    Likes Received:
    31
    Reputations:
    0
    C Socks-версией всё понятно, а поддержка HTTPS когда-нибудь будет?
     
    1 person likes this.
  6. Ty3uK

    Ty3uK Member

    Joined:
    1 Feb 2009
    Messages:
    35
    Likes Received:
    28
    Reputations:
    0
    Написал пару строчек кода к клиенту... Теперь работает строка для юзверь агента...

    plocal.pl
    Code:
    use HTTP::Daemon;
    use MIME::Base64 ();
    use Getopt::Long;
    use POSIX ":sys_wait_h";
    use strict;
    
    my $user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4';
    
    my $errheader = "HTTP/1.1 200 OK\x0D\x0AContent-Type: text/plain\x0D\x0A\x0D\x0A";
    my $errmsg1 = $errheader . 'Could not connect to server';
    my $errmsg2 = $errheader . 'Could not connect to pproxy';
    
    my ($pproxyhost, $pproxyport, $pproxyurl);
    my ($tunnelhost, $tunnelport);
    my ($pproxy, $bindport, $tunnel, $secret);
    my ($destaddr, $destport, $desturl);
    
    #Вывод справки
    Usage() if @ARGV==0;
    
    #Задание опций
    GetOptions(
             "px=s"		=> \$pproxy,
             "bp=s" 	=> \$bindport,
             "tpx=s"	=> \$tunnel,
             "pwd=s"	=> \$secret
         );
    die "need pproxy.php url" unless $pproxy;
    
    
    #Получение параметров
    $pproxy =~ /http:\/\/([\w\.\-]+)(:\d*)?\/(.+)/;
    $pproxyhost = $1; $pproxyport = substr($2, 1); $pproxyurl = '/' . $3;
    
    defined($pproxyport) || ($pproxyport = 80);
    defined($bindport) || ($bindport = 8008);
    
    if(defined($tunnel))
    {
    	$tunnel =~ /http:\/\/([\w\.\-]+):(\d*)?/;
    	$tunnelhost = $1; $tunnelport = $2;
    
    	$destaddr = $tunnelhost;
    	$destport = $tunnelport;
    	$desturl = $pproxy;
    
    	print "# tunnelhost = $tunnelhost\n";
    	print "# tunnelport = $tunnelport\n";
    }else{
    	$destaddr = $pproxyhost;
    	$destport = $pproxyport;
    	$desturl = $pproxyurl;
    }
    
    print "# pproxyhost = $pproxyhost\n";
    print "# pproxyport = $pproxyport\n";
    print "# pproxyurl = $pproxyurl\n";
    print "# bindport = $bindport\n\n";
    
    $|=1;
    my %children;
    my $slave;
    
    #Прием подключений
    my $master = HTTP::Daemon->new(	LocalPort => $bindport,
    				LocalAddr => 'localhost', 
    				Reuse=>1)
    || die "Can't start server ($@)";
    &MainProc($slave) while $slave = $master->accept;
    
    sub MainProc
    {
    		my $conn = shift;
    
    		#Прием HTTP-запроса
    		my $request = $conn->get_request();
    		
    		#Ответвление процесса(потока)
    		my $pid = fork();
    		unless(defined($pid))
    		{
    			print "# Erorr couldn't fork\n";
    			close $conn;
    			return;
    		}
    
    		if($pid)
    		{
    			close $conn;
    			$children{$pid}++;
    			foreach(keys %children )
    			{
    				my $kid = waitpid($_, &WNOHANG);
    				delete $children{$_} if($kid == -1 || $kid == $_);
    			}
    			return;
    		}
    
    		#Преобразование HTTP заголовка
    		$request -> remove_header('Proxy-Connection');
    		$request -> remove_header('Keep-Alive');
    		$request -> header(Connection=>'close');
    		$request -> remove_header('User-Agent');
    		$request -> header('User-Agent'=>$user_agent);
    		my $host = $request -> header('Host');
    		my $http = $request -> as_string();
    		my $head_end = index ($http, "\x0A\x0A") + 2;
    		my $head = substr ($http, 0, $head_end);
    		my $post = substr ($http, $head_end);
    		$head =~ s/\x0A/\x0D\x0A/g;
    		$http = $head . $post;
    		$http =~ s/http:\/\/$host//;
    		my $time_start = time;
    		
    		#Отправка запроса прокси и прием результата
    		SendToPProxy(	MIME::Base64::encode($host),
    				MIME::Base64::encode($http),
    				$conn
    					);
    
    		my $time_end = time;
    		
    		#Лог
    		print &TranslateTimeHour($time_end), "   ", $host,
    			" (", &TranslateTime($time_end - $time_start),
    			")\n";
    
    		close $conn;
    		exit;
    }
    
    sub SendToPProxy
    {
    	my $dest_host = shift;
    	my $query_content = shift;
    	my $clientsock = shift;
    	
    	my $proxysock = IO::Socket::INET->new(Proto=>'tcp',PeerAddr=>$destaddr,PeerPort=>$destport);
    	unless($proxysock)
    	{
    		syswrite($clientsock, $errmsg2, length($errmsg2));
    		return; 
    	}
    	
    	my $post_query;
    	$post_query = 'secret=' . $secret . '&' if defined($secret);
    	$post_query .= 'host=' . $dest_host . '&query=' . $query_content;
    	my $postlen = length($post_query);
    
    	my $request = "POST $desturl HTTP/1.1\x0D\x0A".
    			"Host: $pproxyhost:$pproxyport\x0D\x0A".
    			"Accept: */*\x0D\x0A".
    			"Content-Type: application/x-www-form-urlencoded\x0D\x0A".
    			"Content-Length: $postlen\x0D\x0A".
    			"User-Agent: $user_agent\x0D\x0A".
    			"Connection: close\x0D\x0A\x0D\x0A" . $post_query;
    
    	syswrite($proxysock, $request, length($request));
    	my ($result, $buffer, $response);
    	my $contentstart = -1;
    	my $count = 0;
    	while(1)
    	{
    		$result = sysread($proxysock, $buffer, 1024);
    		last if !defined($result) || !$result;
    
    		if($contentstart == -1)
    		{
    			$response .= $buffer;
    			last if length($response)>65535;
    			$contentstart = index($response,"\x0D\x0A\x0D\x0A");
    			next if $contentstart == -1;
    			$buffer = substr($response, $contentstart+4);
    		}
    		$count += length($buffer);
    		syswrite($clientsock, $buffer, length($buffer));
    	}
    	syswrite($clientsock, $errmsg1, length($errmsg1)) if $count == 0;
    	close $proxysock;
    }
    
    sub TranslateTime
    {
    	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(shift);
    	return sprintf "%02u:%02u", $min, $sec;
    }
    
    sub TranslateTimeHour
    {
    	my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(shift);
    	return sprintf "%02u:%02u:%02u", $hour, $min, $sec;
    }
    
    sub Usage
    {
    	print "Usage: $0 -px proxy_url [-bp bindport] [-tpx tunnel_proxy] [-pwd secret]\n";
    	print "Example: $0 -px http://site.com/proxy/proxy.php -bp 8080\n";
    	print "         $0 -px http://site.com/proxy/proxy.php -pwd pproxypass\n";
    	print "         $0 -px http://site.com/proxy/proxy.php -tpx http://localhost:8118\n";
    	print "\nDefault bind port - 8008\n";
    	exit;
    }
    Серверная часть не изменялась...
     
    #86 Ty3uK, 1 Jun 2009
    Last edited: 1 Jun 2009
  7. Woolf89

    Woolf89 Elder - Старейшина

    Joined:
    5 Jun 2008
    Messages:
    13
    Likes Received:
    6
    Reputations:
    0
    Спасибо, то что нужно, как раз возникла необходимость.
     
  8. Ty3uK

    Ty3uK Member

    Joined:
    1 Feb 2009
    Messages:
    35
    Likes Received:
    28
    Reputations:
    0
    Нету за что! Надеюсь что ТС не обидится если я немного попробую переписать клиента под свои нужды))
     
  9. HIVER

    HIVER Member

    Joined:
    28 Oct 2008
    Messages:
    36
    Likes Received:
    18
    Reputations:
    0
    Code:
    <?php
    
    $secret = 'pwd';
    
    if (isset($_POST["transfer"]) && $_POST["transfer"] != "")
    	{
    	if(isset($secret) && ($_POST['secret'] != $secret))exit;
    	$transfer_hosts = explode("::", base64_decode($_POST["transfer"]));
    	$next_host = array_shift($transfer_hosts);
    	$postfields = array(
    						"query" => $_POST['query'],
    						"host" => $_POST['host'],
    						"secret" => $_POST['secret']
    						);
    	if ($transfer_hosts[0] != "") $postfields["transfer"] = base64_encode(implode("::", $transfer_hosts));
    	$ch = curl_init($next_host);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_POST, 1);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
    	curl_setopt($ch, CURLOPT_HEADER, 1);
    	$result = curl_exec($ch);
    	curl_close($ch);
    	echo $result;
    	} else {
    	if(isset($_POST['query']) && isset($_POST['host']))
    		{
    		if(isset($secret) && ($_POST['secret'] != $secret))exit;
    		header('Content-type: application/octet-stream');
    		@set_time_limit(0);
    		$query = base64_decode(str_replace(" ", "+", $_POST['query']));
    		list($host, $port) = explode(':', base64_decode(str_replace(" ", "+", $_POST['host'])));
    		if(!$port) {if (eregi("https:", $host) && !$port) {$port = 443;} else {$port = 80;}}
    		$ip = gethostbyname($host);
    		if($fp = @fsockopen($ip, $port, $errno, $errstr, 20))
    			{
    			fwrite($fp, $query);        
    			while(!feof($fp))
    				{
    				$answer = fread($fp, 1024);
    				echo $answer;
    				}
    			fclose($fp);
    			}
    		exit;
    		}
    	}
    ?> 
    
    Изменения в строке
    Code:
    if (!$port) $port=80;
    
    на
    Code:
    if(!$port) {if (eregi("https:", $host) && !$port) {$port = 443;} else {$port = 80;}}
    
    и вуаля, https есть :)
     
    #89 HIVER, 13 Jun 2009
    Last edited: 14 Jun 2009
    3 people like this.
  10. HIVER

    HIVER Member

    Joined:
    28 Oct 2008
    Messages:
    36
    Likes Received:
    18
    Reputations:
    0
    з.ы. пардон, в большом блоке очепятка с брекетами была, исправлено.
     
    #90 HIVER, 14 Jun 2009
    Last edited: 14 Jun 2009
  11. needDrivers

    needDrivers New Member

    Joined:
    30 Jan 2009
    Messages:
    16
    Likes Received:
    1
    Reputations:
    0
    HIVER
    На фига два раза на нот порт проверять? :D
    И вообще непонятно почему это должно работать!?
     
  12. zannussi

    zannussi Elder - Старейшина

    Joined:
    22 May 2008
    Messages:
    0
    Likes Received:
    12
    Reputations:
    1
    прочитал все 13 страниц
    Автору респект!
    Но пару раз или даже три раза проскачило прокси для делфи. В ближайшее время намечается?
     
  13. t4Nk

    t4Nk Elder - Старейшина

    Joined:
    23 Sep 2007
    Messages:
    70
    Likes Received:
    33
    Reputations:
    0
    именно на паскакале? а на сях не покатит?
     
  14. needDrivers

    needDrivers New Member

    Joined:
    30 Jan 2009
    Messages:
    16
    Likes Received:
    1
    Reputations:
    0
    t4Nk
    В соседней ветке исходник на Си лежит... никто не берёт
     
  15. bons

    bons Elder - Старейшина

    Joined:
    20 Dec 2007
    Messages:
    286
    Likes Received:
    121
    Reputations:
    21
    клиент на паскале:

    - требует меньше ресурсов чем верcия на perl (неблокирующие сокеты, модель select)
    - кроссплатформенный. Рекомендуемый компилятор Free Pascal. Также компилируется в Delphi (тестировал на Delphi 7).
    - интерфейс такой же как и у программы на perl
    - код достаточно хорошо прокомментирован на русском языке, кодировка комментариев Windows-1251
    - ссылка http://dump.ru/file/3320224
     
    #95 bons, 8 Jul 2009
    Last edited: 29 Aug 2009
    0Dayzz and Nightmarе like this.
  16. [х26]VОLАND

    [х26]VОLАND Elder - Старейшина

    Joined:
    7 Jun 2006
    Messages:
    517
    Likes Received:
    756
    Reputations:
    218
    Если добавить следующее, цены бы не было этому проксику.

    - GZIP-сжатие траффика между pproxy.php и клиентом.
    - Подробное логирование посещённых сайтов и кол-ва трафика (локальная exe версия).
    - GUI версия.
    - Шифрование трафика между pproxy.php и клиентом.

    Ну или хотябы первые 3 пункта...
     
  17. [х26]VОLАND

    [х26]VОLАND Elder - Старейшина

    Joined:
    7 Jun 2006
    Messages:
    517
    Likes Received:
    756
    Reputations:
    218
    Маленькая хитрость для маскировки серверного скрипта проксика.
    Закидываем скрипт в папку с картинками, переименовываем его под местность (например header.jpg) и создаём .htaccess с таким содержимым:
    PHP:
    <Files "^(header\.jpg)$">
        
    AddType application/x-httpd-php .jpg
    </Files>
    Теперь этот файл будет интерпретироваться как php-скрипт, и в тоже время обращение к нему будет выглядеть в логах как обычное скачивание картинки.
    В случае абузы на сайт администратору будет очень сложно определить по логам где спрятан проксик.
     
    3 people like this.
  18. Zemin

    Zemin New Member

    Joined:
    27 Jun 2009
    Messages:
    13
    Likes Received:
    2
    Reputations:
    0
    Проблема с флешем или явой, не могу разобрать.
    пример тому сайт speedtest.net, думаю вам и одного хватит.
    Но автору плюсик и благодарность!
     
    1 person likes this.
  19. Zemin

    Zemin New Member

    Joined:
    27 Jun 2009
    Messages:
    13
    Likes Received:
    2
    Reputations:
    0
    Дело в том, что у меня нету ни антивируса, ни файрвола.

    PS: Можно ли както нстроить ппрокси на качание с торрента?
     
    #99 Zemin, 14 Aug 2009
    Last edited: 14 Aug 2009
  20. medical

    medical New Member

    Joined:
    7 Jun 2009
    Messages:
    0
    Likes Received:
    2
    Reputations:
    0
    Вообще мне кажется если через такую проксю открыть 50-100 соединений, то апач сдохнет и всё накроется медным тазиком, не так ли?
     
    2 people like this.