1
0

tgbot.go 17 KB

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