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

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

11
	cmds "github.com/ipfs/go-ipfs/commands"
12 13 14
	repo "github.com/ipfs/go-ipfs/repo"
	config "github.com/ipfs/go-ipfs/repo/config"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
15
	iaddr "github.com/ipfs/go-ipfs/thirdparty/ipfsaddr"
16
	pstore "gx/ipfs/QmQdnfvZQuhdT93LNc5bos52wAmdr3G2p6G8teLJMEN32P/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
17
	swarm "gx/ipfs/QmVCe3SNMjkcPgnpFhZs719dheq6xE7gJwjzV7aWcUM4Ms/go-libp2p/p2p/net/swarm"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18

Jeromy's avatar
Jeromy committed
19
	mafilter "gx/ipfs/QmSMZwvs3n4GBikZ7hKzT17c3bk65FmyZo2JqtJ16swqCv/multiaddr-filter"
20
	ma "gx/ipfs/QmYzDkkgAEmrcNzFCiYo6L1dTX4EAG1gZkbtdbd9trL4vd/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22 23 24 25 26
)

type stringList struct {
	Strings []string
}

27 28 29 30
type addrMap struct {
	Addrs map[string][]string
}

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

var swarmPeersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
51
		Tagline: "List peers with open connections.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52
		ShortDescription: `
53
'ipfs swarm peers' lists the set of peers this node is connected to.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55
`,
	},
56 57
	Options: []cmds.Option{
		cmds.BoolOption("verbose", "v",
58 59
			"Also display latency along with peer information in the following form: "+
				"<peer address> <latency>"),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
	},
61
	Run: func(req cmds.Request, res cmds.Response) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62 63

		log.Debug("ipfs swarm peers")
Jeromy's avatar
Jeromy committed
64
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65
		if err != nil {
66 67
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
		if n.PeerHost == nil {
71 72
			res.SetError(errNotOnline, cmds.ErrClient)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73 74
		}

75
		verbose, _, _ := req.Option("verbose").Bool()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
		conns := n.PeerHost.Network().Conns()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77
		addrs := make([]string, len(conns))
78

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79
		for i, c := range conns {
80
			pid := c.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81
			addr := c.RemoteMultiaddr()
82 83

			if verbose {
84
				addrs[i] = fmt.Sprintf("%s/ipfs/%s %s", addr, pid.Pretty(), n.Peerstore.LatencyEWMA(pid))
85 86 87
			} else {
				addrs[i] = fmt.Sprintf("%s/ipfs/%s", addr, pid.Pretty())
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88 89
		}

90
		sort.Sort(sort.StringSlice(addrs))
91
		res.SetOutput(&stringList{addrs})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92 93 94 95
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
96
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97 98
}

99 100
var swarmAddrsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
101
		Tagline: "List known addresses. Useful for debugging.",
102
		ShortDescription: `
103
'ipfs swarm addrs' lists all addresses this node is aware of.
104 105
`,
	},
106 107 108
	Subcommands: map[string]*cmds.Command{
		"local": swarmAddrsLocalCmd,
	},
109 110
	Run: func(req cmds.Request, res cmds.Response) {

Jeromy's avatar
Jeromy committed
111
		n, err := req.InvocContext().GetNode()
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
		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))

148
			buf := new(bytes.Buffer)
149 150 151 152 153 154 155
			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")
				}
			}
156
			return buf, nil
157 158 159 160 161
		},
	},
	Type: addrMap{},
}

162 163 164 165
var swarmAddrsLocalCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List local addresses.",
		ShortDescription: `
166
'ipfs swarm addrs local' lists all local addresses the node is listening on.
167 168 169
`,
	},
	Options: []cmds.Option{
170
		cmds.BoolOption("id", "Show peer ID in addresses.").Default(false),
171 172 173
	},
	Run: func(req cmds.Request, res cmds.Response) {

Jeromy's avatar
Jeromy committed
174
		n, err := req.InvocContext().GetNode()
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
		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,
	},
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206 207
var swarmConnectCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
208
		Tagline: "Open connection to a given address.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
		ShortDescription: `
210 211 212
'ipfs swarm connect' opens a new direct connection to a peer address.

The address format is an ipfs multiaddr:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213

214
ipfs swarm connect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
215 216 217
`,
	},
	Arguments: []cmds.Argument{
218
		cmds.StringArg("address", true, true, "Address of peer to connect to."),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
	},
