5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-11-22 14:10:28 +00:00

Accept some golint suggestions (#690)

* Fixed some linter issues

* Simplified isBetter method

* Accept some linter suggestions

* Fix typo

Co-authored-by: klesomik <klesomiks@gmail.com>
Co-authored-by: Neil Alexander <neilalexander@users.noreply.github.com>
This commit is contained in:
Ryan Westlund 2020-09-27 09:42:46 -04:00 committed by GitHub
parent 1492738c9e
commit d6d2d9c19a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 75 additions and 94 deletions

View File

@ -51,7 +51,7 @@ func main() {
for { for {
newKey := <-newKeys newKey := <-newKeys
if isBetter(currentBest[:], newKey.id[:]) || len(currentBest) == 0 { if isBetter(currentBest, newKey.id[:]) || len(currentBest) == 0 {
currentBest = newKey.id currentBest = newKey.id
for _, channel := range threadChannels { for _, channel := range threadChannels {
select { select {
@ -61,13 +61,13 @@ func main() {
fmt.Println("--------------------------------------------------------------------------------") fmt.Println("--------------------------------------------------------------------------------")
switch { switch {
case *doSig: case *doSig:
fmt.Println("sigPriv:", hex.EncodeToString(newKey.priv[:])) fmt.Println("sigPriv:", hex.EncodeToString(newKey.priv))
fmt.Println("sigPub:", hex.EncodeToString(newKey.pub[:])) fmt.Println("sigPub:", hex.EncodeToString(newKey.pub))
fmt.Println("TreeID:", hex.EncodeToString(newKey.id[:])) fmt.Println("TreeID:", hex.EncodeToString(newKey.id))
default: default:
fmt.Println("boxPriv:", hex.EncodeToString(newKey.priv[:])) fmt.Println("boxPriv:", hex.EncodeToString(newKey.priv))
fmt.Println("boxPub:", hex.EncodeToString(newKey.pub[:])) fmt.Println("boxPub:", hex.EncodeToString(newKey.pub))
fmt.Println("NodeID:", hex.EncodeToString(newKey.id[:])) fmt.Println("NodeID:", hex.EncodeToString(newKey.id))
fmt.Println("IP:", newKey.ip) fmt.Println("IP:", newKey.ip)
} }
} }
@ -76,11 +76,8 @@ func main() {
func isBetter(oldID, newID []byte) bool { func isBetter(oldID, newID []byte) bool {
for idx := range oldID { for idx := range oldID {
if newID[idx] > oldID[idx] { if newID[idx] != oldID[idx] {
return true return newID[idx] > oldID[idx]
}
if newID[idx] < oldID[idx] {
return false
} }
} }
return false return false

View File

@ -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 // 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 // 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 // because hjson doesn't know what to do with UTF-16 and will panic
if bytes.Compare(conf[0:2], []byte{0xFF, 0xFE}) == 0 || if bytes.Equal(conf[0:2], []byte{0xFF, 0xFE}) ||
bytes.Compare(conf[0:2], []byte{0xFE, 0xFF}) == 0 { bytes.Equal(conf[0:2], []byte{0xFE, 0xFF}) {
utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM) utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM)
decoder := utf.NewDecoder() decoder := utf.NewDecoder()
conf, err = decoder.Bytes(conf) conf, err = decoder.Bytes(conf)
@ -222,7 +222,7 @@ func main() {
getNodeID := func() *crypto.NodeID { getNodeID := func() *crypto.NodeID {
if pubkey, err := hex.DecodeString(cfg.EncryptionPublicKey); err == nil { if pubkey, err := hex.DecodeString(cfg.EncryptionPublicKey); err == nil {
var box crypto.BoxPubKey var box crypto.BoxPubKey
copy(box[:], pubkey[:]) copy(box[:], pubkey)
return crypto.GetNodeID(&box) return crypto.GetNodeID(&box)
} }
return nil return nil
@ -328,9 +328,9 @@ func main() {
// deferred Stop function above will run which will shut down TUN/TAP. // deferred Stop function above will run which will shut down TUN/TAP.
for { for {
select { select {
case _ = <-c: case <-c:
goto exit goto exit
case _ = <-r: case <-r:
if *useconffile != "" { if *useconffile != "" {
cfg = readConfig(useconf, useconffile, normaliseconf) cfg = readConfig(useconf, useconffile, normaliseconf)
logger.Infoln("Reloading configuration from", *useconffile) logger.Infoln("Reloading configuration from", *useconffile)

View File

@ -78,8 +78,8 @@ func run() int {
if *server == endpoint { if *server == endpoint {
if config, err := ioutil.ReadFile(defaults.GetDefaults().DefaultConfigFile); err == nil { if config, err := ioutil.ReadFile(defaults.GetDefaults().DefaultConfigFile); err == nil {
if bytes.Compare(config[0:2], []byte{0xFF, 0xFE}) == 0 || if bytes.Equal(config[0:2], []byte{0xFF, 0xFE}) ||
bytes.Compare(config[0:2], []byte{0xFE, 0xFF}) == 0 { bytes.Equal(config[0:2], []byte{0xFE, 0xFF}) {
utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM) utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM)
decoder := utf.NewDecoder() decoder := utf.NewDecoder()
config, err = decoder.Bytes(config) config, err = decoder.Bytes(config)

View File

@ -53,7 +53,7 @@ func (a *AdminSocket) AddHandler(name string, args []string, handlerfunc func(In
return nil 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 { func (a *AdminSocket) Init(c *yggdrasil.Core, state *config.NodeState, log *log.Logger, options interface{}) error {
a.core = c a.core = c
a.log = log a.log = log
@ -181,13 +181,12 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) {
in["uri"].(string), in["uri"].(string),
}, },
}, nil }, nil
} else { }
return Info{ return Info{
"not_added": []string{ "not_added": []string{
in["uri"].(string), in["uri"].(string),
}, },
}, errors.New("Failed to add peer") }, errors.New("Failed to add peer")
}
}) })
a.AddHandler("disconnectPeer", []string{"port"}, func(in Info) (Info, error) { a.AddHandler("disconnectPeer", []string{"port"}, func(in Info) (Info, error) {
port, err := strconv.ParseInt(fmt.Sprint(in["port"]), 10, 64) 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") }, 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) { a.AddHandler("getAllowedEncryptionPublicKeys", []string{}, func(in Info) (Info, error) {
return Info{"allowed_box_pubs": a.core.GetAllowedEncryptionPublicKeys()}, nil return Info{"allowed_box_pubs": a.core.GetAllowedEncryptionPublicKeys()}, nil
@ -239,13 +243,12 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) {
in["box_pub_key"].(string), in["box_pub_key"].(string),
}, },
}, nil }, nil
} else { }
return Info{ return Info{
"not_added": []string{ "not_added": []string{
in["box_pub_key"].(string), in["box_pub_key"].(string),
}, },
}, errors.New("Failed to add allowed key") }, errors.New("Failed to add allowed key")
}
}) })
a.AddHandler("removeAllowedEncryptionPublicKey", []string{"box_pub_key"}, func(in Info) (Info, error) { a.AddHandler("removeAllowedEncryptionPublicKey", []string{"box_pub_key"}, func(in Info) (Info, error) {
if a.core.RemoveAllowedEncryptionPublicKey(in["box_pub_key"].(string)) == nil { 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), in["box_pub_key"].(string),
}, },
}, nil }, nil
} else { }
return Info{ return Info{
"not_removed": []string{ "not_removed": []string{
in["box_pub_key"].(string), in["box_pub_key"].(string),
}, },
}, errors.New("Failed to remove allowed key") }, errors.New("Failed to remove allowed key")
}
}) })
a.AddHandler("dhtPing", []string{"box_pub_key", "coords", "[target]"}, func(in Info) (Info, error) { a.AddHandler("dhtPing", []string{"box_pub_key", "coords", "[target]"}, func(in Info) (Info, error) {
var reserr error var reserr error
@ -271,10 +273,10 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) {
coords := util.DecodeCoordString(in["coords"].(string)) coords := util.DecodeCoordString(in["coords"].(string))
var boxPubKey crypto.BoxPubKey var boxPubKey crypto.BoxPubKey
if b, err := hex.DecodeString(in["box_pub_key"].(string)); err == nil { 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 { if n, err := hex.DecodeString(in["target"].(string)); err == nil {
var targetNodeID crypto.NodeID var targetNodeID crypto.NodeID
copy(targetNodeID[:], n[:]) copy(targetNodeID[:], n)
result, reserr = a.core.DHTPing(boxPubKey, coords, &targetNodeID) result, reserr = a.core.DHTPing(boxPubKey, coords, &targetNodeID)
} else { } else {
result, reserr = a.core.DHTPing(boxPubKey, coords, nil) result, reserr = a.core.DHTPing(boxPubKey, coords, nil)
@ -308,14 +310,13 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) {
var jsoninfo interface{} var jsoninfo interface{}
if err := json.Unmarshal(nodeinfo, &jsoninfo); err != nil { if err := json.Unmarshal(nodeinfo, &jsoninfo); err != nil {
return Info{}, err return Info{}, err
} else {
return Info{"nodeinfo": jsoninfo}, nil
} }
return Info{"nodeinfo": jsoninfo}, nil
} else if in["box_pub_key"] == nil || in["coords"] == nil { } else if in["box_pub_key"] == nil || in["coords"] == nil {
return Info{}, errors.New("Expecting both box_pub_key and coords") return Info{}, errors.New("Expecting both box_pub_key and coords")
} else { } else {
if b, err := hex.DecodeString(in["box_pub_key"].(string)); err == nil { if b, err := hex.DecodeString(in["box_pub_key"].(string)); err == nil {
copy(boxPubKey[:], b[:]) copy(boxPubKey[:], b)
} else { } else {
return Info{}, err return Info{}, err
} }
@ -326,12 +327,10 @@ func (a *AdminSocket) SetupAdminHandlers(na *AdminSocket) {
var m map[string]interface{} var m map[string]interface{}
if err = json.Unmarshal(result, &m); err == nil { if err = json.Unmarshal(result, &m); err == nil {
return Info{"nodeinfo": m}, nil return Info{"nodeinfo": m}, nil
} else { }
return Info{}, err return Info{}, err
} }
} else {
return Info{}, err return Info{}, err
}
}) })
} }
@ -354,9 +353,8 @@ func (a *AdminSocket) Stop() error {
if a.listener != nil { if a.listener != nil {
a.started = false a.started = false
return a.listener.Close() return a.listener.Close()
} else {
return nil
} }
return nil
} }
// listen is run by start and manages API connections. // listen is run by start and manages API connections.

View File

@ -272,7 +272,7 @@ func (n *BoxNonce) Increment() {
n[len(n)-1] += 2 n[len(n)-1] += 2
for i := len(n) - 2; i >= 0; i-- { for i := len(n) - 2; i >= 0; i-- {
if n[i+1] < oldNonce[i+1] { if n[i+1] < oldNonce[i+1] {
n[i] += 1 n[i]++
} }
} }
} }

View File

@ -68,16 +68,14 @@ func (t *TunAdapter) SetupAdminHandlers(a *admin.AdminSocket) {
a.AddHandler("addLocalSubnet", []string{"subnet"}, func(in admin.Info) (admin.Info, error) { a.AddHandler("addLocalSubnet", []string{"subnet"}, func(in admin.Info) (admin.Info, error) {
if err := t.ckr.addLocalSubnet(in["subnet"].(string)); err == nil { if err := t.ckr.addLocalSubnet(in["subnet"].(string)); err == nil {
return admin.Info{"added": []string{in["subnet"].(string)}}, 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) { 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 { 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 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) { a.AddHandler("getSourceSubnets", []string{}, func(in admin.Info) (admin.Info, error) {
var subnets []string 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) { a.AddHandler("removeLocalSubnet", []string{"subnet"}, func(in admin.Info) (admin.Info, error) {
if err := t.ckr.removeLocalSubnet(in["subnet"].(string)); err == nil { if err := t.ckr.removeLocalSubnet(in["subnet"].(string)); err == nil {
return admin.Info{"removed": []string{in["subnet"].(string)}}, 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) { 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 { 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 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")
}) })
} }

View File

@ -199,7 +199,6 @@ func (tun *TunAdapter) _handlePacket(recvd []byte, err error) {
tc.writeFrom(nil, packet) tc.writeFrom(nil, packet)
} }
}) })
return
}() }()
} }
} }

View File

@ -54,12 +54,11 @@ func (c *cancellation) Cancel(err error) error {
defer c.mutex.Unlock() defer c.mutex.Unlock()
if c.done { if c.done {
return c.err return c.err
} else { }
c.err = err c.err = err
c.done = true c.done = true
close(c.cancel) close(c.cancel)
return nil return nil
}
} }
// Error returns the error provided to Cancel, or nil if no error has been provided. // Error returns the error provided to Cancel, or nil if no error has been provided.

View File

@ -30,9 +30,8 @@ func UnlockThread() {
func ResizeBytes(bs []byte, length int) []byte { func ResizeBytes(bs []byte, length int) []byte {
if cap(bs) >= length { if cap(bs) >= length {
return 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. // TimerStop stops a timer and makes sure the channel is drained, returns true if the timer was stopped before firing.

View File

@ -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 // A deadline is set, so return a Cancellation that uses it
c := util.CancellationWithDeadline(c.session.cancel, *t) c := util.CancellationWithDeadline(c.session.cancel, *t)
return c, true return c, true
} else { }
// No deadline was set, so just return the existing cancellation and a dummy value // No deadline was set, so just return the existing cancellation and a dummy value
return c.session.cancel, false return c.session.cancel, false
}
} }
// SetReadCallback allows you to specify a function that will be called whenever // 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(): case <-cancel.Finished():
if cancel.Error() == util.CancellationTimeoutError { if cancel.Error() == util.CancellationTimeoutError {
return nil, ConnError{errors.New("read timeout"), true, false, false, 0} 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: case bs := <-c.readBuffer:
return bs, nil return bs, nil
} }

View File

@ -253,7 +253,7 @@ func (intf *linkInterface) handler() error {
<-oldIntf.closed <-oldIntf.closed
} }
return nil return nil
} else { }
intf.closed = make(chan struct{}) intf.closed = make(chan struct{})
intf.link.interfaces[intf.info] = intf intf.link.interfaces[intf.info] = intf
defer func() { defer func() {
@ -263,7 +263,6 @@ func (intf *linkInterface) handler() error {
close(intf.closed) close(intf.closed)
}() }()
intf.link.core.log.Debugln("DEBUG: registered interface for", intf.name) intf.link.core.log.Debugln("DEBUG: registered interface for", intf.name)
}
intf.link.mutex.Unlock() intf.link.mutex.Unlock()
// Create peer // Create peer
shared := crypto.GetSharedKey(myLinkPriv, &meta.link) shared := crypto.GetSharedKey(myLinkPriv, &meta.link)

View File

@ -136,15 +136,15 @@ func (m *nodeinfo) _setNodeInfo(given interface{}, privacy bool) error {
newnodeinfo[key] = value newnodeinfo[key] = value
} }
} }
if newjson, err := json.Marshal(newnodeinfo); err == nil { newjson, err := json.Marshal(newnodeinfo)
if err == nil {
if len(newjson) > 16384 { if len(newjson) > 16384 {
return errors.New("NodeInfo exceeds max length of 16384 bytes") return errors.New("NodeInfo exceeds max length of 16384 bytes")
} }
m.myNodeInfo = newjson m.myNodeInfo = newjson
return nil return nil
} else {
return err
} }
return err
} }
// Add nodeinfo into the cache for a node // Add nodeinfo into the cache for a node

