swarm.go 17.9 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package commands

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"fmt"
6
	"io"
7
	"path"
8
	"sort"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9

Overbool's avatar
Overbool committed
10 11 12 13
	commands "github.com/ipfs/go-ipfs/commands"
	cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
	repo "github.com/ipfs/go-ipfs/repo"
	fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14

Steven Allen's avatar
Steven Allen committed
15 16
	inet "gx/ipfs/QmPtFaR7BWHLAjSwLh9kXcyrgTzDpuhcWLkx8ioa9RMYnx/go-libp2p-net"
	swarm "gx/ipfs/QmQdLXW5JTSsrVb3ZpnpbASRwyM8CcE4XcM5nPbN19dWLr/go-libp2p-swarm"
Steven Allen's avatar
Steven Allen committed
17
	ma "gx/ipfs/QmRKLtwMw131aK7ugC3G7ybpumMz78YrJe5dzneyindvG1/go-multiaddr"
Jeromy's avatar
Jeromy committed
18
	mafilter "gx/ipfs/QmSMZwvs3n4GBikZ7hKzT17c3bk65FmyZo2JqtJ16swqCv/multiaddr-filter"
Steven Allen's avatar
Steven Allen committed
19 20 21 22
	iaddr "gx/ipfs/QmSzEdVLaPMQGAKKGo4mKjsbWcfz6w8CoDjhRPxdk7xYdn/go-ipfs-addr"
	peer "gx/ipfs/QmY5Grm8pJdiSSVsYxx4uNRgweY72EmYwuSDbRnbFok3iY/go-libp2p-peer"
	config "gx/ipfs/QmYyzmMnhNTtoXx5ttgUaRdHHckYnQWjPL98hgLAR2QLDD/go-ipfs-config"
	pstore "gx/ipfs/QmZ9zH2FnLcxv1xyzFeUpDUeo55xEhZQHgveZijcxr7TLj/go-libp2p-peerstore"
23
	cmds "gx/ipfs/QmaAP56JAwdjwisPTu4yx17whcjTr6y5JCSCF77Y1rahWV/go-ipfs-cmds"
Overbool's avatar
Overbool committed
24
	cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26 27 28 29 30
)

type stringList struct {
	Strings []string
}

31 32 33 34
type addrMap struct {
	Addrs map[string][]string
}

35
var SwarmCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
36
	Helptext: cmdkit.HelpText{
37
		Tagline: "Interact with the swarm.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
		ShortDescription: `
39
'ipfs swarm' is a tool to manipulate the network swarm. The swarm is the
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41 42 43 44
component that opens, listens for, and maintains connections to other
ipfs peers in the internet.
`,
	},
	Subcommands: map[string]*cmds.Command{
45
		"addrs":      swarmAddrsCmd,
46 47
		"connect":    swarmConnectCmd,
		"disconnect": swarmDisconnectCmd,
48
		"filters":    swarmFiltersCmd,
Richard Littauer's avatar
Richard Littauer committed
49
		"peers":      swarmPeersCmd,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51 52
	},
}

