multiaddr.go 4 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4
package multiaddr

import (
	"bytes"
5
	"encoding/json"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"fmt"
Jeromy's avatar
Jeromy committed
7
	"log"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9 10 11 12 13 14 15 16
	"strings"
)

// multiaddr is the data structure representing a Multiaddr
type multiaddr struct {
	bytes []byte
}

// NewMultiaddr parses and validates an input string, returning a *Multiaddr
Jeromy's avatar
Jeromy committed
17 18 19 20 21 22 23
func NewMultiaddr(s string) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddr on input %q: %s", s, e)
			err = fmt.Errorf("%v", e)
		}
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24 25 26 27
	b, err := stringToBytes(s)
	if err != nil {
		return nil, err
	}
28
	return &multiaddr{bytes: b}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29 30 31 32
}

// NewMultiaddrBytes initializes a Multiaddr from a byte representation.
// It validates it as an input string.
Jeromy's avatar
Jeromy committed
33 34 35 36 37 38 39 40
func NewMultiaddrBytes(b []byte) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddrBytes on input %q: %s", b, e)
			err = fmt.Errorf("%v", e)
		}
	}()

41
	if err := validateBytes(b); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43
		return nil, err
	}
44

45
	return &multiaddr{bytes: b}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48
}

// Equal tests whether two multiaddrs are equal
49
func (m *multiaddr) Equal(m2 Multiaddr) bool {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51 52 53
	return bytes.Equal(m.bytes, m2.Bytes())
}

// Bytes returns the []byte representation of this Multiaddr
54 55
//
// Do not modify the returned buffer, it may be shared.
56
func (m *multiaddr) Bytes() []byte {
57
	return m.bytes
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58 59 60
}

// String returns the string representation of a Multiaddr
61
func (m *multiaddr) String() string {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62 63
	s, err := bytesToString(m.bytes)
	if err != nil {
64
		panic(fmt.Errorf("multiaddr failed to convert back to string. corrupted? %s", err))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66 67 68
	}
	return s
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
func (m *multiaddr) MarshalBinary() ([]byte, error) {
	return m.Bytes(), nil
}

func (m *multiaddr) UnmarshalBinary(data []byte) error {
	new, err := NewMultiaddrBytes(data)
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalText() ([]byte, error) {
	return []byte(m.String()), nil
}

func (m *multiaddr) UnmarshalText(data []byte) error {
	new, err := NewMultiaddr(string(data))
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalJSON() ([]byte, error) {
	return json.Marshal(m.String())
}

func (m *multiaddr) UnmarshalJSON(data []byte) error {
	var v string
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}
	new, err := NewMultiaddr(v)
	*m = *(new.(*multiaddr))
	return err
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110
// Protocols returns the list of protocols this Multiaddr has.
// will panic in case we access bytes incorrectly.
111
func (m *multiaddr) Protocols() []Protocol {
Steven Allen's avatar
Steven Allen committed
112
	ps := make([]Protocol, 0, 8)
113
	b := m.bytes
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
	for len(b) > 0 {
115 116 117 118 119
		code, n, err := ReadVarintCode(b)
		if err != nil {
			panic(err)
		}

120
		p := ProtocolWithCode(code)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
		if p.Code == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122 123 124 125 126
			// this is a panic (and not returning err) because this should've been
			// caught on constructing the Multiaddr
			panic(fmt.Errorf("no protocol with code %d", b[0]))
		}
		ps = append(ps, p)
127 128
		b = b[n:]

129
		n, size, err := sizeForAddr(p, b)
Jeromy's avatar
Jeromy committed
130 131 132 133
		if err != nil {
			panic(err)
		}

134
		b = b[n+size:]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136 137 138 139
	}
	return ps
}

// Encapsulate wraps a given Multiaddr, returning the resulting joined Multiaddr
140
func (m *multiaddr) Encapsulate(o Multiaddr) Multiaddr {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142 143
	mb := m.bytes
	ob := o.Bytes()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144 145 146
	b := make([]byte, len(mb)+len(ob))
	copy(b, mb)
	copy(b[len(mb):], ob)
147
	return &multiaddr{bytes: b}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149 150
}

// Decapsulate unwraps Multiaddr up until the given Multiaddr is found.
151
func (m *multiaddr) Decapsulate(o Multiaddr) Multiaddr {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152 153 154 155 156 157 158
	s1 := m.String()
	s2 := o.String()
	i := strings.LastIndex(s1, s2)
	if i < 0 {
		// if multiaddr not contained, returns a copy.
		cpy := make([]byte, len(m.bytes))
		copy(cpy, m.bytes)
159
		return &multiaddr{bytes: cpy}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160 161 162 163 164 165 166 167
	}

	ma, err := NewMultiaddr(s1[:i])
	if err != nil {
		panic("Multiaddr.Decapsulate incorrect byte boundaries.")
	}
	return ma
}
168 169 170

var ErrProtocolNotFound = fmt.Errorf("protocol not found in multiaddr")

171
func (m *multiaddr) ValueForProtocol(code int) (value string, err error) {
Steven Allen's avatar
Steven Allen committed
172 173 174 175 176 177
	err = ErrProtocolNotFound
	ForEach(m, func(c Component) bool {
		if c.Protocol().Code == code {
			value = c.Value()
			err = nil
			return false
178
		}
Steven Allen's avatar
Steven Allen committed
179 180 181
		return true
	})
	return
182
}