ipfs_impl.go 7.62 KB
Newer Older
1 2 3
package network

import (
4
	"context"
5
	"fmt"
Jeromy's avatar
Jeromy committed
6
	"io"
7
	"sync/atomic"
8
	"time"
Jeromy's avatar
Jeromy committed
9

Jeromy's avatar
Jeromy committed
10 11 12 13
	bsmsg "github.com/ipfs/go-bitswap/message"

	cid "github.com/ipfs/go-cid"
	logging "github.com/ipfs/go-log"
Raúl Kripalani's avatar
Raúl Kripalani committed
14
	"github.com/libp2p/go-libp2p-core/connmgr"
15
	"github.com/libp2p/go-libp2p-core/helpers"
Raúl Kripalani's avatar
Raúl Kripalani committed
16 17 18 19
	"github.com/libp2p/go-libp2p-core/host"
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	peerstore "github.com/libp2p/go-libp2p-core/peerstore"
20
	"github.com/libp2p/go-libp2p-core/protocol"
Raúl Kripalani's avatar
Raúl Kripalani committed
21
	"github.com/libp2p/go-libp2p-core/routing"
Steven Allen's avatar
Steven Allen committed
22
	msgio "github.com/libp2p/go-msgio"
Jeromy's avatar
Jeromy committed
23
	ma "github.com/multiformats/go-multiaddr"
24 25
)

Jeromy's avatar
Jeromy committed
26
var log = logging.Logger("bitswap_network")
Jeromy's avatar
Jeromy committed
27

28 29
var sendMessageTimeout = time.Minute * 10

30
// NewFromIpfsHost returns a BitSwapNetwork supported by underlying IPFS host.
31
func NewFromIpfsHost(host host.Host, r routing.ContentRouting, opts ...NetOpt) BitSwapNetwork {
dirkmc's avatar
dirkmc committed
32
	s := processSettings(opts...)
33

34
	bitswapNetwork := impl{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
		host:    host,
36
		routing: r,
37

dirkmc's avatar
dirkmc committed
38 39 40 41 42 43
		protocolBitswapNoVers:  s.ProtocolPrefix + ProtocolBitswapNoVers,
		protocolBitswapOneZero: s.ProtocolPrefix + ProtocolBitswapOneZero,
		protocolBitswapOneOne:  s.ProtocolPrefix + ProtocolBitswapOneOne,
		protocolBitswap:        s.ProtocolPrefix + ProtocolBitswap,

		supportedProtocols: s.SupportedProtocols,
44
	}
45
	return &bitswapNetwork
46 47
}

dirkmc's avatar
dirkmc committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
func processSettings(opts ...NetOpt) Settings {
	s := Settings{
		SupportedProtocols: []protocol.ID{
			ProtocolBitswap,
			ProtocolBitswapOneOne,
			ProtocolBitswapOneZero,
			ProtocolBitswapNoVers,
		},
	}
	for _, opt := range opts {
		opt(&s)
	}
	for i, proto := range s.SupportedProtocols {
		s.SupportedProtocols[i] = s.ProtocolPrefix + proto
	}
	return s
}

66 67
// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
68
type impl struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
	host    host.Host
70
	routing routing.ContentRouting
71

dirkmc's avatar
dirkmc committed
72 73 74 75 76 77
	protocolBitswapNoVers  protocol.ID
	protocolBitswapOneZero protocol.ID
	protocolBitswapOneOne  protocol.ID
	protocolBitswap        protocol.ID

	supportedProtocols []protocol.ID
78

79 80
	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
81

82
	stats Stats
83 84
}

Jeromy's avatar
Jeromy committed
85
type streamMessageSender struct {
86 87
	s     network.Stream
	bsnet *impl
Jeromy's avatar
Jeromy committed
88 89 90
}

func (s *streamMessageSender) Close() error {
Raúl Kripalani's avatar
Raúl Kripalani committed
91
	return helpers.FullClose(s.s)
Jeromy's avatar
Jeromy committed
92 93
}

94 95 96 97
func (s *streamMessageSender) Reset() error {
	return s.s.Reset()
}

