1
0

config.go 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package tuic
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "github.com/mhsanaei/3x-ui/v3/internal/config"
  8. )
  9. type ServerConfig struct {
  10. Server string `json:"server"`
  11. Users map[string]string `json:"users"`
  12. Certificate string `json:"certificate"`
  13. PrivateKey string `json:"private_key"`
  14. CongestionControl string `json:"congestion_control"`
  15. ALPN []string `json:"alpn"`
  16. ZeroRTTHandshake bool `json:"zero_rtt_handshake"`
  17. LogLevel string `json:"log_level"`
  18. MaxIdleTime string `json:"max_idle_time,omitempty"`
  19. AuthTimeout string `json:"auth_timeout,omitempty"`
  20. MaxExternalPacketSize int `json:"max_external_packet_size,omitempty"`
  21. }
  22. // bind is where the sidecar itself listens: a loopback port behind the
  23. // panel's relay, never the inbound's public address (see udpRelay).
  24. func GenerateConfig(inst Instance, bind string) ([]byte, error) {
  25. users := make(map[string]string, len(inst.Clients))
  26. for _, c := range inst.Clients {
  27. if c.UUID != "" && c.Password != "" {
  28. users[c.UUID] = c.Password
  29. }
  30. }
  31. authTimeoutStr := ""
  32. if inst.AuthenticationTimeout > 0 {
  33. authTimeoutStr = fmt.Sprintf("%ds", inst.AuthenticationTimeout)
  34. }
  35. maxIdleStr := ""
  36. if inst.MaxIdleTime > 0 {
  37. maxIdleStr = fmt.Sprintf("%ds", inst.MaxIdleTime)
  38. }
  39. logLevel := inst.LogLevel
  40. if logLevel == "" {
  41. logLevel = "info"
  42. }
  43. cfg := ServerConfig{
  44. Server: bind,
  45. Users: users,
  46. Certificate: inst.Certificate,
  47. PrivateKey: inst.PrivateKey,
  48. CongestionControl: inst.CongestionControl,
  49. ALPN: inst.ALPN,
  50. ZeroRTTHandshake: inst.ZeroRTTHandshake,
  51. LogLevel: logLevel,
  52. AuthTimeout: authTimeoutStr,
  53. MaxIdleTime: maxIdleStr,
  54. MaxExternalPacketSize: inst.MaxUdpRelayPacketSize,
  55. }
  56. return json.MarshalIndent(cfg, "", " ")
  57. }
  58. func ConfigDir() string {
  59. return filepath.Join(config.GetBinFolderPath(), "tuic")
  60. }
  61. func ConfigPathForID(id int) string {
  62. return filepath.Join(ConfigDir(), fmt.Sprintf("tuic_%d.json", id))
  63. }
  64. func WriteConfigFile(id int, data []byte) (string, error) {
  65. dir := ConfigDir()
  66. if err := os.MkdirAll(dir, 0o755); err != nil {
  67. return "", err
  68. }
  69. path := ConfigPathForID(id)
  70. if err := os.WriteFile(path, data, 0o600); err != nil {
  71. return "", err
  72. }
  73. return path, nil
  74. }
  75. func RemoveConfigFile(id int) error {
  76. path := ConfigPathForID(id)
  77. if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
  78. return err
  79. }
  80. return nil
  81. }