View File

@ -532,7 +532,6 @@ func (t *switchTable) unlockedHandleMsg(msg *switchMsg, fromPort switchPort, rep
if true || doUpdate { if true || doUpdate {
t.updater.Store(&sync.Once{}) t.updater.Store(&sync.Once{})
} }
return
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@ -615,9 +614,8 @@ func (t *switchTable) portIsCloser(dest []byte, port switchPort) bool {
theirDist := info.locator.dist(dest) theirDist := info.locator.dist(dest)
myDist := table.self.dist(dest) myDist := table.self.dist(dest)
return theirDist < myDist return theirDist < myDist
} else {
return false
} }
return false
} }
// Get the coords of a packet without decoding // Get the coords of a packet without decoding

View File

@ -205,10 +205,9 @@ func (t *tcp) listener(l *TcpListener, listenaddr string) {
t.mutex.Unlock() t.mutex.Unlock()
l.Listener.Close() l.Listener.Close()
return return
} else { }
t.listeners[listenaddr] = l t.listeners[listenaddr] = l
t.mutex.Unlock() t.mutex.Unlock()
}
// And here we go! // And here we go!
defer func() { defer func() {
t.link.core.log.Infoln("Stopping TCP listener on:", l.Listener.Addr().String()) 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 { if sock, err = options.upgrade.upgrade(sock); err != nil {
t.link.core.log.Errorln("TCP handler upgrade failed:", err) t.link.core.log.Errorln("TCP handler upgrade failed:", err)
return return
} else {
upgraded = true
} }
upgraded = true
} }
stream := stream{} stream := stream{}
stream.init(sock) stream.init(sock)

View File

@ -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) { func version_getMetaLength() (mlen int) {
mlen += 4 // meta mlen += 4 // meta
mlen += 1 // ver, 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 += 1 // minorVer, 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.BoxPubKeyLen // box
mlen += crypto.SigPubKeyLen // sig mlen += crypto.SigPubKeyLen // sig
mlen += crypto.BoxPubKeyLen // link mlen += crypto.BoxPubKeyLen // link