local.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package runtime
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  10. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. )
  15. type LocalDeps struct {
  16. APIPort func() int
  17. SetNeedRestart func()
  18. }
  19. type Local struct {
  20. deps LocalDeps
  21. mu sync.Mutex
  22. }
  23. func NewLocal(deps LocalDeps) *Local {
  24. return &Local{deps: deps}
  25. }
  26. func (l *Local) Name() string { return "local" }
  27. func (l *Local) withAPI(fn func(api *xray.XrayAPI) error) error {
  28. l.mu.Lock()
  29. defer l.mu.Unlock()
  30. port := l.deps.APIPort()
  31. if port <= 0 {
  32. return errors.New("local xray is not running")
  33. }
  34. var api xray.XrayAPI
  35. if err := api.Init(port); err != nil {
  36. return err
  37. }
  38. defer api.Close()
  39. return fn(&api)
  40. }
  41. func (l *Local) AddInbound(_ context.Context, ib *model.Inbound) error {
  42. if ib.Protocol == model.MTProto {
  43. inst, ok := mtproto.InstanceFromInbound(ib)
  44. if !ok {
  45. return nil
  46. }
  47. return mtproto.GetManager().Ensure(inst)
  48. }
  49. if ib.Protocol == model.AmneziaWG {
  50. inst, ok := amneziawg.InstanceFromInbound(ib)
  51. if !ok {
  52. return nil
  53. }
  54. err := amneziawgnet.GetManager().Ensure(amneziawgnet.Desired{
  55. Instance: inst,
  56. Options: amneziawgnet.DeviceOptions{
  57. HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
  58. ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
  59. RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
  60. RekeyTimeout: inst.Obfuscation.RekeyTimeout,
  61. RejectAfterTime: inst.Obfuscation.RejectAfterTime,
  62. KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
  63. MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
  64. RandomTrailers: inst.Obfuscation.RandomTrailers,
  65. DisableCookies: inst.Obfuscation.DisableCookies,
  66. },
  67. })
  68. // A brand new inbound can be the first one to qualify for
  69. // injectAmneziawgnetSocks's Xray-side relay inbound (e.g. its first
  70. // valid peer). Ensure only updates the embedded Device -- flag Xray
  71. // for a resync so the relay actually gets created within the next
  72. // ApplyPendingRestart tick instead of only at the next full restart.
  73. if l.deps.SetNeedRestart != nil {
  74. l.deps.SetNeedRestart()
  75. }
  76. return err
  77. }
  78. body, err := json.MarshalIndent(ib.GenXrayInboundConfig(), "", " ")
  79. if err != nil {
  80. return err
  81. }
  82. return l.withAPI(func(api *xray.XrayAPI) error {
  83. return api.AddInbound(body)
  84. })
  85. }
  86. func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error {
  87. if ib.Protocol == model.MTProto {
  88. mtproto.GetManager().Remove(ib.Id)
  89. return nil
  90. }
  91. if ib.Protocol == model.AmneziaWG {
  92. amneziawgnet.GetManager().Remove(ib.Id)
  93. // The removed inbound may have been the only one backing Xray's
  94. // injectAmneziawgnetSocks relay inbound for this tag -- flag a
  95. // resync so the now-stale relay gets torn down promptly.
  96. if l.deps.SetNeedRestart != nil {
  97. l.deps.SetNeedRestart()
  98. }
  99. return nil
  100. }
  101. return l.withAPI(func(api *xray.XrayAPI) error {
  102. return api.DelInbound(ib.Tag)
  103. })
  104. }
  105. func (l *Local) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  106. if oldIb.Protocol == model.MTProto || newIb.Protocol == model.MTProto {
  107. return l.updateMtprotoInbound(ctx, oldIb, newIb)
  108. }
  109. if oldIb.Protocol == model.AmneziaWG || newIb.Protocol == model.AmneziaWG {
  110. return l.updateAmneziaWGInbound(ctx, oldIb, newIb)
  111. }
  112. _ = l.DelInbound(ctx, oldIb)
  113. if !newIb.Enable {
  114. return nil
  115. }
  116. return l.AddInbound(ctx, newIb)
  117. }
  118. // updateMtprotoInbound applies an inbound update without the Del+Add sequence
  119. // the xray path uses: Remove would drop the manager's fingerprint state, which
  120. // is what lets Ensure keep the running mtg process (and its live connections)
  121. // when nothing in the generated config changed. The sidecar is only stopped
  122. // when the inbound is disabled, loses its last active secret, or moves to a
  123. // different protocol.
  124. func (l *Local) updateMtprotoInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  125. if oldIb.Protocol == model.MTProto && newIb.Protocol != model.MTProto {
  126. mtproto.GetManager().Remove(oldIb.Id)
  127. if !newIb.Enable {
  128. return nil
  129. }
  130. return l.AddInbound(ctx, newIb)
  131. }
  132. if oldIb.Protocol != model.MTProto {
  133. _ = l.DelInbound(ctx, oldIb)
  134. }
  135. if !newIb.Enable {
  136. mtproto.GetManager().Remove(newIb.Id)
  137. return nil
  138. }
  139. inst, ok := mtproto.InstanceFromInbound(newIb)
  140. if !ok {
  141. mtproto.GetManager().Remove(newIb.Id)
  142. return nil
  143. }
  144. return mtproto.GetManager().Ensure(inst)
  145. }
  146. // updateAmneziaWGInbound mirrors updateMtprotoInbound: it skips the
  147. // Remove+Ensure sequence a plain Del+Add would force so that, on an
  148. // AmneziaWG-to-AmneziaWG edit, Manager.Ensure's own fingerprint comparison
  149. // can reconfigure the running embedded Device in place via IpcSet instead
  150. // of always rebuilding it (see internal/amneziawgnet.Manager.ensureLocked --
  151. // only an address or effective-MTU change forces a rebuild there, S4
  152. // included, not a peer edit).
  153. //
  154. // Every exit path below only touches the embedded Device via
  155. // amneziawgnet.GetManager() -- none of it rebuilds Xray's own config, which
  156. // is what actually creates/removes injectAmneziawgnetSocks's relay inbound.
  157. // A peer edit that changes whether this inbound has a qualifying peer at
  158. // all (its first peer added, or its last one removed) must still get that
  159. // relay created or torn down, so flag Xray for a resync unconditionally
  160. // here rather than trying to enumerate which of the branches below need it.
  161. func (l *Local) updateAmneziaWGInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  162. if l.deps.SetNeedRestart != nil {
  163. l.deps.SetNeedRestart()
  164. }
  165. if oldIb.Protocol == model.AmneziaWG && newIb.Protocol != model.AmneziaWG {
  166. amneziawgnet.GetManager().Remove(oldIb.Id)
  167. if !newIb.Enable {
  168. return nil
  169. }
  170. return l.AddInbound(ctx, newIb)
  171. }
  172. if oldIb.Protocol != model.AmneziaWG {
  173. _ = l.DelInbound(ctx, oldIb)
  174. }
  175. if !newIb.Enable {
  176. amneziawgnet.GetManager().Remove(newIb.Id)
  177. return nil
  178. }
  179. inst, ok := amneziawg.InstanceFromInbound(newIb)
  180. if !ok {
  181. amneziawgnet.GetManager().Remove(newIb.Id)
  182. return nil
  183. }
  184. return amneziawgnet.GetManager().Ensure(amneziawgnet.Desired{
  185. Instance: inst,
  186. Options: amneziawgnet.DeviceOptions{
  187. HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
  188. ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
  189. RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
  190. RekeyTimeout: inst.Obfuscation.RekeyTimeout,
  191. RejectAfterTime: inst.Obfuscation.RejectAfterTime,
  192. KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
  193. MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
  194. RandomTrailers: inst.Obfuscation.RandomTrailers,
  195. DisableCookies: inst.Obfuscation.DisableCookies,
  196. },
  197. })
  198. }
  199. func (l *Local) AddUser(_ context.Context, ib *model.Inbound, userMap map[string]any) error {
  200. if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG {
  201. return nil
  202. }
  203. return l.withAPI(func(api *xray.XrayAPI) error {
  204. return api.AddUser(string(ib.Protocol), ib.Tag, userMap)
  205. })
  206. }
  207. func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) error {
  208. if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG {
  209. return nil
  210. }
  211. return l.withAPI(func(api *xray.XrayAPI) error {
  212. return api.RemoveUser(ib.Tag, email)
  213. })
  214. }
  215. func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  216. if !client.Enable {
  217. return nil
  218. }
  219. user := map[string]any{
  220. "email": client.Email,
  221. "id": client.ID,
  222. "security": client.Security,
  223. "flow": client.Flow,
  224. "auth": client.Auth,
  225. "password": client.Password,
  226. "publicKey": client.PublicKey,
  227. "allowedIPs": client.AllowedIPs,
  228. "preSharedKey": client.PreSharedKey,
  229. "keepAlive": wgKeepAlive(client.KeepAlive),
  230. }
  231. return l.AddUser(ctx, ib, user)
  232. }
  233. func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error {
  234. if email == "" {
  235. return nil
  236. }
  237. if err := l.RemoveUser(ctx, ib, email); err != nil {
  238. if strings.Contains(err.Error(), "not found") {
  239. return nil
  240. }
  241. return err
  242. }
  243. return nil
  244. }
  245. func (l *Local) DeleteClient(context.Context, string) error {
  246. return nil
  247. }
  248. func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error {
  249. if oldEmail != "" {
  250. if err := l.RemoveUser(ctx, ib, oldEmail); err != nil && !strings.Contains(err.Error(), "not found") {
  251. return err
  252. }
  253. }
  254. if !payload.Enable {
  255. return nil
  256. }
  257. user := map[string]any{
  258. "email": payload.Email,
  259. "id": payload.ID,
  260. "security": payload.Security,
  261. "flow": payload.Flow,
  262. "auth": payload.Auth,
  263. "password": payload.Password,
  264. "publicKey": payload.PublicKey,
  265. "allowedIPs": payload.AllowedIPs,
  266. "preSharedKey": payload.PreSharedKey,
  267. "keepAlive": wgKeepAlive(payload.KeepAlive),
  268. }
  269. return l.AddUser(ctx, ib, user)
  270. }
  271. func wgKeepAlive(seconds int) string {
  272. if seconds <= 0 {
  273. return ""
  274. }
  275. return strconv.Itoa(seconds)
  276. }
  277. func (l *Local) RestartXray(_ context.Context) error {
  278. if l.deps.SetNeedRestart != nil {
  279. l.deps.SetNeedRestart()
  280. }
  281. return nil
  282. }
  283. func (l *Local) ResetClientTraffic(_ context.Context, _ *model.Inbound, _ string) error {
  284. return nil
  285. }
  286. func (l *Local) ResetAllTraffics(_ context.Context) error {
  287. return nil
  288. }
  289. func (l *Local) ResetInboundTraffic(_ context.Context, _ *model.Inbound) error {
  290. return nil
  291. }