transcoders.go 8.63 KB
Newer Older
1 2 3
package multiaddr

import (
Steven Allen's avatar
Steven Allen committed
4
	"bytes"
5
	"encoding/base32"
6
	"encoding/base64"
7 8 9 10 11 12
	"encoding/binary"
	"fmt"
	"net"
	"strconv"
	"strings"

idk's avatar
idk committed
13
	mh "github.com/multiformats/go-multihash"
14 15 16 17 18
)

type Transcoder interface {
	StringToBytes(string) ([]byte, error)
	BytesToString([]byte) (string, error)
19
	ValidateBytes([]byte) error
20 21
}

22 23 24 25 26 27
func NewTranscoderFromFunctions(
	s2b func(string) ([]byte, error),
	b2s func([]byte) (string, error),
	val func([]byte) error,
) Transcoder {
	return twrp{s2b, b2s, val}
28 29
}

30 31 32
type twrp struct {
	strtobyte func(string) ([]byte, error)
	bytetostr func([]byte) (string, error)
33
	validbyte func([]byte) error
34 35 36 37 38 39 40 41 42
}

func (t twrp) StringToBytes(s string) ([]byte, error) {
	return t.strtobyte(s)
}
func (t twrp) BytesToString(b []byte) (string, error) {
	return t.bytetostr(b)
}

43 44 45 46 47 48 49
func (t twrp) ValidateBytes(b []byte) error {
	if t.validbyte == nil {
		return nil
	}
	return t.validbyte(b)
}

50 51
var TranscoderIP4 = NewTranscoderFromFunctions(ip4StB, ip4BtS, nil)
var TranscoderIP6 = NewTranscoderFromFunctions(ip6StB, ip6BtS, nil)
Steven Allen's avatar
Steven Allen committed
52
var TranscoderIP6Zone = NewTranscoderFromFunctions(ip6zoneStB, ip6zoneBtS, ip6zoneVal)
53 54 55 56 57 58 59 60 61

func ip4StB(s string) ([]byte, error) {
	i := net.ParseIP(s).To4()
	if i == nil {
		return nil, fmt.Errorf("failed to parse ip4 addr: %s", s)
	}
	return i, nil
}

mwnx's avatar
mwnx committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75
func ip6zoneStB(s string) ([]byte, error) {
	if len(s) == 0 {
		return nil, fmt.Errorf("empty ip6zone")
	}
	return []byte(s), nil
}

func ip6zoneBtS(b []byte) (string, error) {
	if len(b) == 0 {
		return "", fmt.Errorf("invalid length (should be > 0)")
	}
	return string(b), nil
}

Steven Allen's avatar
Steven Allen committed
76
func ip6zoneVal(b []byte) error {
Steven Allen's avatar
Steven Allen committed
77 78 79
	if len(b) == 0 {
		return fmt.Errorf("invalid length (should be > 0)")
	}
Steven Allen's avatar
Steven Allen committed
80 81 82 83 84 85 86
	// Not supported as this would break multiaddrs.
	if bytes.IndexByte(b, '/') >= 0 {
		return fmt.Errorf("IPv6 zone ID contains '/': %s", string(b))
	}
	return nil
}

87 88 89
func ip6StB(s string) ([]byte, error) {
	i := net.ParseIP(s).To16()
	if i == nil {
90
		return nil, fmt.Errorf("failed to parse ip6 addr: %s", s)
91 92 93 94
	}
	return i, nil
}

95 96 97 98 99 100 101 102 103 104
func ip6BtS(b []byte) (string, error) {
	ip := net.IP(b)
	if ip4 := ip.To4(); ip4 != nil {
		// Go fails to prepend the `::ffff:` part.
		return "::ffff:" + ip4.String(), nil
	}
	return ip.String(), nil
}

func ip4BtS(b []byte) (string, error) {
105 106 107
	return net.IP(b).String(), nil
}

108
var TranscoderPort = NewTranscoderFromFunctions(portStB, portBtS, nil)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

func portStB(s string) ([]byte, error) {
	i, err := strconv.Atoi(s)
	if err != nil {
		return nil, fmt.Errorf("failed to parse port addr: %s", err)
	}
	if i >= 65536 {
		return nil, fmt.Errorf("failed to parse port addr: %s", "greater than 65536")
	}
	b := make([]byte, 2)
	binary.BigEndian.PutUint16(b, uint16(i))
	return b, nil
}

