2013-12-22 19:35:05 -07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"sync"
|
2014-02-17 01:23:37 -07:00
|
|
|
"time"
|
2013-12-22 19:35:05 -07:00
|
|
|
|
|
|
|
"github.com/calmh/syncthing/discover"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Node struct {
|
2014-02-17 01:23:37 -07:00
|
|
|
IP []byte
|
|
|
|
Port uint16
|
|
|
|
Updated time.Time
|
2013-12-22 19:35:05 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2014-02-17 01:23:37 -07:00
|
|
|
nodes = make(map[string]Node)
|
|
|
|
lock sync.Mutex
|
|
|
|
queries = 0
|
2013-12-22 19:35:05 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
addr, _ := net.ResolveUDPAddr("udp", ":22025")
|
|
|
|
conn, err := net.ListenUDP("udp", addr)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2014-02-17 01:23:37 -07:00
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
time.Sleep(600 * time.Second)
|
|
|
|
|
|
|
|
lock.Lock()
|
|
|
|
|
|
|
|
var deleted = 0
|
|
|
|
for id, node := range nodes {
|
|
|
|
if time.Since(node.Updated) > 60*time.Minute {
|
|
|
|
delete(nodes, id)
|
|
|
|
deleted++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
log.Printf("Expired %d nodes; %d nodes in registry; %d queries", deleted, len(nodes), queries)
|
|
|
|
queries = 0
|
|
|
|
|
|
|
|
lock.Unlock()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2013-12-22 19:35:05 -07:00
|
|
|
var buf = make([]byte, 1024)
|
|
|
|
for {
|
|
|
|
n, addr, err := conn.ReadFromUDP(buf)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
pkt, err := discover.DecodePacket(buf[:n])
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Warning:", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
switch pkt.Magic {
|
|
|
|
case 0x20121025:
|
|
|
|
// Announcement
|
2014-02-17 01:23:37 -07:00
|
|
|
lock.Lock()
|
2013-12-22 19:35:05 -07:00
|
|
|
ip := addr.IP.To4()
|
|
|
|
if ip == nil {
|
|
|
|
ip = addr.IP.To16()
|
|
|
|
}
|
2014-02-17 01:23:37 -07:00
|
|
|
node := Node{
|
|
|
|
IP: ip,
|
|
|
|
Port: uint16(pkt.Port),
|
|
|
|
Updated: time.Now(),
|
|
|
|
}
|
|
|
|
//log.Println("<-", pkt.ID, node)
|
2013-12-22 19:35:05 -07:00
|
|
|
nodes[pkt.ID] = node
|
2014-02-17 01:23:37 -07:00
|
|
|
lock.Unlock()
|
2013-12-22 19:35:05 -07:00
|
|
|
case 0x19760309:
|
|
|
|
// Query
|
2014-02-17 01:23:37 -07:00
|
|
|
lock.Lock()
|
2013-12-22 19:35:05 -07:00
|
|
|
node, ok := nodes[pkt.ID]
|
2014-02-17 01:23:37 -07:00
|
|
|
queries++
|
|
|
|
lock.Unlock()
|
2013-12-22 19:35:05 -07:00
|
|
|
if ok {
|
|
|
|
pkt := discover.Packet{
|
|
|
|
Magic: 0x20121025,
|
|
|
|
ID: pkt.ID,
|
|
|
|
Port: node.Port,
|
|
|
|
IP: node.IP,
|
|
|
|
}
|
|
|
|
_, _, err = conn.WriteMsgUDP(discover.EncodePacket(pkt), nil, addr)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Warning:", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|