-
Notifications
You must be signed in to change notification settings - Fork 20
/
Protocol.java
417 lines (380 loc) · 16.9 KB
/
Protocol.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package io.ipfs.multiaddr;
import io.ipfs.multibase.*;
import io.ipfs.multihash.Multihash;
import io.ipfs.cid.Cid;
import java.io.*;
import java.net.*;
import java.util.*;
public class Protocol {
public static int LENGTH_PREFIXED_VAR_SIZE = -1;
private static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
enum Type {
IP4(4, 32, "ip4"),
TCP(6, 16, "tcp"),
DCCP(33, 16, "dccp"),
IP6(41, 128, "ip6"),
IP6ZONE(42, LENGTH_PREFIXED_VAR_SIZE, "ip6zone"),
IPCIDR(43, 8, "ipcidr"),
DNS(53, LENGTH_PREFIXED_VAR_SIZE, "dns"),
DNS4(54, LENGTH_PREFIXED_VAR_SIZE, "dns4"),
DNS6(55, LENGTH_PREFIXED_VAR_SIZE, "dns6"),
DNSADDR(56, LENGTH_PREFIXED_VAR_SIZE, "dnsaddr"),
SCTP(132, 16, "sctp"),
UDP(273, 16, "udp"),
P2PWEBRTC(276, 0, "p2p-webrtc-direct"),
WEBRTC(280, 0, "webrtc"),
UTP(301, 0, "utp"),
UDT(302, 0, "udt"),
UNIX(400, LENGTH_PREFIXED_VAR_SIZE, "unix"),
P2P(421, LENGTH_PREFIXED_VAR_SIZE, "p2p"),
IPFS(421, LENGTH_PREFIXED_VAR_SIZE, "ipfs"),
HTTPS(443, 0, "https"),
ONION(444, 80, "onion"),
ONION3(445, 296, "onion3"),
GARLIC64(446, LENGTH_PREFIXED_VAR_SIZE, "garlic64"),
GARLIC32(447, LENGTH_PREFIXED_VAR_SIZE, "garlic32"),
TLS(448, 0, "tls"),
SNI(449, LENGTH_PREFIXED_VAR_SIZE, "sni"),
NOISE(454, 0, "noise"),
QUIC(460, 0, "quic"),
QUIC_V1(461, 0, "quic-v1"),
WEBTRANSPORT(465, 0, "webtransport"),
CERTHASH(466, LENGTH_PREFIXED_VAR_SIZE, "certhash"),
WS(477, 0, "ws"),
WSS(478, 0, "wss"),
P2PCIRCUIT(290, 0, "p2p-circuit"),
HTTP(480, 0, "http");
public final int code, size;
public final String name;
private final byte[] encoded;
Type(int code, int size, String name) {
this.code = code;
this.size = size;
this.name = name;
this.encoded = encode(code);
}
static byte[] encode(int code) {
byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(code)+6)/7];
putUvarint(varint, code);
return varint;
}
}
public final Type type;
public Protocol(Type type) {
this.type = type;
}
public void appendCode(OutputStream out) throws IOException {
out.write(type.encoded);
}
public boolean isTerminal() {
return type == Type.UNIX;
}
public int size() {
return type.size;
}
public String name() {
return type.name;
}
public int code() {
return type.code;
}
@Override
public String toString() {
return name();
}
public byte[] addressToBytes(String addr) {
try {
switch (type) {
case IP4:
if (! addr.matches(IPV4_REGEX))
throw new IllegalStateException("Invalid IPv4 address: " + addr);
return Inet4Address.getByName(addr).getAddress();
case IP6:
return Inet6Address.getByName(addr).getAddress();
case IPCIDR:
return new byte[] {Byte.parseByte(addr)};
case IP6ZONE:
if (addr.isEmpty())
throw new IllegalStateException("Empty IPv6 zone!");
if (addr.contains("/"))
throw new IllegalStateException("IPv6 zone ID contains '/'");
return addr.getBytes();
case TCP:
case UDP:
case DCCP:
case SCTP:
int x = Integer.parseInt(addr);
if (x > 65535)
throw new IllegalStateException("Failed to parse "+type.name+" address "+addr + " (> 65535");
return new byte[]{(byte)(x >>8), (byte)x};
case P2P:
case IPFS: {
Multihash hash;
if (addr.startsWith("Qm") || addr.startsWith("1"))
hash = Multihash.fromBase58(addr);
else {
Cid cid = Cid.decode(addr);
if (cid.codec != Cid.Codec.Libp2pKey)
throw new IllegalStateException("failed to parse p2p addr: " + addr + " has the invalid codec " + cid.codec);
hash = new Multihash(cid.getType(), cid.getHash());
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] hashBytes = hash.toBytes();
byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7];
putUvarint(varint, hashBytes.length);
bout.write(varint);
bout.write(hashBytes);
return bout.toByteArray();
}
case CERTHASH: {
byte[] raw = Multibase.decode(addr);
Multihash.deserialize(raw);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(raw.length) + 6) / 7];
putUvarint(varint, raw.length);
bout.write(varint);
bout.write(raw);
return bout.toByteArray();
}
case ONION: {
String[] split = addr.split(":");
if (split.length != 2)
throw new IllegalStateException("Onion address needs a port: " + addr);
// onion address without the ".onion" substring
if (split[0].length() != 16)
throw new IllegalStateException("failed to parse " + name() + " addr: " + addr + " not a Tor onion address.");
byte[] onionHostBytes = Multibase.decode(Multibase.Base.Base32.prefix + split[0]);
if (onionHostBytes.length != 10)
throw new IllegalStateException("Invalid onion address host: " + split[0]);
int port = Integer.parseInt(split[1]);
if (port > 65535)
throw new IllegalStateException("Port is > 65535: " + port);
if (port < 1)
throw new IllegalStateException("Port is < 1: " + port);
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(b);
dout.write(onionHostBytes);
dout.writeShort(port);
dout.flush();
return b.toByteArray();
}
case ONION3: {
String[] split = addr.split(":");
if (split.length != 2)
throw new IllegalStateException("Onion3 address needs a port: " + addr);
// onion3 address without the ".onion" substring
if (split[0].length() != 56)
throw new IllegalStateException("failed to parse " + name() + " addr: " + addr + " not a Tor onion3 address.");
byte[] onionHostBytes = Multibase.decode(Multibase.Base.Base32.prefix + split[0]);
if (onionHostBytes.length != 35)
throw new IllegalStateException("Invalid onion3 address host: " + split[0]);
int port = Integer.parseInt(split[1]);
if (port > 65535)
throw new IllegalStateException("Port is > 65535: " + port);
if (port < 1)
throw new IllegalStateException("Port is < 1: " + port);
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(b);
dout.write(onionHostBytes);
dout.writeShort(port);
dout.flush();
return b.toByteArray();
} case GARLIC32: {
// an i2p base32 address with a length of greater than 55 characters is
// using an Encrypted Leaseset v2. all other base32 addresses will always be
// exactly 52 characters
if (addr.length() < 55 && addr.length() != 52 || addr.contains(":")) {
throw new IllegalStateException(String.format("Invalid garlic addr: %s not a i2p base32 address. len: %d", addr, addr.length()));
}
while (addr.length() % 8 != 0) {
addr += "=";
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] hashBytes = Multibase.decode(Multibase.Base.Base32.prefix + addr);
byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7];
putUvarint(varint, hashBytes.length);
bout.write(varint);
bout.write(hashBytes);
return bout.toByteArray();
} case GARLIC64: {
// i2p base64 address will be between 516 and 616 characters long, depending on certificate type
if (addr.length() < 516 || addr.length() > 616 || addr.contains(":")) {
throw new IllegalStateException(String.format("Invalid garlic addr: %s not a i2p base64 address. len: %d", addr, addr.length()));
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] hashBytes = Multibase.decode(Multibase.Base.Base64.prefix + addr.replaceAll("-", "+").replaceAll("~", "/"));
byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7];
putUvarint(varint, hashBytes.length);
bout.write(varint);
bout.write(hashBytes);
return bout.toByteArray();
} case UNIX: {
if (addr.startsWith("/"))
addr = addr.substring(1);
byte[] path = addr.getBytes();
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(b);
byte[] length = new byte[(32 - Integer.numberOfLeadingZeros(path.length)+6)/7];
putUvarint(length, path.length);
dout.write(length);
dout.write(path);
dout.flush();
return b.toByteArray();
}
case DNS:
case DNS4:
case DNS6:
case DNSADDR: {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] hashBytes = addr.getBytes();
byte[] varint = new byte[(32 - Integer.numberOfLeadingZeros(hashBytes.length) + 6) / 7];
putUvarint(varint, hashBytes.length);
bout.write(varint);
bout.write(hashBytes);
return bout.toByteArray();
}
default:
throw new IllegalStateException("Unknown multiaddr type: " + type);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String readAddress(InputStream in) throws IOException {
int sizeForAddress = sizeForAddress(in);
byte[] buf;
switch (type) {
case IP4:
buf = new byte[sizeForAddress];
read(in, buf);
return Inet4Address.getByAddress(buf).toString().substring(1);
case IP6:
buf = new byte[sizeForAddress];
read(in, buf);
return Inet6Address.getByAddress(buf).toString().substring(1);
case IPCIDR:
return Integer.toString(in.read());
case IP6ZONE:
buf = new byte[sizeForAddress];
read(in, buf);
return new String(buf);
case TCP:
case UDP:
case DCCP:
case SCTP:
return Integer.toString((in.read() << 8) | (in.read()));
case IPFS:
buf = new byte[sizeForAddress];
read(in, buf);
return Multihash.deserialize(buf).toString();
case CERTHASH:
buf = new byte[sizeForAddress];
read(in, buf);
return Multibase.encode(Multibase.Base.Base64Url, buf);
case ONION: {
byte[] host = new byte[10];
read(in, host);
String port = Integer.toString((in.read() << 8) | (in.read()));
return Multibase.encode(Multibase.Base.Base32, host).substring(1) + ":" + port;
} case ONION3: {
byte[] host = new byte[35];
read(in, host);
String port = Integer.toString((in.read() << 8) | (in.read()));
return Multibase.encode(Multibase.Base.Base32, host).substring(1) + ":" + port;
} case GARLIC32: {
buf = new byte[sizeForAddress];
read(in, buf);
// an i2p base32 for an Encrypted Leaseset v2 will be at least 35 bytes
// long other than that, they will be exactly 32 bytes
if (buf.length < 35 && buf.length != 32) {
throw new IllegalStateException("Invalid garlic addr length: " + buf.length);
}
return Multibase.encode(Multibase.Base.Base32, buf).substring(1);
} case GARLIC64: {
buf = new byte[sizeForAddress];
read(in, buf);
// A garlic64 address will always be greater than 386 bytes
if (buf.length < 386) {
throw new IllegalStateException("Invalid garlic64 addr length: " + buf.length);
}
return Multibase.encode(Multibase.Base.Base64, buf).substring(1).replaceAll("\\+", "-").replaceAll("/", "~");
} case UNIX:
buf = new byte[sizeForAddress];
read(in, buf);
return new String(buf);
case DNS:
case DNS4:
case DNS6:
case DNSADDR:
buf = new byte[sizeForAddress];
read(in, buf);
return new String(buf);
}
throw new IllegalStateException("Unimplemented protocol type: "+type.name);
}
private static void read(InputStream in, byte[] b) throws IOException {
read(in, b, 0, b.length);
}
private static void read(InputStream in, byte[] b, int offset, int len) throws IOException {
int total=0, r=0;
while (total < len && r != -1) {
r = in.read(b, offset + total, len - total);
if (r >=0)
total += r;
}
}
public int sizeForAddress(InputStream in) throws IOException {
if (type.size > 0)
return type.size/8;
if (type.size == 0)
return 0;
return (int)readVarint(in);
}
static int putUvarint(byte[] buf, long x) {
int i = 0;
while (x >= 0x80) {
buf[i] = (byte)(x | 0x80);
x >>= 7;
i++;
}
buf[i] = (byte)x;
return i + 1;
}
static long readVarint(InputStream in) throws IOException {
long x = 0;
int s=0;
for (int i=0; i < 10; i++) {
int b = in.read();
if (b == -1)
throw new EOFException();
if (b < 0x80) {
if (i > 9 || i == 9 && b > 1) {
throw new IllegalStateException("Overflow reading varint" +(-(i + 1)));
}
return x | (((long)b) << s);
}
x |= ((long)b & 0x7f) << s;
s += 7;
}
throw new IllegalStateException("Varint too long!");
}
private static Map<String, Protocol> byName = new HashMap<>();
private static Map<Integer, Protocol> byCode = new HashMap<>();
static {
for (Protocol.Type t: Protocol.Type.values()) {
Protocol p = new Protocol(t);
byName.put(p.name(), p);
byCode.put(p.code(), p);
}
}
public static Protocol get(String name) {
if (byName.containsKey(name))
return byName.get(name);
throw new IllegalStateException("No protocol with name: "+name);
}
public static Protocol get(int code) {
if (byCode.containsKey(code))
return byCode.get(code);
throw new IllegalStateException("No protocol with code: "+code);
}
}