func portBtS(b []byte) (string, error) {
	i := binary.BigEndian.Uint16(b)
	return strconv.Itoa(int(i)), nil
}

128
var TranscoderOnion = NewTranscoderFromFunctions(onionStB, onionBtS, nil)
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

func onionStB(s string) ([]byte, error) {
	addr := strings.Split(s, ":")
	if len(addr) != 2 {
		return nil, fmt.Errorf("failed to parse onion addr: %s does not contain a port number.", s)
	}

	// onion address without the ".onion" substring
	if len(addr[0]) != 16 {
		return nil, fmt.Errorf("failed to parse onion addr: %s not a Tor onion address.", s)
	}
	onionHostBytes, err := base32.StdEncoding.DecodeString(strings.ToUpper(addr[0]))
	if err != nil {
		return nil, fmt.Errorf("failed to decode base32 onion addr: %s %s", s, err)
	}

	// onion port number
	i, err := strconv.Atoi(addr[1])
	if err != nil {
		return nil, fmt.Errorf("failed to parse onion addr: %s", err)
	}
	if i >= 65536 {
		return nil, fmt.Errorf("failed to parse onion addr: %s", "port greater than 65536")
	}
	if i < 1 {
		return nil, fmt.Errorf("failed to parse onion addr: %s", "port less than 1")
	}

	onionPortBytes := make([]byte, 2)
	binary.BigEndian.PutUint16(onionPortBytes, uint16(i))
	bytes := []byte{}
	bytes = append(bytes, onionHostBytes...)
	bytes = append(bytes, onionPortBytes...)
	return bytes, nil
}

func onionBtS(b []byte) (string, error) {
	addr := strings.ToLower(base32.StdEncoding.EncodeToString(b[0:10]))
	port := binary.BigEndian.Uint16(b[10:12])
	return addr + ":" + strconv.Itoa(int(port)), nil
}

idk's avatar
idk committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
var TranscoderOnion3 = NewTranscoderFromFunctions(onion3StB, onion3BtS, nil)

func onion3StB(s string) ([]byte, error) {
	addr := strings.Split(s, ":")
	if len(addr) != 2 {
		return nil, fmt.Errorf("failed to parse onion addr: %s does not contain a port number.", s)
	}

	// onion address without the ".onion" substring
	if len(addr[0]) != 56 {
		return nil, fmt.Errorf("failed to parse onion addr: %s not a Tor onionv3 address. len == %d", s, len(addr[0]))
	}
	onionHostBytes, err := base32.StdEncoding.DecodeString(strings.ToUpper(addr[0]))
	if err != nil {
		return nil, fmt.Errorf("failed to decode base32 onion addr: %s %s", s, err)
	}

	// onion port number
	i, err := strconv.Atoi(addr[1])
	if err != nil {
		return nil, fmt.Errorf("failed to parse onion addr: %s", err)
	}
	if i >= 65536 {
		return nil, fmt.Errorf("failed to parse onion addr: %s", "port greater than 65536")
	}
	if i < 1 {
		return nil, fmt.Errorf("failed to parse onion addr: %s", "port less than 1")
	}

	onionPortBytes := make([]byte, 2)
	binary.BigEndian.PutUint16(onionPortBytes, uint16(i))
	bytes := []byte{}
	bytes = append(bytes, onionHostBytes[0:35]...)
	bytes = append(bytes, onionPortBytes...)
	return bytes, nil
}

func onion3BtS(b []byte) (string, error) {
	addr := strings.ToLower(base32.StdEncoding.EncodeToString(b[0:35]))
	port := binary.BigEndian.Uint16(b[35:37])
	str := addr + ":" + strconv.Itoa(int(port))
	return str, nil
}

215
var TranscoderGarlic64 = NewTranscoderFromFunctions(garlic64StB, garlic64BtS, garlic64Validate)
idk's avatar
idk committed
216

217
// i2p uses an alternate character set for base64 addresses. This returns an appropriate encoder.
218
var garlicBase64Encoding = base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~")
219 220