220
	Run: func(req cmds.Request, res cmds.Response) {
221
		ctx := req.Context()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222

Jeromy's avatar
Jeromy committed
223
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
		if err != nil {
225 226
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228
		}

229
		addrs := req.Arguments()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
		if n.PeerHost == nil {
232 233
			res.SetError(errNotOnline, cmds.ErrClient)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234 235
		}

Jeromy's avatar
Jeromy committed
236 237 238 239 240 241 242 243
		snet, ok := n.PeerHost.Network().(*swarm.Network)
		if !ok {
			res.SetError(fmt.Errorf("peerhost network was not swarm"), cmds.ErrNormal)
			return
		}

		swrm := snet.Swarm()

244
		pis, err := peersWithAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
		if err != nil {
246 247
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248 249
		}

250 251
		output := make([]string, len(pis))
		for i, pi := range pis {
Jeromy's avatar
Jeromy committed
252 253
			swrm.Backoff().Clear(pi.ID)

254
			output[i] = "connect " + pi.ID.Pretty()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255

256
			err := n.PeerHost.Connect(ctx, pi)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
			if err != nil {
258 259
				res.SetError(fmt.Errorf("%s failure: %s", output[i], err), cmds.ErrNormal)
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
			}
261
			output[i] += " success"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262 263
		}

264
		res.SetOutput(&stringList{output})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265 266 267 268
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
269
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
270 271
}

272 273
var swarmDisconnectCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
274
		Tagline: "Close connection to a given address.",
275
		ShortDescription: `
276 277
'ipfs swarm disconnect' closes a connection to a peer address. The address
format is an ipfs multiaddr:
278 279

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

281 282
The disconnect is not permanent; if ipfs needs to talk to that address later,
it will reconnect.
283 284 285
`,
	},
	Arguments: []cmds.Argument{
286
		cmds.StringArg("address", true, true, "Address of peer to disconnect from."),
287 288
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
289
		n, err := req.InvocContext().GetNode()
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
		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) {
317
					log.Debug("it's not", conn.RemoteMultiaddr(), taddr)
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
					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{},
}

