-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
356 lines (295 loc) · 7.09 KB
/
main.go
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
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
host "github.com/libp2p/go-libp2p-host"
nat "github.com/libp2p/go-libp2p-nat"
peer "github.com/libp2p/go-libp2p-peer"
pstore "github.com/libp2p/go-libp2p-peerstore"
swarm "github.com/libp2p/go-libp2p-swarm"
bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
testutil "github.com/libp2p/go-testutil"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
natinfo "github.com/whyrusleeping/natest/natinfo"
)
type NatCheck struct {
Error error
MappedAddr string
}
type HttpReport struct {
OddPortConnection string
Port443Connection string
}
type Report struct {
OutboundHTTP HttpReport
Nat NatCheck
HavePublicIP bool
Response *natinfo.NATResponse
Request *natinfo.NATRequest
TcpReuseportWorking bool
}
func (r *Report) Print() {
out, _ := json.MarshalIndent(r, "", " ")
fmt.Println(string(out))
}
type ServerInfo struct {
A pstore.PeerInfo
B pstore.PeerInfo
SeenAddr ma.Multiaddr
}
type pinfo struct {
ID string
Addrs []string
}
func (p pinfo) toPeerInfo() (pstore.PeerInfo, error) {
pid, err := peer.IDB58Decode(p.ID)
if err != nil {
return pstore.PeerInfo{}, err
}
out := pstore.PeerInfo{ID: pid}
for _, a := range p.Addrs {
addr, err := ma.NewMultiaddr(a)
if err != nil {
return pstore.PeerInfo{}, err
}
out.Addrs = append(out.Addrs, addr)
}
return out, nil
}
func getServerInfo(server string) (*ServerInfo, error) {
resp, err := http.Get(server + "/peerinfo")
if err != nil {
return nil, fmt.Errorf("could not contact natest server: %s", err)
}
defer resp.Body.Close()
var sresp struct {
A pinfo
B pinfo
SeenAddr string
}
err = json.NewDecoder(resp.Body).Decode(&sresp)
if err != nil {
return nil, err
}
pia, err := sresp.A.toPeerInfo()
if err != nil {
return nil, err
}
pib, err := sresp.B.toPeerInfo()
if err != nil {
return nil, err
}
naddr, err := net.ResolveTCPAddr("tcp", sresp.SeenAddr)
if err != nil {
return nil, err
}
maddr, err := manet.FromNetAddr(naddr)
if err != nil {
return nil, err
}
return &ServerInfo{
A: pia,
B: pib,
SeenAddr: maddr,
}, nil
}
func tryToMakeNatMapping(addr ma.Multiaddr) (ma.Multiaddr, error) {
onat := nat.DiscoverNAT()
mapping, err := onat.NewMapping(addr)
if err != nil {
return nil, err
}
extaddr, err := mapping.ExternalAddr()
if err != nil {
return nil, err
}
return extaddr, nil
}
func checkIfIpInList(addrs []ma.Multiaddr, check ma.Multiaddr) bool {
var proto int
s, err := check.ValueForProtocol(ma.P_IP4)
if err == nil {
proto = ma.P_IP4
} else {
s, err = check.ValueForProtocol(ma.P_IP6)
if err != nil {
fmt.Println("check addr didnt have any ip protocols")
}
proto = ma.P_IP6
}
for _, a := range addrs {
cs, err := a.ValueForProtocol(proto)
if err != nil {
return false
}
if s == cs {
return true
}
}
return false
}
func tryStandardHTTPS() error {
resp, err := http.Get("https://ipfs.io/version")
if err != nil {
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if !bytes.Contains(data, []byte("Protocol Version")) {
return fmt.Errorf("https connections appear to be MITMed")
}
return nil
}
func main() {
defaultServer := "http://mars.i.ipfs.team:7777"
listenF := flag.Int("l", 0, "wait for incoming connections")
natestserver := flag.String("server", defaultServer, "url of natest server")
noNat := flag.Bool("nonat", false, "don't use nat lib")
flag.Parse()
listenaddr := fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", *listenF)
report := new(Report)
defer report.Print()
sresp, err := getServerInfo(*natestserver)
if err != nil {
report.OutboundHTTP.OddPortConnection = err.Error()
err := tryStandardHTTPS()
if err != nil {
report.OutboundHTTP.Port443Connection = err.Error()
}
fmt.Fprintln(os.Stderr, "Non-standard ports being blocked")
return
}
// first host dials out and makes the initial request
ha, err := makeDummyHost("/ip4/127.0.0.1/tcp/9898")
if err != nil {
log.Fatal(err)
}
defer ha.Close()
// second host gets dialed to from the natest server
hb, err := makeDummyHost(listenaddr)
if err != nil {
log.Fatal(err)
}
defer hb.Close()
// get addrs for listener host
myaddrs, err := hb.Network().InterfaceListenAddresses()
if err != nil {
log.Fatalln(err)
}
report.HavePublicIP = checkIfIpInList(myaddrs, sresp.SeenAddr)
var extaddr ma.Multiaddr
if !*noNat {
nataddr, err := tryToMakeNatMapping(myaddrs[0])
if err != nil {
report.Nat.Error = err
fmt.Fprintln(os.Stderr, "Creation of NAT Traversal mapping failed:", err)
} else {
report.Nat.MappedAddr = nataddr.String()
extaddr = nataddr
}
}
err = hb.Connect(context.Background(), sresp.B)
if err != nil {
log.Println(err)
return
}
err = ha.Connect(context.Background(), sresp.A)
if err != nil {
log.Println(err)
return
}
var req natinfo.NATRequest
if extaddr != nil {
req.PortMapped = extaddr.String()
}
req.ListenAddr = myaddrs[0].String()
req.PeerID = hb.ID().Pretty()
report.Request = &req
resp, err := makeReq(ha, &req, sresp.A.ID)
if err != nil {
log.Println(err)
return
}
report.Response = resp
if resp.ConnectBackAddr == req.PortMapped && req.PortMapped != "" {
fmt.Fprintln(os.Stderr, "your routers upnp/NAT-PMP port mapping works!")
}
}
func pinfoFromString(target string) (*pstore.PeerInfo, error) {
if target == "" {
return nil, fmt.Errorf("please specify target")
}
ipfsaddr, err := ma.NewMultiaddr(target)
if err != nil {
return nil, err
}
pid, err := ipfsaddr.ValueForProtocol(ma.P_IPFS)
if err != nil {
return nil, err
}
peerid, err := peer.IDB58Decode(pid)
if err != nil {
return nil, err
}
tptaddr := strings.Split(ipfsaddr.String(), "/ipfs/")[0]
tptmaddr, err := ma.NewMultiaddr(tptaddr)
if err != nil {
return nil, err
}
return &pstore.PeerInfo{
ID: peerid,
Addrs: []ma.Multiaddr{tptmaddr},
}, nil
}
// 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
}
ps := pstore.NewPeerstore()
var pid peer.ID
ident, err := testutil.RandIdentity()
if err != nil {
return nil, err
}
ps.AddPrivKey(ident.ID(), ident.PrivateKey())
ps.AddPubKey(ident.ID(), ident.PublicKey())
pid = ident.ID()
ctx := context.Background()
// create a new swarm to be used by the service host
netw, err := swarm.NewNetwork(ctx, []ma.Multiaddr{addr}, pid, ps, nil)
if err != nil {
return nil, err
}
return bhost.New(netw), nil
}
func makeReq(h host.Host, req *natinfo.NATRequest, peerid peer.ID) (*natinfo.NATResponse, error) {
s, err := h.NewStream(context.Background(), peerid, "/nattest/1.0.0")
if err != nil {
log.Fatalln(err)
}
err = json.NewEncoder(s).Encode(&req)
if err != nil {
return nil, err
}
var resp natinfo.NATResponse
err = json.NewDecoder(s).Decode(&resp)
if err != nil {
return nil, err
}
return &resp, nil
}