registry.go 1.8 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package manet

import (
	"fmt"
	"net"
	"sync"

	ma "github.com/jbenet/go-multiaddr"
)

type AddrParser func(a net.Addr) (ma.Multiaddr, error)
type MaddrParser func(ma ma.Multiaddr) (net.Addr, error)

var maddrParsers map[string]MaddrParser
var addrParsers map[string]AddrParser
var addrParsersLock sync.Mutex

Jeromy's avatar
Jeromy committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
type AddressSpec struct {
	// NetNames is an array of strings that may be returned
	// by net.Addr.Network() calls on addresses belonging to this type
	NetNames []string

	// Key is the string value for Multiaddr address keys
	Key string

	// ParseNetAddr parses a net.Addr belonging to this type into a multiaddr
	ParseNetAddr AddrParser

	// ConvertMultiaddr converts a multiaddr of this type back into a net.Addr
	ConvertMultiaddr MaddrParser

	// Protocol returns the multiaddr protocol struct for this type
	Protocol ma.Protocol
}

func RegisterAddressType(a *AddressSpec) {
Jeromy's avatar
Jeromy committed
37 38
	addrParsersLock.Lock()
	defer addrParsersLock.Unlock()
Jeromy's avatar
Jeromy committed
39 40 41 42 43
	for _, n := range a.NetNames {
		addrParsers[n] = a.ParseNetAddr
	}

	maddrParsers[a.Key] = a.ConvertMultiaddr
Jeromy's avatar
Jeromy committed
44 45 46 47 48 49
}

func init() {
	addrParsers = make(map[string]AddrParser)
	maddrParsers = make(map[string]MaddrParser)

Jeromy's avatar
Jeromy committed
50 51 52 53 54
	RegisterAddressType(tcpAddrSpec)
	RegisterAddressType(udpAddrSpec)
	RegisterAddressType(utpAddrSpec)
	RegisterAddressType(ip4AddrSpec)
	RegisterAddressType(ip6AddrSpec)
Jeromy's avatar
Jeromy committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

	addrParsers["ip+net"] = parseIpPlusNetAddr
}

func getAddrParser(net string) (AddrParser, error) {
	addrParsersLock.Lock()
	defer addrParsersLock.Unlock()

	parser, ok := addrParsers[net]
	if !ok {
		return nil, fmt.Errorf("unknown network %v", net)
	}
	return parser, nil
}

func getMaddrParser(name string) (MaddrParser, error) {
	addrParsersLock.Lock()
	defer addrParsersLock.Unlock()
	p, ok := maddrParsers[name]
	if !ok {
		return nil, fmt.Errorf("network not supported: %s", name)
	}

	return p, nil
}