Exemple #1
0
func main() {
	ip := os.Getenv("OPENSHIFT_GO_IP")
	if ip == "" {
		ip = "127.0.0.1"
	}

	port := os.Getenv("OPENSHIFT_GO_PORT")
	if port == "" {
		port = "8000"
	}

	m, err := ma.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s/ws/echo", ip, port))
	if err != nil {
		panic(err)
	}
	go serve(m, func(s string) string {
		return fmt.Sprintf("you're the \"%s\"\n", s)
	})

	m, err = ma.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s/ws/notecho", ip, port))
	if err != nil {
		panic(err)
	}
	serve(m, func(s string) string {
		return "not speaking to you\n"
	})
}
Exemple #2
0
// FromIP converts a net.IP type to a Multiaddr.
func FromIP(ip net.IP) (ma.Multiaddr, error) {
	switch {
	case ip.To4() != nil:
		return ma.NewMultiaddr("/ip4/" + ip.String())
	case ip.To16() != nil:
		return ma.NewMultiaddr("/ip6/" + ip.String())
	default:
		return nil, fmt.Errorf("incorrect network addr conversion")
	}
}
Exemple #3
0
// FromIP converts a net.IP type to a Multiaddr.
func FromIP(ip net.IP) (ma.Multiaddr, error) {
	switch {
	case ip.To4() != nil:
		return ma.NewMultiaddr("/ip4/" + ip.String())
	case ip.To16() != nil:
		return ma.NewMultiaddr("/ip6/" + ip.String())
	default:
		return nil, errIncorrectNetAddr
	}
}
Exemple #4
0
func newMultiaddr(t *testing.T, m string) ma.Multiaddr {
	maddr, err := ma.NewMultiaddr(m)
	if err != nil {
		t.Fatal("failed to construct multiaddr:", m, err)
	}
	return maddr
}
Exemple #5
0
func newAddrOrFatal(t *testing.T, s string) ma.Multiaddr {
	a, err := ma.NewMultiaddr(s)
	if err != nil {
		t.Fatal("error parsing multiaddr", err)
	}
	return a
}
Exemple #6
0
func doInterface() {
	m, _ := ma.NewMultiaddr("/ip4/127.0.0.1")
	ps := []IPeer{
		Peer{"me", [][]byte{m.Bytes()}, nil},
		Peer{"they", [][]byte{m.Bytes()}, map[string]interface{}{"age": 3}},
	}
	fmt.Printf("Encoding: %+v\n", ps)

	var buf bytes.Buffer
	mx := mux.StandardMux()
	mx.Encoder(&buf).Encode(ps)

	fmt.Printf("Encoded buffer: %s\n", buf.String())

	// Now we'll decode the []Peer structure into []IPeer slice
	// without mentioning the type Peer.
	dec := mx.Decoder(&buf)
	typ := reflect.SliceOf(reflect.TypeOf(ps[0]))
	val, err := reflectDecode(dec, typ)
	if err != nil {
		panic(err)
	}

	v := make([]IPeer, val.Len())
	for i := 0; i < val.Len(); i++ {
		v[i] = val.Index(i).Interface().(IPeer)
	}

	fmt.Printf("Decoded: %+v\n", v)
}
Exemple #7
0
func newMultiaddr(t *testing.T, s string) ma.Multiaddr {
	maddr, err := ma.NewMultiaddr(s)
	if err != nil {
		t.Fatal(err)
	}
	return maddr
}
Exemple #8
0
// Builds and returns the Multiaddrs for the swarm to listen on
func BuildSwarmAddrs(port int) [][]byte {
	// Get all interface addresses
	all, _ := manet.InterfaceMultiaddrs()

	// Filter out loopback and link-local addresses
	var filtered []ma.Multiaddr
	for _, m := range all {
		if manet.IsIPLoopback(m) {
			continue
		}
		if manet.IsIP6LinkLocal(m) {
			continue
		}
		filtered = append(filtered, m)
	}

	// Add tcp/<port> to each address and convert to byte representation
	prt, err := ma.NewMultiaddr(fmt.Sprintf("/tcp/%d", port))
	if err != nil {
		panic(err)
	}

	var listenAddrs [][]byte
	for _, a := range filtered {
		listenAddrs = append(listenAddrs, a.Encapsulate(prt).Bytes())
	}
	return listenAddrs
}
Exemple #9
0
func TestDialBadAddrs(t *testing.T) {

	m := func(s string) ma.Multiaddr {
		maddr, err := ma.NewMultiaddr(s)
		if err != nil {
			t.Fatal(err)
		}
		return maddr
	}

	ctx := context.Background()
	s := makeSwarms(ctx, t, 1)[0]

	test := func(a ma.Multiaddr) {
		p := testutil.RandPeerIDFatal(t)
		s.peers.AddAddr(p, a, peer.PermanentAddrTTL)
		if _, err := s.Dial(ctx, p); err == nil {
			t.Error("swarm should not dial: %s", m)
		}
	}

	test(m("/ip6/fe80::1"))                // link local
	test(m("/ip6/fe80::100"))              // link local
	test(m("/ip4/127.0.0.1/udp/1234/utp")) // utp
}
Exemple #10
0
func MultiaddrsFromServiceEntry(en *mdns.ServiceEntry) [][]byte {
	var addrs []ma.Multiaddr

	// Parse IP addresses
	addr, err := manet.FromIP(en.AddrV4)
	if err == nil {
		addrs = append(addrs, addr)
	}
	addr, err = manet.FromIP(en.AddrV6)
	if err == nil {
		addrs = append(addrs, addr)
	}

	var bytes [][]byte
	for _, addr := range addrs {
		// Append port
		prt, err := ma.NewMultiaddr(fmt.Sprintf("/tcp/%d", en.Port))
		if err != nil {
			continue
		}
		addr = addr.Encapsulate(prt)

		bytes = append(bytes, addr.Bytes())
	}

	return bytes
}
Exemple #11
0
func TestBadProto(t *testing.T) {
	m, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/8002")
	if err != nil {
		t.Fatal(err)
	}

	gw1 := NewGateway()
	defer gw1.Close()
	err = gw1.ListenAll([][]byte{m.Bytes()})
	if err != nil {
		t.Fatal(err)
	}
	pn1 := gw1.NewProtoNet("/foo")
	defer pn1.Close()

	gw2 := NewGateway()
	defer gw2.Close()
	pn2 := gw2.NewProtoNet("/bar")
	defer pn2.Close()

	dest := &PeerInfo{
		ID:     "bob",
		MAddrs: [][]byte{m.Bytes()},
	}

	_, err = pn2.Dial(dest)

	if err == nil {
		t.Fatal("expected error from ProtoNet.Dial, got nil")
	}
}
func MA(t *testing.T, m string) ma.Multiaddr {
	maddr, err := ma.NewMultiaddr(m)
	if err != nil {
		t.Fatal(err)
	}
	return maddr
}
Exemple #13
0
func init() {
	// initialize ZeroLocalTCPAddress
	maddr, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/0")
	if err != nil {
		panic(err)
	}
	ZeroLocalTCPAddress = maddr
}
Exemple #14
0
func address(addr string) ma.Multiaddr {
	m, err := ma.NewMultiaddr(addr)
	if err != nil {
		die(err)
	}

	return m
}
Exemple #15
0
func mkAddr(t *testing.T, s string) ma.Multiaddr {
	a, err := ma.NewMultiaddr(s)
	if err != nil {
		t.Fatal(err)
	}

	return a
}
Exemple #16
0
// FromTCPAddr converts a *net.TCPAddr type to a Multiaddr.
func FromTCPAddr(addr *net.TCPAddr) (ma.Multiaddr, error) {
	ipm, err := impl.FromIP(addr.IP)
	if err != nil {
		return nil, err
	}

	tcpm, err := ma.NewMultiaddr(fmt.Sprintf("/tcp/%d", addr.Port))
	if err != nil {
		return nil, err
	}

	return ipm.Encapsulate(tcpm), nil
}
Exemple #17
0
func setupPeer(id string, addr string) (*peer.Peer, error) {
	tcp, err := ma.NewMultiaddr(addr)
	if err != nil {
		return nil, err
	}

	mh, err := mh.FromHexString(id)
	if err != nil {
		return nil, err
	}

	p := &peer.Peer{ID: peer.ID(mh)}
	p.AddAddress(tcp)
	return p, nil
}
Exemple #18
0
// RandLocalTCPAddress returns a random multiaddr. it suppresses errors
// for nice composability-- do check the address isn't nil.
//
// Note: for real network tests, use ZeroLocalTCPAddress so the kernel
// assigns an unused TCP port. otherwise you may get clashes. This
// function remains here so that p2p/net/mock (which does not touch the
// real network) can assign different addresses to peers.
func RandLocalTCPAddress() ma.Multiaddr {

	// chances are it will work out, but it **might** fail if the port is in use
	// most ports above 10000 aren't in use by long running processes, so yay.
	// (maybe there should be a range of "loopback" ports that are guaranteed
	// to be open for the process, but naturally can only talk to self.)

	lastPort.Lock()
	if lastPort.port == 0 {
		lastPort.port = 10000 + SeededRand.Intn(50000)
	}
	port := lastPort.port
	lastPort.port++
	lastPort.Unlock()

	addr := fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port)
	maddr, _ := ma.NewMultiaddr(addr)
	return maddr
}
Exemple #19
0
// create a 'Host' with a random peer to listen on the given address
func makeDummyHost(listen string) (host.Host, error) {
	addr, err := ma.NewMultiaddr(listen)
	if err != nil {
		return nil, err
	}

	pid, err := testutil.RandPeerID()
	if err != nil {
		return nil, err
	}

	// bandwidth counter, should be optional in the future
	bwc := metrics.NewBandwidthCounter()

	// create a new swarm to be used by the service host
	netw, err := swarm.NewNetwork(context.Background(), []ma.Multiaddr{addr}, pid, pstore.NewPeerstore(), bwc)
	if err != nil {
		return nil, err
	}

	log.Printf("I am %s/ipfs/%s\n", addr, pid.Pretty())
	return bhost.New(netw), nil
}
Exemple #20
0
func (m *mapping) ExternalAddr() (ma.Multiaddr, error) {
	if time.Now().Sub(m.cacheTime) < CacheTime {
		return m.cached, nil
	}

	if m.ExternalPort() == 0 { // dont even try right now.
		return nil, ErrNoMapping
	}

	ip, err := m.nat.nat.GetExternalAddress()
	if err != nil {
		return nil, err
	}

	ipmaddr, err := manet.FromIP(ip)
	if err != nil {
		return nil, fmt.Errorf("error parsing ip")
	}

	// call m.ExternalPort again, as mapping may have changed under our feet. (tocttou)
	extport := m.ExternalPort()
	if extport == 0 {
		return nil, ErrNoMapping
	}

	tcp, err := ma.NewMultiaddr(fmt.Sprintf("/%s/%d", m.Protocol(), extport))
	if err != nil {
		return nil, err
	}

	maddr2 := ipmaddr.Encapsulate(tcp)

	m.cached = maddr2
	m.cacheTime = time.Now()
	return maddr2, nil
}
Exemple #21
0
func main() {
	listen := flag.Bool("l", false, "listen mode, for inbound connections")
	flag.Parse()

	args := flag.Args()
	if len(args) < 1 {
		flag.Usage()
		os.Exit(1)
	}

	m, err := ma.NewMultiaddr(args[0])
	if err != nil {
		log.Fatal(err)
	}

	var c manet.Conn
	if *listen {
		ln, err := manet.Listen(m)
		if err != nil {
			log.Fatal(err)
		}

		c, err = ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
	} else {
		c, err = manet.Dial(m)
		if err != nil {
			log.Fatal(err)
		}
	}

	go io.Copy(c, os.Stdin)
	io.Copy(os.Stdout, c)
}
Exemple #22
0
func main() {
	if len(os.Args) < 3 {
		fmt.Println("to run a listener, specify peer id and listen port")
		fmt.Println("to run a dialer, specify our id and port, and the target id and port")
		Fatal("must specify at least three args")
	}

	// any valid multihash works if we have the secio disabled
	id, err := peer.IDB58Decode(os.Args[1])
	if err != nil {
		Fatal(err)
	}

	addr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/" + os.Args[2])
	if err != nil {
		Fatal(err)
	}

	var dialPeer peer.ID
	var dialAddr ma.Multiaddr
	if len(os.Args) >= 5 {
		p, err := peer.IDB58Decode(os.Args[3])
		if err != nil {
			Fatal(err)
		}

		a, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/" + os.Args[4])
		if err != nil {
			Fatal(err)
		}

		dialPeer = p
		dialAddr = a
	}

	// new empty peerstore
	pstore := peerstore.NewPeerstore()
	ctx := context.Background()

	// construct ourselves a swarmy thingy
	s, err := swarm.NewSwarm(ctx, []ma.Multiaddr{addr}, id, pstore, metrics.NewBandwidthCounter())
	if err != nil {
		Fatal(err)
	}

	// if we are the dialer, do a dial!
	if dialAddr != nil {

		// add the targets address to the peerstore
		pstore.AddAddr(dialPeer, dialAddr, peer.PermanentAddrTTL)

		dialAndSend(s, dialPeer)
		return
	}

	// set a function to handle streams
	s.SetStreamHandler(func(st net.Stream) {
		out, err := ioutil.ReadAll(st)
		if err != nil {
			Fatal(err)
		}

		fmt.Println(string(out))
	})

	// just wait around
	time.Sleep(time.Hour)
}
Exemple #23
0
func TestRouter(t *testing.T) {
	m, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/8001")
	if err != nil {
		t.Fatal(err)
	}

	gw1 := NewGateway()
	defer gw1.Close()
	err = gw1.ListenAll([][]byte{m.Bytes()})
	if err != nil {
		t.Fatal(err)
	}
	pn1foo := gw1.NewProtoNet("/foo")
	defer pn1foo.Close()
	pn1bar := gw1.NewProtoNet("/bar")
	defer pn1bar.Close()

	acceptAndWrite := func(ln pnet.Listener, bts []byte) {
		s, err := ln.Accept()
		if err != nil {
			t.Fatal(err)
		}
		s.Write(bts)
		s.Close()
	}

	toWriteFoo := []byte("hello")
	go acceptAndWrite(pn1foo.Listen(), toWriteFoo)

	toWriteBar := []byte("world")
	go acceptAndWrite(pn1bar.Listen(), toWriteBar)

	gw2 := NewGateway()
	defer gw2.Close()
	pn2foo := gw2.NewProtoNet("/foo")
	defer pn2foo.Close()
	pn2bar := gw2.NewProtoNet("/bar")
	defer pn2bar.Close()

	dialAndRead := func(pn *ProtoNet, p *PeerInfo) []byte {
		s, err := pn.Dial(p)
		if err != nil {
			t.Fatal(err)
		}

		var buf bytes.Buffer
		io.Copy(&buf, s)
		return buf.Bytes()
	}

	dest := &PeerInfo{
		ID:     "bob",
		MAddrs: [][]byte{m.Bytes()},
	}

	toReadFoo := dialAndRead(pn2foo, dest)
	toReadBar := dialAndRead(pn2bar, dest)

	if !bytes.Equal(toWriteFoo, toReadFoo) {
		t.Fatalf("written %v, but read %v", toWriteFoo, toReadFoo)
	}

	if !bytes.Equal(toWriteBar, toReadBar) {
		t.Fatalf("written %v, but read %v", toWriteBar, toReadBar)
	}
}
Exemple #24
0
// TestObsAddrSet
func TestObsAddrSet(t *testing.T) {
	m := func(s string) ma.Multiaddr {
		m, err := ma.NewMultiaddr(s)
		if err != nil {
			t.Error(err)
		}
		return m
	}

	addrsMarch := func(a, b []ma.Multiaddr) bool {
		for _, aa := range a {
			found := false
			for _, bb := range b {
				if aa.Equal(bb) {
					found = true
					break
				}
			}
			if !found {
				return false
			}
		}
		return true
	}

	a1 := m("/ip4/1.2.3.4/tcp/1231")
	a2 := m("/ip4/1.2.3.4/tcp/1232")
	a3 := m("/ip4/1.2.3.4/tcp/1233")
	a4 := m("/ip4/1.2.3.4/tcp/1234")
	a5 := m("/ip4/1.2.3.4/tcp/1235")
	a6 := m("/ip4/1.2.3.6/tcp/1236")
	a7 := m("/ip4/1.2.3.7/tcp/1237")

	oas := ObservedAddrSet{}

	if !addrsMarch(oas.Addrs(), nil) {
		t.Error("addrs should be empty")
	}

	oas.Add(a1, a4)
	oas.Add(a2, a4)
	oas.Add(a3, a4)

	// these are all different so we should not yet get them.
	if !addrsMarch(oas.Addrs(), nil) {
		t.Error("addrs should _still_ be empty (once)")
	}

	// same observer, so should not yet get them.
	oas.Add(a1, a4)
	oas.Add(a2, a4)
	oas.Add(a3, a4)
	if !addrsMarch(oas.Addrs(), nil) {
		t.Error("addrs should _still_ be empty (same obs)")
	}

	// different observer, but same observer group.
	oas.Add(a1, a5)
	oas.Add(a2, a5)
	oas.Add(a3, a5)
	if !addrsMarch(oas.Addrs(), nil) {
		t.Error("addrs should _still_ be empty (same obs group)")
	}

	oas.Add(a1, a6)
	if !addrsMarch(oas.Addrs(), []ma.Multiaddr{a1}) {
		t.Error("addrs should only have a1")
	}

	oas.Add(a2, a5)
	oas.Add(a1, a5)
	oas.Add(a1, a5)
	oas.Add(a2, a6)
	oas.Add(a1, a6)
	oas.Add(a1, a6)
	oas.Add(a2, a7)
	oas.Add(a1, a7)
	oas.Add(a1, a7)
	if !addrsMarch(oas.Addrs(), []ma.Multiaddr{a1, a2}) {
		t.Error("addrs should only have a1, a2")
	}

	// change the timeout constant so we can time it out.
	oas.SetTTL(time.Millisecond * 200)
	<-time.After(time.Millisecond * 210)
	if !addrsMarch(oas.Addrs(), []ma.Multiaddr{nil}) {
		t.Error("addrs should have timed out")
	}
}
Exemple #25
0
// FromNetAddr converts a net.Addr type to a Multiaddr.
func FromNetAddr(a net.Addr) (ma.Multiaddr, error) {
	if a == nil {
		return nil, fmt.Errorf("nil multiaddr")
	}

	switch a.Network() {
	case "tcp", "tcp4", "tcp6":
		ac, ok := a.(*net.TCPAddr)
		if !ok {
			return nil, errIncorrectNetAddr
		}

		// Get IP Addr
		ipm, err := FromIP(ac.IP)
		if err != nil {
			return nil, errIncorrectNetAddr
		}

		// Get TCP Addr
		tcpm, err := ma.NewMultiaddr(fmt.Sprintf("/tcp/%d", ac.Port))
		if err != nil {
			return nil, errIncorrectNetAddr
		}

		// Encapsulate
		return ipm.Encapsulate(tcpm), nil

	case "udp", "upd4", "udp6":
		ac, ok := a.(*net.UDPAddr)
		if !ok {
			return nil, errIncorrectNetAddr
		}

		// Get IP Addr
		ipm, err := FromIP(ac.IP)
		if err != nil {
			return nil, errIncorrectNetAddr
		}

		// Get UDP Addr
		udpm, err := ma.NewMultiaddr(fmt.Sprintf("/udp/%d", ac.Port))
		if err != nil {
			return nil, errIncorrectNetAddr
		}

		// Encapsulate
		return ipm.Encapsulate(udpm), nil

	case "utp", "utp4", "utp6":
		acc, ok := a.(*utp.Addr)
		if !ok {
			return nil, errIncorrectNetAddr
		}

		// Get UDP Addr
		ac, ok := acc.Child().(*net.UDPAddr)
		if !ok {
			return nil, errIncorrectNetAddr
		}

		// Get IP Addr
		ipm, err := FromIP(ac.IP)
		if err != nil {
			return nil, errIncorrectNetAddr
		}

		// Get UDP Addr
		utpm, err := ma.NewMultiaddr(fmt.Sprintf("/udp/%d/utp", ac.Port))
		if err != nil {
			return nil, errIncorrectNetAddr
		}

		// Encapsulate
		return ipm.Encapsulate(utpm), nil

	case "ip", "ip4", "ip6":
		ac, ok := a.(*net.IPAddr)
		if !ok {
			return nil, errIncorrectNetAddr
		}
		return FromIP(ac.IP)

	case "ip+net":
		ac, ok := a.(*net.IPNet)
		if !ok {
			return nil, errIncorrectNetAddr
		}
		return FromIP(ac.IP)

	default:
		return nil, fmt.Errorf("unknown network %v", a.Network())
	}
}
Exemple #26
0
func TestFilterAddrs(t *testing.T) {

	m := func(s string) ma.Multiaddr {
		maddr, err := ma.NewMultiaddr(s)
		if err != nil {
			t.Fatal(err)
		}
		return maddr
	}

	bad := []ma.Multiaddr{
		m("/ip4/1.2.3.4/udp/1234"),           // unreliable
		m("/ip4/1.2.3.4/udp/1234/sctp/1234"), // not in manet
		m("/ip4/1.2.3.4/udp/1234/utp"),       // utp is broken
		m("/ip4/1.2.3.4/udp/1234/udt"),       // udt is broken on arm
		m("/ip6/fe80::1/tcp/0"),              // link local
		m("/ip6/fe80::100/tcp/1234"),         // link local
	}

	good := []ma.Multiaddr{
		m("/ip4/127.0.0.1/tcp/0"),
		m("/ip6/::1/tcp/0"),
	}

	goodAndBad := append(good, bad...)

	// test filters

	for _, a := range bad {
		if addrutil.AddrUsable(a, true) {
			t.Errorf("addr %s should be unusable", a)
		}
	}

	for _, a := range good {
		if !addrutil.AddrUsable(a, true) {
			t.Errorf("addr %s should be usable", a)
		}
	}

	subtestAddrsEqual(t, addrutil.FilterUsableAddrs(bad), []ma.Multiaddr{})
	subtestAddrsEqual(t, addrutil.FilterUsableAddrs(good), good)
	subtestAddrsEqual(t, addrutil.FilterUsableAddrs(goodAndBad), good)

	// now test it with swarm

	id, err := testutil.RandPeerID()
	if err != nil {
		t.Fatal(err)
	}

	ps := peer.NewPeerstore()
	ctx := context.Background()

	if _, err := NewNetwork(ctx, bad, id, ps, metrics.NewBandwidthCounter()); err == nil {
		t.Fatal("should have failed to create swarm")
	}

	if _, err := NewNetwork(ctx, goodAndBad, id, ps, metrics.NewBandwidthCounter()); err != nil {
		t.Fatal("should have succeeded in creating swarm", err)
	}
}