Cloak/internal/client/connector.go

81 lines
2.1 KiB
Go
Raw Normal View History

2020-04-06 12:07:16 +00:00
package client
import (
"encoding/binary"
2020-04-08 23:39:40 +00:00
"github.com/cbeuw/Cloak/internal/common"
2020-04-06 12:07:16 +00:00
"net"
"sync"
"sync/atomic"
"time"
mux "github.com/cbeuw/Cloak/internal/multiplex"
log "github.com/sirupsen/logrus"
)
2020-04-10 13:09:48 +00:00
func MakeSession(connConfig RemoteConnConfig, authInfo AuthInfo, dialer common.Dialer, isAdmin bool) *mux.Session {
2020-04-06 12:07:16 +00:00
log.Info("Attempting to start a new session")
2020-04-10 10:07:38 +00:00
//TODO: let caller set this
2020-04-06 12:07:16 +00:00
if !isAdmin {
// sessionID is usergenerated. There shouldn't be a security concern because the scope of
// sessionID is limited to its UID.
quad := make([]byte, 4)
2020-04-14 00:53:28 +00:00
common.RandRead(authInfo.WorldState.Rand, quad)
2020-04-06 12:07:16 +00:00
authInfo.SessionId = binary.BigEndian.Uint32(quad)
} else {
authInfo.SessionId = 0
}
connsCh := make(chan net.Conn, connConfig.NumConn)
var _sessionKey atomic.Value
var wg sync.WaitGroup
for i := 0; i < connConfig.NumConn; i++ {
wg.Add(1)
go func() {
makeconn:
2020-04-08 23:34:02 +00:00
remoteConn, err := dialer.Dial("tcp", connConfig.RemoteAddr)
2020-04-06 12:07:16 +00:00
if err != nil {
log.Errorf("Failed to establish new connections to remote: %v", err)
// TODO increase the interval if failed multiple times
time.Sleep(time.Second * 3)
goto makeconn
}
transportConn := connConfig.TransportMaker()
sk, err := transportConn.Handshake(remoteConn, authInfo)
2020-04-06 12:07:16 +00:00
if err != nil {
transportConn.Close()
2020-04-06 12:07:16 +00:00
log.Errorf("Failed to prepare connection to remote: %v", err)
time.Sleep(time.Second * 3)
goto makeconn
}
_sessionKey.Store(sk)
connsCh <- transportConn
2020-04-06 12:07:16 +00:00
wg.Done()
}()
}
wg.Wait()
log.Debug("All underlying connections established")
2020-04-07 20:15:28 +00:00
sessionKey := _sessionKey.Load().([32]byte)
obfuscator, err := mux.MakeObfuscator(authInfo.EncryptionMethod, sessionKey)
2020-04-06 12:07:16 +00:00
if err != nil {
log.Fatal(err)
}
seshConfig := mux.SessionConfig{
Obfuscator: obfuscator,
Valve: nil,
Unordered: authInfo.Unordered,
MaxFrameSize: appDataMaxLength,
2020-04-06 12:07:16 +00:00
}
sesh := mux.MakeSession(authInfo.SessionId, seshConfig)
for i := 0; i < connConfig.NumConn; i++ {
conn := <-connsCh
sesh.AddConnection(conn)
}
log.Infof("Session %v established", authInfo.SessionId)
return sesh
}