-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscovery_irc.go
206 lines (186 loc) · 4.45 KB
/
discovery_irc.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
package discovery
import (
"context"
"time"
"github.com/thoj/go-ircevent"
"github.com/Pallinder/go-randomdata"
"crypto/tls"
"encoding/hex"
"strings"
"net"
"strconv"
"github.com/iain17/logger"
"io/ioutil"
ttlru "github.com/iain17/kvcache/lttlru"
"fmt"
"hash"
"hash/crc32"
)
type DiscoveryIRC struct {
connection *irc.Connection
localNode *LocalNode
context context.Context
channel string
logger *logger.Logger
//A fallback way of sharing data.
messages *ttlru.LruWithTTL
message string
crcTable hash.Hash32
retries int
}
func (d *DiscoveryIRC) String() string {
return "DiscoveryIRC"
}
func (d *DiscoveryIRC) init(ctx context.Context) (err error) {
defer func() {
if d.localNode.wg != nil {
d.localNode.wg.Done()
}
}()
d.logger = logger.New(d.String())
d.context = ctx
infoHash := d.localNode.discovery.network.InfoHash()
d.channel = "#"+hex.EncodeToString(infoHash[:])
d.crcTable = crc32.NewIEEE()
d.messages, err = ttlru.NewTTL(10)
if err != nil {
return err
}
name := randomdata.SillyName()
d.connection = irc.IRC(name, name)
d.connection.Log.SetOutput(ioutil.Discard)
//d.connection.Debug = true
d.connection.TLSConfig = &tls.Config{InsecureSkipVerify: true}
d.connection.UseTLS = true
d.connection.AddCallback("001", func(e *irc.Event) {
logger.Debugf("Joined IRC: %s", d.channel)
d.connection.Join(d.channel)
})
d.connection.AddCallback("366", func(e *irc.Event) {
d.Advertise()
})
d.connection.AddCallback("PRIVMSG", func(event *irc.Event) {
if d.localNode.netTableService.isEnoughPeers() {
return
}
message := event.Message()
parts := strings.Split(message, IRC_SEPERATOR)
if len(parts) != 2 {
//legacy
if strings.HasPrefix(message,"JOIN US:") {
d.onReceiveJoin(message[len("JOIN US:"):])
return
}
d.logger.Debugf("Malformed message: '%s'", message)
return
}
switch parts[0] {
case IRC_JOIN_HANDLE:
d.onReceiveJoin(parts[1])
break
case IRC_MESSAGE_HANDLE:
d.onReceiveNetworkMessage(parts[1])
break
default:
d.logger.Warningf("Unknown handle '%s'.", parts[0])
}
})
err = d.connection.Connect(IRC_SERVER)
return err
}
func (d *DiscoveryIRC) onReceiveJoin(data string) {
logger.Debugf("Received IRC join message: %s", data)
ipPort := strings.Split(data, ":")
if len(ipPort) != 2 {
d.logger.Warningf("Received a weird IRC message: %s", data)
return
}
port, err := strconv.Atoi(ipPort[1])
if err != nil {
d.logger.Warning(err)
return
}
d.localNode.netTableService.Discovered(&net.TCPAddr{
IP: net.ParseIP(ipPort[0]),
Port: port,
})
}
func (d *DiscoveryIRC) onReceiveNetworkMessage(data string) {
logger.Debugf("Received IRC network message: %s", data)
d.crcTable.Reset()
d.crcTable.Write([]byte(data))
d.messages.AddWithTTL(d.crcTable.Sum32(), data, 30 * time.Minute)
logger.Debugf("Saved network message: %s", data)
}
func (d *DiscoveryIRC) Serve(ctx context.Context) {
defer d.Stop()
d.localNode.waitTilCoreReady()
if err := d.init(ctx); err != nil {
d.localNode.lastError = err
panic(err)
}
d.localNode.WaitTilReady()
advertiseTicker := time.Tick(30 * time.Second)
messageTicker := time.Tick(120 * time.Second)
for {
select {
case <-d.context.Done():
return
case <-advertiseTicker:
d.check()
d.Advertise()
break
case <-messageTicker:
d.check()
d.Message()
break
}
}
}
func (d *DiscoveryIRC) check() {
if !d.connection.Connected() {
if d.retries > 10 {
panic("Too many retries to IRC")
}
time.Sleep(5 * time.Second)
d.logger.Warning("Reconnecting...")
err := d.connection.Connect(IRC_SERVER)
if err != nil {
d.logger.Error(err)
}
d.retries++
}
}
func (d *DiscoveryIRC) Stop() {
if d.connection != nil && d.connection.Connected() {
d.connection.Disconnect()
}
}
func (d *DiscoveryIRC) Advertise() {
if !d.connection.Connected() {
return
}
if d.localNode.netTableService.isEnoughPeers() {
return
}
if d.localNode.ip == "" {
d.logger.Warning("Not sending advertise message. No ip set.")
return
}
d.Send(IRC_JOIN_HANDLE, fmt.Sprintf("%s:%d", d.localNode.ip, d.localNode.port))
}
func (d *DiscoveryIRC) Message() {
if !d.connection.Connected() {
return
}
if d.message == "" {
d.logger.Debug("Not sending network message. No message set.")
return
}
d.Send(IRC_MESSAGE_HANDLE, d.message)
}
func (d *DiscoveryIRC) Send(handle string, data string) {
payload := handle + IRC_SEPERATOR + data
d.connection.Privmsg(d.channel, payload)
d.logger.Debugf("Sent IRC network: %s", payload)
}