98
func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
99
	return s.bsnet.msgToStream(ctx, s.s, msg)
100 101
}

dirkmc's avatar
dirkmc committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
func (s *streamMessageSender) SupportsHave() bool {
	return s.bsnet.SupportsHave(s.s.Protocol())
}

func (bsnet *impl) Self() peer.ID {
	return bsnet.host.ID()
}

// Indicates whether the given protocol supports HAVE / DONT_HAVE messages
func (bsnet *impl) SupportsHave(proto protocol.ID) bool {
	switch proto {
	case bsnet.protocolBitswapOneOne, bsnet.protocolBitswapOneZero, bsnet.protocolBitswapNoVers:
		return false
	}
	return true
}

119
func (bsnet *impl) msgToStream(ctx context.Context, s network.Stream, msg bsmsg.BitSwapMessage) error {
120 121 122 123
	deadline := time.Now().Add(sendMessageTimeout)
	if dl, ok := ctx.Deadline(); ok {
		deadline = dl
	}
Bob Potter's avatar
Bob Potter committed
124

125 126 127 128
	if err := s.SetWriteDeadline(deadline); err != nil {
		log.Warningf("error setting deadline: %s", err)
	}

dirkmc's avatar
dirkmc committed
129 130 131
	// Older Bitswap versions use a slightly different wire format so we need
	// to convert the message to the appropriate format depending on the remote
	// peer's Bitswap version.
132
	switch s.Protocol() {
dirkmc's avatar
dirkmc committed
133
	case bsnet.protocolBitswapOneOne, bsnet.protocolBitswap:
Bob Potter's avatar
Bob Potter committed
134
		if err := msg.ToNetV1(s); err != nil {
135 136 137
			log.Debugf("error: %s", err)
			return err
		}
dirkmc's avatar
dirkmc committed
138
	case bsnet.protocolBitswapOneZero, bsnet.protocolBitswapNoVers:
Bob Potter's avatar
Bob Potter committed
139
		if err := msg.ToNetV0(s); err != nil {
140 141 142 143 144 145
			log.Debugf("error: %s", err)
			return err
		}
	default:
		return fmt.Errorf("unrecognized protocol on remote: %s", s.Protocol())
	}
146 147 148 149

	if err := s.SetWriteDeadline(time.Time{}); err != nil {
		log.Warningf("error resetting deadline: %s", err)
	}
150
	return nil
Jeromy's avatar
Jeromy committed
151 152 153 154 155 156 157 158
}

func (bsnet *impl) NewMessageSender(ctx context.Context, p peer.ID) (MessageSender, error) {
	s, err := bsnet.newStreamToPeer(ctx, p)
	if err != nil {
		return nil, err
	}

159
	return &streamMessageSender{s: s, bsnet: bsnet}, nil
Jeromy's avatar
Jeromy committed
160 161
}

Raúl Kripalani's avatar
Raúl Kripalani committed
162
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (network.Stream, error) {
dirkmc's avatar
dirkmc committed
163
	return bsnet.host.NewStream(ctx, p, bsnet.supportedProtocols...)
164 165 166 167 168 169 170 171
}

func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.newStreamToPeer(ctx, p)
172 173 174
	if err != nil {
		return err
	}
175

176
	if err = bsnet.msgToStream(ctx, s, outgoing); err != nil {
Steven Allen's avatar
Steven Allen committed
177
		_ = s.Reset()
Steven Allen's avatar
Steven Allen committed
178
		return err
179
	}
180 181
	atomic.AddUint64(&bsnet.stats.MessagesSent, 1)

182
	// TODO(https://github.com/libp2p/go-libp2p-net/issues/28): Avoid this goroutine.
Steven Allen's avatar
Steven Allen committed
183
	//nolint
Raúl Kripalani's avatar
Raúl Kripalani committed
184
	go helpers.AwaitEOF(s)
185 186
	return s.Close()

187 188
}

189 190
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
dirkmc's avatar
dirkmc committed
191 192 193
	for _, proto := range bsnet.supportedProtocols {
		bsnet.host.SetStreamHandler(proto, bsnet.handleNewStream)
	}
