diff --git a/cmd/genkeys/main.go b/cmd/genkeys/main.go index 7b48cdc7..cfab7ec1 100644 --- a/cmd/genkeys/main.go +++ b/cmd/genkeys/main.go @@ -51,7 +51,7 @@ func main() { for { newKey := <-newKeys - if isBetter(currentBest[:], newKey.id[:]) || len(currentBest) == 0 { + if isBetter(currentBest, newKey.id[:]) || len(currentBest) == 0 { currentBest = newKey.id for _, channel := range threadChannels { select { @@ -61,13 +61,13 @@ func main() { fmt.Println("--------------------------------------------------------------------------------") switch { case *doSig: - fmt.Println("sigPriv:", hex.EncodeToString(newKey.priv[:])) - fmt.Println("sigPub:", hex.EncodeToString(newKey.pub[:])) - fmt.Println("TreeID:", hex.EncodeToString(newKey.id[:])) + fmt.Println("sigPriv:", hex.EncodeToString(newKey.priv)) + fmt.Println("sigPub:", hex.EncodeToString(newKey.pub)) + fmt.Println("TreeID:", hex.EncodeToString(newKey.id)) default: - fmt.Println("boxPriv:", hex.EncodeToString(newKey.priv[:])) - fmt.Println("boxPub:", hex.EncodeToString(newKey.pub[:])) - fmt.Println("NodeID:", hex.EncodeToString(newKey.id[:])) + fmt.Println("boxPriv:", hex.EncodeToString(newKey.priv)) + fmt.Println("boxPub:", hex.EncodeToString(newKey.pub)) + fmt.Println("NodeID:", hex.EncodeToString(newKey.id)) fmt.Println("IP:", newKey.ip) } } @@ -76,11 +76,8 @@ func main() { func isBetter(oldID, newID []byte) bool { for idx := range oldID { - if newID[idx] > oldID[idx] { - return true - } - if newID[idx] < oldID[idx] { - return false + if newID[idx] != oldID[idx] { + return newID[idx] > oldID[idx] } } return false diff --git a/cmd/yggdrasil/main.go b/cmd/yggdrasil/main.go index 813e950b..14b76c34 100644 --- a/cmd/yggdrasil/main.go +++ b/cmd/yggdrasil/main.go @@ -60,8 +60,8 @@ func readConfig(useconf *bool, useconffile *string, normaliseconf *bool) *config // throwing everywhere when it's converting things into UTF-16 for the hell // of it - remove it and decode back down into UTF-8. This is necessary // because hjson doesn't know what to do with UTF-16 and will panic - if bytes.Compare(conf[0:2], []byte{0xFF, 0xFE}) == 0 || - bytes.Compare(conf[0:2], []byte{0xFE, 0xFF}) == 0 { + if bytes.Equal(conf[0:2], []byte{0xFF, 0xFE}) || + bytes.Equal(conf[0:2], []byte{0xFE, 0xFF}) { utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM) decoder := utf.NewDecoder() conf, err = decoder.Bytes(conf) @@ -222,7 +222,7 @@ func main() { getNodeID := func() *crypto.NodeID { if pubkey, err := hex.DecodeString(cfg.EncryptionPublicKey); err == nil { var box crypto.BoxPubKey - copy(box[:], pubkey[:]) + copy(box[:], pubkey) return crypto.GetNodeID(&box) } return nil @@ -328,9 +328,9 @@ func main() { // deferred Stop function above will run which will shut down TUN/TAP. for { select { - case _ = <-c: + case <-c: goto exit - case _ = <-r: + case <-r: if *useconffile != "" { cfg = readConfig(useconf, useconffile, normaliseconf) logger.Infoln("Reloading configuration from", *useconffile) diff --git a/cmd/yggdrasilctl/main.go b/cmd/yggdrasilctl/main.go index 697a3faa..38d935a6 100644 --- a/cmd/yggdrasilctl/main.go +++ b/cmd/yggdrasilctl/main.go @@ -78,8 +78,8 @@ func run() int { if *server == endpoint { if config, err := ioutil.ReadFile(defaults.GetDefaults().DefaultConfigFile); err == nil { - if bytes.Compare(config[0:2], []byte{0xFF, 0xFE}) == 0 || - bytes.Compare(config[0:2], []byte{0xFE, 0xFF}) == 0 { + if bytes.Equal(config[0:2], []byte{0xFF, 0xFE}) || + bytes.Equal(config[0:2], []byte{0xFE, 0xFF}) { utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM) decoder := utf.NewDecoder() config, err = decoder.Bytes(config) diff --git a/src/admin/admin.go b/src/admin/admin.go index 5ea5ab89..bdb7cd3a 100644 --- a/src/admin/admin.go +++ b/src/admin/admin.go @@ -53,7 +53,7 @@ func (a *AdminSocket) AddHandler(name string, args []string, handlerfunc func(In return nil } -// init runs the initial admin setup. +// Init runs the initial admin setup. func (a *AdminSocket) Init(c *yggdrasil.Core, state *config.NodeState, log *log.Logger, options interface{}) error { a.core = c a.log = log @@ -181,13 +181,12 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { in["uri"].(string), }, }, nil - } else { - return Info{ - "not_added": []string{ - in["uri"].(string), - }, - }, errors.New("Failed to add peer") } + return Info{ + "not_added": []string{ + in["uri"].(string), + }, + }, errors.New("Failed to add peer") }) a.AddHandler("disconnectPeer", []string{"port"}, func(in Info) (Info, error) { port, err := strconv.ParseInt(fmt.Sprint(in["port"]), 10, 64) @@ -228,6 +227,11 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { }, }, errors.New("Failed to remove peer") } + return Info{ + "not_removed": []string{ + in["uri"].(string), + }, + }, errors.New("Failed to remove peer") }) a.AddHandler("getAllowedEncryptionPublicKeys", []string{}, func(in Info) (Info, error) { return Info{"allowed_box_pubs": a.core.GetAllowedEncryptionPublicKeys()}, nil @@ -239,13 +243,12 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { in["box_pub_key"].(string), }, }, nil - } else { - return Info{ - "not_added": []string{ - in["box_pub_key"].(string), - }, - }, errors.New("Failed to add allowed key") } + return Info{ + "not_added": []string{ + in["box_pub_key"].(string), + }, + }, errors.New("Failed to add allowed key") }) a.AddHandler("removeAllowedEncryptionPublicKey", []string{"box_pub_key"}, func(in Info) (Info, error) { if a.core.RemoveAllowedEncryptionPublicKey(in["box_pub_key"].(string)) == nil { @@ -254,13 +257,12 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { in["box_pub_key"].(string), }, }, nil - } else { - return Info{ - "not_removed": []string{ - in["box_pub_key"].(string), - }, - }, errors.New("Failed to remove allowed key") } + return Info{ + "not_removed": []string{ + in["box_pub_key"].(string), + }, + }, errors.New("Failed to remove allowed key") }) a.AddHandler("dhtPing", []string{"box_pub_key", "coords", "[target]"}, func(in Info) (Info, error) { var reserr error @@ -271,10 +273,10 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { coords := util.DecodeCoordString(in["coords"].(string)) var boxPubKey crypto.BoxPubKey if b, err := hex.DecodeString(in["box_pub_key"].(string)); err == nil { - copy(boxPubKey[:], b[:]) + copy(boxPubKey[:], b) if n, err := hex.DecodeString(in["target"].(string)); err == nil { var targetNodeID crypto.NodeID - copy(targetNodeID[:], n[:]) + copy(targetNodeID[:], n) result, reserr = a.core.DHTPing(boxPubKey, coords, &targetNodeID) } else { result, reserr = a.core.DHTPing(boxPubKey, coords, nil) @@ -308,14 +310,13 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { var jsoninfo interface{} if err := json.Unmarshal(nodeinfo, &jsoninfo); err != nil { return Info{}, err - } else { - return Info{"nodeinfo": jsoninfo}, nil } + return Info{"nodeinfo": jsoninfo}, nil } else if in["box_pub_key"] == nil || in["coords"] == nil { return Info{}, errors.New("Expecting both box_pub_key and coords") } else { if b, err := hex.DecodeString(in["box_pub_key"].(string)); err == nil { - copy(boxPubKey[:], b[:]) + copy(boxPubKey[:], b) } else { return Info{}, err } @@ -326,12 +327,10 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) { var m map[string]interface{} if err = json.Unmarshal(result, &m); err == nil { return Info{"nodeinfo": m}, nil - } else { - return Info{}, err } - } else { return Info{}, err } + return Info{}, err }) } @@ -354,9 +353,8 @@ func (a *AdminSocket) Stop() error { if a.listener != nil { a.started = false return a.listener.Close() - } else { - return nil } + return nil } // listen is run by start and manages API connections. diff --git a/src/crypto/crypto.go b/src/crypto/crypto.go index 211a0e54..dd4013a7 100644 --- a/src/crypto/crypto.go +++ b/src/crypto/crypto.go @@ -272,7 +272,7 @@ func (n *BoxNonce) Increment() { n[len(n)-1] += 2 for i := len(n) - 2; i >= 0; i-- { if n[i+1] < oldNonce[i+1] { - n[i] += 1 + n[i]++ } } } diff --git a/src/tuntap/admin.go b/src/tuntap/admin.go index c7fc20b0..eb1eb69b 100644 --- a/src/tuntap/admin.go +++ b/src/tuntap/admin.go @@ -68,16 +68,14 @@ func (t *TunAdapter) SetupAdminHandlers(a *admin.AdminSocket) { a.AddHandler("addLocalSubnet", []string{"subnet"}, func(in admin.Info) (admin.Info, error) { if err := t.ckr.addLocalSubnet(in["subnet"].(string)); err == nil { return admin.Info{"added": []string{in["subnet"].(string)}}, nil - } else { - return admin.Info{"not_added": []string{in["subnet"].(string)}}, errors.New("Failed to add source subnet") } + return admin.Info{"not_added": []string{in["subnet"].(string)}}, errors.New("Failed to add source subnet") }) a.AddHandler("addRemoteSubnet", []string{"subnet", "box_pub_key"}, func(in admin.Info) (admin.Info, error) { if err := t.ckr.addRemoteSubnet(in["subnet"].(string), in["box_pub_key"].(string)); err == nil { return admin.Info{"added": []string{fmt.Sprintf("%s via %s", in["subnet"].(string), in["box_pub_key"].(string))}}, nil - } else { - return admin.Info{"not_added": []string{fmt.Sprintf("%s via %s", in["subnet"].(string), in["box_pub_key"].(string))}}, errors.New("Failed to add route") } + return admin.Info{"not_added": []string{fmt.Sprintf("%s via %s", in["subnet"].(string), in["box_pub_key"].(string))}}, errors.New("Failed to add route") }) a.AddHandler("getSourceSubnets", []string{}, func(in admin.Info) (admin.Info, error) { var subnets []string @@ -104,15 +102,13 @@ func (t *TunAdapter) SetupAdminHandlers(a *admin.AdminSocket) { a.AddHandler("removeLocalSubnet", []string{"subnet"}, func(in admin.Info) (admin.Info, error) { if err := t.ckr.removeLocalSubnet(in["subnet"].(string)); err == nil { return admin.Info{"removed": []string{in["subnet"].(string)}}, nil - } else { - return admin.Info{"not_removed": []string{in["subnet"].(string)}}, errors.New("Failed to remove source subnet") } + return admin.Info{"not_removed": []string{in["subnet"].(string)}}, errors.New("Failed to remove source subnet") }) a.AddHandler("removeRemoteSubnet", []string{"subnet", "box_pub_key"}, func(in admin.Info) (admin.Info, error) { if err := t.ckr.removeRemoteSubnet(in["subnet"].(string), in["box_pub_key"].(string)); err == nil { return admin.Info{"removed": []string{fmt.Sprintf("%s via %s", in["subnet"].(string), in["box_pub_key"].(string))}}, nil - } else { - return admin.Info{"not_removed": []string{fmt.Sprintf("%s via %s", in["subnet"].(string), in["box_pub_key"].(string))}}, errors.New("Failed to remove route") } + return admin.Info{"not_removed": []string{fmt.Sprintf("%s via %s", in["subnet"].(string), in["box_pub_key"].(string))}}, errors.New("Failed to remove route") }) } diff --git a/src/tuntap/iface.go b/src/tuntap/iface.go index 1e5902e8..bd849c7f 100644 --- a/src/tuntap/iface.go +++ b/src/tuntap/iface.go @@ -199,7 +199,6 @@ func (tun *TunAdapter) _handlePacket(recvd []byte, err error) { tc.writeFrom(nil, packet) } }) - return }() } } diff --git a/src/util/cancellation.go b/src/util/cancellation.go index 1f6d1658..7fc83147 100644 --- a/src/util/cancellation.go +++ b/src/util/cancellation.go @@ -54,12 +54,11 @@ func (c *cancellation) Cancel(err error) error { defer c.mutex.Unlock() if c.done { return c.err - } else { - c.err = err - c.done = true - close(c.cancel) - return nil } + c.err = err + c.done = true + close(c.cancel) + return nil } // Error returns the error provided to Cancel, or nil if no error has been provided. diff --git a/src/util/util.go b/src/util/util.go index c20421d5..d7a7443d 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -30,9 +30,8 @@ func UnlockThread() { func ResizeBytes(bs []byte, length int) []byte { if cap(bs) >= length { return bs[:length] - } else { - return make([]byte, length) } + return make([]byte, length) } // TimerStop stops a timer and makes sure the channel is drained, returns true if the timer was stopped before firing. diff --git a/src/yggdrasil/conn.go b/src/yggdrasil/conn.go index 4cd8b205..1b7a5a1e 100644 --- a/src/yggdrasil/conn.go +++ b/src/yggdrasil/conn.go @@ -167,10 +167,9 @@ func (c *Conn) _getDeadlineCancellation(t *time.Time) (util.Cancellation, bool) // A deadline is set, so return a Cancellation that uses it c := util.CancellationWithDeadline(c.session.cancel, *t) return c, true - } else { - // No deadline was set, so just return the existing cancellation and a dummy value - return c.session.cancel, false } + // No deadline was set, so just return the existing cancellation and a dummy value + return c.session.cancel, false } // SetReadCallback allows you to specify a function that will be called whenever @@ -225,9 +224,8 @@ func (c *Conn) readNoCopy() ([]byte, error) { case <-cancel.Finished(): if cancel.Error() == util.CancellationTimeoutError { return nil, ConnError{errors.New("read timeout"), true, false, false, 0} - } else { - return nil, ConnError{errors.New("session closed"), false, false, true, 0} } + return nil, ConnError{errors.New("session closed"), false, false, true, 0} case bs := <-c.readBuffer: return bs, nil } diff --git a/src/yggdrasil/link.go b/src/yggdrasil/link.go index 0b37eaa2..01d4aff4 100644 --- a/src/yggdrasil/link.go +++ b/src/yggdrasil/link.go @@ -253,17 +253,16 @@ func (intf *linkInterface) handler() error { <-oldIntf.closed } return nil - } else { - intf.closed = make(chan struct{}) - intf.link.interfaces[intf.info] = intf - defer func() { - intf.link.mutex.Lock() - delete(intf.link.interfaces, intf.info) - intf.link.mutex.Unlock() - close(intf.closed) - }() - intf.link.core.log.Debugln("DEBUG: registered interface for", intf.name) } + intf.closed = make(chan struct{}) + intf.link.interfaces[intf.info] = intf + defer func() { + intf.link.mutex.Lock() + delete(intf.link.interfaces, intf.info) + intf.link.mutex.Unlock() + close(intf.closed) + }() + intf.link.core.log.Debugln("DEBUG: registered interface for", intf.name) intf.link.mutex.Unlock() // Create peer shared := crypto.GetSharedKey(myLinkPriv, &meta.link) diff --git a/src/yggdrasil/nodeinfo.go b/src/yggdrasil/nodeinfo.go index fc6250d6..8d502f41 100644 --- a/src/yggdrasil/nodeinfo.go +++ b/src/yggdrasil/nodeinfo.go @@ -136,15 +136,15 @@ func (m *nodeinfo) _setNodeInfo(given interface{}, privacy bool) error { newnodeinfo[key] = value } } - if newjson, err := json.Marshal(newnodeinfo); err == nil { + newjson, err := json.Marshal(newnodeinfo) + if err == nil { if len(newjson) > 16384 { return errors.New("NodeInfo exceeds max length of 16384 bytes") } m.myNodeInfo = newjson return nil - } else { - return err } + return err } // Add nodeinfo into the cache for a node diff --git a/src/yggdrasil/switch.go b/src/yggdrasil/switch.go index 5e4d3e92..23298e76 100644 --- a/src/yggdrasil/switch.go +++ b/src/yggdrasil/switch.go @@ -532,7 +532,6 @@ func (t *switchTable) unlockedHandleMsg(msg *switchMsg, fromPort switchPort, rep if true || doUpdate { t.updater.Store(&sync.Once{}) } - return } //////////////////////////////////////////////////////////////////////////////// @@ -615,9 +614,8 @@ func (t *switchTable) portIsCloser(dest []byte, port switchPort) bool { theirDist := info.locator.dist(dest) myDist := table.self.dist(dest) return theirDist < myDist - } else { - return false } + return false } // Get the coords of a packet without decoding diff --git a/src/yggdrasil/tcp.go b/src/yggdrasil/tcp.go index 129fc0ee..2bc81de1 100644 --- a/src/yggdrasil/tcp.go +++ b/src/yggdrasil/tcp.go @@ -205,10 +205,9 @@ func (t *tcp) listener(l *TcpListener, listenaddr string) { t.mutex.Unlock() l.Listener.Close() return - } else { - t.listeners[listenaddr] = l - t.mutex.Unlock() } + t.listeners[listenaddr] = l + t.mutex.Unlock() // And here we go! defer func() { t.link.core.log.Infoln("Stopping TCP listener on:", l.Listener.Addr().String()) @@ -375,9 +374,8 @@ func (t *tcp) handler(sock net.Conn, incoming bool, options tcpOptions) { if sock, err = options.upgrade.upgrade(sock); err != nil { t.link.core.log.Errorln("TCP handler upgrade failed:", err) return - } else { - upgraded = true } + upgraded = true } stream := stream{} stream.init(sock) diff --git a/src/yggdrasil/version.go b/src/yggdrasil/version.go index 91fcc825..e0cb38e3 100644 --- a/src/yggdrasil/version.go +++ b/src/yggdrasil/version.go @@ -28,11 +28,11 @@ func version_getBaseMetadata() version_metadata { } } -// Gest the length of the metadata for this version, used to know how many bytes to read from the start of a connection. +// Gets the length of the metadata for this version, used to know how many bytes to read from the start of a connection. func version_getMetaLength() (mlen int) { mlen += 4 // meta - mlen += 1 // ver, as long as it's < 127, which it is in this version - mlen += 1 // minorVer, as long as it's < 127, which it is in this version + mlen++ // ver, as long as it's < 127, which it is in this version + mlen++ // minorVer, as long as it's < 127, which it is in this version mlen += crypto.BoxPubKeyLen // box mlen += crypto.SigPubKeyLen // sig mlen += crypto.BoxPubKeyLen // link