func garlic64StB(s string) ([]byte, error) {
221
	// i2p base64 address
idk's avatar
idk committed
222
	if len(s) < 516 || len(s) > 616 {
223
		return nil, fmt.Errorf("failed to parse garlic addr: %s not an i2p base64 address. len: %d\n", s, len(s))
idk's avatar
idk committed
224
	}
225
	garlicHostBytes, err := garlicBase64Encoding.DecodeString(s)
idk's avatar
idk committed
226
	if err != nil {
227
		return nil, fmt.Errorf("failed to decode base64 i2p addr: %s %s", s, err)
idk's avatar
idk committed
228 229
	}

230
	return garlicHostBytes, nil
231 232 233
}

func garlic64BtS(b []byte) (string, error) {
backkem's avatar
backkem committed
234
	if len(b) < 386 {
235 236 237
		return "", fmt.Errorf("failed to validate garlic addr: %s not an i2p base64 address. len: %d\n", b, len(b))
	}
	addr := garlicBase64Encoding.EncodeToString(b)
238 239 240
	return addr, nil
}

241
func garlic64Validate(b []byte) error {
idk's avatar
idk committed
242 243
	if len(b) < 386 {
		return fmt.Errorf("failed to validate garlic addr: %s not an i2p base64 address. len: %d\n", b, len(b))
idk's avatar
idk committed
244 245 246 247
	}
	return nil
}

248 249 250 251 252
var TranscoderGarlic32 = NewTranscoderFromFunctions(garlic32StB, garlic32BtS, garlic32Validate)

var garlicBase32Encoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567")

func garlic32StB(s string) ([]byte, error) {
idk's avatar
idk committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	// garlic address without the ".b32.i2p" substring
	if len(s) < 55 {
		if len(s) != 52 {
			return nil, fmt.Errorf("failed to parse garlic addr: %s not a i2p base32 address. len: %d", s, len(s))
		}
	}

	padout := func(s2 string) string {
		str := ""
		for x := 0; x < 56; x++ {
			if x < len(s) {
				str += string(s[x])
			} else {
				str += "="
			}
		}
		return str
	}

	garlicHostBytes, err := garlicBase32Encoding.DecodeString(padout(s))
273
	if err != nil {
idk's avatar
idk committed
274
		return nil, fmt.Errorf("failed to decode base32 garlic addr: %s err %s len %v", s, err, len(s))
275
	}
idk's avatar
idk committed
276
	return garlicHostBytes, nil
277 278 279
}

func garlic32BtS(b []byte) (string, error) {
idk's avatar
idk committed
280 281 282 283
	if len(b) > 35 {
		if len(b) < 32 {
			return "", fmt.Errorf("failed to validate garlic addr: %s not an i2p base32 address. len: %d\n", b, len(b))
		}
284
	}
idk's avatar
idk committed
285 286 287 288
	unpad := func(s2 string) string {
		return strings.Replace(s2, "=", "", -1)
	}
	return unpad(garlicBase32Encoding.EncodeToString(b)), nil
289 290 291
}

func garlic32Validate(b []byte) error {
idk's avatar
idk committed
292 293 294 295
	if len(b) > 35 {
		if len(b) < 32 {
			return fmt.Errorf("failed to validate garlic addr: %s not an i2p base32 address. len: %d\n", b, len(b))
		}
296 297 298 299
	}
	return nil
}

300
var TranscoderP2P = NewTranscoderFromFunctions(p2pStB, p2pBtS, p2pVal)
301

302
func p2pStB(s string) ([]byte, error) {
303 304 305
	// the address is a varint prefixed multihash string representation
	m, err := mh.FromB58String(s)
	if err != nil {
306
		return nil, fmt.Errorf("failed to parse p2p addr: %s %s", s, err)
307
	}
308
	return m, nil
309 310
}

311 312 313 314 315
func p2pVal(b []byte) error {
	_, err := mh.Cast(b)
	return err
}

316
func p2pBtS(b []byte) (string, error) {
317 318 319 320 321 322 323
	m, err := mh.Cast(b)
	if err != nil {
		return "", err
	}
	return m.B58String(), nil
}

324
var TranscoderUnix = NewTranscoderFromFunctions(unixStB, unixBtS, nil)
325 326

func unixStB(s string) ([]byte, error) {
327
	return []byte(s), nil
328 329 330
}

func unixBtS(b []byte) (string, error) {
331
	return string(b), nil
332
}