Kejie Zhang's avatar
Kejie Zhang committed
53 54 55 56 57 58 59
const (
	swarmVerboseOptionName   = "verbose"
	swarmStreamsOptionName   = "streams"
	swarmLatencyOptionName   = "latency"
	swarmDirectionOptionName = "direction"
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
var swarmPeersCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
61
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
62
		Tagline: "List peers with open connections.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
		ShortDescription: `
64
'ipfs swarm peers' lists the set of peers this node is connected to.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
67
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
68 69 70 71
		cmdkit.BoolOption(swarmVerboseOptionName, "v", "display all extra information"),
		cmdkit.BoolOption(swarmStreamsOptionName, "Also list information about open streams for each peer"),
		cmdkit.BoolOption(swarmLatencyOptionName, "Also list information about latency to each peer"),
		cmdkit.BoolOption(swarmDirectionOptionName, "Also list information about the direction of connection"),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
72
	},
73
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
74
		api, err := cmdenv.GetApi(env)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
		if err != nil {
76
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78
		}

Kejie Zhang's avatar
Kejie Zhang committed
79 80 81 82
		verbose, _ := req.Options[swarmVerboseOptionName].(bool)
		latency, _ := req.Options[swarmLatencyOptionName].(bool)
		streams, _ := req.Options[swarmStreamsOptionName].(bool)
		direction, _ := req.Options[swarmDirectionOptionName].(bool)
83

84 85 86 87 88
		conns, err := api.Swarm().Peers(req.Context)
		if err != nil {
			return err
		}

89 90 91
		var out connInfos
		for _, c := range conns {
			ci := connInfo{
92 93
				Addr: c.Address().String(),
				Peer: c.ID().Pretty(),
94 95
			}

96
			if verbose || direction {
97
				// set direction
98
				ci.Direction = c.Direction()
99
			}
100

101
			if verbose || latency {
102
				lat, err := c.Latency()
103 104 105 106
				if err != nil {
					return err
				}

107 108 109 110 111
				if lat == 0 {
					ci.Latency = "n/a"
				} else {
					ci.Latency = lat.String()
				}
112 113
			}
			if verbose || streams {
114
				strs, err := c.Streams()
115 116 117
				if err != nil {
					return err
				}
118 119

				for _, s := range strs {
120
					ci.Streams = append(ci.Streams, streamInfo{Protocol: string(s)})
121
				}
122
			}
123 124
			sort.Sort(&ci)
			out.Peers = append(out.Peers, ci)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125 126
		}

127
		sort.Sort(&out)
128
		return cmds.EmitOnce(res, &out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
	},
130
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
131
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, ci *connInfos) error {
132
			pipfs := ma.ProtocolWithCode(ma.P_IPFS).Name
133
			for _, info := range ci.Peers {
134
				fmt.Fprintf(w, "%s/%s/%s", info.Addr, pipfs, info.Peer)
135
				if info.Latency != "" {
136
					fmt.Fprintf(w, " %s", info.Latency)
137
				}
138

139
				if info.Direction != inet.DirUnknown {
140
					fmt.Fprintf(w, " %s", directionString(info.Direction))
141
				}
142
				fmt.Fprintln(w)
143 144 145 146 147 148

				for _, s := range info.Streams {
					if s.Protocol == "" {
						s.Protocol = "<no protocol name>"
					}

149
					fmt.Fprintf(w, "  %s\n", s.Protocol)
150 151 152
				}
			}

153 154
			return nil
		}),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155
	},
156 157 158 159 160 161 162 163
	Type: connInfos{},
}

type streamInfo struct {
	Protocol string
}

type connInfo struct {
164 165 166 167 168 169
	Addr      string
	Peer      string
	Latency   string
	Muxer     string
	Direction inet.Direction
	Streams   []streamInfo
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
}

func (ci *connInfo) Less(i, j int) bool {
	return ci.Streams[i].Protocol < ci.Streams[j].Protocol
}

func (ci *connInfo) Len() int {
	return len(ci.Streams)
}

func (ci *connInfo) Swap(i, j int) {
	ci.Streams[i], ci.Streams[j] = ci.Streams[j], ci.Streams[i]
}

type connInfos struct {
	Peers []connInfo
}

func (ci connInfos) Less(i, j int) bool {
	return ci.Peers[i].Addr < ci.Peers[j].Addr
}

func (ci connInfos) Len() int {
	return len(ci.Peers)
}

func (ci connInfos) Swap(i, j int) {
	ci.Peers[i], ci.Peers[j] = ci.Peers[j], ci.Peers[i]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198 199
}

200 201 202 203 204 205 206 207
// directionString transfers to string
func directionString(d inet.Direction) string {
	switch d {
	case inet.DirInbound:
		return "inbound"
	case inet.DirOutbound:
		return "outbound"
	default:
208
		return ""
209 210 211
	}
}

212
var swarmAddrsCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
213
	Helptext: cmdkit.HelpText{
214
		Tagline: "List known addresses. Useful for debugging.",
215
		ShortDescription: `
216
'ipfs swarm addrs' lists all addresses this node is aware of.
217 218
`,
	},
219
	Subcommands: map[string]*cmds.Command{
220 221
		"local":  swarmAddrsLocalCmd,
		"listen": swarmAddrsListenCmd,
222
	},
223
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
224
		api, err := cmdenv.GetApi(env)
225
		if err != nil {
226
			return err
227 228
		}

229 230
		addrs, err := api.Swarm().KnownAddrs(req.Context)
		if err != nil {
231
			return err
232 233
		}

234 235
		out := make(map[string][]string)
		for p, paddrs := range addrs {
236
			s := p.Pretty()
237 238
			for _, a := range paddrs {
				out[s] = append(out[s], a.String())
239 240 241
			}
		}

242
		return cmds.EmitOnce(res, &addrMap{Addrs: out})
243
	},
244
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
245
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, am *addrMap) error {
246
			// sort the ids first
Overbool's avatar
Overbool committed
247 248
			ids := make([]string, 0, len(am.Addrs))
			for p := range am.Addrs {
249 250 251 252 253
				ids = append(ids, p)
			}
			sort.Sort(sort.StringSlice(ids))

			for _, p := range ids {
Overbool's avatar
Overbool committed
254
				paddrs := am.Addrs[p]
255
				fmt.Fprintf(w, "%s (%d)\n", p, len(paddrs))
256
				for _, addr := range paddrs {
257
					fmt.Fprintf(w, "\t"+addr+"\n")
258 259
				}
			}
Overbool's avatar
Overbool committed
260

261 262
			return nil
		}),
263 264 265 266
	},
	Type: addrMap{},
}

267
var swarmAddrsLocalCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
268
	Helptext: cmdkit.HelpText{
269 270
		Tagline: "List local addresses.",
		ShortDescription: `
271
'ipfs swarm addrs local' lists all local listening addresses announced to the network.
272 273
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
274
	Options: []cmdkit.Option{
275
		cmdkit.BoolOption("id", "Show peer ID in addresses."),
276
	},
277
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
278
		api, err := cmdenv.GetApi(env)
279
		if err != nil {
280
			return err
281 282
		}

283 284 285
		showid, _ := req.Options["id"].(bool)
		self, err := api.Key().Self(req.Context)
		if err != nil {
286
			return err
287 288
		}

289 290 291 292
		maddrs, err := api.Swarm().LocalAddrs(req.Context)
		if err != nil {
			return err
		}
293 294

		var addrs []string
295
		for _, addr := range maddrs {
296 297
			saddr := addr.String()
			if showid {
298
				saddr = path.Join(saddr, "ipfs", self.ID().Pretty())
299 300 301 302
			}
			addrs = append(addrs, saddr)
		}
		sort.Sort(sort.StringSlice(addrs))
303
		return cmds.EmitOnce(res, &stringList{addrs})
304 305
	},
	Type: stringList{},
