-
Notifications
You must be signed in to change notification settings - Fork 36
/
stream.go
65 lines (52 loc) · 1.08 KB
/
stream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package p2pd
import (
"io"
"net"
"sync"
"github.com/libp2p/go-libp2p/core/network"
ggio "github.com/gogo/protobuf/io"
manet "github.com/multiformats/go-multiaddr/net"
)
func (d *Daemon) doStreamPipe(c net.Conn, s network.Stream) {
var wg sync.WaitGroup
wg.Add(2)
pipe := func(dst io.WriteCloser, src io.Reader) {
_, err := io.Copy(dst, src)
if err != nil && err != io.EOF {
log.Debugw("stream error", "error", err)
s.Reset()
}
dst.Close()
wg.Done()
}
go pipe(c, s)
go pipe(s, c)
wg.Wait()
}
func (d *Daemon) handleStream(s network.Stream) {
p := s.Protocol()
d.mx.Lock()
maddr, ok := d.handlers[p]
d.mx.Unlock()
if !ok {
log.Debugw("unexpected stream", "protocol", p)
s.Reset()
return
}
c, err := manet.Dial(maddr)
if err != nil {
log.Debugw("error dialing handler", "handler", maddr.String(), "error", err)
s.Reset()
return
}
defer c.Close()
w := ggio.NewDelimitedWriter(c)
msg := makeStreamInfo(s)
err = w.WriteMsg(msg)
if err != nil {
log.Debugw("error accepting stream", "error", err)
s.Reset()
return
}
d.doStreamPipe(c, s)
}