-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
222 lines (184 loc) · 5.25 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"flag"
"io"
"log"
"math/rand"
"net"
"strconv"
"strings"
"sync"
"time"
)
var connectionPool []*net.TCPConn
var poolLock sync.Mutex
var ips []net.IP
var targetHost string
var targetPort int
var initialPoolSize int
func emptyConnectionPool() {
poolLock.Lock()
defer poolLock.Unlock()
for _, conn := range connectionPool {
if conn != nil {
conn.Close()
log.Printf("Closed connection to %v", conn.RemoteAddr())
}
}
connectionPool = []*net.TCPConn{}
log.Println("Connection pool emptied.")
}
func createConnection(ip net.IP, port int) *net.TCPConn {
addr := net.TCPAddr{IP: ip, Port: port}
conn, err := net.DialTCP("tcp", nil, &addr)
if err != nil {
log.Printf("Failed to connect to %v: %v", addr, err)
return nil
}
log.Printf("Connected to %v", addr)
// Enable TCP keep-alive
if err := conn.SetKeepAlive(true); err != nil {
log.Printf("Failed to enable keep-alive for %v: %v", conn.RemoteAddr(), err)
return nil
}
// Set the keep-alive period
keepAlivePeriod := 30 * time.Second // Adjust as needed
if err := conn.SetKeepAlivePeriod(keepAlivePeriod); err != nil {
log.Printf("Failed to set keep-alive period for %v: %v", conn.RemoteAddr(), err)
return nil
}
/*
// Disable Nagle's algorithm to reduce latency
if err := conn.SetNoDelay(true); err != nil {
log.Printf("Failed to disable Nagle's algorithm for %v: %v", conn.RemoteAddr(), err)
return nil
}
*/
return conn
}
func initializePool(target string) {
emptyConnectionPool()
hostPort := strings.Split(target, ":")
host := hostPort[0]
port, err := strconv.Atoi(hostPort[1])
if err != nil {
log.Fatalf("Invalid port in target %s: %v", target, err)
}
// Update globals
targetHost = host
targetPort = port
ips, err = net.LookupIP(host)
if err != nil {
panic(err)
}
log.Printf("Found %d IPs for host %s", len(ips), host)
for _, ip := range ips {
if conn := createConnection(ip, port); conn != nil {
poolLock.Lock()
connectionPool = append(connectionPool, conn)
poolLock.Unlock()
}
}
initialPoolSize = len(connectionPool)
log.Printf("Initialized pool with %d members", initialPoolSize)
}
func getConnectionFromPool() *net.TCPConn {
poolLock.Lock()
defer poolLock.Unlock()
if len(connectionPool) < initialPoolSize {
log.Printf("Pool size %d < initial %d, reinitializing", len(connectionPool), initialPoolSize)
initializePool(targetHost + ":" + strconv.Itoa(targetPort))
}
if len(connectionPool) == 0 {
log.Println("No connections available in pool")
initializePool(targetHost + ":" + strconv.Itoa(targetPort))
}
// Pick a random connection
idx := rand.Intn(len(connectionPool))
conn := connectionPool[idx]
log.Printf("Retrieved connection from pool: %v", conn.RemoteAddr())
return conn
}
func replaceConnectionInPool(closedConn *net.TCPConn) {
poolLock.Lock()
defer poolLock.Unlock()
if len(connectionPool) < initialPoolSize {
initializePool(targetHost + ":" + strconv.Itoa(targetPort))
}
for i, conn := range connectionPool {
if conn == closedConn {
// Only replace if it's a pool member
newConn := createConnection(closedConn.RemoteAddr().(*net.TCPAddr).IP, targetPort)
if newConn != nil {
connectionPool[i] = newConn
log.Printf("Replaced closed connection to %v with %v",
closedConn.RemoteAddr(), newConn.RemoteAddr())
} else {
// Remove closed conn if replacement fails
connectionPool = append(connectionPool[:i], connectionPool[i+1:]...)
log.Printf("Removed closed connection %v", closedConn.RemoteAddr())
}
return
}
}
log.Printf("Connection %v not found in pool, not replacing", closedConn.RemoteAddr())
}
func forward(src, dst net.Conn) {
defer src.Close()
defer dst.Close()
buf := make([]byte, 1024)
for {
n, err := src.Read(buf)
if err != nil {
if err != io.EOF {
log.Printf("Failed to read from %v: %v", src.RemoteAddr(), err)
replaceConnectionInPool(src.(*net.TCPConn))
}
return
}
_, err = dst.Write(buf[:n])
if err != nil {
log.Printf("Failed to write to %v: %v", dst.RemoteAddr(), err)
replaceConnectionInPool(dst.(*net.TCPConn))
return
}
}
}
func handleClient(conn net.Conn) {
poolConn := getConnectionFromPool()
if poolConn == nil {
log.Println("Failed to get connection from pool")
conn.Close()
return
}
go forward(conn, poolConn)
go forward(poolConn, conn)
}
func main() {
target := flag.String("target", "mainnet-pociot.helium.io:9080", "The target host and port to connect to")
listenAddr := flag.String("listen", "127.0.0.1:9080", "The IP and port to listen on")
flag.Parse() // Parse the command-line arguments
log.SetFlags(log.Lshortfile | log.Ldate | log.Ltime | log.Lmicroseconds | log.LUTC)
rand.Seed(time.Now().UnixNano()) // Initialize random seed
initializePool(*target)
tcpAddr, err := net.ResolveTCPAddr("tcp4", *listenAddr)
if err != nil {
panic(err)
}
listener, err := net.ListenTCP("tcp4", tcpAddr)
if err != nil {
panic(err)
}
log.Printf("Listening on %v", listener.Addr())
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Failed to accept connection:", err)
time.Sleep(1 * time.Second)
continue
}
log.Printf("Accepted client connection: %v", conn.RemoteAddr())
go handleClient(conn)
}
}