306
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
307
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
308 309 310 311
	},
}

var swarmAddrsListenCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
312
	Helptext: cmdkit.HelpText{
313 314 315 316 317
		Tagline: "List interface listening addresses.",
		ShortDescription: `
'ipfs swarm addrs listen' lists all interface addresses the node is listening on.
`,
	},
318
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
319
		api, err := cmdenv.GetApi(env)
320
		if err != nil {
321
			return err
322 323 324
		}

		var addrs []string
325
		maddrs, err := api.Swarm().ListenAddrs(req.Context)
326
		if err != nil {
327
			return err
328 329 330 331 332 333
		}

		for _, addr := range maddrs {
			addrs = append(addrs, addr.String())
		}
		sort.Sort(sort.StringSlice(addrs))
334

335
		return cmds.EmitOnce(res, &stringList{addrs})
336 337
	},
	Type: stringList{},
338
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
339
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
340 341 342
	},
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343
var swarmConnectCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
344
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
345
		Tagline: "Open connection to a given address.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
346
		ShortDescription: `
347 348
'ipfs swarm connect' opens a new direct connection to a peer address.

349
The address format is an IPFS multiaddr:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350

351
ipfs swarm connect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
352 353
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
354 355
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("address", true, true, "Address of peer to connect to.").EnableStdin(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
356
	},
357
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
358
		api, err := cmdenv.GetApi(env)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
359
		if err != nil {
360
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
361 362
		}

363
		addrs := req.Arguments
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
364

365
		pis, err := peersWithAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
366
		if err != nil {
367
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368 369
		}

370 371 372
		output := make([]string, len(pis))
		for i, pi := range pis {
			output[i] = "connect " + pi.ID.Pretty()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373

374
			err := api.Swarm().Connect(req.Context, pi)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
375
			if err != nil {
376
				return fmt.Errorf("%s failure: %s", output[i], err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
377
			}
378
			output[i] += " success"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
379 380
		}

381
		return cmds.EmitOnce(res, &stringList{output})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
382
	},
383
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
384
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
385
	},
386
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
387 388
}

389
var swarmDisconnectCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
390
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
391
		Tagline: "Close connection to a given address.",
392
		ShortDescription: `
393
'ipfs swarm disconnect' closes a connection to a peer address. The address
394
format is an IPFS multiaddr:
395 396

ipfs swarm disconnect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
397

398 399
The disconnect is not permanent; if ipfs needs to talk to that address later,
it will reconnect.
400 401
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
402 403
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("address", true, true, "Address of peer to disconnect from.").EnableStdin(),
404
	},
405
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
406
		api, err := cmdenv.GetApi(env)
407
		if err != nil {
408
			return err
409 410
		}

411
		iaddrs, err := parseAddresses(req.Arguments)
412
		if err != nil {
413
			return err
414 415 416 417
		}

		output := make([]string, len(iaddrs))
		for i, addr := range iaddrs {
418
			output[i] = "disconnect " + addr.ID().Pretty()
419

420 421
			if err := api.Swarm().Disconnect(req.Context, addr.Multiaddr()); err != nil {
				output[i] += " failure: " + err.Error()
422
			} else {
423
				output[i] += " success"
424 425
			}
		}
426
		return cmds.EmitOnce(res, &stringList{output})
427
	},
428
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
429
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
430 431 432 433
	},
	Type: stringList{},
}

434
// parseAddresses is a function that takes in a slice of string peer addresses
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
435
// (multiaddr + peerid) and returns slices of multiaddrs and peerids.
436 437 438 439
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)
440
		if err != nil {
441
			return nil, cmds.ClientError("invalid peer address: " + err.Error())
442
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
443 444 445 446 447 448
	}
	return
}

// peersWithAddresses is a function that takes in a slice of string peer addresses
// (multiaddr + peerid) and returns a slice of properly constructed peers
449
func peersWithAddresses(addrs []string) ([]pstore.PeerInfo, error) {
450
	iaddrs, err := parseAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
451 452 453 454
	if err != nil {
		return nil, err
	}

455
	peers := make(map[peer.ID][]ma.Multiaddr, len(iaddrs))
456
	for _, iaddr := range iaddrs {
457 458 459 460 461 462 463 464 465 466
		id := iaddr.ID()
		current, ok := peers[id]
		if tpt := iaddr.Transport(); tpt != nil {
			peers[id] = append(current, tpt)
		} else if !ok {
			peers[id] = nil
		}
	}
	pis := make([]pstore.PeerInfo, 0, len(peers))
	for id, maddrs := range peers {
Jeromy's avatar
Jeromy committed
467
		pis = append(pis, pstore.PeerInfo{
468 469
			ID:    id,
			Addrs: maddrs,
470
		})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
471
	}
472
	return pis, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
473
}
474 475

var swarmFiltersCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
476
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
477
		Tagline: "Manipulate address filters.",
478
		ShortDescription: `
479 480 481
'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:
482

483
Example:
484 485 486 487 488 489 490

    /ip4/192.168.0.0/ipcidr/16

Where the above is equivalent to the standard CIDR:

    192.168.0.0/16

491
Filters default to those specified under the "Swarm.AddrFilters" config key.
492 493 494 495 496 497
`,
	},
	Subcommands: map[string]*cmds.Command{
		"add": swarmFiltersAddCmd,
		"rm":  swarmFiltersRmCmd,
	},
498 499
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		n, err := cmdenv.GetNode(env)
500
		if err != nil {
501
			return err
502 503
		}

504
		if n.PeerHost == nil {
505
			return ErrNotOnline
506 507
		}

Steven Allen's avatar
Steven Allen committed
508 509
		// FIXME(steb)
		swrm, ok := n.PeerHost.Network().(*swarm.Swarm)
510
		if !ok {
511
			return errors.New("failed to cast network to swarm network")
512 513 514
		}

		var output []string
Steven Allen's avatar
Steven Allen committed
515
		for _, f := range swrm.Filters.Filters() {
516 517
			s, err := mafilter.ConvertIPNet(f)
			if err != nil {
518
				return err
519 520 521
			}
			output = append(output, s)
		}
522
		return cmds.EmitOnce(res, &stringList{output})
523
	},
524
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
525
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
526 527 528 529 530
	},
	Type: stringList{},
}

var swarmFiltersAddCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
531
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
532
		Tagline: "Add an address filter.",
533
		ShortDescription: `
534
'ipfs swarm filters add' will add an address filter to the daemons swarm.
Richard Littauer's avatar
Richard Littauer committed
535
Filters applied this way will not persist daemon reboots, to achieve that,
536 537 538
add your filters to the ipfs config file.
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
539 540
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("address", true, true, "Multiaddr to filter.").EnableStdin(),
541
	},
542 543
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		n, err := cmdenv.GetNode(env)
544
		if err != nil {
545
			return err
546 547
		}

548
		if n.PeerHost == nil {
549
			return ErrNotOnline
550 551
		}

Steven Allen's avatar
Steven Allen committed
552 553
		// FIXME(steb)
		swrm, ok := n.PeerHost.Network().(*swarm.Swarm)
554
		if !ok {
555
			return errors.New("failed to cast network to swarm network")
556 557
		}

558 559
		if len(req.Arguments) == 0 {
			return errors.New("no filters to add")
560 561
		}

562
		r, err := fsrepo.Open(env.(*commands.Context).ConfigRoot)
563
		if err != nil {
564
			return err
565 566 567 568
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
569
			return err
570 571
		}

572
		for _, arg := range req.Arguments {
573 574
			mask, err := mafilter.NewMask(arg)
			if err != nil {
575
				return err
576 577
			}

Steven Allen's avatar
Steven Allen committed
578
			swrm.Filters.AddDialFilter(mask)
579
		}
580

581
		added, err := filtersAdd(r, cfg, req.Arguments)
582
		if err != nil {
583
			return err
584 585
		}

586
		return cmds.EmitOnce(res, &stringList{added})
587
	},
588
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
589
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
590 591
	},
	Type: stringList{},
592 593 594
}

var swarmFiltersRmCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
595
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
596
		Tagline: "Remove an address filter.",
597
		ShortDescription: `
598
'ipfs swarm filters rm' will remove an address filter from the daemons swarm.
Richard Littauer's avatar
Richard Littauer committed
599
Filters removed this way will not persist daemon reboots, to achieve that,
600 601 602
remove your filters from the ipfs config file.
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
603 604
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("address", true, true, "Multiaddr filter to remove.").EnableStdin(),
605
	},
606 607
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		n, err := cmdenv.GetNode(env)
608
		if err != nil {
609
			return err
610 611 612
		}

		if n.PeerHost == nil {
613
			return ErrNotOnline
614 615
		}

Steven Allen's avatar
Steven Allen committed
616
		swrm, ok := n.PeerHost.Network().(*swarm.Swarm)
617
		if !ok {
618
			return errors.New("failed to cast network to swarm network")
619 620
		}

621
		r, err := fsrepo.Open(env.(*commands.Context).ConfigRoot)
622
		if err != nil {
623
			return err
624 625 626 627
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
628
			return err
629 630
		}

631
		if req.Arguments[0] == "all" || req.Arguments[0] == "*" {
Steven Allen's avatar
Steven Allen committed
632
			fs := swrm.Filters.Filters()
633
			for _, f := range fs {
Steven Allen's avatar
Steven Allen committed
634
				swrm.Filters.Remove(f)
635
			}
636 637 638

			removed, err := filtersRemoveAll(r, cfg)
			if err != nil {
639
				return err
640 641
			}

642
			return cmds.EmitOnce(res, &stringList{removed})
643 644
		}

645
		for _, arg := range req.Arguments {
646 647
			mask, err := mafilter.NewMask(arg)
			if err != nil {
648
				return err
649 650
			}

Steven Allen's avatar
Steven Allen committed
651
			swrm.Filters.Remove(mask)
652
		}
653

654
		removed, err := filtersRemove(r, cfg, req.Arguments)
655
		if err != nil {
656
			return err
657
		}
658

659
		return cmds.EmitOnce(res, &stringList{removed})
660
	},
661
	Encoders: cmds.EncoderMap{
Overbool's avatar
Overbool committed
662
		cmds.Text: cmds.MakeTypedEncoder(stringListEncoder),
663
	},
664
	Type: stringList{},
665
}
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

func filtersAdd(r repo.Repo, cfg *config.Config, filters []string) ([]string, error) {
	addedMap := map[string]struct{}{}
	addedList := make([]string, 0, len(filters))

	// re-add cfg swarm filters to rm dupes
	oldFilters := cfg.Swarm.AddrFilters
	cfg.Swarm.AddrFilters = nil

	// add new filters
	for _, filter := range filters {
		if _, found := addedMap[filter]; found {
			continue
		}

		cfg.Swarm.AddrFilters = append(cfg.Swarm.AddrFilters, filter)
		addedList = append(addedList, filter)
		addedMap[filter] = struct{}{}
	}

	// add back original filters. in this order so that we output them.
	for _, filter := range oldFilters {
		if _, found := addedMap[filter]; found {
			continue
		}

		cfg.Swarm.AddrFilters = append(cfg.Swarm.AddrFilters, filter)
		addedMap[filter] = struct{}{}
	}

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return addedList, nil
}
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

func filtersRemoveAll(r repo.Repo, cfg *config.Config) ([]string, error) {
	removed := cfg.Swarm.AddrFilters
	cfg.Swarm.AddrFilters = nil

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return removed, nil
}

func filtersRemove(r repo.Repo, cfg *config.Config, toRemoveFilters []string) ([]string, error) {
	removed := make([]string, 0, len(toRemoveFilters))
	keep := make([]string, 0, len(cfg.Swarm.AddrFilters))

	oldFilters := cfg.Swarm.AddrFilters

	for _, oldFilter := range oldFilters {
		found := false
		for _, toRemoveFilter := range toRemoveFilters {
			if oldFilter == toRemoveFilter {
				found = true
				removed = append(removed, toRemoveFilter)
				break
			}
		}

		if !found {
			keep = append(keep, oldFilter)
		}
	}
	cfg.Swarm.AddrFilters = keep

	if err := r.SetConfig(cfg); err != nil {
		return nil, err
	}

	return removed, nil
}