2017-11-08 12:00:18 +08:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/anacrolix/torrent/mse"
|
2017-12-01 15:12:29 +08:00
|
|
|
pp "github.com/anacrolix/torrent/peer_protocol"
|
2017-11-08 12:00:18 +08: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)
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleEncryption(
|
|
|
|
rw io.ReadWriter,
|
|
|
|
skeys mse.SecretKeyIter,
|
|
|
|
policy EncryptionPolicy,
|
|
|
|
) (
|
|
|
|
ret io.ReadWriter,
|
|
|
|
headerEncrypted bool,
|
2018-02-16 07:36:29 +08:00
|
|
|
cryptoMethod mse.CryptoMethod,
|
2017-11-08 12:00:18 +08:00
|
|
|
err error,
|
|
|
|
) {
|
|
|
|
if !policy.ForceEncryption {
|
|
|
|
var protocol [len(pp.Protocol)]byte
|
|
|
|
_, err = io.ReadFull(rw, protocol[:])
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
rw = struct {
|
|
|
|
io.Reader
|
|
|
|
io.Writer
|
|
|
|
}{
|
|
|
|
io.MultiReader(bytes.NewReader(protocol[:]), rw),
|
|
|
|
rw,
|
|
|
|
}
|
|
|
|
if string(protocol[:]) == pp.Protocol {
|
|
|
|
ret = rw
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
headerEncrypted = true
|
2018-02-16 07:59:56 +08:00
|
|
|
ret, cryptoMethod, err = mse.ReceiveHandshake(rw, skeys, func(provides mse.CryptoMethod) mse.CryptoMethod {
|
2018-02-08 20:52:31 +08:00
|
|
|
switch {
|
|
|
|
case policy.ForceEncryption:
|
|
|
|
return mse.CryptoMethodRC4
|
|
|
|
case policy.DisableEncryption:
|
|
|
|
return mse.CryptoMethodPlaintext
|
|
|
|
case policy.PreferNoEncryption && provides&mse.CryptoMethodPlaintext != 0:
|
|
|
|
return mse.CryptoMethodPlaintext
|
|
|
|
default:
|
|
|
|
return mse.DefaultCryptoSelector(provides)
|
|
|
|
}
|
2017-11-08 12:00:18 +08:00
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
2018-07-07 09:31:29 +08:00
|
|
|
|
2018-07-07 09:36:58 +08:00
|
|
|
type PeerExtensionBits = pp.PeerExtensionBits
|