swarm.go 12.3 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 14
	swarm "gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/net/swarm"
	peer "gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15

16
	mafilter "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/whyrusleeping/multiaddr-filter"
17
	ma "gx/ipfs/QmR3JkmZBKYXgNMNsNZawm914455Qof3PEopwuVSeXG7aV/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
		Synopsis: `
32
ipfs swarm peers                - List peers with open connections
33
ipfs swarm addrs                - List known addresses. Useful to debug.
34 35
ipfs swarm connect <address>    - Open connection to a given address
ipfs swarm disconnect <address> - Close connection to a given address
36
ipfs swarm filters              - Manipulate filters addresses
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37 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
		"peers":      swarmPeersCmd,
46
		"addrs":      swarmAddrsCmd,
47 48
		"connect":    swarmConnectCmd,
		"disconnect": swarmDisconnectCmd,
49
		"filters":    swarmFiltersCmd,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51 52 53 54
	},
}

var swarmPeersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
55
		Tagline: "List peers with open connections.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
		ShortDescription: `
57
'ipfs swarm peers' lists the set of peers this node is connected to.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58 59
`,
	},
60
	Run: func(req cmds.Request, res cmds.Response) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61 62

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
		conns := n.PeerHost.Network().Conns()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76
		addrs := make([]string, len(conns))
		for i, c := range conns {
77
			pid := c.RemotePeer()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
			addr := c.RemoteMultiaddr()
79
			addrs[i] = fmt.Sprintf("%s/ipfs/%s", addr, pid.Pretty())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80 81
		}

82
		sort.Sort(sort.StringSlice(addrs))
83
		res.SetOutput(&stringList{addrs})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85 86 87
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
88
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90
}

91 92 93 94
var swarmAddrsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List known addresses. Useful to debug.",
		ShortDescription: `
95
'ipfs swarm addrs' lists all addresses this node is aware of.
96 97
`,
	},
98 99 100
	Subcommands: map[string]*cmds.Command{
		"local": swarmAddrsLocalCmd,
	},
101 102
	Run: func(req cmds.Request, res cmds.Response) {

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

140
			buf := new(bytes.Buffer)
141 142 143 144 145 146 147
			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")
				}
			}
148
			return buf, nil
149 150 151 152 153
		},
	},
	Type: addrMap{},
}

154 155 156 157
var swarmAddrsLocalCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List local addresses.",
		ShortDescription: `
158
'ipfs swarm addrs local' lists all local addresses the node is listening on.
159 160 161
`,
	},
	Options: []cmds.Option{
162
		cmds.BoolOption("id", "Show peer ID in addresses."),
163 164 165
	},
	Run: func(req cmds.Request, res cmds.Response) {

Jeromy's avatar
Jeromy committed
166
		n, err := req.InvocContext().GetNode()
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
		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
198 199
var swarmConnectCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
200
		Tagline: "Open connection to a given address.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201
		ShortDescription: `
202 203 204
'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
205

206
ipfs swarm connect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207 208 209
`,
	},
	Arguments: []cmds.Argument{
210
		cmds.StringArg("address", true, true, "Address of peer to connect to.").EnableStdin(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211
	},
212
	Run: func(req cmds.Request, res cmds.Response) {
213
		ctx := req.Context()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214

Jeromy's avatar
Jeromy committed
215
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216
		if err != nil {
217 218
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219 220
		}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
223
		if n.PeerHost == nil {
224 225
			res.SetError(errNotOnline, cmds.ErrClient)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226 227
		}

228
		pis, err := peersWithAddresses(addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229
		if err != nil {
230 231
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233
		}

234 235 236
		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
237

238
			err := n.PeerHost.Connect(ctx, pi)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
			if err != nil {
240 241
				res.SetError(fmt.Errorf("%s failure: %s", output[i], err), cmds.ErrNormal)
				return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242
			}
243
			output[i] += " success"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244 245
		}

246
		res.SetOutput(&stringList{output})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249 250
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: stringListMarshaler,
	},
251
	Type: stringList{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253
}

254 255
var swarmDisconnectCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
256
		Tagline: "Close connection to a given address.",
257 258 259 260 261 262 263 264
		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{
265
		cmds.StringArg("address", true, true, "Address of peer to connect to.").EnableStdin(),
266 267
	},
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
268
		n, err := req.InvocContext().GetNode()
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
		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) {
296
					log.Debug("it's not", conn.RemoteMultiaddr(), taddr)
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
					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{},
}

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

327
	buf := new(bytes.Buffer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
328
	for _, s := range list.Strings {
329 330
		buf.WriteString(s)
		buf.WriteString("\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
331
	}
332
	return buf, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
333
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334

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

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

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

var swarmFiltersCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
367
		Tagline: "Manipulate address filters.",
368 369 370 371 372 373 374 375 376 377 378 379
		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

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

394 395 396 397 398
		if n.PeerHost == nil {
			res.SetError(errNotOnline, cmds.ErrNormal)
			return
		}

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

441 442 443 444 445
		if n.PeerHost == nil {
			res.SetError(errNotOnline, cmds.ErrNormal)
			return
		}

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