-
-
Save xantus/b5d7e840fd7c61a90c06 to your computer and use it in GitHub Desktop.
A socket proxy (like port forwarding)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
# Use bundled libraries | |
use FindBin; | |
use lib "$FindBin::Bin/../lib"; | |
# Cheating in a fake fight. That's low. | |
use Mojo::ByteStream 'b'; | |
use Mojo::IOLoop; | |
# The loop | |
my $loop = Mojo::IOLoop->new; | |
# Connection buffer | |
my $c = {}; | |
# listen on | |
my $srv_port = 9000; | |
# proxy to | |
my $port = 443; | |
my $host = 'example.com'; | |
die "You must change the host and port in this file first" if $host eq 'example.com'; | |
# turn off stdout buffering, so we can print . for recv and + for tx without delay | |
$|++; | |
$loop->listen( | |
port => $srv_port, | |
accept_cb => sub { | |
my ( $loop, $client ) = @_; | |
$c->{$client}->{client} = b; | |
$loop->connect( | |
address => $host, | |
port => $port, | |
connect_cb => sub { | |
my ($loop, $server) = @_; | |
print "\nConnected to $host:$port\n"; | |
$c->{$client}->{connection} = $server; | |
$loop->write($server, delete $c->{$client}->{client} ) | |
if $c->{$client}->{client}->raw_size; | |
}, | |
read_cb => sub { | |
my ($loop, $server, $chunk) = @_; | |
print "+"; | |
$loop->write($client, $chunk); | |
}, | |
error_cb => sub { | |
shift->drop($client); | |
delete $c->{$client}; | |
} | |
); | |
}, | |
read_cb => sub { | |
my ($loop, $client, $chunk) = @_; | |
if (my $server = $c->{$client}->{connection}) { | |
print "."; | |
return $loop->write($server, $chunk); | |
} | |
$c->{$client}->{client}->add_chunk($chunk) | |
if $c->{$client}->{client}; | |
}, | |
error_cb => sub { | |
my ($self, $client) = @_; | |
shift->drop($c->{$client}->{connection}) | |
if $c->{$client}->{connection}; | |
delete $c->{$client}; | |
} | |
) or die "Couldn't create listen socket!\n"; | |
print "Starting socket proxy on port $srv_port\n"; | |
# Start loop | |
$loop->start; | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment