-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
198 lines (176 loc) · 4.85 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
var Rules []Rule
var ConfigFileName = "rules.json"
var SimultaneousConnections = make([]int, 0)
var Verbose = false
const Version = "0.2.0 / Build 3"
type Rule struct {
Listen uint16
Expiration time.Time
Forward string
Quota int64
IPLimit int
Simultaneous int
ConnectedIPs []string
}
type Config struct {
SaveDuration int
Rules []Rule
}
func ListContains(list []string, ip string) bool {
for _, a := range list {
if a == ip {
return true
}
}
return false
}
func main() {
{ //Parse arguments
configFileName := flag.String("config", "rules.json", "The config filename")
verbose := flag.Bool("v", false, "Verbose mode")
help := flag.Bool("h", false, "Show help")
flag.Parse()
Verbose = *verbose
ConfigFileName = *configFileName
if *help {
fmt.Println("Created by Hirbod Behnam")
fmt.Println("Source at https://github.com/HirbodBehnam/PortForwarder")
fmt.Println("Version", Version)
flag.PrintDefaults()
os.Exit(0)
}
}
//Read config file
confF, err := ioutil.ReadFile(ConfigFileName)
if err != nil {
panic("Cannot read the config file. (io Error) " + err.Error())
}
var conf Config
err = json.Unmarshal(confF, &conf)
if err != nil {
panic("Cannot read the config file. (Parse Error) " + err.Error())
}
Rules = conf.Rules
SimultaneousConnections = make([]int, len(Rules))
//Start listeners
for index := range Rules {
go func(i int) {
// Check expiration
if Rules[i].Expiration.Before(time.Now()) {
fmt.Println("Rule expired for port", Rules[i].Forward, "pointing to", Rules[i].Forward)
return
}
if Rules[i].Quota < 0 { //If the quota is already reached why listen for connections?
return
}
fmt.Println("Forwarding from", Rules[i].Listen, "port to", Rules[i].Forward)
ln, err := net.Listen("tcp", ":"+strconv.Itoa(int(Rules[i].Listen))) //Listen on port
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept() //The loop will be held here
if Rules[i].Quota < 0 {
fmt.Println("Quota reached for port", Rules[i].Forward, "pointing to", Rules[i].Forward)
if err == nil {
_ = conn.Close()
}
saveConfig(conf)
break
}
if err != nil {
println("Error on accepting connection:", err.Error())
continue
}
// Check use ip
ip := strings.Split(conn.RemoteAddr().String(), ":")[0]
if !ListContains(Rules[i].ConnectedIPs, ip) {
Rules[i].ConnectedIPs = append(Rules[i].ConnectedIPs, ip)
if len(Rules[i].ConnectedIPs) > Rules[i].IPLimit {
fmt.Println("IP limit reached for port", Rules[i].Forward, "pointing to", Rules[i].Forward)
_ = conn.Close()
}
}
go handleRequest(conn, i)
}
}(index)
}
//Save config file
go func() {
for {
time.Sleep(time.Duration(conf.SaveDuration) * time.Second) //Save file every x seconds
saveConfig(conf)
}
}()
//https://gobyexample.com/signals
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() { //This will wait for a signal
<-sigs
done <- true
}()
fmt.Println("Ctrl + C to stop")
<-done
saveConfig(conf) //Save the config file one last time before exiting
fmt.Println("Exiting")
}
func saveConfig(config Config) {
// Reset the connected ips
for i := range Rules {
Rules[i].ConnectedIPs = []string{}
}
config.Rules = Rules
b, err := json.Marshal(config)
if err != nil {
fmt.Println("Error parsing rules: ", err)
return
}
err = ioutil.WriteFile(ConfigFileName, b, 0644)
if err != nil {
fmt.Println("Error re-writing rules: ", err)
}
if Verbose {
fmt.Println("Saved the config file at ", time.Now().Format("2006-01-02 15:04:05"))
}
}
func handleRequest(conn net.Conn, index int) {
if Rules[index].Simultaneous != 0 && SimultaneousConnections[index] >= (Rules[index].Simultaneous*2) { //If we have reached quota just terminate the connection; 0 means no limits
if Verbose {
fmt.Println("Blocking new connection for port", Rules[index].Listen, "because the connection limit is reached. The current active connections count is", SimultaneousConnections[index]/2)
}
_ = conn.Close()
return
}
proxy, err := net.Dial("tcp", Rules[index].Forward) //Open a connection to remote host
if err != nil {
println("Error on dialing remote host:", err.Error())
_ = conn.Close()
return
}
SimultaneousConnections[index] += 2 //Two is added; One for client to server and another for server to client
go copyIO(conn, proxy, index)
go copyIO(proxy, conn, index)
}
func copyIO(src, dest net.Conn, index int) {
defer src.Close()
defer dest.Close()
r, _ := io.Copy(src, dest) //r is the amount of bytes transferred
Rules[index].Quota -= r
SimultaneousConnections[index]-- //This will actually run twice
}