common.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package scenarios
  2. import (
  3. "sync/atomic"
  4. "time"
  5. "net"
  6. "github.com/golang/protobuf/proto"
  7. "v2ray.com/core"
  8. v2net "v2ray.com/core/common/net"
  9. )
  10. var (
  11. port uint32 = 40000
  12. )
  13. func pickPort() v2net.Port {
  14. return v2net.Port(atomic.AddUint32(&port, 1))
  15. }
  16. func xor(b []byte) []byte {
  17. r := make([]byte, len(b))
  18. for i, v := range b {
  19. r[i] = v ^ 'c'
  20. }
  21. return r
  22. }
  23. func readFrom(conn net.Conn, timeout time.Duration, length int) []byte {
  24. b := make([]byte, 2048)
  25. totalBytes := 0
  26. deadline := time.Now().Add(timeout)
  27. conn.SetReadDeadline(deadline)
  28. for totalBytes < length {
  29. if time.Now().After(deadline) {
  30. break
  31. }
  32. n, err := conn.Read(b[totalBytes:])
  33. if err != nil {
  34. break
  35. }
  36. totalBytes += n
  37. }
  38. return b[:totalBytes]
  39. }
  40. func InitializeServerConfig(config *core.Config) error {
  41. err := BuildV2Ray()
  42. if err != nil {
  43. return err
  44. }
  45. configBytes, err := proto.Marshal(config)
  46. if err != nil {
  47. return err
  48. }
  49. proc := RunV2RayProtobuf(configBytes)
  50. err = proc.Start()
  51. if err != nil {
  52. return err
  53. }
  54. time.Sleep(time.Second)
  55. runningServers = append(runningServers, proc)
  56. return nil
  57. }