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

import (
Steven Allen's avatar
Steven Allen committed
4
	"bufio"
5
	"context"
6
	"fmt"
Jeromy's avatar
Jeromy committed
7
	"io"
8
	"time"
Jeromy's avatar
Jeromy committed
9

Jeromy's avatar
Jeromy committed
10 11 12 13 14 15 16 17 18 19 20 21
	bsmsg "github.com/ipfs/go-bitswap/message"

	ggio "github.com/gogo/protobuf/io"
	cid "github.com/ipfs/go-cid"
	logging "github.com/ipfs/go-log"
	host "github.com/libp2p/go-libp2p-host"
	ifconnmgr "github.com/libp2p/go-libp2p-interface-connmgr"
	inet "github.com/libp2p/go-libp2p-net"
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	routing "github.com/libp2p/go-libp2p-routing"
	ma "github.com/multiformats/go-multiaddr"
22 23
)

Jeromy's avatar
Jeromy committed
24
var log = logging.Logger("bitswap_network")
Jeromy's avatar
Jeromy committed
25

26 27
var sendMessageTimeout = time.Minute * 10

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28
// NewFromIpfsHost returns a BitSwapNetwork supported by underlying IPFS host
29
func NewFromIpfsHost(host host.Host, r routing.ContentRouting) BitSwapNetwork {
30
	bitswapNetwork := impl{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
		host:    host,
32
		routing: r,
33
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34
	host.SetStreamHandler(ProtocolBitswap, bitswapNetwork.handleNewStream)
35 36
	host.SetStreamHandler(ProtocolBitswapOne, bitswapNetwork.handleNewStream)
	host.SetStreamHandler(ProtocolBitswapNoVers, bitswapNetwork.handleNewStream)
37 38 39
	host.Network().Notify((*netNotifiee)(&bitswapNetwork))
	// TODO: StopNotify.

40
	return &bitswapNetwork
41 42
}

43 44
// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
45
type impl struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46
	host    host.Host
47
	routing routing.ContentRouting
48 49 50

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
51 52
}

Jeromy's avatar
Jeromy committed
53 54 55 56 57
type streamMessageSender struct {
	s inet.Stream
}

func (s *streamMessageSender) Close() error {
Steven Allen's avatar
Steven Allen committed
58
	return inet.FullClose(s.s)
Jeromy's avatar
Jeromy committed
59 60
}

61 62 63 64
func (s *streamMessageSender) Reset() error {
	return s.s.Reset()
}

65 66
func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	return msgToStream(ctx, s.s, msg)
67 68
}

69 70 71 72 73 74 75 76 77
func msgToStream(ctx context.Context, s inet.Stream, msg bsmsg.BitSwapMessage) error {
	deadline := time.Now().Add(sendMessageTimeout)
	if dl, ok := ctx.Deadline(); ok {
		deadline = dl
	}
	if err := s.SetWriteDeadline(deadline); err != nil {
		log.Warningf("error setting deadline: %s", err)
	}

Steven Allen's avatar
Steven Allen committed
78 79
	w := bufio.NewWriter(s)

80 81
	switch s.Protocol() {
	case ProtocolBitswap:
Steven Allen's avatar
Steven Allen committed
82
		if err := msg.ToNetV1(w); err != nil {
83 84 85 86
			log.Debugf("error: %s", err)
			return err
		}
	case ProtocolBitswapOne, ProtocolBitswapNoVers:
Steven Allen's avatar
Steven Allen committed
87
		if err := msg.ToNetV0(w); err != nil {
88 89 90 91 92 93
			log.Debugf("error: %s", err)
			return err
		}
	default:
		return fmt.Errorf("unrecognized protocol on remote: %s", s.Protocol())
	}
94

Steven Allen's avatar
Steven Allen committed
95 96 97 98 99
	if err := w.Flush(); err != nil {
		log.Debugf("error: %s", err)
		return err
	}

100 101 102
	if err := s.SetWriteDeadline(time.Time{}); err != nil {
		log.Warningf("error resetting deadline: %s", err)
	}
103
	return nil
Jeromy's avatar
Jeromy committed
104 105 106 107 108 109 110 111 112 113 114
}

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

	return &streamMessageSender{s: s}, nil
}

