4
0

session.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. package webapi
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "log/slog"
  9. mrand "math/rand/v2"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/mk6i/open-oscar-server/state"
  16. "github.com/mk6i/open-oscar-server/wire"
  17. )
  18. var (
  19. // ErrNoWebAPISession is returned when a WebAPI session is not found.
  20. ErrNoWebAPISession = errors.New("WebAPI session not found")
  21. // ErrWebAPISessionExpired is returned when a WebAPI session has expired.
  22. ErrWebAPISessionExpired = errors.New("WebAPI session expired")
  23. // ErrWebAPISessionManagerClosed is returned when a session is requested from
  24. // a manager that has been shut down.
  25. ErrWebAPISessionManagerClosed = errors.New("WebAPI session manager is shut down")
  26. )
  27. // Web API session lifecycle timeline.
  28. //
  29. // A web client keeps its session alive by long-polling GET /aim/fetchEvents.
  30. // Every authenticated request touches the session (middleware.RequireSession
  31. // calls TouchSession at request arrival), sliding expiry to now + the TTL. A
  32. // single poll blocks for up to 60s (the fetchEvents long-poll cap) and the
  33. // client waits ~500ms (TimeToNextFetch) before re-polling, so in steady state a
  34. // healthy client touches the session at worst every ~60-65s once jitter is
  35. // included. That worst-case touch interval is the floor the TTL must clear.
  36. //
  37. // If a client hangs up without calling endSession, its last touch was at its
  38. // last poll: the session then expires webAPISessionTTL later and the reaper
  39. // sweeps it within one webAPISessionReapInterval tick. So a silent client is
  40. // removed (and its OSCAR session closed) within TTL + tick of going quiet.
  41. const (
  42. // webAPISessionTTL bounds how long a session survives without a poll. It is
  43. // sized to absorb one missed poll cycle: ~60s for the normal cycle, ~60s for
  44. // the absorbed miss, plus ~20s of jitter margin. Two consecutive misses mean
  45. // the client is genuinely gone and the session is reaped.
  46. webAPISessionTTL = 150 * time.Second
  47. // webAPISessionReapInterval is how often the cleanup goroutine sweeps for
  48. // expired sessions (~TTL/5). A dead session lingers at most
  49. // webAPISessionTTL + webAPISessionReapInterval before removal.
  50. webAPISessionReapInterval = 30 * time.Second
  51. )
  52. // Session represents an active Web AIM API session.
  53. type Session struct {
  54. AimSID string // Unique session ID for web client
  55. ScreenName state.DisplayScreenName // User identity
  56. OSCARSession *state.SessionInstance // Bridge to existing OSCAR session
  57. BaseURL string // Web API base URL advertised to the web client, used to build absolute asset URLs
  58. Events []string // Subscribed event types
  59. EventQueue *EventQueue // Per-session event queue
  60. ClientName string // Client application name
  61. ClientVersion string // Client application version
  62. CreatedAt time.Time // SessionInstance creation time
  63. LastAccessed time.Time // Last activity time
  64. ExpiresAt time.Time // SessionInstance expiration time
  65. FetchTimeout int // Long-polling timeout in milliseconds
  66. TimeToNextFetch int // Suggested delay before next fetch
  67. RemoteAddr string // Client IP address
  68. BuddyListRefresher func(ctx context.Context) (interface{}, error) // Called on feedbag changes to push buddylist event
  69. PermitDenyRefresher func(ctx context.Context) (interface{}, error) // Called on feedbag changes to push permitDeny event
  70. MyInfoRefresher func(ctx context.Context) (interface{}, error) // Called on self user-info updates (e.g. icon change) to push myInfo event
  71. BuddyAliasLoader func(ctx context.Context) (map[string]string, error)
  72. // BuddyIconURL formats the absolute buddyIcon URL for a buddy from the icon
  73. // hash carried in a presence SNAC. Returns "" when no URL can be published.
  74. BuddyIconURL func(screenName state.IdentScreenName, hash []byte) string
  75. aliases map[string]string // cached BuddyAliasLoader result, nil when unloaded or invalidated
  76. aliasMu sync.Mutex
  77. imLog map[string][]WebAPIStoredIM
  78. imLogMu sync.Mutex
  79. sentIMs map[uint64]string // OSCAR message cookie -> the msgId given to the client
  80. sentIMOrder []uint64 // insertion order of sentIMs, oldest first
  81. sentIMMu sync.Mutex
  82. // IMRateClassID is the rate class that sending an IM spends. The web client
  83. // renders any rate limit event as the IM banner, so only this class's updates
  84. // may reach it. Zero disables the alert.
  85. IMRateClassID wire.RateLimitClassID
  86. logger *slog.Logger // Logger for debugging
  87. listeners sync.WaitGroup
  88. ctx context.Context
  89. cancel context.CancelFunc
  90. closeMu sync.Mutex
  91. closed bool
  92. }
  93. // IsExpired checks if the session has expired.
  94. func (s *Session) IsExpired() bool {
  95. return time.Now().After(s.ExpiresAt)
  96. }
  97. // Aliases returns this session owner's private buddy aliases, keyed by normalized
  98. // screen name. Aliases live in the owner's feedbag, so the map is loaded once and
  99. // cached until a feedbag change invalidates it: a signon that brings a large buddy
  100. // list online costs one feedbag query instead of one per buddy.
  101. //
  102. // The map is owned by the session and must not be mutated by callers.
  103. //
  104. // aliasMu is deliberately held across the load rather than released while the
  105. // feedbag is queried. Another instance of the owner can rename a buddy mid-query,
  106. // and its FeedbagUpdateItem SNAC invalidates this cache; if the load ran outside
  107. // the lock, that query's pre-rename result could be stored *after* the
  108. // invalidation and serve the old alias until the next feedbag change. Holding the
  109. // lock makes the invalidation wait for the load and then win.
  110. func (s *Session) Aliases(ctx context.Context) map[string]string {
  111. s.aliasMu.Lock()
  112. defer s.aliasMu.Unlock()
  113. // The loader is wired after the session is created, so an event arriving in
  114. // that window has no way to resolve aliases.
  115. if s.BuddyAliasLoader == nil {
  116. return nil
  117. }
  118. if s.aliases == nil {
  119. aliases, err := s.BuddyAliasLoader(ctx)
  120. if err != nil {
  121. s.logger.Error("failed to load buddy aliases", "err", err.Error())
  122. return nil
  123. }
  124. s.aliases = aliases
  125. }
  126. return s.aliases
  127. }
  128. // InvalidateAliases drops the cached alias map so the next Aliases call reloads it.
  129. // Callers that change the owner's feedbag must call this: the feedbag service
  130. // relays FeedbagUpdateItem only to the owner's *other* instances, so a session
  131. // never sees a SNAC for its own writes.
  132. func (s *Session) InvalidateAliases() {
  133. s.aliasMu.Lock()
  134. defer s.aliasMu.Unlock()
  135. s.aliases = nil
  136. }
  137. // aliasFor returns this session owner's private alias for buddy, or "" when none is
  138. // set. The web client deletes the alias it holds whenever it merges a user map, so
  139. // every event naming a buddy has to repeat it.
  140. func (s *Session) aliasFor(buddy state.IdentScreenName) string {
  141. // Runs on the SNAC listener goroutine, which has no request context.
  142. return s.Aliases(s.ctx)[buddy.String()]
  143. }
  144. // Touch updates the last accessed time and extends expiration if needed.
  145. func (s *Session) Touch() {
  146. s.LastAccessed = time.Now()
  147. newExpiry := s.LastAccessed.Add(webAPISessionTTL)
  148. if newExpiry.After(s.ExpiresAt) {
  149. s.ExpiresAt = newExpiry
  150. }
  151. }
  152. // IsSubscribedTo checks if the session is subscribed to a specific event type.
  153. func (s *Session) IsSubscribedTo(eventType string) bool {
  154. for _, event := range s.Events {
  155. if event == eventType {
  156. return true
  157. }
  158. }
  159. return false
  160. }
  161. // StartListeningToOSCARSession starts a goroutine that listens to the OSCAR session's
  162. // message channel and converts SNAC messages into WebAPI events.
  163. func (s *Session) StartListeningToOSCARSession() {
  164. s.closeMu.Lock()
  165. defer s.closeMu.Unlock()
  166. if s.closed {
  167. return
  168. }
  169. s.listeners.Add(1)
  170. go func() {
  171. defer s.listeners.Done()
  172. msgCh := s.OSCARSession.ReceiveMessage()
  173. for {
  174. select {
  175. case msg, ok := <-msgCh:
  176. if !ok {
  177. // Channel closed, OSCAR session ended
  178. return
  179. }
  180. s.handleSNACMessage(msg)
  181. case <-s.OSCARSession.Closed():
  182. // The OSCAR instance went away without this session asking — a
  183. // boot, a rate-limit disconnect. Tell the client rather than
  184. // leaving its parked fetcher to hang: a sessionEnded event
  185. // releases the poll at once and the client signs off on the
  186. // spot, instead of waiting out the reaper's next sweep.
  187. //
  188. // A teardown this session started needs no event, and gets
  189. // none: Close closes the queue before it closes the instance,
  190. // so this Push is a no-op on that path.
  191. s.EventQueue.Push(EventTypeSessionEnded, struct{}{})
  192. return
  193. }
  194. }
  195. }()
  196. }
  197. // Close tears down the session: it releases any parked event fetchers, closes
  198. // the OSCAR instance, and waits for the listener goroutine to unwind. Safe to
  199. // call more than once.
  200. func (s *Session) Close() {
  201. s.closeMu.Lock()
  202. if s.closed {
  203. s.closeMu.Unlock()
  204. return
  205. }
  206. s.closed = true
  207. s.closeMu.Unlock()
  208. s.EventQueue.Close()
  209. s.OSCARSession.CloseInstance()
  210. s.cancel()
  211. s.listeners.Wait()
  212. }
  213. // handleSNACMessage converts a SNAC message into WebAPI events and pushes them to the event queue.
  214. func (s *Session) handleSNACMessage(msg wire.SNACMessage) {
  215. // Convert SNAC message to WebAPI events based on food group and subgroup
  216. switch msg.Frame.FoodGroup {
  217. case wire.ICBM:
  218. s.handleICBMMessage(msg)
  219. case wire.Buddy:
  220. s.handleBuddyMessage(msg)
  221. case wire.Feedbag:
  222. s.handleFeedbagMessage(msg)
  223. case wire.OService:
  224. s.handleOServiceMessage(msg)
  225. }
  226. }
  227. // handleOServiceMessage handles OService SNAC messages relayed to the session's
  228. // own OSCAR instance.
  229. func (s *Session) handleOServiceMessage(msg wire.SNACMessage) {
  230. switch msg.Frame.SubGroup {
  231. case wire.OServiceUserInfoUpdate:
  232. s.handleUserInfoUpdate(msg)
  233. case wire.OServiceRateParamChange:
  234. s.handleRateLimitUpdate(msg)
  235. }
  236. }
  237. // handleUserInfoUpdate surfaces OServiceUserInfoUpdate, which the server relays to
  238. // a user when their own user info changes (notably a buddy icon upload or clear).
  239. // The client re-renders its identity badge from myInfo events only, so we
  240. // translate this into a fresh myInfo.
  241. func (s *Session) handleUserInfoUpdate(msg wire.SNACMessage) {
  242. if !s.IsSubscribedTo("myInfo") && !s.IsSubscribedTo("presence") {
  243. return
  244. }
  245. if s.MyInfoRefresher == nil {
  246. return
  247. }
  248. data, err := s.MyInfoRefresher(s.ctx)
  249. if err != nil {
  250. s.logger.Error("failed to refresh myInfo after user-info update", "err", err)
  251. return
  252. }
  253. s.EventQueue.Push(EventType("myInfo"), data)
  254. }
  255. // handleRateLimitUpdate translates a rate limit status change — broadcast by the
  256. // account's rate limit monitor — into a rateLimit event. Only the IM class is
  257. // surfaced, since the client feeds any rateLimit event into the
  258. // conversation-window alert. Code 1 is a class-params change, not a status
  259. // transition, and is ignored.
  260. func (s *Session) handleRateLimitUpdate(msg wire.SNACMessage) {
  261. if s.IMRateClassID == 0 {
  262. return
  263. }
  264. body, ok := msg.Body.(wire.SNAC_0x01_0x0A_OServiceRateParamsChange)
  265. if !ok {
  266. return
  267. }
  268. if wire.RateLimitClassID(body.Rate.ID) != s.IMRateClassID {
  269. return
  270. }
  271. var status string
  272. switch body.Code {
  273. case 2:
  274. status = "warn"
  275. case 3:
  276. status = "limit"
  277. case 4:
  278. status = "clear"
  279. default:
  280. return
  281. }
  282. s.EventQueue.Push(EventTypeRateLimit, RateLimitEvent{
  283. Classes: []RateLimitClass{
  284. {ID: int(body.Rate.ID), Status: status},
  285. },
  286. })
  287. }
  288. // handleICBMMessage handles ICBM (instant messaging) SNAC messages.
  289. func (s *Session) handleICBMMessage(msg wire.SNACMessage) {
  290. switch msg.Frame.SubGroup {
  291. case wire.ICBMChannelMsgToClient:
  292. s.handleIncomingIM(msg)
  293. case wire.ICBMClientEvent:
  294. s.handleTypingNotification(msg)
  295. case wire.ICBMClientErr:
  296. s.handleClientError(msg)
  297. }
  298. }
  299. // handleIncomingIM handles incoming instant messages.
  300. func (s *Session) handleIncomingIM(msg wire.SNACMessage) {
  301. body, ok := msg.Body.(wire.SNAC_0x04_0x07_ICBMChannelMsgToClient)
  302. if !ok {
  303. return
  304. }
  305. // A send time is only stamped on a message replayed out of the offline store,
  306. // so its presence marks this as a delivery of something sent while the user was
  307. // signed off, and carries the moment the sender actually sent it.
  308. sentTime, isOffline := body.Uint32BE(wire.ICBMTLVSendTime)
  309. // Retrieval answers only the instance that asked, and StartSession asks only
  310. // when the client subscribed to offlineIM, so a stamped message here is one
  311. // this session requested. A live IM still needs the im subscription.
  312. if !isOffline && !s.IsSubscribedTo("im") {
  313. return
  314. }
  315. // Extract message text from TLV data
  316. var messageText string
  317. if msgData, hasMsg := body.Bytes(wire.ICBMTLVAOLIMData); hasMsg {
  318. if text, err := wire.UnmarshalICBMMessageText(msgData); err == nil {
  319. messageText = text
  320. }
  321. }
  322. if messageText == "" {
  323. return
  324. }
  325. // Check if it's an auto-response (channel 2)
  326. autoResponse := body.ChannelID == 0x0002
  327. // msgId must be unique per delivered event. The OSCAR cookie is not a
  328. // reliable unique id (some clients reuse it across messages), and the web
  329. // client dedupes its conversation list by msgId, silently dropping any
  330. // collisions. Mint a fresh random id instead of reusing body.Cookie.
  331. msgID := strconv.FormatUint(mrand.Uint64(), 16)
  332. // SNAC user info carries the sender's display screen name. The web client
  333. // keys conversations and users by the normalized aimId and only renders
  334. // displayId, so the two forms must not be interchanged.
  335. partnerDisplay := body.ScreenName
  336. partnerAimID := state.NewIdentScreenName(partnerDisplay).String()
  337. // An offline message is logged under the time it was sent, so the stored-IM
  338. // history it lands in stays in the order the conversation happened.
  339. timestamp := time.Now().Unix()
  340. if isOffline {
  341. timestamp = int64(sentTime)
  342. }
  343. s.AddStoredIM(partnerAimID, partnerAimID, messageText, msgID, timestamp)
  344. if isOffline {
  345. // The client resolves an offline sender from aimId and friendly alone,
  346. // so friendly falls back to the sender's own formatting when the viewer
  347. // has no alias for them.
  348. friendly := s.aliasFor(state.NewIdentScreenName(partnerAimID))
  349. if friendly == "" {
  350. friendly = partnerDisplay
  351. }
  352. s.EventQueue.Push(EventTypeOfflineIM, OfflineIMEvent{
  353. AimID: partnerAimID,
  354. Friendly: friendly,
  355. Message: messageText,
  356. MsgID: msgID,
  357. Timestamp: timestamp,
  358. Imf: imfPlainText,
  359. AutoResp: autoResponse,
  360. })
  361. s.logger.Debug("delivered offline instant message",
  362. "from", partnerDisplay,
  363. "to", s.ScreenName,
  364. "sent", timestamp)
  365. } else {
  366. s.EventQueue.Push(EventTypeIM, IMEvent{
  367. Source: UserInfo{
  368. AimID: partnerAimID,
  369. DisplayID: partnerDisplay,
  370. Friendly: s.aliasFor(state.NewIdentScreenName(partnerAimID)),
  371. UserType: "aim",
  372. State: "online",
  373. },
  374. Message: messageText,
  375. MsgID: msgID,
  376. Timestamp: timestamp,
  377. Imf: imfPlainText,
  378. AutoResp: autoResponse,
  379. })
  380. s.logger.Debug("delivered instant message",
  381. "from", partnerDisplay,
  382. "to", s.ScreenName)
  383. }
  384. if s.IsSubscribedTo("conversation") {
  385. // unread is 0 here, not 1, because the "im"/"offlineIM" event pushed above
  386. // already causes the client to increment its own persisted per-buddy unread
  387. // tally. The "Recent chats" badge is the sum of that persisted tally and
  388. // this conversation's unreadCount, so sending 1 here would double-count
  389. // the message (badge shows 2 for the first IM). Mirrors the sent-IM path,
  390. // which also passes 0.
  391. s.EventQueue.Push(EventTypeConversation, ConversationEventData("update", []ConversationEntryData{
  392. ConversationEntry(
  393. partnerAimID,
  394. partnerDisplay,
  395. messageText,
  396. msgID,
  397. partnerAimID,
  398. false,
  399. 0,
  400. ),
  401. }))
  402. }
  403. }
  404. // handleClientError translates ICBMClientErr — the recipient reporting that it
  405. // could not handle a message already delivered to it — into a clientError event
  406. // for the sender. Only OSCAR clients raise this SNAC.
  407. func (s *Session) handleClientError(msg wire.SNACMessage) {
  408. if !s.IsSubscribedTo("im") {
  409. return
  410. }
  411. body, ok := msg.Body.(wire.SNAC_0x04_0x0B_ICBMClientErr)
  412. if !ok {
  413. return
  414. }
  415. // The SNAC names the erroring party by their own formatting, so both the
  416. // normalized aimId and displayId are sent, along with the viewer's alias.
  417. sender := state.NewIdentScreenName(body.ScreenName)
  418. channel := "im"
  419. if body.ChannelID == wire.ICBMChannelRendezvous {
  420. channel = "data"
  421. }
  422. s.EventQueue.Push(EventTypeClientError, ClientErrorEvent{
  423. Source: UserInfo{
  424. AimID: sender.String(),
  425. DisplayID: body.ScreenName,
  426. Friendly: s.aliasFor(sender),
  427. UserType: "aim",
  428. },
  429. Cookie: s.msgIDForCookie(body.Cookie),
  430. Channel: channel,
  431. })
  432. }
  433. // handleTypingNotification handles typing notifications.
  434. func (s *Session) handleTypingNotification(msg wire.SNACMessage) {
  435. if !s.IsSubscribedTo("typing") {
  436. return
  437. }
  438. body, ok := msg.Body.(wire.SNAC_0x04_0x14_ICBMClientEvent)
  439. if !ok {
  440. return
  441. }
  442. // Event types: 0x0000=none, 0x0001=typed (paused), 0x0002=typing
  443. var typingStatus string
  444. switch body.Event {
  445. case 0x0002:
  446. typingStatus = "typing"
  447. case 0x0001:
  448. typingStatus = "typed"
  449. default:
  450. typingStatus = "none"
  451. }
  452. typingEvent := TypingEvent{
  453. AimID: state.NewIdentScreenName(body.ScreenName).String(),
  454. TypingStatus: typingStatus,
  455. }
  456. s.EventQueue.Push(EventTypeTyping, typingEvent)
  457. }
  458. // handleBuddyMessage handles buddy/presence SNAC messages.
  459. func (s *Session) handleBuddyMessage(msg wire.SNACMessage) {
  460. switch msg.Frame.SubGroup {
  461. case wire.BuddyArrived:
  462. s.handleBuddyArrived(msg)
  463. case wire.BuddyDeparted:
  464. s.handleBuddyDeparted(msg)
  465. }
  466. }
  467. // handleBuddyArrived handles when a buddy comes online.
  468. func (s *Session) handleBuddyArrived(msg wire.SNACMessage) {
  469. if !s.IsSubscribedTo("presence") {
  470. return
  471. }
  472. body, ok := msg.Body.(wire.SNAC_0x03_0x0B_BuddyArrived)
  473. if !ok {
  474. return
  475. }
  476. stateStr := "online"
  477. // For BuddyArrived updates, infer presence state from the TLVUserInfo.
  478. // Away and invisible transitions are typically broadcast using BuddyArrived
  479. // with updated user flags/status bits, not BuddyDeparted.
  480. if body.IsInvisible() {
  481. stateStr = "offline"
  482. } else if st := statusBitState(body.TLVUserInfo); st != "" {
  483. stateStr = st
  484. } else if body.IsAway() {
  485. stateStr = "away"
  486. } else if mask, ok := body.Uint32BE(wire.OServiceUserInfoStatus); ok {
  487. if mask&wire.OServiceUserStatusDND == wire.OServiceUserStatusDND {
  488. stateStr = "dnd"
  489. } else if mask&wire.OServiceUserStatusAway == wire.OServiceUserStatusAway {
  490. stateStr = "away"
  491. }
  492. }
  493. buddy := state.NewIdentScreenName(body.ScreenName)
  494. presenceEvent := PresenceEvent{
  495. AimID: buddy.String(),
  496. Friendly: s.aliasFor(buddy),
  497. State: stateStr,
  498. UserType: "aim",
  499. }
  500. // A BuddyArrived carries the buddy's current icon in TLV 0x1D whenever they
  501. // have one, so an icon change (or clear, which arrives as the sentinel hash)
  502. // rides along on the presence broadcast. Publish the matching URL: with an
  503. // icon it is content-addressed; without one it is the placeholder URL, which
  504. // differs from any prior icon URL and so clears a removed icon under the
  505. // client's shallow merge. An empty result (no origin known) is omitted, which
  506. // preserves whatever icon the client already holds.
  507. if s.BuddyIconURL != nil {
  508. var hash []byte
  509. if b, ok := body.Bytes(wire.OServiceUserInfoBARTInfo); ok {
  510. var id wire.BARTID
  511. if err := wire.UnmarshalBE(&id, bytes.NewBuffer(b)); err == nil {
  512. hash = id.Hash
  513. }
  514. }
  515. presenceEvent.BuddyIcon = s.BuddyIconURL(buddy, hash)
  516. }
  517. s.EventQueue.Push(EventTypePresence, presenceEvent)
  518. }
  519. // handleBuddyDeparted handles when a buddy goes offline.
  520. func (s *Session) handleBuddyDeparted(msg wire.SNACMessage) {
  521. if !s.IsSubscribedTo("presence") {
  522. return
  523. }
  524. body, ok := msg.Body.(wire.SNAC_0x03_0x0C_BuddyDeparted)
  525. if !ok {
  526. return
  527. }
  528. buddy := state.NewIdentScreenName(body.ScreenName)
  529. // BuddyIcon is deliberately omitted: an offline buddy keeps their icon, and
  530. // omitting it lets the client's merge preserve the icon it already holds.
  531. presenceEvent := PresenceEvent{
  532. AimID: buddy.String(),
  533. Friendly: s.aliasFor(buddy),
  534. State: "offline",
  535. UserType: "aim",
  536. }
  537. s.EventQueue.Push(EventTypePresence, presenceEvent)
  538. }
  539. // feedbagResultAuthRequired is the per-item feedbag result meaning the target's ICQ
  540. // settings require authorization, so the item was not stored.
  541. const feedbagResultAuthRequired = uint16(0x000E)
  542. // refreshBuddyList re-reads the roster and pushes it to the client. Runs on the SNAC
  543. // listener goroutine, so it uses the session context rather than a request context.
  544. func (s *Session) refreshBuddyList() {
  545. // A buddy item carries its alias, so any feedbag write can change the map.
  546. s.InvalidateAliases()
  547. if s.BuddyListRefresher == nil {
  548. return
  549. }
  550. payload, err := s.BuddyListRefresher(s.ctx)
  551. if err != nil {
  552. s.logger.Error("failed to refresh buddy list after feedbag change", "err", err)
  553. return
  554. }
  555. s.EventQueue.Push(EventTypeBuddyList, payload)
  556. }
  557. func (s *Session) handleFeedbagMessage(msg wire.SNACMessage) {
  558. switch msg.Frame.SubGroup {
  559. case wire.FeedbagStatus:
  560. // Insert/update/delete below reach only a user's *other* instances, so this
  561. // is the one notification a session gets for its own feedbag write.
  562. if !s.IsSubscribedTo(string(EventTypeBuddyList)) {
  563. return
  564. }
  565. if body, ok := msg.Body.(wire.SNAC_0x13_0x0E_FeedbagStatus); ok {
  566. // A buddy declined for authorization is not stored, and is simply
  567. // absent from the refreshed roster.
  568. for _, result := range body.Results {
  569. if result == feedbagResultAuthRequired {
  570. s.logger.Info("feedbag item declined pending authorization")
  571. break
  572. }
  573. }
  574. }
  575. s.refreshBuddyList()
  576. case wire.FeedbagInsertItem, wire.FeedbagUpdateItem, wire.FeedbagDeleteItem:
  577. s.refreshBuddyList()
  578. if s.PermitDenyRefresher != nil {
  579. // An insert and an update both relay an UpdateItem body; only a
  580. // delete carries a DeleteItem body.
  581. var items []wire.FeedbagItem
  582. switch body := msg.Body.(type) {
  583. case wire.SNAC_0x13_0x09_FeedbagUpdateItem:
  584. items = body.Items
  585. case wire.SNAC_0x13_0x0A_FeedbagDeleteItem:
  586. items = body.Items
  587. }
  588. for _, item := range items {
  589. if item.ClassID == wire.FeedbagClassIDPermit ||
  590. item.ClassID == wire.FeedbagClassIDDeny ||
  591. item.ClassID == wire.FeedbagClassIdPdinfo {
  592. pdd, err := s.PermitDenyRefresher(s.ctx)
  593. if err != nil {
  594. s.logger.Error("failed to refresh permit/deny after feedbag change", "err", err)
  595. } else {
  596. s.EventQueue.Push(EventTypePermitDeny, pdd)
  597. }
  598. break
  599. }
  600. }
  601. }
  602. }
  603. }
  604. // SessionManager manages Web API sessions with thread-safe operations.
  605. // Construct it with NewSessionManager and drive its reaper with Run.
  606. type SessionManager struct {
  607. sessions map[string]*Session // Keyed by aimsid
  608. mu sync.RWMutex
  609. closed bool // set by Shutdown; rejects new sessions and makes drain idempotent
  610. stopCh chan struct{} // closed by Shutdown to stop the reaper
  611. reaperWG sync.WaitGroup // tracks a running reaper so Shutdown can join it
  612. }
  613. // NewSessionManager creates a new WebAPI session manager. It does not start
  614. // any goroutines; call Run to start reaping expired sessions.
  615. func NewSessionManager() *SessionManager {
  616. return &SessionManager{
  617. sessions: make(map[string]*Session),
  618. stopCh: make(chan struct{}),
  619. }
  620. }
  621. // CreateSession creates a new WebAPI session.
  622. //
  623. // The session does not begin listening to its OSCAR instance yet: the caller
  624. // must wire the session's refresher callbacks (BuddyListRefresher, BuddyIconURL,
  625. // MyInfoRefresher, ...) and then call StartListeningToOSCARSession. Wiring them
  626. // after the listener starts would race the goroutine, which reads them as it
  627. // converts SNACs into events.
  628. func (m *SessionManager) CreateSession(screenName state.DisplayScreenName, events []string, oscarSession *state.SessionInstance, baseURL string, logger *slog.Logger) (*Session, error) {
  629. m.mu.Lock()
  630. defer m.mu.Unlock()
  631. // Refuse to create sessions once shut down: the reaper is stopped, so a
  632. // session added now would never be closed or reaped.
  633. if m.closed {
  634. return nil, ErrWebAPISessionManagerClosed
  635. }
  636. // Generate unique session ID
  637. aimsid, err := generateSessionID()
  638. if err != nil {
  639. return nil, err
  640. }
  641. now := time.Now()
  642. sessCtx, sessCancel := context.WithCancel(context.Background())
  643. session := &Session{
  644. ctx: sessCtx,
  645. cancel: sessCancel,
  646. AimSID: aimsid,
  647. ScreenName: screenName,
  648. OSCARSession: oscarSession,
  649. BaseURL: baseURL,
  650. Events: events,
  651. EventQueue: NewEventQueue(1000), // Max 1000 events per session
  652. CreatedAt: now,
  653. LastAccessed: now,
  654. ExpiresAt: now.Add(webAPISessionTTL),
  655. FetchTimeout: 60000, // 60 seconds default for better stability
  656. TimeToNextFetch: 500, // 500ms suggested delay
  657. logger: logger,
  658. }
  659. m.sessions[aimsid] = session
  660. // The caller starts the OSCAR listener (StartListeningToOSCARSession) once it
  661. // has wired the session's refresher callbacks; starting it here would race
  662. // those assignments.
  663. return session, nil
  664. }
  665. // GetSession retrieves a session by aimsid.
  666. func (m *SessionManager) GetSession(ctx context.Context, aimsid string) (*Session, error) {
  667. m.mu.RLock()
  668. defer m.mu.RUnlock()
  669. session, exists := m.sessions[aimsid]
  670. if !exists {
  671. return nil, ErrNoWebAPISession
  672. }
  673. if session.IsExpired() {
  674. return nil, ErrWebAPISessionExpired
  675. }
  676. // A rate-limit disconnect (EvaluateRateLimit -> Session.CloseSession) closes
  677. // every instance for the account while this web session is still unexpired.
  678. // The aimsid must stop resolving at that point, otherwise a client told to
  679. // disconnect could keep issuing charged requests against a dead session (the
  680. // reaper only removes it on time expiry, up to a TTL later).
  681. if session.OSCARSession.IsClosed() {
  682. return nil, ErrWebAPISessionExpired
  683. }
  684. return session, nil
  685. }
  686. // RemoveSession removes a session by aimsid.
  687. func (m *SessionManager) RemoveSession(ctx context.Context, aimsid string) error {
  688. m.mu.Lock()
  689. session, exists := m.sessions[aimsid]
  690. if !exists {
  691. m.mu.Unlock()
  692. return ErrNoWebAPISession
  693. }
  694. delete(m.sessions, aimsid)
  695. m.mu.Unlock()
  696. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  697. // broadcasts and signout, which we don't want to run under m.mu.
  698. session.Close()
  699. return nil
  700. }
  701. // TouchSession updates the last accessed time for a session.
  702. func (m *SessionManager) TouchSession(ctx context.Context, aimsid string) error {
  703. m.mu.Lock()
  704. defer m.mu.Unlock()
  705. session, exists := m.sessions[aimsid]
  706. if !exists {
  707. return ErrNoWebAPISession
  708. }
  709. session.Touch()
  710. return nil
  711. }
  712. // Run reaps expired sessions on a fixed interval until ctx is cancelled or
  713. // Shutdown is called. The caller owns the goroutine's lifecycle; typically
  714. // launch it under the server's errgroup:
  715. //
  716. // g.Go(func() error { mgr.Run(ctx); return nil })
  717. //
  718. // Run is a no-op once the manager is closed, so a reaper that loses the race
  719. // with Shutdown never starts reaping a drained manager.
  720. func (m *SessionManager) Run(ctx context.Context) {
  721. m.mu.Lock()
  722. if m.closed {
  723. m.mu.Unlock()
  724. return
  725. }
  726. // Registering under m.mu is what makes Shutdown's join sound: Shutdown flips
  727. // closed under the same lock, so a reaper either registers before Shutdown
  728. // waits or is turned away here.
  729. m.reaperWG.Add(1)
  730. m.mu.Unlock()
  731. defer m.reaperWG.Done()
  732. ticker := time.NewTicker(webAPISessionReapInterval)
  733. defer ticker.Stop()
  734. for {
  735. select {
  736. case <-ticker.C:
  737. m.reapExpired()
  738. case <-m.stopCh:
  739. return
  740. case <-ctx.Done():
  741. return
  742. }
  743. }
  744. }
  745. // reapExpired removes every dead session and tears it down. A session is dead
  746. // once it has passed its expiry, or once its underlying OSCAR session has been
  747. // closed out from under it (e.g. by a rate-limit disconnect) — the latter is
  748. // already rejected by GetSession, and reaping it here frees the entry promptly
  749. // rather than leaving it until time expiry.
  750. func (m *SessionManager) reapExpired() {
  751. m.mu.Lock()
  752. now := time.Now()
  753. var expired []*Session
  754. for aimsid, session := range m.sessions {
  755. if now.After(session.ExpiresAt) || session.OSCARSession.IsClosed() {
  756. delete(m.sessions, aimsid)
  757. expired = append(expired, session)
  758. }
  759. }
  760. m.mu.Unlock()
  761. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  762. // broadcasts and signout, which we don't want to run under m.mu.
  763. for _, session := range expired {
  764. session.Close()
  765. }
  766. }
  767. // Shutdown drains and closes all sessions, stops the reaper started by Run, and
  768. // blocks further CreateSession calls. It does not depend on the caller
  769. // cancelling Run's context. Safe to call more than once, though only the first
  770. // call waits for the drain. The drain is bounded by ctx: Shutdown returns
  771. // ctx.Err() rather than block forever on a listener that ignores cancellation.
  772. func (m *SessionManager) Shutdown(ctx context.Context) error {
  773. m.mu.Lock()
  774. if m.closed {
  775. m.mu.Unlock()
  776. return nil
  777. }
  778. m.closed = true
  779. close(m.stopCh)
  780. sessions := make([]*Session, 0, len(m.sessions))
  781. for _, session := range m.sessions {
  782. sessions = append(sessions, session)
  783. }
  784. // Clear all sessions
  785. m.sessions = make(map[string]*Session)
  786. m.mu.Unlock()
  787. drained := make(chan struct{})
  788. go func() {
  789. defer close(drained)
  790. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  791. // broadcasts and signout, which we don't want to run under m.mu.
  792. for _, session := range sessions {
  793. session.Close()
  794. }
  795. m.reaperWG.Wait()
  796. }()
  797. select {
  798. case <-drained:
  799. return nil
  800. case <-ctx.Done():
  801. return ctx.Err()
  802. }
  803. }
  804. // generateSessionID creates a cryptographically secure session ID.
  805. func generateSessionID() (string, error) {
  806. bytes := make([]byte, 32) // 256 bits
  807. if _, err := rand.Read(bytes); err != nil {
  808. return "", err
  809. }
  810. return hex.EncodeToString(bytes), nil
  811. }
  812. // sentIMCookieLimit bounds the cookie->msgId map. An error arrives within seconds
  813. // of the send, so a small window suffices; the oldest entry is evicted once full.
  814. const sentIMCookieLimit = 256
  815. // RecordSentIM remembers the msgId handed out for an outgoing message, keyed by the
  816. // OSCAR cookie that message carries on the wire. The two are unrelated by
  817. // construction, so a clientError — which names its message by cookie — could not
  818. // otherwise say which message it refers to.
  819. func (s *Session) RecordSentIM(cookie uint64, msgID string) {
  820. if s == nil || msgID == "" {
  821. return
  822. }
  823. s.sentIMMu.Lock()
  824. defer s.sentIMMu.Unlock()
  825. if s.sentIMs == nil {
  826. s.sentIMs = make(map[uint64]string)
  827. }
  828. if _, seen := s.sentIMs[cookie]; !seen {
  829. s.sentIMOrder = append(s.sentIMOrder, cookie)
  830. }
  831. s.sentIMs[cookie] = msgID
  832. if len(s.sentIMOrder) > sentIMCookieLimit {
  833. delete(s.sentIMs, s.sentIMOrder[0])
  834. s.sentIMOrder = s.sentIMOrder[1:]
  835. }
  836. }
  837. // msgIDForCookie resolves an OSCAR message cookie back to the msgId handed out for
  838. // it, or "" when the message is not one this session sent.
  839. func (s *Session) msgIDForCookie(cookie uint64) string {
  840. if s == nil {
  841. return ""
  842. }
  843. s.sentIMMu.Lock()
  844. defer s.sentIMMu.Unlock()
  845. return s.sentIMs[cookie]
  846. }
  847. // WebAPIStoredIM is one message in a Web AIM session's in-memory IM log.
  848. // The Web AIM client expects fetchStoredIMs entries with sender, message, msgId, and date.
  849. type WebAPIStoredIM struct {
  850. Sender string
  851. Message string
  852. MsgID string
  853. Date int64 // Unix seconds
  854. }
  855. // AddStoredIM appends a message to the per-partner log for this session.
  856. func (s *Session) AddStoredIM(partnerAimID, sender, message, msgID string, date int64) {
  857. if s == nil || partnerAimID == "" || message == "" {
  858. return
  859. }
  860. s.imLogMu.Lock()
  861. defer s.imLogMu.Unlock()
  862. if s.imLog == nil {
  863. s.imLog = make(map[string][]WebAPIStoredIM)
  864. }
  865. s.imLog[normalizeWebAPIAimID(partnerAimID)] = append(s.imLog[normalizeWebAPIAimID(partnerAimID)], WebAPIStoredIM{
  866. Sender: sender,
  867. Message: message,
  868. MsgID: msgID,
  869. Date: date,
  870. })
  871. }
  872. // StoredIM is one entry in a fetchStoredIMs reply.
  873. type StoredIM struct {
  874. Sender string `json:"sender" xml:"sender"`
  875. Message string `json:"message" xml:"message"`
  876. MsgID string `json:"msgId" xml:"msgId"`
  877. Date int64 `json:"date" xml:"date"`
  878. }
  879. // StoredIMQuery describes filters for fetchStoredIMs.
  880. type StoredIMQuery struct {
  881. PartnerAimID string
  882. StartTime int64
  883. EndTime int64
  884. NToGet int
  885. SortOrder string
  886. SkipMsgID string
  887. StopMsgID string
  888. }
  889. // GetStoredIMs returns stored messages for a conversation partner, filtered and sorted
  890. // per the Web AIM client's fetchStoredIMs parameters.
  891. func (s *Session) GetStoredIMs(q StoredIMQuery) []StoredIM {
  892. if s == nil || q.PartnerAimID == "" {
  893. return nil
  894. }
  895. s.imLogMu.Lock()
  896. msgs := append([]WebAPIStoredIM(nil), s.imLog[normalizeWebAPIAimID(q.PartnerAimID)]...)
  897. s.imLogMu.Unlock()
  898. if len(msgs) == 0 {
  899. return []StoredIM{}
  900. }
  901. filtered := make([]WebAPIStoredIM, 0, len(msgs))
  902. for _, msg := range msgs {
  903. if q.StartTime > 0 && msg.Date < q.StartTime {
  904. continue
  905. }
  906. if q.EndTime > 0 && msg.Date > q.EndTime {
  907. continue
  908. }
  909. filtered = append(filtered, msg)
  910. }
  911. descending := strings.EqualFold(q.SortOrder, "descendingDate")
  912. sort.Slice(filtered, func(i, j int) bool {
  913. if descending {
  914. return filtered[i].Date > filtered[j].Date
  915. }
  916. return filtered[i].Date < filtered[j].Date
  917. })
  918. if q.SkipMsgID != "" {
  919. for i, msg := range filtered {
  920. if msg.MsgID == q.SkipMsgID {
  921. filtered = filtered[i+1:]
  922. break
  923. }
  924. }
  925. }
  926. if q.StopMsgID != "" {
  927. for i, msg := range filtered {
  928. if msg.MsgID == q.StopMsgID {
  929. filtered = filtered[:i]
  930. break
  931. }
  932. }
  933. }
  934. n := q.NToGet
  935. if n <= 0 {
  936. n = 100
  937. }
  938. if len(filtered) > n {
  939. filtered = filtered[:n]
  940. }
  941. out := make([]StoredIM, len(filtered))
  942. for i, msg := range filtered {
  943. out[i] = StoredIM(msg)
  944. }
  945. return out
  946. }
  947. // normalizeWebAPIAimID keys the IM log by the same normalization the web client
  948. // applies to aimIds, so a partner stored from a display screen name is still
  949. // found when the client queries by aimId.
  950. func normalizeWebAPIAimID(aimID string) string {
  951. return state.NewIdentScreenName(aimID).String()
  952. }