File: tcp-proxy.pl

package info (click to toggle)
libio-async-perl 0.64-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,068 kB
  • ctags: 491
  • sloc: perl: 12,530; makefile: 8
file content (84 lines) | stat: -rw-r--r-- 2,057 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/perl

use strict;
use warnings;

use IO::Async::Loop;
use IO::Async::Stream;
use IO::Async::Listener;

my $LISTEN_PORT = 12345;
my $CONNECT_HOST = "localhost";
my $CONNECT_PORT = 80;

my $loop = IO::Async::Loop->new;

my $listener = ProxyListener->new;

$loop->add( $listener );

$listener->listen(
   service  => $LISTEN_PORT,
   socktype => 'stream',

   on_resolve_error => sub { die "Cannot resolve - $_[0]\n"; },
   on_listen_error  => sub { die "Cannot listen\n"; },
);

$loop->run;

package ProxyListener;
use base qw( IO::Async::Listener );

sub on_stream
{
   my $self = shift;
   my ( $stream1 ) = @_;

   # $socket is just an IO::Socket reference
   my $socket1 = $stream1->read_handle;
   my $peeraddr = $socket1->peerhost . ":" . $socket1->peerport;

   print STDERR "Accepted new connection from $peeraddr\n";

   $loop->connect(
      host    => $CONNECT_HOST,
      service => $CONNECT_PORT,

      on_stream => sub {
         my ( $stream2 ) = @_;

         $stream1->configure(
            on_read => sub {
               my ( $self, $buffref, $eof ) = @_;
               # Just copy all the data
               $stream2->write( $$buffref ); $$buffref = "";
               return 0;
            },
            on_closed => sub {
               $stream2->close_when_empty;
               print STDERR "Connection from $peeraddr closed\n";
            },
         );

         $stream2->configure(
            on_read => sub {
               my ( $self, $buffref, $eof ) = @_;
               # Just copy all the data
               $stream1->write( $$buffref ); $$buffref = "";
               return 0;
            },
            on_closed => sub {
               $stream1->close_when_empty;
               print STDERR "Connection to $CONNECT_HOST:$CONNECT_PORT closed\n";
            },
         );

         $loop->add( $stream1 );
         $loop->add( $stream2 );
      },

      on_resolve_error => sub { print STDERR "Cannot resolve - $_[0]\n"; },
      on_connect_error => sub { print STDERR "Cannot connect\n"; },
   );
}