115
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (inet.Stream, error) {
116
	return bsnet.host.NewStream(ctx, p, ProtocolBitswap, ProtocolBitswapOne, ProtocolBitswapNoVers)
117 118 119 120 121 122 123 124
}

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

	s, err := bsnet.newStreamToPeer(ctx, p)
125 126 127
	if err != nil {
		return err
	}
128

Steven Allen's avatar
Steven Allen committed
129
	if err = msgToStream(ctx, s, outgoing); err != nil {
130
		s.Reset()
Steven Allen's avatar
Steven Allen committed
131
		return err
132
	}
133 134 135 136
	// TODO(https://github.com/libp2p/go-libp2p-net/issues/28): Avoid this goroutine.
	go inet.AwaitEOF(s)
	return s.Close()

137 138
}

139 140
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
141
}
142

143
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Jeromy's avatar
Jeromy committed
144
	return bsnet.host.Connect(ctx, pstore.PeerInfo{ID: p})
145 146
}

147
// FindProvidersAsync returns a channel of providers for the given key
148
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
149 150 151 152 153 154 155 156 157

	// Since routing queries are expensive, give bitswap the peers to which we
	// have open connections. Note that this may cause issues if bitswap starts
	// precisely tracking which peers provide certain keys. This optimization
	// would be misleading. In the long run, this may not be the most
	// appropriate place for this optimization, but it won't cause any harm in
	// the short term.
	connectedPeers := bsnet.host.Network().Peers()
	out := make(chan peer.ID, len(connectedPeers)) // just enough buffer for these connectedPeers
158
	for _, id := range connectedPeers {
159 160 161
		if id == bsnet.host.ID() {
			continue // ignore self as provider
		}
162 163 164
		out <- id
	}

165 166
	go func() {
		defer close(out)
167
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
168
		for info := range providers {
169 170
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
171
			}
Jeromy's avatar
Jeromy committed
172
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, pstore.TempAddrTTL)
173 174
			select {
			case <-ctx.Done():
175
				return
176 177 178 179 180
			case out <- info.ID:
			}
		}
	}()
	return out
181 182 183
}

// Provide provides the key to the network
184
func (bsnet *impl) Provide(ctx context.Context, k cid.Cid) error {
185
	return bsnet.routing.Provide(ctx, k, true)
186 187
}

188 189
// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190
	defer s.Close()
191 192

	if bsnet.receiver == nil {
193
		s.Reset()
194 195 196
		return
	}

Jeromy's avatar
Jeromy committed
197
	reader := ggio.NewDelimitedReader(s, inet.MessageSizeMax)
198
	for {
Jeromy's avatar
Jeromy committed
199
		received, err := bsmsg.FromPBReader(reader)
200
		if err != nil {
Jeromy's avatar
Jeromy committed
201
			if err != io.EOF {
202
				s.Reset()
Jeromy's avatar
Jeromy committed
203 204 205
				go bsnet.receiver.ReceiveError(err)
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
206 207
			return
		}
208

209 210 211 212 213
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}
214
}
215

216 217 218 219
func (bsnet *impl) ConnectionManager() ifconnmgr.ConnManager {
	return bsnet.host.ConnManager()
}

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
type netNotifiee impl

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

func (nn *netNotifiee) Connected(n inet.Network, v inet.Conn) {
	nn.impl().receiver.PeerConnected(v.RemotePeer())
}

func (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) {
	nn.impl().receiver.PeerDisconnected(v.RemotePeer())
}

func (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) {}
func (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) {}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236 237
func (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr)      {}
func (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}