5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-09-19 14:59:38 +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 {
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

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
// 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)

View File

@ -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)

View File

@ -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.

View File

@ -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]++
}
}
}

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) {
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")
})
}

View File

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

View File

@ -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.

View File

@ -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.

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
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
}

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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)

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) {
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