github.com/imannamdari/v2ray-core/v5@v5.0.5/infra/conf/v4/http.go (about)

     1  package v4
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/golang/protobuf/proto"
     7  
     8  	"github.com/imannamdari/v2ray-core/v5/common/protocol"
     9  	"github.com/imannamdari/v2ray-core/v5/common/serial"
    10  	"github.com/imannamdari/v2ray-core/v5/infra/conf/cfgcommon"
    11  	"github.com/imannamdari/v2ray-core/v5/proxy/http"
    12  )
    13  
    14  type HTTPAccount struct {
    15  	Username string `json:"user"`
    16  	Password string `json:"pass"`
    17  }
    18  
    19  func (v *HTTPAccount) Build() *http.Account {
    20  	return &http.Account{
    21  		Username: v.Username,
    22  		Password: v.Password,
    23  	}
    24  }
    25  
    26  type HTTPServerConfig struct {
    27  	Timeout     uint32         `json:"timeout"`
    28  	Accounts    []*HTTPAccount `json:"accounts"`
    29  	Transparent bool           `json:"allowTransparent"`
    30  	UserLevel   uint32         `json:"userLevel"`
    31  }
    32  
    33  func (c *HTTPServerConfig) Build() (proto.Message, error) {
    34  	config := &http.ServerConfig{
    35  		Timeout:          c.Timeout,
    36  		AllowTransparent: c.Transparent,
    37  		UserLevel:        c.UserLevel,
    38  	}
    39  
    40  	if len(c.Accounts) > 0 {
    41  		config.Accounts = make(map[string]string)
    42  		for _, account := range c.Accounts {
    43  			config.Accounts[account.Username] = account.Password
    44  		}
    45  	}
    46  
    47  	return config, nil
    48  }
    49  
    50  type HTTPRemoteConfig struct {
    51  	Address *cfgcommon.Address `json:"address"`
    52  	Port    uint16             `json:"port"`
    53  	Users   []json.RawMessage  `json:"users"`
    54  }
    55  
    56  type HTTPClientConfig struct {
    57  	Servers []*HTTPRemoteConfig `json:"servers"`
    58  }
    59  
    60  func (v *HTTPClientConfig) Build() (proto.Message, error) {
    61  	config := new(http.ClientConfig)
    62  	config.Server = make([]*protocol.ServerEndpoint, len(v.Servers))
    63  	for idx, serverConfig := range v.Servers {
    64  		server := &protocol.ServerEndpoint{
    65  			Address: serverConfig.Address.Build(),
    66  			Port:    uint32(serverConfig.Port),
    67  		}
    68  		for _, rawUser := range serverConfig.Users {
    69  			user := new(protocol.User)
    70  			if err := json.Unmarshal(rawUser, user); err != nil {
    71  				return nil, newError("failed to parse HTTP user").Base(err).AtError()
    72  			}
    73  			account := new(HTTPAccount)
    74  			if err := json.Unmarshal(rawUser, account); err != nil {
    75  				return nil, newError("failed to parse HTTP account").Base(err).AtError()
    76  			}
    77  			user.Account = serial.ToTypedMessage(account.Build())
    78  			server.User = append(server.User, user)
    79  		}
    80  		config.Server[idx] = server
    81  	}
    82  	return config, nil
    83  }