mux.go 3.27 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
package protocol
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
2
3
4
5
6
7
8
9

import (
	"fmt"
	"io"
	"sync"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	inet "github.com/jbenet/go-ipfs/p2p/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11
12
13
14
15
16
	eventlog "github.com/jbenet/go-ipfs/util/eventlog"
	lgbl "github.com/jbenet/go-ipfs/util/eventlog/loggables"
)

var log = eventlog.Logger("net/mux")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
type StreamHandlerMap map[ID]inet.StreamHandler
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

// Mux provides simple stream multixplexing.
// It helps you precisely when:
//  * You have many streams
//  * You have function handlers
//
// It contains the handlers for each protocol accepted.
// It dispatches handlers for streams opened by remote peers.
//
// WARNING: this datastructure IS NOT threadsafe.
// do not modify it once the network is using it.
type Mux struct {
	Default  inet.StreamHandler // handles unknown protocols.
	Handlers StreamHandlerMap

	sync.RWMutex
}

// Protocols returns the list of protocols this muxer has handlers for
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37
func (m *Mux) Protocols() []ID {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
	m.RLock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
	l := make([]ID, 0, len(m.Handlers))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40
41
42
43
44
45
46
47
48
	for p := range m.Handlers {
		l = append(l, p)
	}
	m.RUnlock()
	return l
}

// readHeader reads the stream and returns the next Handler function
// according to the muxer encoding.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49
func (m *Mux) readHeader(s io.Reader) (ID, inet.StreamHandler, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50
	// log.Error("ReadProtocolHeader")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51
	p, err := ReadHeader(s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
	if err != nil {
		return "", nil, err
	}

	// log.Debug("readHeader got:", p)
	m.RLock()
	h, found := m.Handlers[p]
	m.RUnlock()

	switch {
	case !found && m.Default != nil:
		return p, m.Default, nil
	case !found && m.Default == nil:
		return p, nil, fmt.Errorf("%s no handler with name: %s (%d)", m, p, len(p))
	default:
		return p, h, nil
	}
}

// String returns the muxer's printing representation
func (m *Mux) String() string {
	m.RLock()
	defer m.RUnlock()
	return fmt.Sprintf("<Muxer %p %d>", m, len(m.Handlers))
}

// SetHandler sets the protocol handler on the Network's Muxer.
// This operation is threadsafe.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80
func (m *Mux) SetHandler(p ID, h inet.StreamHandler) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
	log.Debugf("%s setting handler for protocol: %s (%d)", m, p, len(p))
	m.Lock()
	m.Handlers[p] = h
	m.Unlock()
}

// Handle reads the next name off the Stream, and calls a handler function
// This is done in its own goroutine, to avoid blocking the caller.
func (m *Mux) Handle(s inet.Stream) {
	go m.HandleSync(s)
}

// HandleSync reads the next name off the Stream, and calls a handler function
// This is done synchronously. The handler function will return before
// HandleSync returns.
func (m *Mux) HandleSync(s inet.Stream) {
	ctx := context.Background()

	name, handler, err := m.readHeader(s)
	if err != nil {
		err = fmt.Errorf("protocol mux error: %s", err)
		log.Error(err)
		log.Event(ctx, "muxError", lgbl.Error(err))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
		s.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
		return
	}

	log.Infof("muxer handle protocol: %s", name)
	log.Event(ctx, "muxHandle", eventlog.Metadata{"protocol": name})
	handler(s)
}

// ReadLengthPrefix reads the name from Reader with a length-byte-prefix.
func ReadLengthPrefix(r io.Reader) (string, error) {
	// c-string identifier
	// the first byte is our length
	l := make([]byte, 1)
	if _, err := io.ReadFull(r, l); err != nil {
		return "", err
	}
	length := int(l[0])

	// the next are our identifier
	name := make([]byte, length)
	if _, err := io.ReadFull(r, name); err != nil {
		return "", err
	}

	return string(name), nil
}