local.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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/MTU change forces a rebuild there, not a peer edit).
  152. //
  153. // Every exit path below only touches the embedded Device via
  154. // amneziawgnet.GetManager() -- none of it rebuilds Xray's own config, which
  155. // is what actually creates/removes injectAmneziawgnetSocks's relay inbound.
  156. // A peer edit that changes whether this inbound has a qualifying peer at
  157. // all (its first peer added, or its last one removed) must still get that
  158. // relay created or torn down, so flag Xray for a resync unconditionally
  159. // here rather than trying to enumerate which of the branches below need it.
  160. func (l *Local) updateAmneziaWGInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  161. if l.deps.SetNeedRestart != nil {
  162. l.deps.SetNeedRestart()
  163. }
  164. if oldIb.Protocol == model.AmneziaWG && newIb.Protocol != model.AmneziaWG {
  165. amneziawgnet.GetManager().Remove(oldIb.Id)
  166. if !newIb.Enable {
  167. return nil
  168. }
  169. return l.AddInbound(ctx, newIb)
  170. }
  171. if oldIb.Protocol != model.AmneziaWG {
  172. _ = l.DelInbound(ctx, oldIb)
  173. }
  174. if !newIb.Enable {
  175. amneziawgnet.GetManager().Remove(newIb.Id)
  176. return nil
  177. }
  178. inst, ok := amneziawg.InstanceFromInbound(newIb)
  179. if !ok {
  180. amneziawgnet.GetManager().Remove(newIb.Id)
  181. return nil
  182. }
  183. return amneziawgnet.GetManager().Ensure(amneziawgnet.Desired{
  184. Instance: inst,
  185. Options: amneziawgnet.DeviceOptions{
  186. HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
  187. ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
  188. RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
  189. RekeyTimeout: inst.Obfuscation.RekeyTimeout,
  190. RejectAfterTime: inst.Obfuscation.RejectAfterTime,
  191. KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
  192. MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
  193. RandomTrailers: inst.Obfuscation.RandomTrailers,
  194. DisableCookies: inst.Obfuscation.DisableCookies,
  195. },
  196. })
  197. }
  198. func (l *Local) AddUser(_ context.Context, ib *model.Inbound, userMap map[string]any) error {
  199. if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG {
  200. return nil
  201. }
  202. return l.withAPI(func(api *xray.XrayAPI) error {
  203. return api.AddUser(string(ib.Protocol), ib.Tag, userMap)
  204. })
  205. }
  206. func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) error {
  207. if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG {
  208. return nil
  209. }
  210. return l.withAPI(func(api *xray.XrayAPI) error {
  211. return api.RemoveUser(ib.Tag, email)
  212. })
  213. }
  214. func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  215. if !client.Enable {
  216. return nil
  217. }
  218. user := map[string]any{
  219. "email": client.Email,
  220. "id": client.ID,
  221. "security": client.Security,
  222. "flow": client.Flow,
  223. "auth": client.Auth,
  224. "password": client.Password,
  225. "publicKey": client.PublicKey,
  226. "allowedIPs": client.AllowedIPs,
  227. "preSharedKey": client.PreSharedKey,
  228. "keepAlive": wgKeepAlive(client.KeepAlive),
  229. }
  230. return l.AddUser(ctx, ib, user)
  231. }
  232. func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error {
  233. if email == "" {
  234. return nil
  235. }
  236. if err := l.RemoveUser(ctx, ib, email); err != nil {
  237. if strings.Contains(err.Error(), "not found") {
  238. return nil
  239. }
  240. return err
  241. }
  242. return nil
  243. }
  244. func (l *Local) DeleteClient(context.Context, string) error {
  245. return nil
  246. }
  247. func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error {
  248. if oldEmail != "" {
  249. if err := l.RemoveUser(ctx, ib, oldEmail); err != nil && !strings.Contains(err.Error(), "not found") {
  250. return err
  251. }
  252. }
  253. if !payload.Enable {
  254. return nil
  255. }
  256. user := map[string]any{
  257. "email": payload.Email,
  258. "id": payload.ID,
  259. "security": payload.Security,
  260. "flow": payload.Flow,
  261. "auth": payload.Auth,
  262. "password": payload.Password,
  263. "publicKey": payload.PublicKey,
  264. "allowedIPs": payload.AllowedIPs,
  265. "preSharedKey": payload.PreSharedKey,
  266. "keepAlive": wgKeepAlive(payload.KeepAlive),
  267. }
  268. return l.AddUser(ctx, ib, user)
  269. }
  270. func wgKeepAlive(seconds int) string {
  271. if seconds <= 0 {
  272. return ""
  273. }
  274. return strconv.Itoa(seconds)
  275. }
  276. func (l *Local) RestartXray(_ context.Context) error {
  277. if l.deps.SetNeedRestart != nil {
  278. l.deps.SetNeedRestart()
  279. }
  280. return nil
  281. }
  282. func (l *Local) ResetClientTraffic(_ context.Context, _ *model.Inbound, _ string) error {
  283. return nil
  284. }
  285. func (l *Local) ResetAllTraffics(_ context.Context) error {
  286. return nil
  287. }
  288. func (l *Local) ResetInboundTraffic(_ context.Context, _ *model.Inbound) error {
  289. return nil
  290. }