local.go 10 KB

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