2017-11-08 04:00:18 +00:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/anacrolix/torrent/mse"
|
2017-12-01 07:12:29 +00:00
|
|
|
pp "github.com/anacrolix/torrent/peer_protocol"
|
2017-11-08 04:00:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Wraps a raw connection and provides the interface we want for using the
|
|
|
|
// connection in the message loop.
|
|
|
|
type deadlineReader struct {
|
|
|
|
nc net.Conn
|
|
|
|
r io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r deadlineReader) Read(b []byte) (int, error) {
|
|
|
|
// Keep-alives should be received every 2 mins. Give a bit of gracetime.
|
|
|
|
err := r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
|
|
|
|
if err != nil {
|
|
|
|
return 0, fmt.Errorf("error setting read deadline: %s", err)
|
|
|
|
}
|
|
|
|
return r.r.Read(b)
|
|
|
|
}
|
|
|
|
|
2020-11-05 02:28:45 +00:00
|
|
|
// Handles stream encryption for inbound connections.
|
2017-11-08 04:00:18 +00:00
|
|
|
func handleEncryption(
|
|
|
|
rw io.ReadWriter,
|
|
|
|
skeys mse.SecretKeyIter,
|
2019-07-19 03:23:36 +00:00
|
|
|
policy HeaderObfuscationPolicy,
|
|
|
|
selector mse.CryptoSelector,
|
2017-11-08 04:00:18 +00:00
|
|
|
) (
|
|
|
|
ret io.ReadWriter,
|
|
|
|
headerEncrypted bool,
|
2018-02-15 23:36:29 +00:00
|
|
|
cryptoMethod mse.CryptoMethod,
|
2017-11-08 04:00:18 +00:00
|
|
|
err error,
|
|
|
|
) {
|
2020-11-05 02:28:45 +00:00
|
|
|
// Tries to start an unencrypted stream.
|
2019-07-19 03:23:36 +00:00
|
|
|
if !policy.RequirePreferred || !policy.Preferred {
|
2017-11-08 04:00:18 +00:00
|
|
|
var protocol [len(pp.Protocol)]byte
|
|
|
|
_, err = io.ReadFull(rw, protocol[:])
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2020-11-05 02:28:45 +00:00
|
|
|
// Put the protocol back into the stream.
|
2017-11-08 04:00:18 +00:00
|
|
|
rw = struct {
|
|
|
|
io.Reader
|
|
|
|
io.Writer
|
|
|
|
}{
|
|
|
|
io.MultiReader(bytes.NewReader(protocol[:]), rw),
|
|
|
|
rw,
|
|
|
|
}
|
|
|
|
if string(protocol[:]) == pp.Protocol {
|
|
|
|
ret = rw
|
|
|
|
return
|
|
|
|
}
|
2019-07-19 03:23:36 +00:00
|
|
|
if policy.RequirePreferred {
|
2020-11-05 02:28:45 +00:00
|
|
|
// We are here because we require unencrypted connections.
|
2019-07-19 03:23:36 +00:00
|
|
|
err = fmt.Errorf("unexpected protocol string %q and header obfuscation disabled", protocol)
|
|
|
|
return
|
|
|
|
}
|
2017-11-08 04:00:18 +00:00
|
|
|
}
|
|
|
|
headerEncrypted = true
|
2019-07-19 03:23:36 +00:00
|
|
|
ret, cryptoMethod, err = mse.ReceiveHandshake(rw, skeys, selector)
|
2017-11-08 04:00:18 +00:00
|
|
|
return
|
|
|
|
}
|
2018-07-07 01:31:29 +00:00
|
|
|
|
2018-07-07 01:36:58 +00:00
|
|
|
type PeerExtensionBits = pp.PeerExtensionBits
|