forked from kaspanet/dnsseeder
-
Notifications
You must be signed in to change notification settings - Fork 4
/
dnsseed.go
262 lines (222 loc) · 7.12 KB
/
dnsseed.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
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
// Copyright (c) 2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/karlsen-network/karlsend/app/protocol/common"
"github.com/karlsen-network/karlsend/infrastructure/config"
"github.com/karlsen-network/karlsend/infrastructure/network/netadapter/standalone"
"github.com/pkg/errors"
"github.com/karlsen-network/dnsseeder/version"
"github.com/karlsen-network/karlsend/infrastructure/network/dnsseed"
"github.com/karlsen-network/karlsend/util/panics"
"github.com/karlsen-network/karlsend/util/profiling"
"github.com/karlsen-network/karlsend/app/appmessage"
"github.com/karlsen-network/karlsend/infrastructure/os/signal"
_ "net/http/pprof"
)
var (
amgr *Manager
wg sync.WaitGroup
peersDefaultPort int
systemShutdown int32
defaultSeeder *appmessage.NetAddress
)
// hostLookup returns the correct DNS lookup function to use depending on the
// passed host and configuration options. For example, .onion addresses will be
// resolved using the onion specific proxy if one was specified, but will
// otherwise treat the normal proxy as tor unless --noonion was specified in
// which case the lookup will fail. Meanwhile, normal IP addresses will be
// resolved using tor if a proxy was specified unless --noonion was also
// specified in which case the normal system DNS resolver will be used.
func hostLookup(host string) ([]net.IP, error) {
return net.LookupIP(host)
}
func creep() {
defer wg.Done()
netAdapter, err := standalone.NewMinimalNetAdapter(&config.Config{Flags: &config.Flags{NetworkFlags: ActiveConfig().NetworkFlags}})
if err != nil {
panic(errors.Wrap(err, "Could not start net adapter"))
}
var knownPeers []*appmessage.NetAddress
if len(ActiveConfig().KnownPeers) != 0 {
for _, p := range strings.Split(ActiveConfig().KnownPeers, ",") {
addressStr := strings.Split(p, ":")
if len(addressStr) != 2 {
log.Errorf("Invalid peer address: %s; addresses should be in format \"IP\":\"port\"", p)
return
}
ip := net.ParseIP(addressStr[0])
if ip == nil {
log.Errorf("Invalid peer IP address: %s", addressStr[0])
return
}
port, err := strconv.Atoi(addressStr[1])
if err != nil {
log.Errorf("Invalid peer port: %s", addressStr[1])
return
}
knownPeers = append(knownPeers, appmessage.NewNetAddressIPPort(ip, uint16(port)))
}
amgr.AddAddresses(knownPeers)
for _, peer := range knownPeers {
amgr.Good(peer.IP, nil)
amgr.Attempt(peer.IP)
}
}
var wgCreep sync.WaitGroup
for {
peers := amgr.Addresses()
if len(peers) == 0 && amgr.AddressCount() == 0 {
// Add peers discovered through DNS to the address manager.
dnsseed.SeedFromDNS(ActiveConfig().NetParams(), "", true,
nil, hostLookup, func(addrs []*appmessage.NetAddress) {
amgr.AddAddresses(addrs)
})
peers = amgr.Addresses()
}
if len(peers) == 0 {
log.Infof("No stale addresses -- sleeping for 10 minutes")
for i := 0; i < 600; i++ {
time.Sleep(time.Second)
if atomic.LoadInt32(&systemShutdown) != 0 {
log.Infof("Creep thread shutdown")
return
}
}
continue
}
for _, addr := range peers {
if atomic.LoadInt32(&systemShutdown) != 0 {
log.Infof("Waiting creep threads to terminate")
wgCreep.Wait()
log.Infof("Creep thread shutdown")
return
}
wgCreep.Add(1)
go func(addr *appmessage.NetAddress) {
defer wgCreep.Done()
err := pollPeer(netAdapter, addr)
if err != nil {
log.Debugf(err.Error())
if defaultSeeder != nil && addr == defaultSeeder {
panics.Exit(log, "failed to poll default seeder")
}
}
}(addr)
}
wgCreep.Wait()
}
}
func pollPeer(netAdapter *standalone.MinimalNetAdapter, addr *appmessage.NetAddress) error {
defer amgr.Attempt(addr.IP)
peerAddress := net.JoinHostPort(addr.IP.String(), strconv.Itoa(int(addr.Port)))
routes, err := netAdapter.Connect(peerAddress)
if err != nil {
return errors.Wrapf(err, "could not connect to %s", peerAddress)
}
defer routes.Disconnect()
msgRequestAddresses := appmessage.NewMsgRequestAddresses(true, nil)
err = routes.OutgoingRoute.Enqueue(msgRequestAddresses)
if err != nil {
return errors.Wrapf(err, "failed to request addresses from %s", peerAddress)
}
message, err := routes.WaitForMessageOfType(appmessage.CmdAddresses, common.DefaultTimeout)
if err != nil {
return errors.Wrapf(err, "failed to receive addresses from %s", peerAddress)
}
msgAddresses := message.(*appmessage.MsgAddresses)
added := amgr.AddAddresses(msgAddresses.AddressList)
log.Infof("Peer %s sent %d addresses, %d new",
peerAddress, len(msgAddresses.AddressList), added)
amgr.Good(addr.IP, nil)
return nil
}
func main() {
defer panics.HandlePanic(log, "main", nil)
interrupt := signal.InterruptListener()
cfg, err := loadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "loadConfig: %v\n", err)
os.Exit(1)
}
// Show version at startup.
log.Infof("Version %s", version.Version())
// Enable http profiling server if requested.
if cfg.Profile != "" {
profiling.Start(cfg.Profile, log)
}
amgr, err = NewManager(cfg.AppDir)
if err != nil {
fmt.Fprintf(os.Stderr, "NewManager: %v\n", err)
os.Exit(1)
}
peersDefaultPort, err = strconv.Atoi(ActiveConfig().NetParams().DefaultPort)
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid peers default port %s: %v\n", ActiveConfig().NetParams().DefaultPort, err)
os.Exit(1)
}
if len(cfg.Seeder) != 0 {
// Prepare the seeder address, supporting either a simple IP with default network port
// or a full IP:port format
seederIp := cfg.Seeder
seederPort := peersDefaultPort
// Try to split seeder host and port
foundIp, foundPort, err := net.SplitHostPort(cfg.Seeder)
if (err == nil) {
seederIp = foundIp
seederPort, err = strconv.Atoi(foundPort)
if err != nil {
log.Errorf("Invalid seeder port: %s", foundPort)
return
}
}
ip := net.ParseIP(seederIp)
if ip == nil {
hostAddrs, err := net.LookupHost(seederIp)
if err != nil {
log.Warnf("Failed to resolve seed host: %v, %v, ignoring", seederIp, err)
} else {
ip = net.ParseIP(hostAddrs[0])
if ip == nil {
log.Warnf("Failed to resolve seed host: %v, ignoring", seederIp)
}
}
}
if ip != nil {
defaultSeeder = appmessage.NewNetAddressIPPort(ip, uint16(seederPort))
amgr.AddAddresses([]*appmessage.NetAddress{defaultSeeder})
}
}
wg.Add(1)
spawn("main-creep", creep)
dnsServer := NewDNSServer(cfg.Host, cfg.Nameserver, cfg.Listen)
wg.Add(1)
spawn("main-DNSServer.Start", dnsServer.Start)
grpcServer := NewGRPCServer(amgr)
err = grpcServer.Start(cfg.GRPCListen)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to start gRPC server")
return
}
defer func() {
log.Infof("Gracefully shutting down the seeder...")
atomic.StoreInt32(&systemShutdown, 1)
close(amgr.quit)
wg.Wait()
amgr.wg.Wait()
log.Infof("Seeder shutdown complete")
}()
// Wait until the interrupt signal is received from an OS signal or
// shutdown is requested through one of the subsystems such as the RPC
// server.
<-interrupt
}