-
Notifications
You must be signed in to change notification settings - Fork 0
/
swarm.go
513 lines (445 loc) · 12.2 KB
/
swarm.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
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package commands
import (
"bytes"
"errors"
"fmt"
"io"
"path"
"sort"
cmds "github.com/ipfs/go-ipfs/commands"
swarm "github.com/ipfs/go-ipfs/p2p/net/swarm"
peer "github.com/ipfs/go-ipfs/p2p/peer"
iaddr "github.com/ipfs/go-ipfs/util/ipfsaddr"
ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
mafilter "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/whyrusleeping/multiaddr-filter"
context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
)
type stringList struct {
Strings []string
}
type addrMap struct {
Addrs map[string][]string
}
var SwarmCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "swarm inspection tool",
Synopsis: `
ipfs swarm peers - List peers with open connections
ipfs swarm addrs - List known addresses. Useful to debug.
ipfs swarm connect <address> - Open connection to a given address
ipfs swarm disconnect <address> - Close connection to a given address
ipfs swarm filters - Manipulate filters addresses
`,
ShortDescription: `
ipfs swarm is a tool to manipulate the network swarm. The swarm is the
component that opens, listens for, and maintains connections to other
ipfs peers in the internet.
`,
},
Subcommands: map[string]*cmds.Command{
"peers": swarmPeersCmd,
"addrs": swarmAddrsCmd,
"connect": swarmConnectCmd,
"disconnect": swarmDisconnectCmd,
"filters": swarmFiltersCmd,
},
}
var swarmPeersCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List peers with open connections",
ShortDescription: `
ipfs swarm peers lists the set of peers this node is connected to.
`,
},
Run: func(req cmds.Request, res cmds.Response) {
log.Debug("ipfs swarm peers")
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrClient)
return
}
conns := n.PeerHost.Network().Conns()
addrs := make([]string, len(conns))
for i, c := range conns {
pid := c.RemotePeer()
addr := c.RemoteMultiaddr()
addrs[i] = fmt.Sprintf("%s/ipfs/%s", addr, pid.Pretty())
}
sort.Sort(sort.StringSlice(addrs))
res.SetOutput(&stringList{addrs})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: stringListMarshaler,
},
Type: stringList{},
}
var swarmAddrsCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List known addresses. Useful to debug.",
ShortDescription: `
ipfs swarm addrs lists all addresses this node is aware of.
`,
},
Subcommands: map[string]*cmds.Command{
"local": swarmAddrsLocalCmd,
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrClient)
return
}
addrs := make(map[string][]string)
ps := n.PeerHost.Network().Peerstore()
for _, p := range ps.Peers() {
s := p.Pretty()
for _, a := range ps.Addrs(p) {
addrs[s] = append(addrs[s], a.String())
}
sort.Sort(sort.StringSlice(addrs[s]))
}
res.SetOutput(&addrMap{Addrs: addrs})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
m, ok := res.Output().(*addrMap)
if !ok {
return nil, errors.New("failed to cast map[string]string")
}
// sort the ids first
ids := make([]string, 0, len(m.Addrs))
for p := range m.Addrs {
ids = append(ids, p)
}
sort.Sort(sort.StringSlice(ids))
buf := new(bytes.Buffer)
for _, p := range ids {
paddrs := m.Addrs[p]
buf.WriteString(fmt.Sprintf("%s (%d)\n", p, len(paddrs)))
for _, addr := range paddrs {
buf.WriteString("\t" + addr + "\n")
}
}
return buf, nil
},
},
Type: addrMap{},
}
var swarmAddrsLocalCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List local addresses.",
ShortDescription: `
ipfs swarm addrs local lists all local addresses the node is listening on.
`,
},
Options: []cmds.Option{
cmds.BoolOption("id", "Show peer ID in addresses"),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrClient)
return
}
showid, _, _ := req.Option("id").Bool()
id := n.Identity.Pretty()
var addrs []string
for _, addr := range n.PeerHost.Addrs() {
saddr := addr.String()
if showid {
saddr = path.Join(saddr, "ipfs", id)
}
addrs = append(addrs, saddr)
}
sort.Sort(sort.StringSlice(addrs))
res.SetOutput(&stringList{addrs})
},
Type: stringList{},
Marshalers: cmds.MarshalerMap{
cmds.Text: stringListMarshaler,
},
}
var swarmConnectCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Open connection to a given address",
ShortDescription: `
'ipfs swarm connect' opens a new direct connection to a peer address.
The address format is an ipfs multiaddr:
ipfs swarm connect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("address", true, true, "address of peer to connect to").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
ctx := context.TODO()
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
addrs := req.Arguments()
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrClient)
return
}
pis, err := peersWithAddresses(addrs)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
output := make([]string, len(pis))
for i, pi := range pis {
output[i] = "connect " + pi.ID.Pretty()
err := n.PeerHost.Connect(ctx, pi)
if err != nil {
output[i] += " failure: " + err.Error()
} else {
output[i] += " success"
}
}
res.SetOutput(&stringList{output})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: stringListMarshaler,
},
Type: stringList{},
}
var swarmDisconnectCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Close connection to a given address",
ShortDescription: `
'ipfs swarm disconnect' closes a connection to a peer address. The address format
is an ipfs multiaddr:
ipfs swarm disconnect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("address", true, true, "address of peer to connect to").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
addrs := req.Arguments()
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrClient)
return
}
iaddrs, err := parseAddresses(addrs)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
output := make([]string, len(iaddrs))
for i, addr := range iaddrs {
taddr := addr.Transport()
output[i] = "disconnect " + addr.ID().Pretty()
found := false
conns := n.PeerHost.Network().ConnsToPeer(addr.ID())
for _, conn := range conns {
if !conn.RemoteMultiaddr().Equal(taddr) {
log.Debug("it's not", conn.RemoteMultiaddr(), taddr)
continue
}
if err := conn.Close(); err != nil {
output[i] += " failure: " + err.Error()
} else {
output[i] += " success"
}
found = true
break
}
if !found {
output[i] += " failure: conn not found"
}
}
res.SetOutput(&stringList{output})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: stringListMarshaler,
},
Type: stringList{},
}
func stringListMarshaler(res cmds.Response) (io.Reader, error) {
list, ok := res.Output().(*stringList)
if !ok {
return nil, errors.New("failed to cast []string")
}
buf := new(bytes.Buffer)
for _, s := range list.Strings {
buf.WriteString(s)
buf.WriteString("\n")
}
return buf, nil
}
// parseAddresses is a function that takes in a slice of string peer addresses
// (multiaddr + peerid) and returns slices of multiaddrs and peerids.
func parseAddresses(addrs []string) (iaddrs []iaddr.IPFSAddr, err error) {
iaddrs = make([]iaddr.IPFSAddr, len(addrs))
for i, saddr := range addrs {
iaddrs[i], err = iaddr.ParseString(saddr)
if err != nil {
return nil, cmds.ClientError("invalid peer address: " + err.Error())
}
}
return
}
// peersWithAddresses is a function that takes in a slice of string peer addresses
// (multiaddr + peerid) and returns a slice of properly constructed peers
func peersWithAddresses(addrs []string) (pis []peer.PeerInfo, err error) {
iaddrs, err := parseAddresses(addrs)
if err != nil {
return nil, err
}
for _, iaddr := range iaddrs {
pis = append(pis, peer.PeerInfo{
ID: iaddr.ID(),
Addrs: []ma.Multiaddr{iaddr.Transport()},
})
}
return pis, nil
}
var swarmFiltersCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Manipulate address filters",
ShortDescription: `
'ipfs swarm filters' will list out currently applied filters. Its subcommands can be used
to add or remove said filters. Filters are specified using the multiaddr-filter format:
example:
/ip4/192.168.0.0/ipcidr/16
Where the above is equivalent to the standard CIDR:
192.168.0.0/16
Filters default to those specified under the "Swarm.AddrFilters" config key.
`,
},
Subcommands: map[string]*cmds.Command{
"add": swarmFiltersAddCmd,
"rm": swarmFiltersRmCmd,
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrNormal)
return
}
snet, ok := n.PeerHost.Network().(*swarm.Network)
if !ok {
res.SetError(errors.New("failed to cast network to swarm network"), cmds.ErrNormal)
return
}
var output []string
for _, f := range snet.Filters.Filters() {
s, err := mafilter.ConvertIPNet(f)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
output = append(output, s)
}
res.SetOutput(&stringList{output})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: stringListMarshaler,
},
Type: stringList{},
}
var swarmFiltersAddCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "add an address filter",
ShortDescription: `
'ipfs swarm filters add' will add an address filter to the daemons swarm.
Filters applied this way will not persist daemon reboots, to acheive that,
add your filters to the ipfs config file.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("address", true, true, "multiaddr to filter").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrNormal)
return
}
snet, ok := n.PeerHost.Network().(*swarm.Network)
if !ok {
res.SetError(errors.New("failed to cast network to swarm network"), cmds.ErrNormal)
return
}
for _, arg := range req.Arguments() {
mask, err := mafilter.NewMask(arg)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
snet.Filters.AddDialFilter(mask)
}
},
}
var swarmFiltersRmCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "remove an address filter",
ShortDescription: `
'ipfs swarm filters rm' will remove an address filter from the daemons swarm.
Filters removed this way will not persist daemon reboots, to acheive that,
remove your filters from the ipfs config file.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("address", true, true, "multiaddr filter to remove").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if n.PeerHost == nil {
res.SetError(errNotOnline, cmds.ErrNormal)
return
}
snet, ok := n.PeerHost.Network().(*swarm.Network)
if !ok {
res.SetError(errors.New("failed to cast network to swarm network"), cmds.ErrNormal)
return
}
if req.Arguments()[0] == "all" || req.Arguments()[0] == "*" {
fs := snet.Filters.Filters()
for _, f := range fs {
snet.Filters.Remove(f)
}
return
}
for _, arg := range req.Arguments() {
mask, err := mafilter.NewMask(arg)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
snet.Filters.Remove(mask)
}
},
}