func (s *querysrv) handleQuery(conn *net.UDPConn, addr *net.UDPAddr, buf []byte) error { var pkt discover.Query err := pkt.UnmarshalXDR(buf) if err != nil { return err } var id protocol.DeviceID copy(id[:], pkt.DeviceID) addrs, err := s.getAddresses(id) if err != nil { return err } relays, err := s.getRelays(id) if err != nil { return err } if len(addrs) > 0 { ann := discover.Announce{ Magic: discover.AnnouncementMagic, This: discover.Device{ ID: pkt.DeviceID, Addresses: addrs, Relays: relays, }, } tb, err := ann.MarshalXDR() if err != nil { return fmt.Errorf("QueryV2 response marshal: %v", err) } _, err = conn.WriteToUDP(tb, addr) if err != nil { return fmt.Errorf("QueryV2 response write: %v", err) } globalStats.Answer() } return nil }
func handleQueryV2(db *leveldb.DB, conn *net.UDPConn, addr *net.UDPAddr, buf []byte) error { var pkt discover.Query err := pkt.UnmarshalXDR(buf) if err != nil { return err } if debug { log.Printf("<- %v %#v", addr, pkt) } var id protocol.DeviceID if len(pkt.DeviceID) == 32 { // Raw node ID copy(id[:], pkt.DeviceID) } else { err = id.UnmarshalText(pkt.DeviceID) if err != nil { return err } } lock.Lock() queries++ lock.Unlock() addrs := get(db, id) now := time.Now().Unix() if len(addrs) > 0 { ann := discover.Announce{ Magic: discover.AnnouncementMagic, This: discover.Device{ ID: pkt.DeviceID, }, } for _, addr := range addrs { if now-addr.seen > cacheLimitSeconds { continue } ann.This.Addresses = append(ann.This.Addresses, discover.Address{IP: addr.ip, Port: addr.port}) } if debug { log.Printf("-> %v %#v", addr, pkt) } if len(ann.This.Addresses) == 0 { return nil } tb, err := ann.MarshalXDR() if err != nil { log.Println("QueryV2 response marshal:", err) return nil } _, err = conn.WriteToUDP(tb, addr) if err != nil { log.Println("QueryV2 response write:", err) return nil } lock.Lock() answered++ lock.Unlock() } return nil }