2018-09-13 13:47:08 +00:00
|
|
|
package p2pd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
ggio "github.com/gogo/protobuf/io"
|
|
|
|
inet "github.com/libp2p/go-libp2p-net"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (d *Daemon) doStreamPipe(c net.Conn, s inet.Stream) {
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(2)
|
|
|
|
|
|
|
|
pipe := func(dst io.Writer, src io.Reader) {
|
|
|
|
_, err := io.Copy(dst, src)
|
|
|
|
if err != nil && err != io.EOF {
|
|
|
|
log.Debugf("stream error: %s", err.Error())
|
2018-09-13 14:44:08 +00:00
|
|
|
s.Reset()
|
2018-09-13 13:47:08 +00:00
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}
|
|
|
|
|
|
|
|
go pipe(c, s)
|
|
|
|
go pipe(s, c)
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
s.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Daemon) handleStream(s inet.Stream) {
|
|
|
|
p := s.Protocol()
|
|
|
|
|
|
|
|
d.mx.Lock()
|
|
|
|
path, ok := d.handlers[p]
|
|
|
|
d.mx.Unlock()
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
log.Debugf("unexpected stream: %s", p)
|
2018-09-13 14:44:08 +00:00
|
|
|
s.Reset()
|
2018-09-13 13:47:08 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c, err := net.Dial("unix", path)
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("error dialing handler at %s: %s", path, err.Error())
|
2018-09-13 14:44:08 +00:00
|
|
|
s.Reset()
|
2018-09-13 13:47:08 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
w := ggio.NewDelimitedWriter(c)
|
2018-09-13 14:26:58 +00:00
|
|
|
msg := makeStreamInfo(s)
|
|
|
|
err = w.WriteMsg(msg)
|
2018-09-13 13:47:08 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Debugf("error accepting stream: %s", err.Error())
|
2018-09-13 14:44:08 +00:00
|
|
|
s.Reset()
|
2018-09-13 13:47:08 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
d.doStreamPipe(c, s)
|
|
|
|
}
|