hannahhoward's avatar
hannahhoward committed
194 195 196
	bsnet.host.Network().Notify((*netNotifiee)(bsnet))
	// TODO: StopNotify.

197
}
198

199
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Raúl Kripalani's avatar
Raúl Kripalani committed
200
	return bsnet.host.Connect(ctx, peer.AddrInfo{ID: p})
201 202
}

dirkmc's avatar
dirkmc committed
203 204 205 206
func (bsnet *impl) DisconnectFrom(ctx context.Context, p peer.ID) error {
	panic("Not implemented: DisconnectFrom() is only used by tests")
}

207
// FindProvidersAsync returns a channel of providers for the given key.
208
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
209
	out := make(chan peer.ID, max)
210 211
	go func() {
		defer close(out)
212
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
213
		for info := range providers {
214 215
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
216
			}
Raúl Kripalani's avatar
Raúl Kripalani committed
217
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.TempAddrTTL)
218 219
			select {
			case <-ctx.Done():
220
				return
221 222 223 224 225
			case out <- info.ID:
			}
		}
	}()
	return out
226 227 228
}

// Provide provides the key to the network
229
func (bsnet *impl) Provide(ctx context.Context, k cid.Cid) error {
230
	return bsnet.routing.Provide(ctx, k, true)
231 232
}

233
// handleNewStream receives a new stream from the network.
Raúl Kripalani's avatar
Raúl Kripalani committed
234
func (bsnet *impl) handleNewStream(s network.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
	defer s.Close()
236 237

	if bsnet.receiver == nil {
Steven Allen's avatar
Steven Allen committed
238
		_ = s.Reset()
239 240 241
		return
	}

Steven Allen's avatar
Steven Allen committed
242
	reader := msgio.NewVarintReaderSize(s, network.MessageSizeMax)
243
	for {
Steven Allen's avatar
Steven Allen committed
244
		received, err := bsmsg.FromMsgReader(reader)
245
		if err != nil {
Jeromy's avatar
Jeromy committed
246
			if err != io.EOF {
Steven Allen's avatar
Steven Allen committed
247
				_ = s.Reset()
Jeromy's avatar
Jeromy committed
248 249 250
				go bsnet.receiver.ReceiveError(err)
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
251 252
			return
		}
253

254 255 256 257
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
		bsnet.receiver.ReceiveMessage(ctx, p, received)
258
		atomic.AddUint64(&bsnet.stats.MessagesRecvd, 1)
259
	}
260
}
261

Raúl Kripalani's avatar
Raúl Kripalani committed
262
func (bsnet *impl) ConnectionManager() connmgr.ConnManager {
263 264 265
	return bsnet.host.ConnManager()
}

266 267
func (bsnet *impl) Stats() Stats {
	return Stats{
268 269 270 271 272
		MessagesRecvd: atomic.LoadUint64(&bsnet.stats.MessagesRecvd),
		MessagesSent:  atomic.LoadUint64(&bsnet.stats.MessagesSent),
	}
}

273 274 275 276 277 278
type netNotifiee impl

func (nn *netNotifiee) impl() *impl {
	return (*impl)(nn)
}

Raúl Kripalani's avatar
Raúl Kripalani committed
279
func (nn *netNotifiee) Connected(n network.Network, v network.Conn) {
280 281
	nn.impl().receiver.PeerConnected(v.RemotePeer())
}
Raúl Kripalani's avatar
Raúl Kripalani committed
282
func (nn *netNotifiee) Disconnected(n network.Network, v network.Conn) {
283 284
	nn.impl().receiver.PeerDisconnected(v.RemotePeer())
}
dirkmc's avatar
dirkmc committed
285
func (nn *netNotifiee) OpenedStream(n network.Network, s network.Stream) {}
Raúl Kripalani's avatar
Raúl Kripalani committed
286 287 288
func (nn *netNotifiee) ClosedStream(n network.Network, v network.Stream) {}
func (nn *netNotifiee) Listen(n network.Network, a ma.Multiaddr)         {}
func (nn *netNotifiee) ListenClose(n network.Network, a ma.Multiaddr)    {}