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
|
package server
import (
"bufio"
"context"
"fmt"
"log"
"net"
"codeberg.org/snonux/gorum/internal/config"
"codeberg.org/snonux/gorum/internal/vote"
)
func tcpServerRun(ctx context.Context, conf config.Config,
ch chan<- vote.Vote) error {
listener, err := net.Listen("tcp", conf.Address)
if err != nil {
return fmt.Errorf("Error starting TCP server: %s", err.Error())
}
defer listener.Close()
log.Printf("TCP server started on %s\n", conf.Address)
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Error accepting connection: %s\n", err.Error())
continue
}
if !conf.IsNodeWithLookup(conn.RemoteAddr().String(), net.LookupIP) {
log.Printf("Denying connection, peer not a node: %v\n", conn.RemoteAddr().String())
conn.Close()
continue
}
log.Printf("Client connected: %s\n", conn.RemoteAddr().String())
go handleConnection(ctx, conf, conn, ch)
}
}
func handleConnection(ctx context.Context, conf config.Config,
conn net.Conn, ch chan<- vote.Vote) {
defer conn.Close()
var (
remoteAddr = conn.RemoteAddr().String()
reader = bufio.NewReader(conn)
)
for {
select {
case <-ctx.Done():
log.Printf("Server context done, disconnecting client %s\n", remoteAddr)
return
default:
message, err := reader.ReadString('\n')
if err != nil {
log.Printf("Client %s disconnected: %s\n", remoteAddr, err.Error())
return
}
log.Printf("Received message from %s: %s", remoteAddr, message)
ch <- vote.New(conf, message)
conn.Write([]byte(message))
}
}
}
|