-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
250 lines (206 loc) · 6.17 KB
/
Copy pathmain.go
File metadata and controls
250 lines (206 loc) · 6.17 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
package main
import (
"encoding/json"
"errors"
"log"
"net"
"net/netip"
"net/url"
"os"
"slices"
"strings"
"time"
"github.com/yggdrasil-network/yggdrasil-go/src/admin"
"github.com/yggdrasil-network/yggdrasil-go/src/core"
zfg "github.com/chaindead/zerocfg"
"github.com/chaindead/zerocfg/env"
"github.com/chaindead/zerocfg/yaml"
)
var (
configPath = zfg.Str("config", "/etc/yggdrasil/peerman.yaml", "path to yaml conf file", zfg.Alias("c"))
loopTime = zfg.Dur("looptime", 1*time.Minute, "cycle time for checking peers")
endpoint = zfg.Str("endpoint", "unix:///var/run/yggdrasil/yggdrasil.sock", "yggdrasil admin endpoint")
routers = zfg.Strs("routers", []string{}, "trusted router public keys")
soloPeers = zfg.Strs("peers", []string{}, "peer URIs to toggle")
)
func main() {
os.Exit(run())
}
func run() int {
logger := log.New(os.Stderr, "", log.Flags())
defer func() int {
if r := recover(); r != nil {
logger.Println("panic caught:", r)
return 1
}
return 0
}()
logger.Println("reading configuration from", *configPath)
err := zfg.Parse(
env.New(),
yaml.New(configPath),
)
if err != nil {
panic(err)
}
// Sanity checking: see if urls parse and that public keys are a set length.
for _, key := range *routers {
if len(key) != 64 {
logger.Fatal("router public keys are expected to be exactly 64 characters long:", key)
}
}
for _, uri := range *soloPeers {
_, err := url.Parse(uri)
if err != nil {
logger.Fatal("could not parse peer uri:", uri)
}
}
server, err := NewServer(*endpoint, logger)
if err != nil {
panic(err)
}
defer server.Shutdown()
for {
server.GetPeers()
hasTrustedRouters := server.hasLocalPeers(*routers)
for _, peerUri := range *soloPeers {
server.SetPeer(peerUri, !hasTrustedRouters)
}
time.Sleep(*loopTime)
}
}
type Server struct {
conn *net.Conn
logger *log.Logger
peers *[]admin.PeerEntry
}
func NewServer(endpoint string, logger *log.Logger) (*Server, error) {
var conn net.Conn
u, err := url.Parse(endpoint)
if err == nil {
switch strings.ToLower(u.Scheme) {
case "unix":
logger.Println("connecting to UNIX socket", (endpoint)[7:])
conn, err = net.Dial("unix", (endpoint)[7:])
case "tcp":
logger.Println("connecting to TCP socket", u.Host)
conn, err = net.Dial("tcp", u.Host)
default:
logger.Println("unknown protocol or malformed address")
err = errors.New("protocol not supported")
}
} else {
logger.Println("connecting to TCP socket", u.Host)
conn, err = net.Dial("tcp", endpoint)
}
if err != nil {
return nil, err
}
logger.Println("connected")
return &Server{
conn: &conn,
logger: logger,
}, nil
}
func (s *Server) Shutdown() {
(*s.conn).Close()
}
func (s *Server) query(send *admin.AdminSocketRequest) *admin.AdminSocketResponse {
decoder := json.NewDecoder(*s.conn)
encoder := json.NewEncoder(*s.conn)
// We're a daemon with a persistent connection, so all our requests are keepalive.
send.KeepAlive = true
recv := &admin.AdminSocketResponse{}
if err := encoder.Encode(&send); err != nil {
s.logger.Fatal("json error when encoding request", err.Error())
}
if err := decoder.Decode(&recv); err != nil {
s.logger.Fatal("json error when decoding response", err.Error())
}
if recv.Status == "error" {
if err := recv.Error; err != "" {
// This one is permissible, it means we tried to remove a peer that wasn't defined,
// or add a peer that is already there.
if err != core.ErrLinkNotConfigured.Error() && err != core.ErrLinkAlreadyConfigured.Error() {
s.logger.Fatalf("Admin socket returned an unhandled error: %s", err)
}
} else {
s.logger.Fatal("Admin socket returned an error but didn't specify any error text")
}
}
return recv
}
func (s *Server) GetPeers() {
request := &admin.AdminSocketRequest{Name: "getpeers"}
s.logger.Println("getting peers")
recv := s.query(request)
var resp admin.GetPeersResponse
if err := json.Unmarshal(recv.Response, &resp); err != nil {
s.logger.Fatal("json error when parsing peers", err.Error())
}
s.peers = &resp.Peers
}
func (s *Server) SetPeer(uri string, state bool) {
var err error
send := &admin.AdminSocketRequest{Name: "removepeer"}
// This kind of request actually requires building arguments.
if state {
s.logger.Println("adding peer:", uri)
send.Name = "addpeer"
} else {
// removepeer apparently wants an argument with no query string parameters.
// We already parsed these before on startup, so no need to panic here.
uri, _ = stripQuery(uri)
// Check if the peer is in the connected peer list.
// if not, don't bother the server.
if !slices.ContainsFunc(*s.peers, func(e admin.PeerEntry) bool { return uri == e.URI }) {
return
}
s.logger.Println("removing peer:", uri)
}
args := map[string]string{
"uri": uri,
}
if send.Arguments, err = json.Marshal(args); err != nil {
s.logger.Fatal("json error while building arguments", err.Error())
}
// If I understand the code of yggdrasilctl, these are actually blind,
// i.e. if they don't error out they don't return anything.
s.query(send)
}
func (s *Server) hasLocalPeers(keys []string) bool {
// Now the issue is with determining if any of them are local peers,
// because PeerEntry structure does not contain this information.
// We can only assume that peers connected on a link-local address
// are what we want to check for a matching key.
return slices.ContainsFunc(*s.peers, func(peer admin.PeerEntry) bool {
// Peers that are not up are not considered.
if !peer.Up {
return false
}
// Peers whose urls we can't parse are not considered either.
url, err := url.Parse(peer.URI)
if err != nil {
return false
}
// Peer URIs that are not actually IP addresses are not autoconfigured anyway.
ip, err := netip.ParseAddr(url.Hostname())
if err != nil {
return false
}
// Only link-local unicast addresses are actually multicast peers.
if !ip.IsLinkLocalUnicast() {
return false
}
// if the key matches, it's a trusted router.
return slices.Contains(keys, peer.PublicKey)
})
}
func stripQuery(thatUrl string) (string, error) {
parsedURL, err := url.Parse(thatUrl)
if err != nil {
return "", err
}
parsedURL.RawQuery = ""
return parsedURL.String(), nil
}