You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/testing/scenarios/common.go

114 lines
2.0 KiB

8 years ago
package scenarios
import (
"fmt"
8 years ago
"io"
"io/ioutil"
8 years ago
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
8 years ago
"time"
"github.com/golang/protobuf/proto"
8 years ago
"v2ray.com/core"
"v2ray.com/core/app/log"
"v2ray.com/core/common"
8 years ago
v2net "v2ray.com/core/common/net"
"v2ray.com/core/common/retry"
8 years ago
)
func pickPort() v2net.Port {
listener, err := net.Listen("tcp4", ":0")
common.Must(err)
defer listener.Close()
addr := listener.Addr().(*net.TCPAddr)
return v2net.Port(addr.Port)
8 years ago
}
func xor(b []byte) []byte {
r := make([]byte, len(b))
for i, v := range b {
r[i] = v ^ 'c'
}
return r
}
func readFrom(conn net.Conn, timeout time.Duration, length int) []byte {
b := make([]byte, length)
deadline := time.Now().Add(timeout)
conn.SetReadDeadline(deadline)
8 years ago
n, _ := io.ReadFull(conn, b[:length])
return b[:n]
}
8 years ago
func InitializeServerConfig(config *core.Config) error {
err := BuildV2Ray()
if err != nil {
return err
}
configBytes, err := proto.Marshal(config)
if err != nil {
return err
}
proc := RunV2RayProtobuf(configBytes)
err = proc.Start()
if err != nil {
return err
}
time.Sleep(time.Second)
runningServers = append(runningServers, proc)
return nil
}
var (
runningServers = make([]*exec.Cmd, 0, 10)
testBinaryPath string
testBinaryPathGen sync.Once
)
func genTestBinaryPath() {
testBinaryPathGen.Do(func() {
var tempDir string
err := retry.Timed(5, 100).On(func() error {
dir, err := ioutil.TempDir("", "v2ray")
if err != nil {
return err
}
tempDir = dir
return nil
})
if err != nil {
panic(err)
}
file := filepath.Join(tempDir, "v2ray.test")
if runtime.GOOS == "windows" {
file += ".exe"
}
testBinaryPath = file
fmt.Printf("Generated binary path: %s\n", file)
})
}
func GetSourcePath() string {
return filepath.Join("v2ray.com", "core", "main")
}
func CloseAllServers() {
log.Info("Closing all servers.")
for _, server := range runningServers {
server.Process.Signal(os.Interrupt)
server.Process.Wait()
}
runningServers = make([]*exec.Cmd, 0, 10)
log.Info("All server closed.")
}