Files
weave/utils.go
T

134 lines
2.7 KiB
Go

package weave
import (
"crypto/rand"
"fmt"
"log"
"net"
"strconv"
)
func checkFatal(e error) {
if e != nil {
log.Fatal(e)
}
}
func checkWarn(e error) {
if e != nil {
log.Println(e)
}
}
func PosixError(err error) error {
if err == nil {
return nil
}
operr, ok := err.(*net.OpError)
if !ok {
return nil
}
return operr.Err
}
func (mtbe MsgTooBigError) Error() string {
return fmt.Sprint("Msg too big error. PMTU is ", mtbe.PMTU)
}
func (ftbe FrameTooBigError) Error() string {
return fmt.Sprint("Frame too big error. Effective PMTU is ", ftbe.EPMTU)
}
func (upe UnknownPeersError) Error() string {
return fmt.Sprint("Reference to unknown peers")
}
func (nce NameCollisionError) Error() string {
return fmt.Sprint("Multiple peers found with same name: ", nce.Name)
}
func (packet UDPPacket) String() string {
return fmt.Sprintf("UDP Packet\n name: %s\n sender: %v\n payload: % X", packet.Name, packet.Sender, packet.Packet)
}
func Concat(elems ...[]byte) []byte {
res := []byte{}
for _, e := range elems {
res = append(res, e...)
}
return res
}
func randUint64() (r uint64) {
buf := make([]byte, 8)
_, err := rand.Read(buf)
checkFatal(err)
for _, v := range buf {
r <<= 8
r |= uint64(v)
}
return
}
func macint(mac net.HardwareAddr) (r uint64) {
for _, b := range mac {
r <<= 8
r |= uint64(b)
}
return
}
func intmac(key uint64) (r net.HardwareAddr) {
r = make([]byte, 6)
for i := 5; i >= 0; i-- {
r[i] = byte(key)
key >>= 8
}
return
}
type ListOfPeers []*Peer
func (lop ListOfPeers) Len() int {
return len(lop)
}
func (lop ListOfPeers) Swap(i, j int) {
lop[i], lop[j] = lop[j], lop[i]
}
func (lop ListOfPeers) Less(i, j int) bool {
return lop[i].Name < lop[i].Name
}
func StripPortFromAddr(address string) string {
// If we've been given a port number, take it off
if addrHost, _, err := net.SplitHostPort(address); err == nil {
return addrHost
}
return address
}
// given an address like '1.2.3.4:567', return the host and port number,
// given an address like '1.2.3.4', return the host and weave's standard port number
func ExtractHostPort(address string) (host string, port int, err error) {
if host, port, err := net.SplitHostPort(address); err == nil {
if portnum, err := strconv.Atoi(port); err == nil {
return host, portnum, nil
} else {
return host, 0, err
}
} else {
return host, Port, nil
}
}
// given an address like '1.2.3.4:567', return the address if it has a port,
// otherwise return the address with weave's standard port number
func NormalisePeerAddr(peerAddr string) string {
_, _, err := net.SplitHostPort(peerAddr)
if err == nil {
return peerAddr
} else {
return fmt.Sprintf("%s:%d", peerAddr, Port)
}
}