http.go 2.3 KB

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