swarm.go 12.1 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
	iaddr "github.com/ipfs/go-ipfs/thirdparty/ipfsaddr"
Jeromy's avatar
Jeromy committed
13
	swarm "gx/ipfs/QmUHrgorZ1F9yGkgF2His5fsQ9xtCzjdsPGjizmcEW94i5/go-libp2p/p2p/net/swarm"
14
	peer "gx/ipfs/QmZpD74pUj6vuxTp1o6LhA3JavC2Bvh9fsWPPVvHnD9sE7/go-libp2p-peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15

16 17
	mafilter "gx/ipfs/QmUaRHbB7pUwj5mS9BS4CMvBiW48MpaH2wbGxeWfFhhHxK/multiaddr-filter"
	ma "gx/ipfs/QmYzDkkgAEmrcNzFCiYo6L1dTX4EAG1gZkbtdbd9trL4vd/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19 20 21 22 23
)

type stringList struct {
	Strings []string
}

24 25 26 27
type addrMap struct {
	Addrs map[string][]string
}

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

var swarmPeersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
48
		Tagline: "List peers with open connections.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49
		ShortDescription: `
50
'ipfs swarm peers' lists the set of peers this node is connected to.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51 52
`,
	},
53
	Run: func(req cmds.Request, res cmds.Response) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55

		log.Debug("ipfs swarm peers")
Jeromy's avatar
Jeromy committed
56
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
		if err != nil {
58 59
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62
		if n.PeerHost == nil {
63 64
			res.SetError(errNotOnline, cmds.ErrClient)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
		conns := n.PeerHost.Network().Conns()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69
		addrs := make([]string, len(conns))
		for i, c := range conns {
70
			pid := c.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71
			addr := c.RemoteMultiaddr()
72
			addrs[i] = fmt.Sprintf("%s/ipfs/%s", addr, pid.Pretty())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73 74
		}

75
		sort.Sort(sort.StringSlice(addrs))
76
		res.SetOutput(&stringList{addrs})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78 79 80
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
81
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82 83
}

84 85
var swarmAddrsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
86
		Tagline: "List known addresses. Useful for debugging.",
87
		ShortDescription: `
88
'ipfs swarm addrs' lists all addresses this node is aware of.
89 90
`,
	},
91 92 93
	Subcommands: map[string]*cmds.Command{
		"local": swarmAddrsLocalCmd,
	},
94 95
	Run: func(req cmds.Request, res cmds.Response) {

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

133
			buf := new(bytes.Buffer)
134 135 136 137 138 139 140
			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")
				}
			}
141
			return buf, nil
142 143 144 145 146
		},
	},
	Type: addrMap{},
}

147 148 149 150
var swarmAddrsLocalCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List local addresses.",
		ShortDescription: `
151
'ipfs swarm addrs local' lists all local addresses the node is listening on.
152 153 154
`,
	},
	Options: []cmds.Option{
155
		cmds.BoolOption("id", "Show peer ID in addresses.").Default(false),
156 157 158
	},
	Run: func(req cmds.Request, res cmds.Response) {

Jeromy's avatar
Jeromy committed
159
		n, err := req.InvocContext().GetNode()
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
		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
191 192
var swarmConnectCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
193
		Tagline: "Open connection to a given address.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
		ShortDescription: `
195 196 197
'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
198

199
ipfs swarm connect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200 201 202
`,
	},
	Arguments: []cmds.Argument{
203
		cmds.StringArg("address", true, true, "Address of peer to connect to.").EnableStdin(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
	},
205
	Run: func(req cmds.Request, res cmds.Response) {
206
		ctx := req.Context()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207

Jeromy's avatar
Jeromy committed
208
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
		if err != nil {
210 211
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212 213
		}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
		if n.PeerHost == nil {
217 218
			res.SetError(errNotOnline, cmds.ErrClient)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219 220
		}

221
		pis, err := peersWithAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222
		if err != nil {
223 224
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225 226
		}

227 228 229
		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
230

231
			err := n.PeerHost.Connect(ctx, pi)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232
			if err != nil {
233 234
				res.SetError(fmt.Errorf("%s failure: %s", output[i], err), cmds.ErrNormal)
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
			}
236
			output[i] += " success"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237 238
		}

239
		res.SetOutput(&stringList{output})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240 241 242 243
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
244
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245 246
}

