conn.go 1.92 KB
Newer Older
1 2 3
package swarm

import (
4
	"fmt"
5 6
	"net"

7 8
	msgio "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-msgio"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
9 10
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
11 12
)

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
13
// ChanBuffer is the size of the buffer in the Conn Chan
14 15
const ChanBuffer = 10

16 17
// 1 MB
const MaxMessageSize = 1 << 20
18

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
19
// Conn represents a connection to another Peer (IPFS Node).
20
type Conn struct {
21 22 23
	Peer *peer.Peer
	Addr *ma.Multiaddr
	Conn net.Conn
24

25 26 27
	Closed   chan bool
	Outgoing *msgio.Chan
	Incoming *msgio.Chan
28 29
	secIn    <-chan []byte
	secOut   chan<- []byte
30 31
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32 33
// Map maps Keys (Peer.IDs) to Connections.
type Map map[u.Key]*Conn
34

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
35 36
// Dial connects to a particular peer, over a given network
// Example: Dial("udp", peer)
37
func Dial(network string, peer *peer.Peer) (*Conn, error) {
38 39 40 41
	addr := peer.NetAddress(network)
	if addr == nil {
		return nil, fmt.Errorf("No address for network %s", network)
	}
42

43 44 45 46
	network, host, err := addr.DialArgs()
	if err != nil {
		return nil, err
	}
47

48 49 50 51
	nconn, err := net.Dial(network, host)
	if err != nil {
		return nil, err
	}
52

53 54 55 56
	conn := &Conn{
		Peer: peer,
		Addr: addr,
		Conn: nconn,
57
	}
58

59 60 61 62 63 64 65 66
	newConnChans(conn)
	return conn, nil
}

// Construct new channels for given Conn.
func newConnChans(c *Conn) error {
	if c.Outgoing != nil || c.Incoming != nil {
		return fmt.Errorf("Conn already initialized")
67
	}
68

69 70 71
	c.Outgoing = msgio.NewChan(10)
	c.Incoming = msgio.NewChan(10)
	c.Closed = make(chan bool, 1)
72

73
	go c.Outgoing.WriteTo(c.Conn)
74
	go c.Incoming.ReadFrom(c.Conn, MaxMessageSize)
75 76

	return nil
77 78
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
79
// Close closes the connection, and associated channels.
80
func (s *Conn) Close() error {
81
	u.DOut("Closing Conn.\n")
82
	if s.Conn == nil {
83
		return fmt.Errorf("Already closed") // already closed
84
	}
85

86 87 88 89 90 91 92 93
	// closing net connection
	err := s.Conn.Close()
	s.Conn = nil
	// closing channels
	s.Incoming.Close()
	s.Outgoing.Close()
	s.Closed <- true
	return err
94
}