process.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package tuic
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "syscall"
  14. "time"
  15. "github.com/mhsanaei/3x-ui/v3/internal/config"
  16. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  17. )
  18. func GetBinaryName() string {
  19. name := fmt.Sprintf("tuic-server-%s-%s", runtime.GOOS, runtime.GOARCH)
  20. if runtime.GOOS == "windows" {
  21. name += ".exe"
  22. }
  23. return name
  24. }
  25. func GetBinaryPath() string {
  26. custom := filepath.Join(config.GetBinFolderPath(), GetBinaryName())
  27. if _, err := os.Stat(custom); err == nil {
  28. return custom
  29. }
  30. binTuic := filepath.Join(config.GetBinFolderPath(), "tuic-server")
  31. if runtime.GOOS == "windows" {
  32. binTuic += ".exe"
  33. }
  34. if _, err := os.Stat(binTuic); err == nil {
  35. return binTuic
  36. }
  37. for _, p := range []string{"/usr/local/bin/tuic-server", "/usr/bin/tuic-server"} {
  38. if _, err := os.Stat(p); err == nil {
  39. return p
  40. }
  41. }
  42. if path, err := exec.LookPath("tuic-server"); err == nil {
  43. return path
  44. }
  45. return binTuic
  46. }
  47. var (
  48. gracefulStopTimeout = 5 * time.Second
  49. forceStopTimeout = 2 * time.Second
  50. )
  51. type procLogWriter struct {
  52. mu sync.Mutex
  53. label string
  54. buf string
  55. lastLine string
  56. uuidToEmail map[string]string
  57. lastActive map[string]int64
  58. }
  59. func (w *procLogWriter) Write(p []byte) (int, error) {
  60. w.mu.Lock()
  61. defer w.mu.Unlock()
  62. w.buf += string(p)
  63. for {
  64. i := strings.IndexByte(w.buf, '\n')
  65. if i < 0 {
  66. break
  67. }
  68. line := w.buf[:i]
  69. w.buf = w.buf[i+1:]
  70. w.emitLocked(line)
  71. }
  72. return len(p), nil
  73. }
  74. func (w *procLogWriter) Flush() {
  75. w.mu.Lock()
  76. defer w.mu.Unlock()
  77. if w.buf != "" {
  78. line := w.buf
  79. w.buf = ""
  80. w.emitLocked(line)
  81. }
  82. }
  83. func (w *procLogWriter) emitLocked(line string) {
  84. trimmed := strings.TrimSpace(strings.TrimRight(line, "\r"))
  85. if trimmed == "" {
  86. return
  87. }
  88. w.lastLine = trimmed
  89. logger.Infof("tuic: tuic-server %s | %s", w.label, trimmed)
  90. now := time.Now().UnixMilli()
  91. lowerLine := strings.ToLower(line)
  92. for uuid, email := range w.uuidToEmail {
  93. if strings.Contains(lowerLine, uuid) {
  94. if w.lastActive == nil {
  95. w.lastActive = make(map[string]int64)
  96. }
  97. w.lastActive[email] = now
  98. }
  99. }
  100. }
  101. func (w *procLogWriter) LastLine() string {
  102. w.mu.Lock()
  103. defer w.mu.Unlock()
  104. return w.lastLine
  105. }
  106. type Process struct {
  107. mu sync.RWMutex
  108. cmd *exec.Cmd
  109. done chan struct{}
  110. configPath string
  111. logWriter *procLogWriter
  112. exitErr error
  113. intentionalStop atomic.Bool
  114. }
  115. func newProcess(configPath, label string, uuidToEmail map[string]string) *Process {
  116. return &Process{
  117. configPath: configPath,
  118. logWriter: &procLogWriter{
  119. label: label,
  120. uuidToEmail: uuidToEmail,
  121. lastActive: make(map[string]int64),
  122. },
  123. }
  124. }
  125. func (p *Process) GetActiveEmails(window time.Duration) []string {
  126. if p == nil || p.logWriter == nil {
  127. return nil
  128. }
  129. p.logWriter.mu.Lock()
  130. defer p.logWriter.mu.Unlock()
  131. cutoff := time.Now().Add(-window).UnixMilli()
  132. var active []string
  133. for email, last := range p.logWriter.lastActive {
  134. if last >= cutoff {
  135. active = append(active, email)
  136. }
  137. }
  138. return active
  139. }
  140. func (p *Process) UpdateClients(uuidToEmail map[string]string) {
  141. if p == nil || p.logWriter == nil {
  142. return
  143. }
  144. p.logWriter.mu.Lock()
  145. defer p.logWriter.mu.Unlock()
  146. p.logWriter.uuidToEmail = uuidToEmail
  147. }
  148. func (p *Process) IsRunning() bool {
  149. p.mu.RLock()
  150. cmd, done := p.cmd, p.done
  151. p.mu.RUnlock()
  152. if cmd == nil || cmd.Process == nil {
  153. return false
  154. }
  155. if done != nil {
  156. select {
  157. case <-done:
  158. return false
  159. default:
  160. }
  161. }
  162. return true
  163. }
  164. func (p *Process) GetResult() string {
  165. if line := p.logWriter.LastLine(); line != "" {
  166. return line
  167. }
  168. p.mu.RLock()
  169. exitErr := p.exitErr
  170. p.mu.RUnlock()
  171. if exitErr != nil {
  172. return exitErr.Error()
  173. }
  174. return ""
  175. }
  176. func (p *Process) Start() error {
  177. if p.IsRunning() {
  178. return errors.New("tuic-server is already running")
  179. }
  180. cmd := exec.CommandContext(context.Background(), GetBinaryPath(), "-c", p.configPath)
  181. cmd.Stdout = p.logWriter
  182. cmd.Stderr = p.logWriter
  183. done := make(chan struct{})
  184. p.mu.Lock()
  185. p.cmd = cmd
  186. p.done = done
  187. p.exitErr = nil
  188. p.mu.Unlock()
  189. p.intentionalStop.Store(false)
  190. if err := cmd.Start(); err != nil {
  191. close(done)
  192. p.mu.Lock()
  193. p.cmd = nil
  194. p.mu.Unlock()
  195. return err
  196. }
  197. attachChildLifetime(cmd)
  198. go p.wait(cmd, done)
  199. return nil
  200. }
  201. func (p *Process) wait(cmd *exec.Cmd, done chan struct{}) {
  202. defer close(done)
  203. err := cmd.Wait()
  204. p.logWriter.Flush()
  205. if err == nil || p.intentionalStop.Load() {
  206. return
  207. }
  208. if runtime.GOOS == "windows" {
  209. if strings.Contains(strings.ToLower(err.Error()), "exit status 1") {
  210. p.setExitErr(err)
  211. return
  212. }
  213. }
  214. logger.Errorf("tuic: tuic-server process exited: %v", err)
  215. p.setExitErr(err)
  216. }
  217. func (p *Process) setExitErr(err error) {
  218. p.mu.Lock()
  219. p.exitErr = err
  220. p.mu.Unlock()
  221. }
  222. func (p *Process) Stop() error {
  223. if !p.IsRunning() {
  224. return errors.New("tuic-server is not running")
  225. }
  226. p.intentionalStop.Store(true)
  227. p.mu.RLock()
  228. cmd, done := p.cmd, p.done
  229. p.mu.RUnlock()
  230. if cmd == nil || cmd.Process == nil {
  231. return errors.New("tuic-server is not running")
  232. }
  233. if runtime.GOOS == "windows" {
  234. if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  235. return err
  236. }
  237. return waitForExit(done, forceStopTimeout)
  238. }
  239. if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
  240. if errors.Is(err, os.ErrProcessDone) {
  241. return waitForExit(done, forceStopTimeout)
  242. }
  243. return err
  244. }
  245. if err := waitForExit(done, gracefulStopTimeout); err == nil {
  246. return nil
  247. }
  248. logger.Warning("tuic: tuic-server did not stop after SIGTERM, killing process")
  249. if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  250. return err
  251. }
  252. return waitForExit(done, forceStopTimeout)
  253. }
  254. func waitForExit(done <-chan struct{}, timeout time.Duration) error {
  255. if done == nil {
  256. return nil
  257. }
  258. timer := time.NewTimer(timeout)
  259. defer timer.Stop()
  260. select {
  261. case <-done:
  262. return nil
  263. case <-timer.C:
  264. return fmt.Errorf("timed out waiting for tuic-server process to stop after %s", timeout)
  265. }
  266. }