247 248
var swarmDisconnectCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
249
		Tagline: "Close connection to a given address.",
250 251 252 253 254
		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
255 256

The disconnect is not permanent; if ipfs needs to talk to that address later, it will reconnect.
257 258 259
`,
	},
	Arguments: []cmds.Argument{
260
		cmds.StringArg("address", true, true, "Address of peer to disconnect from.").EnableStdin(),
261 262
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
263
		n, err := req.InvocContext().GetNode()
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
		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) {
291
					log.Debug("it's not", conn.RemoteMultiaddr(), taddr)
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
					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{},
}

316
func stringListMarshaler(res cmds.Response) (io.Reader, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
317 318 319 320 321
	list, ok := res.Output().(*stringList)
	if !ok {
		return nil, errors.New("failed to cast []string")
	}

322
	buf := new(bytes.Buffer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
323
	for _, s := range list.Strings {
324 325
		buf.WriteString(s)
		buf.WriteString("\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326
	}
327
	return buf, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
328
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329

330
// parseAddresses is a function that takes in a slice of string peer addresses
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
331
// (multiaddr + peerid) and returns slices of multiaddrs and peerids.
332 333 334 335
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)
336
		if err != nil {
337
			return nil, cmds.ClientError("invalid peer address: " + err.Error())
338
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339 340 341 342 343 344
	}
	return
}

// peersWithAddresses is a function that takes in a slice of string peer addresses
// (multiaddr + peerid) and returns a slice of properly constructed peers
345
func peersWithAddresses(addrs []string) (pis []peer.PeerInfo, err error) {
346
	iaddrs, err := parseAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
347 348 349 350
	if err != nil {
		return nil, err
	}

351
	for _, iaddr := range iaddrs {
352 353 354 355
		pis = append(pis, peer.PeerInfo{
			ID:    iaddr.ID(),
			Addrs: []ma.Multiaddr{iaddr.Transport()},
		})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
356
	}
357
	return pis, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
358
}
359 360 361

var swarmFiltersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
362
		Tagline: "Manipulate address filters.",
363 364 365 366 367 368 369 370 371 372 373 374
		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

375
Filters default to those specified under the "Swarm.AddrFilters" config key.
376 377 378 379 380 381 382
`,
	},
	Subcommands: map[string]*cmds.Command{
		"add": swarmFiltersAddCmd,
		"rm":  swarmFiltersRmCmd,
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
383
		n, err := req.InvocContext().GetNode()
384 385 386 387 388
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

389 390 391 392 393
		if n.PeerHost == nil {
			res.SetError(errNotOnline, cmds.ErrNormal)
			return
		}

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
		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
419
		Tagline: "Add an address filter.",
420
		ShortDescription: `
421
'ipfs swarm filters add' will add an address filter to the daemons swarm.
Richard Littauer's avatar
Richard Littauer committed
422
Filters applied this way will not persist daemon reboots, to achieve that,
423 424 425 426
add your filters to the ipfs config file.
`,
	},
	Arguments: []cmds.Argument{
427
		cmds.StringArg("address", true, true, "Multiaddr to filter.").EnableStdin(),
428 429
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
430
		n, err := req.InvocContext().GetNode()
431 432 433 434 435
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

436 437 438 439 440
		if n.PeerHost == nil {
			res.SetError(errNotOnline, cmds.ErrNormal)
			return
		}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
		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{
rht's avatar
rht committed
461
		Tagline: "Remove an address filter.",
462
		ShortDescription: `
463
'ipfs swarm filters rm' will remove an address filter from the daemons swarm.
Richard Littauer's avatar
Richard Littauer committed
464
Filters removed this way will not persist daemon reboots, to achieve that,
465 466 467 468
remove your filters from the ipfs config file.
`,
	},
	Arguments: []cmds.Argument{
469
		cmds.StringArg("address", true, true, "Multiaddr filter to remove.").EnableStdin(),
470 471
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
472
		n, err := req.InvocContext().GetNode()
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
		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)
		}
	},
}