1
0

local.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. err := tuic.GetManager().Ensure(inst)
  85. if l.deps.SetNeedRestart != nil {
  86. l.deps.SetNeedRestart()
  87. }
  88. return err
  89. }
  90. body, err := json.MarshalIndent(ib.GenXrayInboundConfig(), "", " ")
  91. if err != nil {
  92. return err
  93. }
  94. return l.withAPI(func(api *xray.XrayAPI) error {
  95. return api.AddInbound(body)
  96. })
  97. }
  98. func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error {
  99. if ib.Protocol == model.MTProto {
  100. mtproto.GetManager().Remove(ib.Id)
  101. return nil
  102. }
  103. if ib.Protocol == model.AmneziaWG {
  104. amneziawgnet.GetManager().Remove(ib.Id)
  105. // The removed inbound may have been the only one backing Xray's
  106. // injectAmneziawgnetSocks relay inbound for this tag -- flag a
  107. // resync so the now-stale relay gets torn down promptly.
  108. if l.deps.SetNeedRestart != nil {
  109. l.deps.SetNeedRestart()
  110. }
  111. return nil
  112. }
  113. if ib.Protocol == model.TUIC {
  114. tuic.GetManager().Remove(ib.Id)
  115. if l.deps.SetNeedRestart != nil {
  116. l.deps.SetNeedRestart()
  117. }
  118. return nil
  119. }
  120. return l.withAPI(func(api *xray.XrayAPI) error {
  121. return api.DelInbound(ib.Tag)
  122. })
  123. }
  124. func (l *Local) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  125. if oldIb.Protocol == model.MTProto || newIb.Protocol == model.MTProto {
  126. return l.updateMtprotoInbound(ctx, oldIb, newIb)
  127. }
  128. if oldIb.Protocol == model.AmneziaWG || newIb.Protocol == model.AmneziaWG {
  129. return l.updateAmneziaWGInbound(ctx, oldIb, newIb)
  130. }
  131. if oldIb.Protocol == model.TUIC || newIb.Protocol == model.TUIC {
  132. return l.updateTuicInbound(ctx, oldIb, newIb)
  133. }
  134. _ = l.DelInbound(ctx, oldIb)
  135. if !newIb.Enable {
  136. return nil
  137. }
  138. return l.AddInbound(ctx, newIb)
  139. }
  140. // updateMtprotoInbound applies an inbound update without the Del+Add sequence
  141. // the xray path uses: Remove would drop the manager's fingerprint state, which
  142. // is what lets Ensure keep the running mtg process (and its live connections)
  143. // when nothing in the generated config changed. The sidecar is only stopped
  144. // when the inbound is disabled, loses its last active secret, or moves to a
  145. // different protocol.
  146. func (l *Local) updateMtprotoInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  147. if oldIb.Protocol == model.MTProto && newIb.Protocol != model.MTProto {
  148. mtproto.GetManager().Remove(oldIb.Id)
  149. if !newIb.Enable {
  150. return nil
  151. }
  152. return l.AddInbound(ctx, newIb)
  153. }
  154. if oldIb.Protocol != model.MTProto {
  155. _ = l.DelInbound(ctx, oldIb)
  156. }
  157. if !newIb.Enable {
  158. mtproto.GetManager().Remove(newIb.Id)
  159. return nil
  160. }
  161. inst, ok := mtproto.InstanceFromInbound(newIb)
  162. if !ok {
  163. mtproto.GetManager().Remove(newIb.Id)
  164. return nil
  165. }
  166. return mtproto.GetManager().Ensure(inst)
  167. }
  168. // updateAmneziaWGInbound mirrors updateMtprotoInbound: it skips the
  169. // Remove+Ensure sequence a plain Del+Add would force so that, on an
  170. // AmneziaWG-to-AmneziaWG edit, Manager.Ensure's own fingerprint comparison
  171. // can reconfigure the running embedded Device in place via IpcSet instead
  172. // of always rebuilding it (see internal/amneziawgnet.Manager.ensureLocked --
  173. // only an address or effective-MTU change forces a rebuild there, S4
  174. // included, not a peer edit).
  175. //
  176. // Every exit path below only touches the embedded Device via
  177. // amneziawgnet.GetManager() -- none of it rebuilds Xray's own config, which
  178. // is what actually creates/removes injectAmneziawgnetSocks's relay inbound.
  179. // A peer edit that changes whether this inbound has a qualifying peer at
  180. // all (its first peer added, or its last one removed) must still get that
  181. // relay created or torn down, so flag Xray for a resync unconditionally
  182. // here rather than trying to enumerate which of the branches below need it.
  183. func (l *Local) updateAmneziaWGInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  184. if l.deps.SetNeedRestart != nil {
  185. l.deps.SetNeedRestart()
  186. }
  187. if oldIb.Protocol == model.AmneziaWG && newIb.Protocol != model.AmneziaWG {
  188. amneziawgnet.GetManager().Remove(oldIb.Id)
  189. if !newIb.Enable {
  190. return nil
  191. }
  192. return l.AddInbound(ctx, newIb)
  193. }
  194. if oldIb.Protocol != model.AmneziaWG {
  195. _ = l.DelInbound(ctx, oldIb)
  196. }
  197. if !newIb.Enable {
  198. amneziawgnet.GetManager().Remove(newIb.Id)
  199. return nil
  200. }
  201. inst, ok := amneziawg.InstanceFromInbound(newIb)
  202. if !ok {
  203. amneziawgnet.GetManager().Remove(newIb.Id)
  204. return nil
  205. }
  206. return amneziawgnet.GetManager().Ensure(amneziawgnet.Desired{
  207. Instance: inst,
  208. Options: amneziawgnet.DeviceOptions{
  209. HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
  210. ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
  211. RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
  212. RekeyTimeout: inst.Obfuscation.RekeyTimeout,
  213. RejectAfterTime: inst.Obfuscation.RejectAfterTime,
  214. KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
  215. MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
  216. RandomTrailers: inst.Obfuscation.RandomTrailers,
  217. DisableCookies: inst.Obfuscation.DisableCookies,
  218. },
  219. })
  220. }
  221. func (l *Local) updateTuicInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
  222. if oldIb.Protocol == model.TUIC && newIb.Protocol != model.TUIC {
  223. tuic.GetManager().Remove(oldIb.Id)
  224. if l.deps.SetNeedRestart != nil {
  225. l.deps.SetNeedRestart()
  226. }
  227. if !newIb.Enable {
  228. return nil
  229. }
  230. return l.AddInbound(ctx, newIb)
  231. }
  232. if oldIb.Protocol != model.TUIC {
  233. _ = l.DelInbound(ctx, oldIb)
  234. if l.deps.SetNeedRestart != nil {
  235. l.deps.SetNeedRestart()
  236. }
  237. }
  238. if oldIb.Protocol == model.TUIC && newIb.Protocol == model.TUIC && oldIb.Enable && newIb.Enable && oldIb.Tag != newIb.Tag && l.deps.SetNeedRestart != nil {
  239. l.deps.SetNeedRestart()
  240. }
  241. if !newIb.Enable {
  242. tuic.GetManager().Remove(newIb.Id)
  243. if oldIb.Enable && l.deps.SetNeedRestart != nil {
  244. l.deps.SetNeedRestart()
  245. }
  246. return nil
  247. }
  248. if !oldIb.Enable && newIb.Enable {
  249. if l.deps.SetNeedRestart != nil {
  250. l.deps.SetNeedRestart()
  251. }
  252. }
  253. inst, ok := tuic.InstanceFromInbound(newIb)
  254. if !ok {
  255. tuic.GetManager().Remove(newIb.Id)
  256. return nil
  257. }
  258. return tuic.GetManager().Ensure(inst)
  259. }
  260. func (l *Local) AddUser(_ context.Context, ib *model.Inbound, userMap map[string]any) error {
  261. if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG || ib.Protocol == model.TUIC {
  262. return nil
  263. }
  264. return l.withAPI(func(api *xray.XrayAPI) error {
  265. return api.AddUser(string(ib.Protocol), ib.Tag, userMap)
  266. })
  267. }
  268. func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) error {
  269. if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG || ib.Protocol == model.TUIC {
  270. return nil
  271. }
  272. return l.withAPI(func(api *xray.XrayAPI) error {
  273. return api.RemoveUser(ib.Tag, email)
  274. })
  275. }
  276. func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error {
  277. if !client.Enable {
  278. return nil
  279. }
  280. user := map[string]any{
  281. "email": client.Email,
  282. "id": client.ID,
  283. "security": client.Security,
  284. "flow": client.Flow,
  285. "auth": client.Auth,
  286. "password": client.Password,
  287. "publicKey": client.PublicKey,
  288. "allowedIPs": client.AllowedIPs,
  289. "preSharedKey": client.PreSharedKey,
  290. "keepAlive": wgKeepAlive(client.KeepAliveSeconds()),
  291. }
  292. return l.AddUser(ctx, ib, user)
  293. }
  294. func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error {
  295. if email == "" {
  296. return nil
  297. }
  298. if err := l.RemoveUser(ctx, ib, email); err != nil {
  299. if strings.Contains(err.Error(), "not found") {
  300. return nil
  301. }
  302. return err
  303. }
  304. return nil
  305. }
  306. func (l *Local) DeleteClient(context.Context, string) error {
  307. return nil
  308. }
  309. func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error {
  310. if oldEmail != "" {
  311. if err := l.RemoveUser(ctx, ib, oldEmail); err != nil && !strings.Contains(err.Error(), "not found") {
  312. return err
  313. }
  314. }
  315. if !payload.Enable {
  316. return nil
  317. }
  318. user := map[string]any{
  319. "email": payload.Email,
  320. "id": payload.ID,
  321. "security": payload.Security,
  322. "flow": payload.Flow,
  323. "auth": payload.Auth,
  324. "password": payload.Password,
  325. "publicKey": payload.PublicKey,
  326. "allowedIPs": payload.AllowedIPs,
  327. "preSharedKey": payload.PreSharedKey,
  328. "keepAlive": wgKeepAlive(payload.KeepAliveSeconds()),
  329. }
  330. return l.AddUser(ctx, ib, user)
  331. }
  332. func wgKeepAlive(seconds int) string {
  333. if seconds <= 0 {
  334. return ""
  335. }
  336. return strconv.Itoa(seconds)
  337. }
  338. func (l *Local) RestartXray(_ context.Context) error {
  339. if l.deps.SetNeedRestart != nil {
  340. l.deps.SetNeedRestart()
  341. }
  342. return nil
  343. }
  344. func (l *Local) ResetClientTraffic(_ context.Context, _ *model.Inbound, _ string) error {
  345. return nil
  346. }
  347. func (l *Local) ResetAllTraffics(_ context.Context) error {
  348. return nil
  349. }
  350. func (l *Local) ResetInboundTraffic(_ context.Context, _ *model.Inbound) error {
  351. return nil
  352. }