342
func stringListMarshaler(res cmds.Response) (io.Reader, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343 344 345 346 347
	list, ok := res.Output().(*stringList)
	if !ok {
		return nil, errors.New("failed to cast []string")
	}

348
	buf := new(bytes.Buffer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
349
	for _, s := range list.Strings {
350 351
		buf.WriteString(s)
		buf.WriteString("\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
352
	}
353
	return buf, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
354
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
355

356
// parseAddresses is a function that takes in a slice of string peer addresses
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
357
// (multiaddr + peerid) and returns slices of multiaddrs and peerids.
358 359 360 361
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)
362
		if err != nil {
363
			return nil, cmds.ClientError("invalid peer address: " + err.Error())
364
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
365 366 367 368 369 370
	}
	return
}

// peersWithAddresses is a function that takes in a slice of string peer addresses
// (multiaddr + peerid) and returns a slice of properly constructed peers
Jeromy's avatar
Jeromy committed
371
func peersWithAddresses(addrs []string) (pis []pstore.PeerInfo, err error) {
372
	iaddrs, err := parseAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373 374 375 376
	if err != nil {
		return nil, err
	}

377
	for _, iaddr := range iaddrs {
Jeromy's avatar
Jeromy committed
378
		pis = append(pis, pstore.PeerInfo{
379 380 381
			ID:    iaddr.ID(),
			Addrs: []ma.Multiaddr{iaddr.Transport()},
		})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
382
	}
383
	return pis, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
384
}
385 386 387

var swarmFiltersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
388
		Tagline: "Manipulate address filters.",
389
		ShortDescription: `
390 391 392
'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:
393

394
Example:
395 396 397 398 399 400 401

    /ip4/192.168.0.0/ipcidr/16

Where the above is equivalent to the standard CIDR:

    192.168.0.0/16

402
Filters default to those specified under the "Swarm.AddrFilters" config key.
403 404 405 406 407 408 409
`,
	},
	Subcommands: map[string]*cmds.Command{
		"add": swarmFiltersAddCmd,
		"rm":  swarmFiltersRmCmd,
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
410
		n, err := req.InvocContext().GetNode()
411 412 413 414 415
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

416 417 418 419 420
		if n.PeerHost == nil {
			res.SetError(errNotOnline, cmds.ErrNormal)
			return
		}

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
		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{
rht's avatar
rht committed
446
		Tagline: "Add an address filter.",
447
		ShortDescription: `
448
'ipfs swarm filters add' will add an address filter to the daemons swarm.
Richard Littauer's avatar
Richard Littauer committed
449
Filters applied this way will not persist daemon reboots, to achieve that,
450 451 452 453
add your filters to the ipfs config file.
`,
	},
	Arguments: []cmds.Argument{
454
		cmds.StringArg("address", true, true, "Multiaddr to filter."),
455 456
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
457
		n, err := req.InvocContext().GetNode()
458 459 460 461 462
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

463 464 465 466 467
		if n.PeerHost == nil {
			res.SetError(errNotOnline, cmds.ErrNormal)
			return
		}

468 469 470 471 472 473
		snet, ok := n.PeerHost.Network().(*swarm.Network)
		if !ok {
			res.SetError(errors.New("failed to cast network to swarm network"), cmds.ErrNormal)
			return
		}

474 475 476 477 478
		if len(req.Arguments()) == 0 {
			res.SetError(errors.New("no filters to add"), cmds.ErrClient)
			return
		}

479 480 481 482 483 484 485 486 487 488 489 490
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

491 492 493 494 495 496 497 498 499
		for _, arg := range req.Arguments() {
			mask, err := mafilter.NewMask(arg)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			snet.Filters.AddDialFilter(mask)
		}
500 501 502 503 504 505 506 507 508

		added, err := filtersAdd(r, cfg, req.Arguments())
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return

		}

		res.SetOutput(&stringList{added})
509
	},
510 511 512 513
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
	Type: stringList{},
514 515 516 517
}

var swarmFiltersRmCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
518
		Tagline: "Remove an address filter.",
519
		ShortDescription: `
520
'ipfs swarm filters rm' will remove an address filter from the daemons swarm.
Richard Littauer's avatar
Richard Littauer committed
521
Filters removed this way will not persist daemon reboots, to achieve that,
522 523 524 525
remove your filters from the ipfs config file.
`,
	},
	Arguments: []cmds.Argument{
526
		cmds.StringArg("address", true, true, "Multiaddr filter to remove."),
527 528
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
529
		n, err := req.InvocContext().GetNode()
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
		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
		}

546 547 548 549 550 551 552 553 554 555 556 557
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		defer r.Close()
		cfg, err := r.Config()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

558 559 560 561 562
		if req.Arguments()[0] == "all" || req.Arguments()[0] == "*" {
			fs := snet.Filters.Filters()
			for _, f := range fs {
				snet.Filters.Remove(f)
			}
563 564 565 566 567 568 569 570 571

			removed, err := filtersRemoveAll(r, cfg)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			res.SetOutput(&stringList{removed})

572 573 574 575 576 577 578 579 580 581 582 583
			return
		}

		for _, arg := range req.Arguments() {
			mask, err := mafilter.NewMask(arg)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			snet.Filters.Remove(mask)
		}
584 585 586 587 588 589 590

		removed, err := filtersRemove(r, cfg, req.Arguments())

		res.SetOutput(&stringList{removed})
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
591
	},
592
	Type: stringList{},
593
}
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

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
}
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

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
}