always.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package inbound
  2. import (
  3. "context"
  4. "v2ray.com/core/app/proxyman"
  5. "v2ray.com/core/common/dice"
  6. "v2ray.com/core/app/log"
  7. "v2ray.com/core/common/net"
  8. "v2ray.com/core/proxy"
  9. )
  10. type AlwaysOnInboundHandler struct {
  11. proxy proxy.Inbound
  12. workers []worker
  13. }
  14. func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.ReceiverConfig, proxyConfig interface{}) (*AlwaysOnInboundHandler, error) {
  15. p, err := proxy.CreateInboundHandler(ctx, proxyConfig)
  16. if err != nil {
  17. return nil, err
  18. }
  19. h := &AlwaysOnInboundHandler{
  20. proxy: p,
  21. }
  22. nl := p.Network()
  23. pr := receiverConfig.PortRange
  24. address := receiverConfig.Listen.AsAddress()
  25. if address == nil {
  26. address = net.AnyIP
  27. }
  28. for port := pr.From; port <= pr.To; port++ {
  29. if nl.HasNetwork(net.Network_TCP) {
  30. log.Debug("Proxyman|DefaultInboundHandler: creating tcp worker on ", address, ":", port)
  31. worker := &tcpWorker{
  32. address: address,
  33. port: net.Port(port),
  34. proxy: p,
  35. stream: receiverConfig.StreamSettings,
  36. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  37. tag: tag,
  38. allowPassiveConn: receiverConfig.AllowPassiveConnection,
  39. }
  40. h.workers = append(h.workers, worker)
  41. }
  42. if nl.HasNetwork(net.Network_UDP) {
  43. worker := &udpWorker{
  44. tag: tag,
  45. proxy: p,
  46. address: address,
  47. port: net.Port(port),
  48. recvOrigDest: receiverConfig.ReceiveOriginalDestination,
  49. }
  50. h.workers = append(h.workers, worker)
  51. }
  52. }
  53. return h, nil
  54. }
  55. func (h *AlwaysOnInboundHandler) Start() error {
  56. for _, worker := range h.workers {
  57. if err := worker.Start(); err != nil {
  58. return err
  59. }
  60. }
  61. return nil
  62. }
  63. func (h *AlwaysOnInboundHandler) Close() {
  64. for _, worker := range h.workers {
  65. worker.Close()
  66. }
  67. }
  68. func (h *AlwaysOnInboundHandler) GetRandomInboundProxy() (proxy.Inbound, net.Port, int) {
  69. w := h.workers[dice.Roll(len(h.workers))]
  70. return w.Proxy(), w.Port(), 9999
  71. }