Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // Copyright (c) 2017 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/goshuirc/irc-go/ircfmt"
  10. "github.com/oragono/oragono/irc/caps"
  11. )
  12. const (
  13. // RegisterTimeout is how long clients have to register before we disconnect them
  14. RegisterTimeout = time.Minute
  15. // DefaultIdleTimeout is how long without traffic before we send the client a PING
  16. DefaultIdleTimeout = time.Minute + 30*time.Second
  17. // For Tor clients, we send a PING at least every 30 seconds, as a workaround for this bug
  18. // (single-onion circuits will close unless the client sends data once every 60 seconds):
  19. // https://bugs.torproject.org/29665
  20. TorIdleTimeout = time.Second * 30
  21. // This is how long a client gets without sending any message, including the PONG to our
  22. // PING, before we disconnect them:
  23. DefaultTotalTimeout = 2*time.Minute + 30*time.Second
  24. // Resumeable clients (clients who have negotiated caps.Resume) get longer:
  25. ResumeableTotalTimeout = 3*time.Minute + 30*time.Second
  26. )
  27. // client idleness state machine
  28. type TimerState uint
  29. const (
  30. TimerUnregistered TimerState = iota // client is unregistered
  31. TimerActive // client is actively sending commands
  32. TimerIdle // client is idle, we sent PING and are waiting for PONG
  33. TimerDead // client was terminated
  34. )
  35. type IdleTimer struct {
  36. sync.Mutex // tier 1
  37. // immutable after construction
  38. registerTimeout time.Duration
  39. session *Session
  40. // mutable
  41. idleTimeout time.Duration
  42. quitTimeout time.Duration
  43. state TimerState
  44. timer *time.Timer
  45. }
  46. // Initialize sets up an IdleTimer and starts counting idle time;
  47. // if there is no activity from the client, it will eventually be stopped.
  48. func (it *IdleTimer) Initialize(session *Session) {
  49. it.session = session
  50. it.registerTimeout = RegisterTimeout
  51. it.idleTimeout, it.quitTimeout = it.recomputeDurations()
  52. registered := session.client.Registered()
  53. it.Lock()
  54. defer it.Unlock()
  55. if registered {
  56. it.state = TimerActive
  57. } else {
  58. it.state = TimerUnregistered
  59. }
  60. it.resetTimeout()
  61. }
  62. // recomputeDurations recomputes the idle and quit durations, given the client's caps.
  63. func (it *IdleTimer) recomputeDurations() (idleTimeout, quitTimeout time.Duration) {
  64. totalTimeout := DefaultTotalTimeout
  65. // if they have the resume cap, wait longer before pinging them out
  66. // to give them a chance to resume their connection
  67. if it.session.capabilities.Has(caps.Resume) {
  68. totalTimeout = ResumeableTotalTimeout
  69. }
  70. idleTimeout = DefaultIdleTimeout
  71. if it.session.client.isTor {
  72. idleTimeout = TorIdleTimeout
  73. }
  74. quitTimeout = totalTimeout - idleTimeout
  75. return
  76. }
  77. func (it *IdleTimer) Touch() {
  78. idleTimeout, quitTimeout := it.recomputeDurations()
  79. it.Lock()
  80. defer it.Unlock()
  81. it.idleTimeout, it.quitTimeout = idleTimeout, quitTimeout
  82. // a touch transitions TimerUnregistered or TimerIdle into TimerActive
  83. if it.state != TimerDead {
  84. it.state = TimerActive
  85. it.resetTimeout()
  86. }
  87. }
  88. func (it *IdleTimer) processTimeout() {
  89. idleTimeout, quitTimeout := it.recomputeDurations()
  90. var previousState TimerState
  91. func() {
  92. it.Lock()
  93. defer it.Unlock()
  94. it.idleTimeout, it.quitTimeout = idleTimeout, quitTimeout
  95. previousState = it.state
  96. // TimerActive transitions to TimerIdle, all others to TimerDead
  97. if it.state == TimerActive {
  98. // send them a ping, give them time to respond
  99. it.state = TimerIdle
  100. it.resetTimeout()
  101. } else {
  102. it.state = TimerDead
  103. }
  104. }()
  105. if previousState == TimerActive {
  106. it.session.Ping()
  107. } else {
  108. it.session.client.Quit(it.quitMessage(previousState), it.session)
  109. it.session.client.destroy(it.session)
  110. }
  111. }
  112. // Stop stops counting idle time.
  113. func (it *IdleTimer) Stop() {
  114. if it == nil {
  115. return
  116. }
  117. it.Lock()
  118. defer it.Unlock()
  119. it.state = TimerDead
  120. it.resetTimeout()
  121. }
  122. func (it *IdleTimer) resetTimeout() {
  123. if it.timer != nil {
  124. it.timer.Stop()
  125. }
  126. var nextTimeout time.Duration
  127. switch it.state {
  128. case TimerUnregistered:
  129. nextTimeout = it.registerTimeout
  130. case TimerActive:
  131. nextTimeout = it.idleTimeout
  132. case TimerIdle:
  133. nextTimeout = it.quitTimeout
  134. case TimerDead:
  135. return
  136. }
  137. if it.timer != nil {
  138. it.timer.Reset(nextTimeout)
  139. } else {
  140. it.timer = time.AfterFunc(nextTimeout, it.processTimeout)
  141. }
  142. }
  143. func (it *IdleTimer) quitMessage(state TimerState) string {
  144. switch state {
  145. case TimerUnregistered:
  146. return fmt.Sprintf("Registration timeout: %v", it.registerTimeout)
  147. case TimerIdle:
  148. // how many seconds before registered clients are timed out (IdleTimeout plus QuitTimeout).
  149. it.Lock()
  150. defer it.Unlock()
  151. return fmt.Sprintf("Ping timeout: %v", (it.idleTimeout + it.quitTimeout))
  152. default:
  153. // shouldn't happen
  154. return ""
  155. }
  156. }
  157. // NickTimer manages timing out of clients who are squatting reserved nicks
  158. type NickTimer struct {
  159. sync.Mutex // tier 1
  160. // immutable after construction
  161. client *Client
  162. // mutable
  163. nick string
  164. accountForNick string
  165. account string
  166. timeout time.Duration
  167. timer *time.Timer
  168. enabled uint32
  169. }
  170. // Initialize sets up a NickTimer, based on server config settings.
  171. func (nt *NickTimer) Initialize(client *Client) {
  172. if nt.client == nil {
  173. nt.client = client // placate the race detector
  174. }
  175. config := &client.server.Config().Accounts.NickReservation
  176. enabled := config.Enabled && (config.Method == NickEnforcementWithTimeout || config.AllowCustomEnforcement)
  177. nt.Lock()
  178. defer nt.Unlock()
  179. nt.timeout = config.RenameTimeout
  180. if enabled {
  181. atomic.StoreUint32(&nt.enabled, 1)
  182. } else {
  183. nt.stopInternal()
  184. }
  185. }
  186. func (nt *NickTimer) Enabled() bool {
  187. return atomic.LoadUint32(&nt.enabled) == 1
  188. }
  189. func (nt *NickTimer) Timeout() (timeout time.Duration) {
  190. nt.Lock()
  191. timeout = nt.timeout
  192. nt.Unlock()
  193. return
  194. }
  195. // Touch records a nick change and updates the timer as necessary
  196. func (nt *NickTimer) Touch(rb *ResponseBuffer) {
  197. if !nt.Enabled() {
  198. return
  199. }
  200. var session *Session
  201. if rb != nil {
  202. session = rb.session
  203. }
  204. cfnick, skeleton := nt.client.uniqueIdentifiers()
  205. account := nt.client.Account()
  206. accountForNick, method := nt.client.server.accounts.EnforcementStatus(cfnick, skeleton)
  207. enforceTimeout := method == NickEnforcementWithTimeout
  208. var shouldWarn, shouldRename bool
  209. func() {
  210. nt.Lock()
  211. defer nt.Unlock()
  212. // the timer will not reset as long as the squatter is targeting the same account
  213. accountChanged := accountForNick != nt.accountForNick
  214. // change state
  215. nt.nick = cfnick
  216. nt.account = account
  217. nt.accountForNick = accountForNick
  218. delinquent := accountForNick != "" && accountForNick != account
  219. if nt.timer != nil && (!enforceTimeout || !delinquent || accountChanged) {
  220. nt.timer.Stop()
  221. nt.timer = nil
  222. }
  223. if enforceTimeout && delinquent && (accountChanged || nt.timer == nil) {
  224. nt.timer = time.AfterFunc(nt.timeout, nt.processTimeout)
  225. shouldWarn = true
  226. } else if method == NickEnforcementStrict && delinquent {
  227. shouldRename = true // this can happen if reservation was enabled by rehash
  228. }
  229. }()
  230. if shouldWarn {
  231. tnick := nt.client.Nick()
  232. message := fmt.Sprintf(ircfmt.Unescape(nt.client.t(nsTimeoutNotice)), nt.Timeout())
  233. // #449
  234. for _, mSession := range nt.client.Sessions() {
  235. if mSession == session {
  236. rb.Add(nil, nsPrefix, "NOTICE", tnick, message)
  237. rb.Add(nil, nt.client.server.name, "WARN", "*", "ACCOUNT_REQUIRED", message)
  238. } else {
  239. mSession.Send(nil, nsPrefix, "NOTICE", tnick, message)
  240. mSession.Send(nil, nt.client.server.name, "WARN", "*", "ACCOUNT_REQUIRED", message)
  241. }
  242. }
  243. } else if shouldRename {
  244. nt.client.Notice(nt.client.t("Nickname is reserved by a different account"))
  245. nt.client.server.RandomlyRename(nt.client)
  246. }
  247. }
  248. // Stop stops counting time and cleans up the timer
  249. func (nt *NickTimer) Stop() {
  250. nt.Lock()
  251. defer nt.Unlock()
  252. nt.stopInternal()
  253. }
  254. func (nt *NickTimer) stopInternal() {
  255. if nt.timer != nil {
  256. nt.timer.Stop()
  257. nt.timer = nil
  258. }
  259. atomic.StoreUint32(&nt.enabled, 0)
  260. }
  261. func (nt *NickTimer) processTimeout() {
  262. baseMsg := "Nick is reserved and authentication timeout expired: %v"
  263. nt.client.Notice(fmt.Sprintf(nt.client.t(baseMsg), nt.Timeout()))
  264. nt.client.server.RandomlyRename(nt.client)
  265. }
  266. // BrbTimer is a timer on the client as a whole (not an individual session) for implementing
  267. // the BRB command and related functionality (where a client can remain online without
  268. // having any connected sessions).
  269. type BrbState uint
  270. const (
  271. // BrbDisabled is the default state; the client will be disconnected if it has no sessions
  272. BrbDisabled BrbState = iota
  273. // BrbEnabled allows the client to remain online without sessions; if a timeout is
  274. // reached, it will be removed
  275. BrbEnabled
  276. // BrbDead is the state of a client after its timeout has expired; it will be removed
  277. // and therefore new sessions cannot be attached to it
  278. BrbDead
  279. // BrbSticky allows a client to remain online without sessions, with no timeout.
  280. // This is not used yet.
  281. BrbSticky
  282. )
  283. type BrbTimer struct {
  284. // XXX we use client.stateMutex for synchronization, so we can atomically test
  285. // conditions that use both brbTimer.state and client.sessions. This code
  286. // is tightly coupled with the rest of Client.
  287. client *Client
  288. state BrbState
  289. brbAt time.Time
  290. duration time.Duration
  291. timer *time.Timer
  292. }
  293. func (bt *BrbTimer) Initialize(client *Client) {
  294. bt.client = client
  295. }
  296. // attempts to enable BRB for a client, returns whether it succeeded
  297. func (bt *BrbTimer) Enable() (success bool, duration time.Duration) {
  298. if !bt.client.Registered() || bt.client.ResumeID() == "" {
  299. return
  300. }
  301. // TODO make this configurable
  302. duration = ResumeableTotalTimeout
  303. bt.client.stateMutex.Lock()
  304. defer bt.client.stateMutex.Unlock()
  305. switch bt.state {
  306. case BrbDisabled, BrbEnabled:
  307. bt.state = BrbEnabled
  308. bt.duration = duration
  309. bt.resetTimeout()
  310. // only track the earliest BRB, if multiple sessions are BRB'ing at once
  311. // TODO(#524) this is inaccurate in case of an auto-BRB
  312. if bt.brbAt.IsZero() {
  313. bt.brbAt = time.Now().UTC()
  314. }
  315. success = true
  316. case BrbSticky:
  317. success = true
  318. default:
  319. // BrbDead
  320. success = false
  321. }
  322. return
  323. }
  324. // turns off BRB for a client and stops the timer; used on resume and during
  325. // client teardown
  326. func (bt *BrbTimer) Disable() (brbAt time.Time) {
  327. bt.client.stateMutex.Lock()
  328. defer bt.client.stateMutex.Unlock()
  329. if bt.state == BrbEnabled {
  330. bt.state = BrbDisabled
  331. brbAt = bt.brbAt
  332. bt.brbAt = time.Time{}
  333. }
  334. bt.resetTimeout()
  335. return
  336. }
  337. func (bt *BrbTimer) resetTimeout() {
  338. if bt.timer != nil {
  339. bt.timer.Stop()
  340. }
  341. if bt.state != BrbEnabled {
  342. return
  343. }
  344. if bt.timer == nil {
  345. bt.timer = time.AfterFunc(bt.duration, bt.processTimeout)
  346. } else {
  347. bt.timer.Reset(bt.duration)
  348. }
  349. }
  350. func (bt *BrbTimer) processTimeout() {
  351. dead := false
  352. defer func() {
  353. if dead {
  354. bt.client.Quit(bt.client.AwayMessage(), nil)
  355. bt.client.destroy(nil)
  356. }
  357. }()
  358. bt.client.stateMutex.Lock()
  359. defer bt.client.stateMutex.Unlock()
  360. switch bt.state {
  361. case BrbDisabled, BrbEnabled:
  362. if len(bt.client.sessions) == 0 {
  363. // client never returned, quit them
  364. bt.state = BrbDead
  365. dead = true
  366. } else {
  367. // client resumed, reattached, or has another active session
  368. bt.state = BrbDisabled
  369. bt.brbAt = time.Time{}
  370. }
  371. case BrbDead:
  372. dead = true // shouldn't be possible but whatever
  373. }
  374. bt.resetTimeout()
  375. }
  376. // sets a client to be "sticky", i.e., indefinitely exempt from removal for
  377. // lack of sessions
  378. func (bt *BrbTimer) SetSticky() (success bool) {
  379. bt.client.stateMutex.Lock()
  380. defer bt.client.stateMutex.Unlock()
  381. if bt.state != BrbDead {
  382. success = true
  383. bt.state = BrbSticky
  384. }
  385. bt.resetTimeout()
  386. return
  387. }