tgbot.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. package tgbot
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "embed"
  6. "math/big"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "regexp"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/mhsanaei/3x-ui/v3/internal/eventbus"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/internal/web/global"
  20. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  21. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  22. "github.com/mymmrac/telego"
  23. th "github.com/mymmrac/telego/telegohandler"
  24. "github.com/valyala/fasthttp"
  25. "github.com/valyala/fasthttp/fasthttpproxy"
  26. )
  27. var (
  28. bot *telego.Bot
  29. // botCancel stores the function to cancel the context, stopping Long Polling gracefully.
  30. botCancel context.CancelFunc
  31. // tgBotMutex protects concurrent access to botCancel variable
  32. tgBotMutex sync.Mutex
  33. // botWG waits for the OnReceive Long Polling goroutine to finish.
  34. botWG sync.WaitGroup
  35. botHandler *th.BotHandler
  36. adminIds []int64
  37. isRunning bool
  38. hostname string
  39. hashStorage *global.HashStorage
  40. // EventBus is set from web layer to publish login/security events.
  41. EventBus *eventbus.Bus
  42. // Performance improvements
  43. messageWorkerPool chan struct{} // Semaphore for limiting concurrent message processing
  44. optimizedHTTPClient *http.Client // HTTP client with connection pooling and timeouts
  45. // Simple cache for frequently accessed data
  46. statusCache struct {
  47. data *service.Status
  48. timestamp time.Time
  49. mutex sync.RWMutex
  50. }
  51. serverStatsCache struct {
  52. data string
  53. timestamp time.Time
  54. mutex sync.RWMutex
  55. }
  56. )
  57. // clientDraft is one chat's add-client wizard state. Per-protocol secrets are
  58. // filled per-inbound on submit, so only the universal fields live here.
  59. type clientDraft struct {
  60. sync.Mutex
  61. receiverInboundID int
  62. receiverInboundIDs []int
  63. email string
  64. limitIP int
  65. totalGB int64
  66. expiryTime int64
  67. enable bool
  68. tgID string
  69. subID string
  70. comment string
  71. reset int
  72. }
  73. // clientDrafts keys a draft by chat: the steps arrive on the worker pool, so a
  74. // single draft let two admins fill in one client between them.
  75. type clientDrafts struct {
  76. mu sync.Mutex
  77. drafts map[int64]*clientDraft
  78. }
  79. var addClientDrafts = &clientDrafts{drafts: make(map[int64]*clientDraft)}
  80. func (s *clientDrafts) forChat(chatID int64) *clientDraft {
  81. s.mu.Lock()
  82. defer s.mu.Unlock()
  83. draft, ok := s.drafts[chatID]
  84. if !ok {
  85. draft = &clientDraft{}
  86. s.drafts[chatID] = draft
  87. }
  88. return draft
  89. }
  90. func (s *clientDrafts) reset(chatID int64) {
  91. s.mu.Lock()
  92. defer s.mu.Unlock()
  93. delete(s.drafts, chatID)
  94. }
  95. // isAddClientStep reports whether callback data belongs to the add-client
  96. // wizard, the only flow that reads or writes a draft.
  97. func isAddClientStep(data string) bool {
  98. return strings.HasPrefix(data, "add_client")
  99. }
  100. func (s *clientDrafts) resetAll() {
  101. s.mu.Lock()
  102. defer s.mu.Unlock()
  103. s.drafts = make(map[int64]*clientDraft)
  104. }
  105. // userStateStore guards the per-chat conversation states. The Telegram command
  106. // and callback handlers run on a worker-pool goroutine while the message handler
  107. // runs on the dispatch goroutine, so a bare map would be a concurrent-map-write
  108. // crash. It also expires abandoned conversations so a user who starts a flow and
  109. // goes silent doesn't leave an entry forever.
  110. type userStateStore struct {
  111. mu sync.Mutex
  112. states map[int64]userStateEntry
  113. lastPrune time.Time
  114. }
  115. type userStateEntry struct {
  116. state string
  117. at time.Time
  118. }
  119. var userStateMgr = &userStateStore{states: make(map[int64]userStateEntry)}
  120. func (s *userStateStore) set(chatID int64, state string) {
  121. s.mu.Lock()
  122. s.states[chatID] = userStateEntry{state: state, at: time.Now()}
  123. s.mu.Unlock()
  124. }
  125. func (s *userStateStore) get(chatID int64) (string, bool) {
  126. s.mu.Lock()
  127. defer s.mu.Unlock()
  128. e, ok := s.states[chatID]
  129. return e.state, ok
  130. }
  131. func (s *userStateStore) clear(chatID int64) {
  132. s.mu.Lock()
  133. delete(s.states, chatID)
  134. s.mu.Unlock()
  135. }
  136. func (s *userStateStore) reset() {
  137. s.mu.Lock()
  138. s.states = make(map[int64]userStateEntry)
  139. s.mu.Unlock()
  140. }
  141. // maybePrune drops conversations older than maxAge, at most once per maxAge so a
  142. // busy bot doesn't sweep the whole map on every message.
  143. func (s *userStateStore) maybePrune(maxAge time.Duration) {
  144. s.mu.Lock()
  145. defer s.mu.Unlock()
  146. now := time.Now()
  147. if now.Sub(s.lastPrune) < maxAge {
  148. return
  149. }
  150. s.lastPrune = now
  151. for id, e := range s.states {
  152. if now.Sub(e.at) > maxAge {
  153. delete(s.states, id)
  154. }
  155. }
  156. }
  157. // LoginStatus represents the result of a login attempt.
  158. type LoginStatus byte
  159. // Login status constants
  160. const (
  161. LoginSuccess LoginStatus = 1 // Login was successful
  162. LoginFail LoginStatus = 0 // Login failed
  163. EmptyTelegramUserID = int64(0) // Default value for empty Telegram user ID
  164. )
  165. // LoginAttempt contains safe metadata for panel login notifications.
  166. // It intentionally does not include attempted passwords.
  167. type LoginAttempt struct {
  168. Username string
  169. IP string
  170. Time string
  171. Status LoginStatus
  172. Reason string
  173. }
  174. // Tgbot provides business logic for Telegram bot integration.
  175. // It handles bot commands, user interactions, and status reporting via Telegram.
  176. type Tgbot struct {
  177. inboundService service.InboundService
  178. clientService service.ClientService
  179. settingService service.SettingService
  180. serverService service.ServerService
  181. xrayService service.XrayService
  182. lastStatus *service.Status
  183. }
  184. // NewTgbot creates a new Tgbot instance.
  185. func (t *Tgbot) NewTgbot() *Tgbot {
  186. return new(Tgbot)
  187. }
  188. // I18nBot retrieves a localized message for the bot interface.
  189. func (t *Tgbot) I18nBot(name string, params ...string) string {
  190. return locale.I18n(locale.Bot, name, params...)
  191. }
  192. // GetHashStorage returns the hash storage instance for callback queries.
  193. func (t *Tgbot) GetHashStorage() *global.HashStorage {
  194. return hashStorage
  195. }
  196. // getCachedStatus returns cached server status if it's fresh enough (less than 5 seconds old)
  197. func (t *Tgbot) getCachedStatus() (*service.Status, bool) {
  198. statusCache.mutex.RLock()
  199. defer statusCache.mutex.RUnlock()
  200. if statusCache.data != nil && time.Since(statusCache.timestamp) < 5*time.Second {
  201. return statusCache.data, true
  202. }
  203. return nil, false
  204. }
  205. // setCachedStatus updates the status cache
  206. func (t *Tgbot) setCachedStatus(status *service.Status) {
  207. statusCache.mutex.Lock()
  208. defer statusCache.mutex.Unlock()
  209. statusCache.data = status
  210. statusCache.timestamp = time.Now()
  211. }
  212. // getCachedServerStats returns cached server stats if it's fresh enough (less than 10 seconds old)
  213. func (t *Tgbot) getCachedServerStats() (string, bool) {
  214. serverStatsCache.mutex.RLock()
  215. defer serverStatsCache.mutex.RUnlock()
  216. if serverStatsCache.data != "" && time.Since(serverStatsCache.timestamp) < 10*time.Second {
  217. return serverStatsCache.data, true
  218. }
  219. return "", false
  220. }
  221. // setCachedServerStats updates the server stats cache
  222. func (t *Tgbot) setCachedServerStats(stats string) {
  223. serverStatsCache.mutex.Lock()
  224. defer serverStatsCache.mutex.Unlock()
  225. serverStatsCache.data = stats
  226. serverStatsCache.timestamp = time.Now()
  227. }
  228. // Start initializes and starts the Telegram bot with the provided translation files.
  229. func (t *Tgbot) Start(i18nFS embed.FS) error {
  230. // Initialize localizer
  231. err := locale.InitLocalizer(i18nFS, &t.settingService)
  232. if err != nil {
  233. return err
  234. }
  235. // If Start is called again (e.g. during reload), ensure any previous long-polling
  236. // loop is stopped before creating a new bot / receiver.
  237. StopBot()
  238. // Initialize hash storage to store callback queries
  239. hashStorage = global.NewHashStorage(20 * time.Minute)
  240. // Initialize worker pool for concurrent message processing (max 10 concurrent handlers)
  241. messageWorkerPool = make(chan struct{}, 10)
  242. // Initialize optimized HTTP client with connection pooling
  243. optimizedHTTPClient = &http.Client{
  244. Timeout: 15 * time.Second,
  245. Transport: &http.Transport{
  246. MaxIdleConns: 100,
  247. MaxIdleConnsPerHost: 10,
  248. IdleConnTimeout: 30 * time.Second,
  249. DisableKeepAlives: false,
  250. },
  251. }
  252. t.SetHostname()
  253. // Get Telegram bot token
  254. tgBotToken, err := t.settingService.GetTgBotToken()
  255. if err != nil || tgBotToken == "" {
  256. logger.Warning("Failed to get Telegram bot token:", err)
  257. return err
  258. }
  259. // Get Telegram bot chat ID(s)
  260. tgBotID, err := t.settingService.GetTgBotChatId()
  261. if err != nil {
  262. logger.Warning("Failed to get Telegram bot chat ID:", err)
  263. return err
  264. }
  265. parsedAdminIds := make([]int64, 0)
  266. // Parse admin IDs from comma-separated string
  267. if tgBotID != "" {
  268. for adminID := range strings.SplitSeq(tgBotID, ",") {
  269. id, err := strconv.ParseInt(adminID, 10, 64)
  270. if err != nil {
  271. logger.Warning("Failed to parse admin ID from Telegram bot chat ID:", err)
  272. return err
  273. }
  274. parsedAdminIds = append(parsedAdminIds, id)
  275. }
  276. }
  277. tgBotMutex.Lock()
  278. adminIds = parsedAdminIds
  279. tgBotMutex.Unlock()
  280. // Get Telegram bot proxy URL
  281. tgBotProxy, err := t.settingService.GetTgBotProxy()
  282. if err != nil {
  283. logger.Warning("Failed to get Telegram bot proxy URL:", err)
  284. }
  285. // Fall back to the panel-wide egress bridge when no dedicated bot proxy is
  286. // set. Resolved once at bot start: if Xray comes up later, the bot keeps
  287. // its direct connection until it is restarted.
  288. if tgBotProxy == "" {
  289. if egress := t.settingService.PanelEgressProxyURL(); egress != "" && isSupportedBotProxyScheme(egress) {
  290. tgBotProxy = egress
  291. }
  292. }
  293. // Get Telegram bot API server URL
  294. tgBotAPIServer, err := t.settingService.GetTgBotAPIServer()
  295. if err != nil {
  296. logger.Warning("Failed to get Telegram bot API server URL:", err)
  297. }
  298. // Create new Telegram bot instance
  299. bot, err = t.NewBot(tgBotToken, tgBotProxy, tgBotAPIServer)
  300. if err != nil {
  301. logger.Error("Failed to initialize Telegram bot API:", err)
  302. return err
  303. }
  304. t.trySetBotCommands(bot)
  305. // Start receiving Telegram bot messages
  306. tgBotMutex.Lock()
  307. alreadyRunning := isRunning || botCancel != nil
  308. tgBotMutex.Unlock()
  309. if !alreadyRunning {
  310. logger.Info("Telegram bot receiver started")
  311. go t.OnReceive()
  312. }
  313. return nil
  314. }
  315. func (t *Tgbot) trySetBotCommands(bot *telego.Bot) {
  316. defer func() {
  317. if r := recover(); r != nil {
  318. logger.Warning("Failed to register bot commands (Telegram may be rate-limiting); bot will continue without them:", r)
  319. }
  320. }()
  321. err := bot.SetMyCommands(context.Background(), &telego.SetMyCommandsParams{
  322. Commands: []telego.BotCommand{
  323. {Command: "start", Description: t.I18nBot("tgbot.commands.startDesc")},
  324. {Command: "help", Description: t.I18nBot("tgbot.commands.helpDesc")},
  325. {Command: "status", Description: t.I18nBot("tgbot.commands.statusDesc")},
  326. {Command: "id", Description: t.I18nBot("tgbot.commands.idDesc")},
  327. {Command: "usage", Description: t.I18nBot("tgbot.commands.usageDesc")},
  328. {Command: "inbound", Description: t.I18nBot("tgbot.commands.inboundDesc")},
  329. {Command: "restart", Description: t.I18nBot("tgbot.commands.restartDesc")},
  330. {Command: "clearall", Description: t.I18nBot("tgbot.commands.clearallDesc")},
  331. },
  332. })
  333. if err != nil {
  334. logger.Warning("Failed to set bot commands:", err)
  335. }
  336. }
  337. func isSupportedBotProxyScheme(proxyUrl string) bool {
  338. return strings.HasPrefix(proxyUrl, "socks5://") ||
  339. strings.HasPrefix(proxyUrl, "http://") ||
  340. strings.HasPrefix(proxyUrl, "https://")
  341. }
  342. // createRobustFastHTTPClient creates a fasthttp.Client with proper connection handling
  343. func (t *Tgbot) createRobustFastHTTPClient(proxyUrl string) *fasthttp.Client {
  344. client := &fasthttp.Client{
  345. // Connection timeouts
  346. ReadTimeout: 30 * time.Second,
  347. WriteTimeout: 30 * time.Second,
  348. MaxIdleConnDuration: 60 * time.Second,
  349. MaxConnDuration: 0, // unlimited, but controlled by MaxIdleConnDuration
  350. MaxIdemponentCallAttempts: 3,
  351. ReadBufferSize: 4096,
  352. WriteBufferSize: 4096,
  353. MaxConnsPerHost: 100,
  354. MaxConnWaitTimeout: 10 * time.Second,
  355. DisableHeaderNamesNormalizing: false,
  356. DisablePathNormalizing: false,
  357. // resetTimeout stays false to keep the pre-RetryIfErr retry timing.
  358. RetryIfErr: func(request *fasthttp.Request, _ int, _ error) (bool, bool) {
  359. method := string(request.Header.Method())
  360. return false, method == "GET" || method == "POST"
  361. },
  362. }
  363. if proxyUrl != "" {
  364. if strings.HasPrefix(proxyUrl, "socks5://") {
  365. client.Dial = fasthttpproxy.FasthttpSocksDialer(proxyUrl)
  366. } else {
  367. client.Dial = fasthttpproxy.FasthttpHTTPDialer(proxyUrl)
  368. }
  369. }
  370. return client
  371. }
  372. // NewBot creates a new Telegram bot instance with optional proxy and API server settings.
  373. func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*telego.Bot, error) {
  374. // Validate proxy URL if provided
  375. if proxyUrl != "" {
  376. if !isSupportedBotProxyScheme(proxyUrl) {
  377. logger.Warning("Unsupported proxy scheme (want socks5:// or http(s)://), ignoring proxy")
  378. proxyUrl = "" // Clear invalid proxy
  379. } else if _, err := url.Parse(proxyUrl); err != nil {
  380. logger.Warningf("Can't parse proxy URL, ignoring proxy: %v", err)
  381. proxyUrl = ""
  382. }
  383. }
  384. // Validate API server URL if provided
  385. if apiServerUrl != "" {
  386. safeURL, err := service.SanitizePublicHTTPURL(apiServerUrl, false)
  387. if err != nil {
  388. logger.Warningf("Invalid or blocked API server URL, using default: %v", err)
  389. apiServerUrl = ""
  390. } else {
  391. apiServerUrl = safeURL
  392. }
  393. }
  394. // Create robust fasthttp client
  395. client := t.createRobustFastHTTPClient(proxyUrl)
  396. // Build bot options
  397. var options []telego.BotOption
  398. options = append(options, telego.WithFastHTTPClient(client))
  399. if apiServerUrl != "" {
  400. options = append(options, telego.WithAPIServer(apiServerUrl))
  401. }
  402. return telego.NewBot(token, options...)
  403. }
  404. // IsRunning checks if the Telegram bot is currently running.
  405. func (t *Tgbot) IsRunning() bool {
  406. tgBotMutex.Lock()
  407. defer tgBotMutex.Unlock()
  408. return isRunning
  409. }
  410. // adminSnapshot returns the admin chat list under the mutex Start and Stop
  411. // replace it under: a torn slice header is not a harmless race.
  412. func adminSnapshot() []int64 {
  413. tgBotMutex.Lock()
  414. defer tgBotMutex.Unlock()
  415. return slices.Clone(adminIds)
  416. }
  417. // SetHostname sets the hostname for the bot.
  418. func (t *Tgbot) SetHostname() {
  419. host, err := os.Hostname()
  420. if err != nil {
  421. logger.Error("get hostname error:", err)
  422. hostname = ""
  423. return
  424. }
  425. hostname = host
  426. }
  427. // Stop safely stops the Telegram bot's Long Polling operation.
  428. // This method now calls the global StopBot function and cleans up other resources.
  429. func (t *Tgbot) Stop() {
  430. StopBot()
  431. logger.Info("Stop Telegram receiver ...")
  432. tgBotMutex.Lock()
  433. adminIds = nil
  434. tgBotMutex.Unlock()
  435. }
  436. // StopBot safely stops the Telegram bot's Long Polling operation by cancelling its context.
  437. // This is the global function called from main.go's signal handler and t.Stop().
  438. func StopBot() {
  439. // Don't hold the mutex while cancelling/waiting.
  440. tgBotMutex.Lock()
  441. cancel := botCancel
  442. botCancel = nil
  443. handler := botHandler
  444. botHandler = nil
  445. isRunning = false
  446. tgBotMutex.Unlock()
  447. userStateMgr.reset()
  448. addClientDrafts.resetAll()
  449. if handler != nil {
  450. _ = handler.Stop()
  451. }
  452. if cancel != nil {
  453. logger.Info("Sending cancellation signal to Telegram bot...")
  454. // Cancels the context passed to UpdatesViaLongPolling; this closes updates channel
  455. // and lets botHandler.Start() exit cleanly.
  456. cancel()
  457. botWG.Wait()
  458. logger.Info("Telegram bot successfully stopped.")
  459. }
  460. }
  461. // encodeQuery encodes the query string if it's longer than 64 characters.
  462. func (t *Tgbot) encodeQuery(query string) string {
  463. // NOTE: we only need to hash for more than 64 chars
  464. if len(query) <= 64 {
  465. return query
  466. }
  467. return hashStorage.SaveHash(query)
  468. }
  469. // decodeQuery decodes a hashed query string back to its original form.
  470. func (t *Tgbot) decodeQuery(query string) (string, error) {
  471. if !hashStorage.IsMD5(query) {
  472. return query, nil
  473. }
  474. decoded, exists := hashStorage.GetValue(query)
  475. if !exists {
  476. return "", common.NewError("hash not found in storage!")
  477. }
  478. return decoded, nil
  479. }
  480. // randomLowerAndNum generates a random string of lowercase letters and numbers.
  481. func (t *Tgbot) randomLowerAndNum(length int) string {
  482. charset := "abcdefghijklmnopqrstuvwxyz0123456789"
  483. bytes := make([]byte, length)
  484. for i := range bytes {
  485. randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
  486. bytes[i] = charset[randomIndex.Int64()]
  487. }
  488. return string(bytes)
  489. }
  490. // int64Contains checks if an int64 slice contains a specific item.
  491. func int64Contains(slice []int64, item int64) bool {
  492. return slices.Contains(slice, item)
  493. }
  494. // isSingleWord checks if the text contains only a single word.
  495. func (t *Tgbot) isSingleWord(text string) bool {
  496. text = strings.TrimSpace(text)
  497. re := regexp.MustCompile(`\s+`)
  498. return re.MatchString(text)
  499. }