-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquic_sync.go
More file actions
318 lines (265 loc) · 8.34 KB
/
Copy pathquic_sync.go
File metadata and controls
318 lines (265 loc) · 8.34 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package main
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"net"
"os/exec"
"strconv"
"strings"
"time"
"github.com/quic-go/quic-go"
)
var recvPort int = 49152
var tr *quic.Transport = nil
// all the local IPs
func GetAllIPs() {
// 1. Get the list of interfaces
interfaces, err := net.Interfaces()
if err != nil {
fmt.Println("Error fetching interfaces:", err)
return
}
for _, iface := range interfaces {
// Print interface name (e.g., eth0, lo, wlan0)
fmt.Printf("Interface: %s\n", iface.Name)
// 2. Get addresses specifically for THIS interface
addrs, err := iface.Addrs()
if err != nil {
fmt.Printf(" Error getting addresses: %v\n", err)
continue
}
// 3. List all IPs bound to it
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok {
continue
}
// Get the mask sizing (ones = current prefix, bits = total size 32 or 128)
// ones, bits := ipNet.Mask.Size()
fmt.Printf(" -> IP Address: %s | MASK: %s\n", addr.String(), ipNet.Mask)
}
fmt.Println()
}
}
func GetIPToUse() (string, error) {
Logger.Info("Finding temporary IPv6")
// Query the system routing binary for the IP address attributes
cmd := exec.Command("ip", "-6", "addr", "show", "dev", "wlp44s0")
output, err := cmd.Output()
if err != nil {
Logger.Error("Error executing command", "error", err)
// fmt.Println("Error executing command:", err)
return "", errors.New("Something Went Wrong. Make sure it has admin privileges")
}
lines := strings.Split(string(output), "\n")
for _, line := range lines {
// Clean line whitespace and search for the IP definitions
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "inet6 ") {
fields := strings.Fields(line)
ipAndMask := fields[1]
if strings.Contains(line, "temporary") {
return ipAndMask, nil
}
// Evaluate system flags tagged at the end of the line
// if strings.Contains(line, "temporary") {
// fmt.Printf("[TEMPORARY PRIVACY IP] -> %s\n", ipAndMask)
// } else if strings.Contains(line, "mngtmpaddr") || strings.Contains(line, "noprefixroute") {
// fmt.Printf("[STABLE GLOBAL IP] -> %s\n", ipAndMask)
// } else if strings.Contains(line, "scope link") {
// fmt.Printf("[LINK-LOCAL IP] -> %s\n", ipAndMask)
// }
}
}
Logger.Error("Temporary IPv6 Not Found. Either enable that or change the browser setting and restart.")
return "", errors.New("Temporary IPv6 Not Found. Either enable that or change the browser setting and restart.")
}
func CreateTransport() {
if !Settings.Sync {
Logger.Info("Sync is disabled")
fmt.Println("Sync is disabled")
return
}
// setup single UDP transport
udpConn, err := net.ListenUDP("udp4", &net.UDPAddr{Port: recvPort})
if err != nil {
Logger.Error("Transport did not initialize", "error", err)
fmt.Print(err)
}
tr = &quic.Transport{
Conn: udpConn,
}
}
func generateServerTLSConfig() (*tls.Config, error) {
// self-signed TLS certificate for QUIC (QUIC requires TLS 1.3)
// not for production use
Logger.Info("Generating Certificate")
// Generate an RSA private key
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
Logger.Error("Failed to generate private key", "error", err)
return nil, fmt.Errorf("failed to generate private key: %w", err)
}
// Define the certificate template and create certificate
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"QUO In-Memory Temporary Cert"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour), // Valid for 24 hours
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
Logger.Error("Failed to create certificate", "error", err)
return nil, fmt.Errorf("failed to create certificate: %w", err)
}
// Encode the certificate and key into PEM format and load it in-memory
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
Logger.Error("Failed to load x509 key pair", "error", err)
return nil, fmt.Errorf("failed to load x509 key pair: %w", err)
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
NextProtos: []string{"quic-echo-example"},
}, nil
}
func generateClientTLSConfig() *tls.Config {
return &tls.Config{
NextProtos: []string{"quic-echo-example"},
// InSecureSkipVerify is required for self-signed development certs
// WARNING: Do not use this in production!
InsecureSkipVerify: true,
}
}
// sender utilities
func send(stream *quic.Stream, payload string) {
_, err := stream.Write([]byte(payload))
if err != nil {
Logger.Error("Write error", "error", err)
}
// ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout
// defer cancel()
// tlsConfig := generateClientTLSConfig()
// conn, err := tr.Dial(ctx, ip, tlsConfig, nil)
// if err != nil {
// Logger.Error("Dialer did not initialize", "error", err)
// fmt.Print(err)
// }
// stream, err := conn.OpenStream()
// if err != nil {
// Logger.Error("Stream did not open", "error", err)
// fmt.Print(err)
// }
}
// receiver utilities
func recv(listener *quic.Listener) {
for {
// Accept connection: This blocks until the QUIC/TLS handshake finishes
conn, err := listener.Accept(context.Background())
if err != nil {
Logger.Error("Listener did not accept connection", "error", err)
continue
}
Logger.Info("New connection made")
// Pass the established connection to a handler
go handleConn(conn)
}
}
func handleConn(conn *quic.Conn) {
for {
stream, err := conn.AcceptStream(context.Background())
if err != nil {
var appErr *quic.ApplicationError
if errors.As(err, &appErr) {
Logger.Info("Client closed connection", "code", appErr.ErrorCode)
return
}
Logger.Error("Failed to accept stream", "error", err)
return
}
defer stream.Close()
Logger.Info("New stream accepted")
buf := make([]byte, 1024)
n, err := stream.Read(buf)
if err != nil && err != io.EOF {
Logger.Error("Read error", "error", err)
return
}
Logger.Info("Received data successfully! Now Processing...")
processRecvData(conn.RemoteAddr(), stream, string(buf[:n]))
// // Send ack so the client knows it's safe to close
// _, err = stream.Write([]byte("ACK"))
// if err != nil {
// Logger.Error("Write ack error", "error", err)
// }
}
}
func processRecvData(ip net.Addr, steam *quic.Stream, data string) {
substrings := strings.Split(data, ",")
if len(substrings) == 0 {
return
}
// if sync not allowed the client side will get no connection error and no data (alive but not interested in sharing)
if strings.TrimSpace(substrings[0]) == "1" && Settings.SendNodes {
Logger.Info("Sending Nodes", "client IP", ip)
var nodes []string
for _, n := range AllNodes {
nodes = append(nodes, fmt.Sprintf("%s:%d", n.Addr, n.Port))
}
payload := "n" + "," + strings.Join(nodes, ",") + "," + "0"
// Logger.Info("Nodes", "nodes", payload)
send(steam, payload)
return
}
if strings.TrimSpace(substrings[0]) == "n" && len(substrings) > 2 && Settings.ReceiveNodes {
Logger.Info("Receiving Nodes", "client IP", ip)
for i := 1; i < len(substrings); i++ {
values := strings.Split(substrings[i], ":")
if len(values) != 2 {
continue
}
port, err := strconv.Atoi(values[1])
if err != nil {
continue
}
UpdateNodes(values[0], port)
}
SaveNodes()
}
}
func Receiver() {
if tr == nil {
return
}
Logger.Info("Starting Receiver", "port", recvPort)
// Generate standard TLS configuration required by QUIC
tlsConfig, err := generateServerTLSConfig()
if err != nil {
fmt.Print(err)
}
// Start the QUIC Listener
listener, err := tr.Listen(tlsConfig, nil)
// listener, err := quic.ListenAddr("localhost:49152", tlsConfig, nil)
if err != nil {
Logger.Error("Listener did not initialize", "error", err)
fmt.Print(err)
}
ReceiverStarted = true
go recv(listener)
}