-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (93 loc) · 1.88 KB
/
main.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strconv"
"sync"
"time"
)
var (
host string
ports []string
usage string = fmt.Sprintf(
"%s: [-h|--help] HOST PORTS...\n"+
"\n"+
"Forwards all TCP connections to HOST, from a list of PORTS.\n"+
"\n"+
"Arguments:\n"+
" HOST destination host or address (e.g. \"example.com\")\n"+
" PORTS space-delimited list of ports (e.g. \"80 443\")",
os.Args[0],
)
)
func main() {
log.SetFlags(0)
if err := parse(); err != nil {
log.Printf("parse error: %s\nuse --help to print usage", err)
os.Exit(1)
}
wg := sync.WaitGroup{}
defer wg.Wait()
for _, port := range ports {
wg.Add(1)
go func(port string) {
defer wg.Done()
forwardPort(port)
}(port)
}
}
func parse() error {
if len(os.Args) == 1 || (len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help")) {
fmt.Fprintln(os.Stdout, usage)
os.Exit(1)
} else if len(os.Args) < 3 {
return errors.New("too few arguments")
} else {
host = os.Args[1]
for _, arg := range os.Args[2:] {
port, err := strconv.Atoi(arg)
if err != nil {
return fmt.Errorf("argument '%s': %w", arg, err)
}
if port < 0 || port > 65535 {
return fmt.Errorf("argument '%s': not in range [1,65535]", arg)
}
ports = append(ports, arg)
}
}
return nil
}
func forwardPort(port string) {
l, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
if err != nil {
log.Println(err)
return
}
defer l.Close()
log.Printf("forwarding port %s to %s:%s", port, host, port)
for {
src, err := l.Accept()
if err != nil {
log.Println(err)
return
}
dst, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", host, port), 5*time.Second)
if err != nil {
log.Println(err)
src.Close()
continue
}
go func() {
io.Copy(src, dst)
src.Close()
dst.Close()
}()
io.Copy(src, dst)
src.Close()
dst.Close()
}
}