session.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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. "slices"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/google/uuid"
  17. "github.com/mk6i/open-oscar-server/state"
  18. "github.com/mk6i/open-oscar-server/wire"
  19. )
  20. var (
  21. // ErrNoWebAPISession is returned when a WebAPI session is not found.
  22. ErrNoWebAPISession = errors.New("WebAPI session not found")
  23. // ErrWebAPISessionExpired is returned when a WebAPI session has expired.
  24. ErrWebAPISessionExpired = errors.New("WebAPI session expired")
  25. // ErrWebAPISessionManagerClosed is returned when a session is requested from
  26. // a manager that has been shut down.
  27. ErrWebAPISessionManagerClosed = errors.New("WebAPI session manager is shut down")
  28. )
  29. // Web API session lifecycle timeline.
  30. //
  31. // A web client keeps its session alive by long-polling GET /aim/fetchEvents.
  32. // Every authenticated request touches the session (middleware.RequireSession
  33. // calls TouchSession at request arrival), sliding expiry to now + the TTL. A
  34. // single poll blocks for up to 60s (the fetchEvents long-poll cap) and the
  35. // client waits ~500ms (TimeToNextFetch) before re-polling, so in steady state a
  36. // healthy client touches the session at worst every ~60-65s once jitter is
  37. // included. That worst-case touch interval is the floor the TTL must clear.
  38. //
  39. // If a client hangs up without calling endSession, its last touch was at its
  40. // last poll: the session then expires webAPISessionTTL later and the reaper
  41. // sweeps it within one webAPISessionReapInterval tick. So a silent client is
  42. // removed (and its OSCAR session closed) within TTL + tick of going quiet.
  43. const (
  44. // webAPISessionTTL bounds how long a session survives without a poll. It is
  45. // sized to absorb one missed poll cycle: ~60s for the normal cycle, ~60s for
  46. // the absorbed miss, plus ~20s of jitter margin. Two consecutive misses mean
  47. // the client is genuinely gone and the session is reaped.
  48. webAPISessionTTL = 150 * time.Second
  49. // webAPISessionReapInterval is how often the cleanup goroutine sweeps for
  50. // expired sessions (~TTL/5). A dead session lingers at most
  51. // webAPISessionTTL + webAPISessionReapInterval before removal.
  52. webAPISessionReapInterval = 30 * time.Second
  53. )
  54. // webAPICaps are the capabilities the Web API advertises on behalf of its
  55. // clients. It seeds every session's capability list and is sent as-is at
  56. // sign-on, so the two never drift.
  57. var webAPICaps = [][16]byte{
  58. wire.CapICQCh2Extended,
  59. wire.CapUTF8Messages,
  60. }
  61. // Session represents an active Web AIM API session.
  62. type Session struct {
  63. AimSID string // Unique session ID for web client
  64. ScreenName state.DisplayScreenName // User identity
  65. OSCARSession *state.SessionInstance // Bridge to existing OSCAR session
  66. BaseURL string // Web API base URL advertised to the web client, used to build absolute asset URLs
  67. Events []string // Subscribed event types
  68. EventQueue *EventQueue // Per-session event queue
  69. ClientName string // Client application name
  70. ClientVersion string // Client application version
  71. CreatedAt time.Time // SessionInstance creation time
  72. LastAccessed time.Time // Last activity time
  73. ExpiresAt time.Time // SessionInstance expiration time
  74. FetchTimeout int // Long-polling timeout in milliseconds
  75. TimeToNextFetch int // Suggested delay before next fetch
  76. RemoteAddr string // Client IP address
  77. BuddyListRefresher func(ctx context.Context) (any, error) // Called on feedbag changes to push buddylist event
  78. PermitDenyRefresher func(ctx context.Context) (any, error) // Called on feedbag changes to push permitDeny event
  79. FeedbagLoader func(ctx context.Context) ([]wire.FeedbagItem, error) // Reads the owner's feedbag; every read-only view of the roster derives from it
  80. // BuddyIconURL formats the absolute buddyIcon URL for a buddy from the icon
  81. // hash carried in a presence SNAC. Returns "" when no URL can be published.
  82. BuddyIconURL func(screenName state.IdentScreenName, hash []byte) string
  83. feedbag []wire.FeedbagItem // cached FeedbagLoader result, nil when unloaded or invalidated
  84. aliases map[string]string // aliases derived from feedbag, nil when unloaded or invalidated
  85. feedbagMu sync.Mutex
  86. // presence is the session's view of its buddies' last-known presence, keyed by
  87. // normalized aimId and fed by the BuddyArrived/BuddyDeparted SNACs the listener
  88. // receives.
  89. presence map[string]BuddyPresence
  90. presenceMu sync.RWMutex
  91. imLog map[string][]WebAPIStoredIM
  92. imLogMu sync.Mutex
  93. sentIMs map[uint64]string // OSCAR message cookie -> the msgId given to the client
  94. sentIMOrder []uint64 // insertion order of sentIMs, oldest first
  95. sentIMMu sync.Mutex
  96. // IMRateClassID is the rate class that sending an IM spends. The web client
  97. // renders any rate limit event as the IM banner, so only this class's updates
  98. // may reach it. Zero disables the alert.
  99. IMRateClassID wire.RateLimitClassID
  100. logger *slog.Logger // Logger for debugging
  101. listeners sync.WaitGroup
  102. ctx context.Context
  103. cancel context.CancelFunc
  104. closeMu sync.Mutex
  105. closed bool
  106. capabilities [][16]byte
  107. capsMu sync.RWMutex
  108. }
  109. // IsExpired checks if the session has expired.
  110. func (s *Session) IsExpired() bool {
  111. return time.Now().After(s.ExpiresAt)
  112. }
  113. // Aliases returns this session owner's private buddy aliases, keyed by normalized
  114. // screen name, derived from the cached feedbag and memoized alongside it. Buddies
  115. // without an alias are absent. The map is owned by the session and must not be
  116. // mutated by callers.
  117. func (s *Session) Aliases(ctx context.Context) map[string]string {
  118. s.feedbagMu.Lock()
  119. defer s.feedbagMu.Unlock()
  120. if s.aliases == nil {
  121. items, err := s.feedbagLocked(ctx)
  122. if err != nil {
  123. return nil
  124. }
  125. aliases := make(map[string]string)
  126. for _, item := range items {
  127. if item.ClassID != wire.FeedbagClassIdBuddy || item.Name == "" {
  128. continue
  129. }
  130. alias, ok := item.String(wire.FeedbagAttributesAlias)
  131. if !ok || alias == "" {
  132. continue
  133. }
  134. aliases[state.NewIdentScreenName(item.Name).String()] = alias
  135. }
  136. s.aliases = aliases
  137. }
  138. return s.aliases
  139. }
  140. // Feedbag returns the owner's feedbag rows, reading them through FeedbagLoader on
  141. // the first call after a change and serving the cached copy afterwards. The slice
  142. // is owned by the session and must not be mutated by callers.
  143. //
  144. // Code that rewrites the feedbag must re-read it rather than use this: it computes
  145. // item ids and a pending diff from what it reads, and a stale snapshot would
  146. // overwrite another instance's change.
  147. func (s *Session) Feedbag(ctx context.Context) ([]wire.FeedbagItem, error) {
  148. s.feedbagMu.Lock()
  149. defer s.feedbagMu.Unlock()
  150. return s.feedbagLocked(ctx)
  151. }
  152. // feedbagLocked loads and caches the feedbag. Callers hold feedbagMu.
  153. //
  154. // The lock is deliberately held across the load. Another instance can change the
  155. // list mid-read, and its feedbag SNAC invalidates this cache; a load outside the
  156. // lock could store its pre-change result after that invalidation.
  157. func (s *Session) feedbagLocked(ctx context.Context) ([]wire.FeedbagItem, error) {
  158. if s.feedbag == nil {
  159. items, err := s.FeedbagLoader(ctx)
  160. if err != nil {
  161. s.logger.Error("failed to load feedbag", "err", err.Error())
  162. return nil, err
  163. }
  164. if items == nil {
  165. // An empty feedbag must still count as loaded.
  166. items = []wire.FeedbagItem{}
  167. }
  168. s.feedbag = items
  169. }
  170. return s.feedbag, nil
  171. }
  172. // InvalidateFeedbag drops the cached feedbag and the aliases derived from it.
  173. // Callers that change the owner's feedbag must call this: the feedbag service
  174. // relays its item SNACs only to the owner's *other* instances.
  175. func (s *Session) InvalidateFeedbag() {
  176. s.feedbagMu.Lock()
  177. defer s.feedbagMu.Unlock()
  178. s.feedbag = nil
  179. s.aliases = nil
  180. }
  181. // aliasFor returns this session owner's private alias for buddy, or "" when none is
  182. // set. The web client deletes the alias it holds whenever it merges a user map, so
  183. // every event naming a buddy has to repeat it.
  184. func (s *Session) aliasFor(buddy state.IdentScreenName) string {
  185. // Runs on the SNAC listener goroutine, which has no request context.
  186. return s.Aliases(s.ctx)[buddy.String()]
  187. }
  188. // BuddyPresence is a buddy's last-known presence, assembled from the
  189. // BuddyArrived and BuddyDeparted SNACs a session receives. It carries only what
  190. // those SNACs carry: an away message lives in the locate reply's LocateInfo and
  191. // is not part of a presence broadcast.
  192. type BuddyPresence struct {
  193. DisplayID string // screen name as the buddy formats it
  194. State string // "online", "away", "idle", "occupied", "dnd", "offline"
  195. StatusMsg string
  196. OnlineTime int64
  197. IdleTime int // minutes
  198. Caps [][16]byte
  199. IconHash []byte
  200. }
  201. // Online reports whether the buddy is visible to the viewer.
  202. func (p BuddyPresence) Online() bool {
  203. return p.State != "offline"
  204. }
  205. // BuddyPresence returns a buddy's last-known presence and whether the session
  206. // has one. Callers rendering the roster treat a miss as offline.
  207. func (s *Session) BuddyPresence(buddy state.IdentScreenName) (BuddyPresence, bool) {
  208. s.presenceMu.RLock()
  209. defer s.presenceMu.RUnlock()
  210. p, ok := s.presence[buddy.String()]
  211. return p, ok
  212. }
  213. // setBuddyPresence records a buddy's presence, replacing whatever was there.
  214. func (s *Session) setBuddyPresence(buddy state.IdentScreenName, p BuddyPresence) {
  215. s.presenceMu.Lock()
  216. defer s.presenceMu.Unlock()
  217. if s.presence == nil {
  218. s.presence = make(map[string]BuddyPresence)
  219. }
  220. s.presence[buddy.String()] = p
  221. }
  222. // setBuddyOffline marks a buddy offline, keeping the display name last seen for
  223. // them. A BuddyDeparted carries no TLV block, so nothing else survives: an
  224. // offline buddy publishes no icon, status message or mood.
  225. func (s *Session) setBuddyOffline(buddy state.IdentScreenName) {
  226. s.presenceMu.Lock()
  227. defer s.presenceMu.Unlock()
  228. if s.presence == nil {
  229. s.presence = make(map[string]BuddyPresence)
  230. }
  231. s.presence[buddy.String()] = BuddyPresence{
  232. DisplayID: s.presence[buddy.String()].DisplayID,
  233. State: "offline",
  234. }
  235. }
  236. // forgetBuddyPresence drops a buddy's cached presence. Callers do this when the
  237. // viewer stops watching them: OSCAR notifies only users who currently watch each
  238. // other, so no arrival or departure for that buddy is relayed here again.
  239. func (s *Session) forgetBuddyPresence(buddy state.IdentScreenName) {
  240. s.presenceMu.Lock()
  241. defer s.presenceMu.Unlock()
  242. delete(s.presence, buddy.String())
  243. }
  244. // forgetUnlistedBuddies drops the cached presence of the named buddies that are no
  245. // longer on the roster. One still listed in another group is still watched.
  246. func (s *Session) forgetUnlistedBuddies(names []string) {
  247. if len(names) == 0 {
  248. return
  249. }
  250. items, err := s.Feedbag(s.ctx)
  251. if err != nil {
  252. // Without the roster a partial removal cannot be told from a full one, and
  253. // a wrongly dropped entry reads offline until the buddy changes presence.
  254. return
  255. }
  256. for _, name := range names {
  257. if stillListsBuddy(items, name) {
  258. continue
  259. }
  260. s.forgetBuddyPresence(state.NewIdentScreenName(name))
  261. }
  262. }
  263. // isAIMViewer reports whether the session owner is an AIM account.
  264. func (s *Session) isAIMViewer() bool {
  265. return s.ScreenName.IdentScreenName().UIN() == 0
  266. }
  267. // Touch updates the last accessed time and extends expiration if needed.
  268. func (s *Session) Touch() {
  269. s.LastAccessed = time.Now()
  270. newExpiry := s.LastAccessed.Add(webAPISessionTTL)
  271. if newExpiry.After(s.ExpiresAt) {
  272. s.ExpiresAt = newExpiry
  273. }
  274. }
  275. // IsSubscribedTo checks if the session is subscribed to a specific event type.
  276. func (s *Session) IsSubscribedTo(eventType string) bool {
  277. return slices.Contains(s.Events, eventType)
  278. }
  279. // StartListeningToOSCARSession starts a goroutine that listens to the OSCAR session's
  280. // message channel and converts SNAC messages into WebAPI events.
  281. func (s *Session) StartListeningToOSCARSession() {
  282. s.closeMu.Lock()
  283. defer s.closeMu.Unlock()
  284. if s.closed {
  285. return
  286. }
  287. s.listeners.Go(func() {
  288. msgCh := s.OSCARSession.ReceiveMessage()
  289. for {
  290. select {
  291. case msg, ok := <-msgCh:
  292. if !ok {
  293. // Channel closed, OSCAR session ended
  294. return
  295. }
  296. s.handleSNACMessage(msg)
  297. case <-s.OSCARSession.Closed():
  298. // The OSCAR instance went away without this session asking — a
  299. // boot, a rate-limit disconnect. Tell the client rather than
  300. // leaving its parked fetcher to hang: a sessionEnded event
  301. // releases the poll at once and the client signs off on the
  302. // spot, instead of waiting out the reaper's next sweep.
  303. //
  304. // A teardown this session started needs no event, and gets
  305. // none: Close closes the queue before it closes the instance,
  306. // so this Push is a no-op on that path.
  307. s.EventQueue.Push(EventTypeSessionEnded, struct{}{})
  308. return
  309. }
  310. }
  311. })
  312. }
  313. // Close tears down the session: it releases any parked event fetchers, closes
  314. // the OSCAR instance, and waits for the listener goroutine to unwind. Safe to
  315. // call more than once.
  316. func (s *Session) Close() {
  317. s.closeMu.Lock()
  318. if s.closed {
  319. s.closeMu.Unlock()
  320. return
  321. }
  322. s.closed = true
  323. s.closeMu.Unlock()
  324. s.EventQueue.Close()
  325. s.OSCARSession.CloseInstance()
  326. s.cancel()
  327. s.listeners.Wait()
  328. }
  329. // handleSNACMessage converts a SNAC message into WebAPI events and pushes them to the event queue.
  330. func (s *Session) handleSNACMessage(msg wire.SNACMessage) {
  331. // Convert SNAC message to WebAPI events based on food group and subgroup
  332. switch msg.Frame.FoodGroup {
  333. case wire.ICBM:
  334. s.handleICBMMessage(msg)
  335. case wire.Buddy:
  336. s.handleBuddyMessage(msg)
  337. case wire.Feedbag:
  338. s.handleFeedbagMessage(msg)
  339. case wire.OService:
  340. s.handleOServiceMessage(msg)
  341. }
  342. }
  343. // handleOServiceMessage handles OService SNAC messages relayed to the session's
  344. // own OSCAR instance.
  345. func (s *Session) handleOServiceMessage(msg wire.SNACMessage) {
  346. switch msg.Frame.SubGroup {
  347. case wire.OServiceUserInfoUpdate:
  348. s.handleUserInfoUpdate(msg)
  349. case wire.OServiceRateParamChange:
  350. s.handleRateLimitUpdate(msg)
  351. }
  352. }
  353. // handleUserInfoUpdate surfaces OServiceUserInfoUpdate, which the server relays to
  354. // a user when their own user info changes (notably a buddy icon upload or clear).
  355. // The client re-renders its identity badge from myInfo events only, so we
  356. // translate this into a fresh myInfo. The away message is the one field read off
  357. // the session, since no user info block carries the text.
  358. func (s *Session) handleUserInfoUpdate(msg wire.SNACMessage) {
  359. if !s.IsSubscribedTo("myInfo") && !s.IsSubscribedTo("presence") {
  360. return
  361. }
  362. body, ok := msg.Body.(wire.SNAC_0x01_0x0F_OServiceUserInfoUpdate)
  363. if !ok || len(body.UserInfo) == 0 {
  364. return
  365. }
  366. info := body.UserInfo[0]
  367. screenName := state.DisplayScreenName(info.ScreenName)
  368. webState := selfWebState(info, screenName.IdentScreenName().UIN() == 0)
  369. // A missing icon TLV yields a nil hash, which publishes the placeholder URL
  370. // and so clears an icon the client still holds.
  371. hash := buddyIconHash(info)
  372. myInfo := buildMyInfo(
  373. screenName,
  374. webState,
  375. s.BuddyIconURL(screenName.IdentScreenName(), hash),
  376. moodIconURL(s.BaseURL, webState, userInfoCaps(info)),
  377. )
  378. myInfo.AwayMsg = s.OSCARSession.Session().AwayMessage()
  379. myInfo.StatusMsg = userStatusMsg(info)
  380. s.EventQueue.Push(EventTypeMyInfo, myInfo)
  381. }
  382. // handleRateLimitUpdate translates a rate limit status change — broadcast by the
  383. // account's rate limit monitor — into a rateLimit event. Only the IM class is
  384. // surfaced, since the client feeds any rateLimit event into the
  385. // conversation-window alert. Code 1 is a class-params change, not a status
  386. // transition, and is ignored.
  387. func (s *Session) handleRateLimitUpdate(msg wire.SNACMessage) {
  388. if s.IMRateClassID == 0 {
  389. return
  390. }
  391. body, ok := msg.Body.(wire.SNAC_0x01_0x0A_OServiceRateParamsChange)
  392. if !ok {
  393. return
  394. }
  395. if wire.RateLimitClassID(body.Rate.ID) != s.IMRateClassID {
  396. return
  397. }
  398. var status string
  399. switch body.Code {
  400. case 2:
  401. status = "warn"
  402. case 3:
  403. status = "limit"
  404. case 4:
  405. status = "clear"
  406. default:
  407. return
  408. }
  409. s.EventQueue.Push(EventTypeRateLimit, RateLimitEvent{
  410. Classes: []RateLimitClass{
  411. {ID: int(body.Rate.ID), Status: status},
  412. },
  413. })
  414. }
  415. // handleICBMMessage handles ICBM (instant messaging) SNAC messages.
  416. func (s *Session) handleICBMMessage(msg wire.SNACMessage) {
  417. switch msg.Frame.SubGroup {
  418. case wire.ICBMChannelMsgToClient:
  419. s.handleIncomingIM(msg)
  420. case wire.ICBMClientEvent:
  421. s.handleTypingNotification(msg)
  422. case wire.ICBMClientErr:
  423. s.handleClientError(msg)
  424. }
  425. }
  426. // handleIncomingIM handles incoming instant messages.
  427. func (s *Session) handleIncomingIM(msg wire.SNACMessage) {
  428. body, ok := msg.Body.(wire.SNAC_0x04_0x07_ICBMChannelMsgToClient)
  429. if !ok {
  430. return
  431. }
  432. // A send time is only stamped on a message replayed out of the offline store,
  433. // so its presence marks this as a delivery of something sent while the user was
  434. // signed off, and carries the moment the sender actually sent it.
  435. sentTime, isOffline := body.Uint32BE(wire.ICBMTLVSendTime)
  436. // Retrieval answers only the instance that asked, and StartSession asks only
  437. // when the client subscribed to offlineIM, so a stamped message here is one
  438. // this session requested. A live IM still needs the im subscription.
  439. if !isOffline && !s.IsSubscribedTo("im") {
  440. return
  441. }
  442. // Extract message text from TLV data
  443. var messageText string
  444. if msgData, hasMsg := body.Bytes(wire.ICBMTLVAOLIMData); hasMsg {
  445. if text, err := wire.UnmarshalICBMMessageText(msgData); err == nil {
  446. messageText = text
  447. }
  448. }
  449. if messageText == "" {
  450. return
  451. }
  452. // Check if it's an auto-response (channel 2)
  453. autoResponse := body.ChannelID == 0x0002
  454. // msgId must be unique per delivered event. The OSCAR cookie is not a
  455. // reliable unique id (some clients reuse it across messages), and the web
  456. // client dedupes its conversation list by msgId, silently dropping any
  457. // collisions. Mint a fresh random id instead of reusing body.Cookie.
  458. msgID := strconv.FormatUint(mrand.Uint64(), 16)
  459. // SNAC user info carries the sender's display screen name. The web client
  460. // keys conversations and users by the normalized aimId and only renders
  461. // displayId, so the two forms must not be interchanged.
  462. partnerDisplay := body.ScreenName
  463. partner := state.NewIdentScreenName(partnerDisplay)
  464. partnerAimID := partner.String()
  465. // An offline message is logged under the time it was sent, so the stored-IM
  466. // history it lands in stays in the order the conversation happened.
  467. timestamp := time.Now().Unix()
  468. if isOffline {
  469. timestamp = int64(sentTime)
  470. }
  471. s.AddStoredIM(partnerAimID, partnerAimID, messageText, msgID, timestamp)
  472. if isOffline {
  473. // The client resolves an offline sender from aimId and friendly alone,
  474. // so friendly falls back to the sender's own formatting when the viewer
  475. // has no alias for them.
  476. friendly := s.aliasFor(partner)
  477. if friendly == "" {
  478. friendly = partnerDisplay
  479. }
  480. s.EventQueue.Push(EventTypeOfflineIM, OfflineIMEvent{
  481. AimID: partnerAimID,
  482. Friendly: friendly,
  483. Message: messageText,
  484. MsgID: msgID,
  485. Timestamp: timestamp,
  486. Imf: imfPlainText,
  487. AutoResp: autoResponse,
  488. })
  489. s.logger.Debug("delivered offline instant message",
  490. "from", partnerDisplay,
  491. "to", s.ScreenName,
  492. "sent", timestamp)
  493. } else {
  494. source := UserInfo{
  495. AimID: partnerAimID,
  496. DisplayID: partnerDisplay,
  497. Friendly: s.aliasFor(partner),
  498. UserType: userTypeFor(partner),
  499. }
  500. if presence, ok := s.BuddyPresence(partner); ok {
  501. source.State = presence.State
  502. source.OnlineTime = presence.OnlineTime
  503. }
  504. s.EventQueue.Push(EventTypeIM, IMEvent{
  505. Source: source,
  506. Message: messageText,
  507. MsgID: msgID,
  508. Timestamp: timestamp,
  509. Imf: imfPlainText,
  510. AutoResp: autoResponse,
  511. })
  512. s.logger.Debug("delivered instant message",
  513. "from", partnerDisplay,
  514. "to", s.ScreenName)
  515. }
  516. if s.IsSubscribedTo("conversation") {
  517. // unread is 0 here, not 1, because the "im"/"offlineIM" event pushed above
  518. // already causes the client to increment its own persisted per-buddy unread
  519. // tally. The "Recent chats" badge is the sum of that persisted tally and
  520. // this conversation's unreadCount, so sending 1 here would double-count
  521. // the message (badge shows 2 for the first IM). Mirrors the sent-IM path,
  522. // which also passes 0.
  523. s.EventQueue.Push(EventTypeConversation, ConversationEventData("update", []ConversationEntryData{
  524. ConversationEntry(
  525. partnerAimID,
  526. partnerDisplay,
  527. messageText,
  528. msgID,
  529. partnerAimID,
  530. false,
  531. 0,
  532. ),
  533. }))
  534. }
  535. }
  536. // handleClientError translates ICBMClientErr — the recipient reporting that it
  537. // could not handle a message already delivered to it — into a clientError event
  538. // for the sender. Only OSCAR clients raise this SNAC.
  539. func (s *Session) handleClientError(msg wire.SNACMessage) {
  540. if !s.IsSubscribedTo("im") {
  541. return
  542. }
  543. body, ok := msg.Body.(wire.SNAC_0x04_0x0B_ICBMClientErr)
  544. if !ok {
  545. return
  546. }
  547. // The SNAC names the erroring party by their own formatting, so both the
  548. // normalized aimId and displayId are sent, along with the viewer's alias.
  549. sender := state.NewIdentScreenName(body.ScreenName)
  550. channel := "im"
  551. if body.ChannelID == wire.ICBMChannelRendezvous {
  552. channel = "data"
  553. }
  554. s.EventQueue.Push(EventTypeClientError, ClientErrorEvent{
  555. Source: UserInfo{
  556. AimID: sender.String(),
  557. DisplayID: body.ScreenName,
  558. Friendly: s.aliasFor(sender),
  559. UserType: userTypeFor(sender),
  560. },
  561. Cookie: s.msgIDForCookie(body.Cookie),
  562. Channel: channel,
  563. })
  564. }
  565. // handleTypingNotification handles typing notifications.
  566. func (s *Session) handleTypingNotification(msg wire.SNACMessage) {
  567. if !s.IsSubscribedTo("typing") {
  568. return
  569. }
  570. body, ok := msg.Body.(wire.SNAC_0x04_0x14_ICBMClientEvent)
  571. if !ok {
  572. return
  573. }
  574. // Event types: 0x0000=none, 0x0001=typed (paused), 0x0002=typing
  575. var typingStatus string
  576. switch body.Event {
  577. case 0x0002:
  578. typingStatus = "typing"
  579. case 0x0001:
  580. typingStatus = "typed"
  581. default:
  582. typingStatus = "none"
  583. }
  584. typingEvent := TypingEvent{
  585. AimID: state.NewIdentScreenName(body.ScreenName).String(),
  586. TypingStatus: typingStatus,
  587. }
  588. s.EventQueue.Push(EventTypeTyping, typingEvent)
  589. }
  590. // handleBuddyMessage handles buddy/presence SNAC messages.
  591. func (s *Session) handleBuddyMessage(msg wire.SNACMessage) {
  592. switch msg.Frame.SubGroup {
  593. case wire.BuddyArrived:
  594. s.handleBuddyArrived(msg)
  595. case wire.BuddyDeparted:
  596. s.handleBuddyDeparted(msg)
  597. }
  598. }
  599. // handleBuddyArrived handles when a buddy comes online.
  600. //
  601. // For BuddyArrived updates, presence state is inferred from the TLVUserInfo.
  602. // Away and invisible transitions are typically broadcast using BuddyArrived
  603. // with updated user flags/status bits, not BuddyDeparted.
  604. func (s *Session) handleBuddyArrived(msg wire.SNACMessage) {
  605. body, ok := msg.Body.(wire.SNAC_0x03_0x0B_BuddyArrived)
  606. if !ok {
  607. return
  608. }
  609. buddy := state.NewIdentScreenName(body.ScreenName)
  610. presence := buddyPresenceFrom(body.TLVUserInfo, s.isAIMViewer())
  611. s.setBuddyPresence(buddy, presence)
  612. if !s.IsSubscribedTo("presence") {
  613. return
  614. }
  615. presenceEvent := PresenceEvent{
  616. AimID: buddy.String(),
  617. Friendly: s.aliasFor(buddy),
  618. State: presence.State,
  619. UserType: userTypeFor(buddy),
  620. StatusMsg: presence.StatusMsg,
  621. IdleTime: presence.IdleTime,
  622. OnlineTime: presence.OnlineTime,
  623. MoodIcon: moodIconURL(s.BaseURL, presence.State, presence.Caps),
  624. }
  625. // A BuddyArrived carries the buddy's current icon in TLV 0x1D whenever they
  626. // have one, so an icon change (or clear, which arrives as the sentinel hash)
  627. // rides along on the presence broadcast. Publish the matching URL: with an
  628. // icon it is content-addressed; without one it is the placeholder URL, which
  629. // differs from any prior icon URL and so clears a removed icon under the
  630. // client's shallow merge. An empty result (no origin known) is omitted, which
  631. // preserves whatever icon the client already holds.
  632. if s.BuddyIconURL != nil {
  633. presenceEvent.BuddyIcon = s.BuddyIconURL(buddy, presence.IconHash)
  634. }
  635. s.EventQueue.Push(EventTypePresence, presenceEvent)
  636. }
  637. // bartIDs returns the BART items a user info block carries. They travel as a list
  638. // in one TLV: a user's buddy icon and status message ride in it together.
  639. func bartIDs(info wire.TLVUserInfo) []wire.BARTID {
  640. b, ok := info.Bytes(wire.OServiceUserInfoBARTInfo)
  641. if !ok {
  642. return nil
  643. }
  644. var ids []wire.BARTID
  645. if err := wire.UnmarshalBE(&ids, bytes.NewReader(b)); err != nil {
  646. return nil
  647. }
  648. return ids
  649. }
  650. // buddyIconHash returns the buddy icon hash carried in a user info block, or nil
  651. // when it carries none.
  652. func buddyIconHash(info wire.TLVUserInfo) []byte {
  653. for _, id := range bartIDs(info) {
  654. if id.Type == wire.BARTTypesBuddyIcon || id.Type == wire.BARTTypesBuddyIconSmall {
  655. return id.Hash
  656. }
  657. }
  658. return nil
  659. }
  660. // userStatusMsg returns the status message carried in a user info block, or ""
  661. // when it carries none or one that cannot be decoded.
  662. func userStatusMsg(info wire.TLVUserInfo) string {
  663. for _, id := range bartIDs(info) {
  664. msg, err := id.StatusText()
  665. if err != nil {
  666. continue
  667. }
  668. if msg != "" {
  669. return msg
  670. }
  671. }
  672. return ""
  673. }
  674. // sessionStatusMsg returns the status message a session currently advertises.
  675. func sessionStatusMsg(instance *state.SessionInstance) string {
  676. status, _ := instance.Session().Status()
  677. msg, err := status.StatusText()
  678. if err != nil {
  679. return ""
  680. }
  681. return msg
  682. }
  683. // buddyWebState reports the web state a buddy's user info describes, along with
  684. // the minutes they have been idle. Invisibility reads as offline. Idle is always
  685. // reported, but only upgrades an otherwise online user to "idle".
  686. func buddyWebState(info wire.TLVUserInfo, isAIMViewer bool) (string, int) {
  687. idle := 0
  688. if mins, ok := info.Uint16BE(wire.OServiceUserInfoIdleTime); ok {
  689. idle = int(mins)
  690. }
  691. if info.IsInvisible() {
  692. return "offline", idle
  693. }
  694. // statusBitState must be consulted before IsAway: Busy and DND also raise
  695. // the unavailable flag, so an away-first test reports every busy user as
  696. // away.
  697. if st := statusBitState(info, isAIMViewer); st != "" {
  698. return st, idle
  699. }
  700. if info.IsAway() {
  701. return "away", idle
  702. }
  703. if mask, ok := info.Uint32BE(wire.OServiceUserInfoStatus); ok && mask&wire.OServiceUserStatusAway != 0 {
  704. return "away", idle
  705. }
  706. if idle > 0 {
  707. return "idle", idle
  708. }
  709. return "online", idle
  710. }
  711. // buddyPresenceFrom builds a presence record from the user info block a
  712. // BuddyArrived carries. isAIMViewer decides whether Busy and DND collapse to
  713. // "away".
  714. func buddyPresenceFrom(info wire.TLVUserInfo, isAIMViewer bool) BuddyPresence {
  715. st, idle := buddyWebState(info, isAIMViewer)
  716. p := BuddyPresence{
  717. DisplayID: info.ScreenName,
  718. State: st,
  719. IdleTime: idle,
  720. StatusMsg: userStatusMsg(info),
  721. Caps: userInfoCaps(info),
  722. IconHash: buddyIconHash(info),
  723. }
  724. if tod, ok := info.Uint32BE(wire.OServiceUserInfoSignonTOD); ok {
  725. p.OnlineTime = int64(tod)
  726. }
  727. return p
  728. }
  729. // hasAwayMsg reports whether a state is one whose user may be advertising an
  730. // away message.
  731. func hasAwayMsg(webState string) bool {
  732. switch webState {
  733. case "away", "occupied", "dnd":
  734. return true
  735. }
  736. return false
  737. }
  738. // awayMessage reads a buddy's away message, which lives in the locate reply's
  739. // LocateInfo and so is absent from presence broadcasts. Callers ask only for a
  740. // buddy the view already reports as unavailable.
  741. func awayMessage(
  742. ctx context.Context,
  743. locateService LocateService,
  744. instance *state.SessionInstance,
  745. buddy state.IdentScreenName,
  746. logger *slog.Logger,
  747. ) string {
  748. reply, err := locateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  749. wire.SNAC_0x02_0x05_LocateUserInfoQuery{
  750. Type: uint16(wire.LocateTypeUnavailable),
  751. ScreenName: buddy.String(),
  752. })
  753. if err != nil {
  754. logger.WarnContext(ctx, "failed to query away message",
  755. "screenName", buddy.String(), "error", err)
  756. return ""
  757. }
  758. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  759. if !ok {
  760. // Locate error => the buddy went offline or blocked the caller between
  761. // their arrival and this query.
  762. return ""
  763. }
  764. msg, _ := info.LocateInfo.String(wire.LocateTLVTagsInfoUnavailableData)
  765. return msg
  766. }
  767. // handleBuddyDeparted handles when a buddy goes offline.
  768. func (s *Session) handleBuddyDeparted(msg wire.SNACMessage) {
  769. body, ok := msg.Body.(wire.SNAC_0x03_0x0C_BuddyDeparted)
  770. if !ok {
  771. return
  772. }
  773. buddy := state.NewIdentScreenName(body.ScreenName)
  774. // Recorded before the subscription check, for the same reason as arrivals.
  775. s.setBuddyOffline(buddy)
  776. if !s.IsSubscribedTo("presence") {
  777. return
  778. }
  779. // BuddyIcon is deliberately omitted: an offline buddy keeps their icon, and
  780. // omitting it lets the client's merge preserve the icon it already holds.
  781. presenceEvent := PresenceEvent{
  782. AimID: buddy.String(),
  783. Friendly: s.aliasFor(buddy),
  784. State: "offline",
  785. UserType: userTypeFor(buddy),
  786. }
  787. s.EventQueue.Push(EventTypePresence, presenceEvent)
  788. }
  789. // feedbagResultAuthRequired is the per-item feedbag result meaning the target's ICQ
  790. // settings require authorization, so the item was not stored.
  791. const feedbagResultAuthRequired = uint16(0x000E)
  792. // refreshBuddyList re-reads the roster and pushes it to the client. Runs on the SNAC
  793. // listener goroutine, so it uses the session context rather than a request context.
  794. func (s *Session) refreshBuddyList() {
  795. if s.BuddyListRefresher == nil {
  796. return
  797. }
  798. payload, err := s.BuddyListRefresher(s.ctx)
  799. if err != nil {
  800. s.logger.Error("failed to refresh buddy list after feedbag change", "err", err)
  801. return
  802. }
  803. s.EventQueue.Push(EventTypeBuddyList, payload)
  804. }
  805. func (s *Session) handleFeedbagMessage(msg wire.SNACMessage) {
  806. s.InvalidateFeedbag()
  807. switch msg.Frame.SubGroup {
  808. case wire.FeedbagStatus:
  809. // Insert/update/delete below reach only a user's *other* instances, so this
  810. // is the one notification a session gets for its own feedbag write.
  811. if !s.IsSubscribedTo(string(EventTypeBuddyList)) {
  812. return
  813. }
  814. if body, ok := msg.Body.(wire.SNAC_0x13_0x0E_FeedbagStatus); ok {
  815. // A buddy declined for authorization is not stored, and is simply
  816. // absent from the refreshed roster.
  817. if slices.Contains(body.Results, feedbagResultAuthRequired) {
  818. s.logger.Info("feedbag item declined pending authorization")
  819. }
  820. }
  821. s.refreshBuddyList()
  822. case wire.FeedbagInsertItem, wire.FeedbagUpdateItem, wire.FeedbagDeleteItem:
  823. // An insert and an update both relay an UpdateItem body; only a delete
  824. // carries a DeleteItem body.
  825. var items []wire.FeedbagItem
  826. isDelete := false
  827. switch body := msg.Body.(type) {
  828. case wire.SNAC_0x13_0x09_FeedbagUpdateItem:
  829. items = body.Items
  830. case wire.SNAC_0x13_0x0A_FeedbagDeleteItem:
  831. items = body.Items
  832. isDelete = true
  833. }
  834. if isDelete {
  835. var removed []string
  836. for _, item := range items {
  837. if item.ClassID == wire.FeedbagClassIdBuddy && item.Name != "" {
  838. removed = append(removed, item.Name)
  839. }
  840. }
  841. s.forgetUnlistedBuddies(removed)
  842. }
  843. s.refreshBuddyList()
  844. if s.PermitDenyRefresher != nil {
  845. for _, item := range items {
  846. if item.ClassID == wire.FeedbagClassIDPermit ||
  847. item.ClassID == wire.FeedbagClassIDDeny ||
  848. item.ClassID == wire.FeedbagClassIdPdinfo {
  849. pdd, err := s.PermitDenyRefresher(s.ctx)
  850. if err != nil {
  851. s.logger.Error("failed to refresh permit/deny after feedbag change", "err", err)
  852. } else {
  853. s.EventQueue.Push(EventTypePermitDeny, pdd)
  854. }
  855. break
  856. }
  857. }
  858. }
  859. }
  860. }
  861. // SessionManager manages Web API sessions with thread-safe operations.
  862. // Construct it with NewSessionManager and drive its reaper with Run.
  863. type SessionManager struct {
  864. sessions map[string]*Session // Keyed by aimsid
  865. mu sync.RWMutex
  866. closed bool // set by Shutdown; rejects new sessions and makes drain idempotent
  867. stopCh chan struct{} // closed by Shutdown to stop the reaper
  868. reaperWG sync.WaitGroup // tracks a running reaper so Shutdown can join it
  869. }
  870. // NewSessionManager creates a new WebAPI session manager. It does not start
  871. // any goroutines; call Run to start reaping expired sessions.
  872. func NewSessionManager() *SessionManager {
  873. return &SessionManager{
  874. sessions: make(map[string]*Session),
  875. stopCh: make(chan struct{}),
  876. }
  877. }
  878. // CreateSession creates a new WebAPI session.
  879. //
  880. // The session does not begin listening to its OSCAR instance yet: the caller
  881. // must wire the session's refresher callbacks (BuddyListRefresher, BuddyIconURL,
  882. // ...) and then call StartListeningToOSCARSession. Wiring them after the
  883. // listener starts would race the goroutine, which reads them as it converts
  884. // SNACs into events.
  885. func (m *SessionManager) CreateSession(screenName state.DisplayScreenName, events []string, oscarSession *state.SessionInstance, baseURL string, logger *slog.Logger) (*Session, error) {
  886. m.mu.Lock()
  887. defer m.mu.Unlock()
  888. // Refuse to create sessions once shut down: the reaper is stopped, so a
  889. // session added now would never be closed or reaped.
  890. if m.closed {
  891. return nil, ErrWebAPISessionManagerClosed
  892. }
  893. // Generate unique session ID
  894. aimsid, err := generateSessionID()
  895. if err != nil {
  896. return nil, err
  897. }
  898. now := time.Now()
  899. sessCtx, sessCancel := context.WithCancel(context.Background())
  900. session := &Session{
  901. ctx: sessCtx,
  902. cancel: sessCancel,
  903. AimSID: aimsid,
  904. ScreenName: screenName,
  905. OSCARSession: oscarSession,
  906. BaseURL: baseURL,
  907. Events: events,
  908. EventQueue: NewEventQueue(1000), // Max 1000 events per session
  909. CreatedAt: now,
  910. LastAccessed: now,
  911. ExpiresAt: now.Add(webAPISessionTTL),
  912. FetchTimeout: 60000, // 60 seconds default for better stability
  913. TimeToNextFetch: 500, // 500ms suggested delay
  914. logger: logger,
  915. capabilities: slices.Clone(webAPICaps),
  916. }
  917. m.sessions[aimsid] = session
  918. // The caller starts the OSCAR listener (StartListeningToOSCARSession) once it
  919. // has wired the session's refresher callbacks; starting it here would race
  920. // those assignments.
  921. return session, nil
  922. }
  923. // GetSession retrieves a session by aimsid.
  924. func (m *SessionManager) GetSession(ctx context.Context, aimsid string) (*Session, error) {
  925. m.mu.RLock()
  926. defer m.mu.RUnlock()
  927. session, exists := m.sessions[aimsid]
  928. if !exists {
  929. return nil, ErrNoWebAPISession
  930. }
  931. if session.IsExpired() {
  932. return nil, ErrWebAPISessionExpired
  933. }
  934. // A rate-limit disconnect (EvaluateRateLimit -> Session.CloseSession) closes
  935. // every instance for the account while this web session is still unexpired.
  936. // The aimsid must stop resolving at that point, otherwise a client told to
  937. // disconnect could keep issuing charged requests against a dead session (the
  938. // reaper only removes it on time expiry, up to a TTL later).
  939. if session.OSCARSession.IsClosed() {
  940. return nil, ErrWebAPISessionExpired
  941. }
  942. return session, nil
  943. }
  944. // RemoveSession removes a session by aimsid.
  945. func (m *SessionManager) RemoveSession(ctx context.Context, aimsid string) error {
  946. m.mu.Lock()
  947. session, exists := m.sessions[aimsid]
  948. if !exists {
  949. m.mu.Unlock()
  950. return ErrNoWebAPISession
  951. }
  952. delete(m.sessions, aimsid)
  953. m.mu.Unlock()
  954. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  955. // broadcasts and signout, which we don't want to run under m.mu.
  956. session.Close()
  957. return nil
  958. }
  959. // TouchSession updates the last accessed time for a session.
  960. func (m *SessionManager) TouchSession(ctx context.Context, aimsid string) error {
  961. m.mu.Lock()
  962. defer m.mu.Unlock()
  963. session, exists := m.sessions[aimsid]
  964. if !exists {
  965. return ErrNoWebAPISession
  966. }
  967. session.Touch()
  968. return nil
  969. }
  970. // Run reaps expired sessions on a fixed interval until ctx is cancelled or
  971. // Shutdown is called. The caller owns the goroutine's lifecycle; typically
  972. // launch it under the server's errgroup:
  973. //
  974. // g.Go(func() error { mgr.Run(ctx); return nil })
  975. //
  976. // Run is a no-op once the manager is closed, so a reaper that loses the race
  977. // with Shutdown never starts reaping a drained manager.
  978. func (m *SessionManager) Run(ctx context.Context) {
  979. m.mu.Lock()
  980. if m.closed {
  981. m.mu.Unlock()
  982. return
  983. }
  984. // Registering under m.mu is what makes Shutdown's join sound: Shutdown flips
  985. // closed under the same lock, so a reaper either registers before Shutdown
  986. // waits or is turned away here.
  987. m.reaperWG.Add(1)
  988. m.mu.Unlock()
  989. defer m.reaperWG.Done()
  990. ticker := time.NewTicker(webAPISessionReapInterval)
  991. defer ticker.Stop()
  992. for {
  993. select {
  994. case <-ticker.C:
  995. m.reapExpired()
  996. case <-m.stopCh:
  997. return
  998. case <-ctx.Done():
  999. return
  1000. }
  1001. }
  1002. }
  1003. // reapExpired removes every dead session and tears it down. A session is dead
  1004. // once it has passed its expiry, or once its underlying OSCAR session has been
  1005. // closed out from under it (e.g. by a rate-limit disconnect) — the latter is
  1006. // already rejected by GetSession, and reaping it here frees the entry promptly
  1007. // rather than leaving it until time expiry.
  1008. func (m *SessionManager) reapExpired() {
  1009. m.mu.Lock()
  1010. now := time.Now()
  1011. var expired []*Session
  1012. for aimsid, session := range m.sessions {
  1013. if now.After(session.ExpiresAt) || session.OSCARSession.IsClosed() {
  1014. delete(m.sessions, aimsid)
  1015. expired = append(expired, session)
  1016. }
  1017. }
  1018. m.mu.Unlock()
  1019. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  1020. // broadcasts and signout, which we don't want to run under m.mu.
  1021. for _, session := range expired {
  1022. session.Close()
  1023. }
  1024. }
  1025. // Shutdown drains and closes all sessions, stops the reaper started by Run, and
  1026. // blocks further CreateSession calls. It does not depend on the caller
  1027. // cancelling Run's context. Safe to call more than once, though only the first
  1028. // call waits for the drain. The drain is bounded by ctx: Shutdown returns
  1029. // ctx.Err() rather than block forever on a listener that ignores cancellation.
  1030. func (m *SessionManager) Shutdown(ctx context.Context) error {
  1031. m.mu.Lock()
  1032. if m.closed {
  1033. m.mu.Unlock()
  1034. return nil
  1035. }
  1036. m.closed = true
  1037. close(m.stopCh)
  1038. sessions := make([]*Session, 0, len(m.sessions))
  1039. for _, session := range m.sessions {
  1040. sessions = append(sessions, session)
  1041. }
  1042. // Clear all sessions
  1043. m.sessions = make(map[string]*Session)
  1044. m.mu.Unlock()
  1045. drained := make(chan struct{})
  1046. go func() {
  1047. defer close(drained)
  1048. // Tear down outside the lock: CloseInstance fans out to buddy-departed
  1049. // broadcasts and signout, which we don't want to run under m.mu.
  1050. for _, session := range sessions {
  1051. session.Close()
  1052. }
  1053. m.reaperWG.Wait()
  1054. }()
  1055. select {
  1056. case <-drained:
  1057. return nil
  1058. case <-ctx.Done():
  1059. return ctx.Err()
  1060. }
  1061. }
  1062. // generateSessionID creates a cryptographically secure session ID.
  1063. func generateSessionID() (string, error) {
  1064. bytes := make([]byte, 32) // 256 bits
  1065. if _, err := rand.Read(bytes); err != nil {
  1066. return "", err
  1067. }
  1068. return hex.EncodeToString(bytes), nil
  1069. }
  1070. // sentIMCookieLimit bounds the cookie->msgId map. An error arrives within seconds
  1071. // of the send, so a small window suffices; the oldest entry is evicted once full.
  1072. const sentIMCookieLimit = 256
  1073. // RecordSentIM remembers the msgId handed out for an outgoing message, keyed by the
  1074. // OSCAR cookie that message carries on the wire. The two are unrelated by
  1075. // construction, so a clientError — which names its message by cookie — could not
  1076. // otherwise say which message it refers to.
  1077. func (s *Session) RecordSentIM(cookie uint64, msgID string) {
  1078. if s == nil || msgID == "" {
  1079. return
  1080. }
  1081. s.sentIMMu.Lock()
  1082. defer s.sentIMMu.Unlock()
  1083. if s.sentIMs == nil {
  1084. s.sentIMs = make(map[uint64]string)
  1085. }
  1086. if _, seen := s.sentIMs[cookie]; !seen {
  1087. s.sentIMOrder = append(s.sentIMOrder, cookie)
  1088. }
  1089. s.sentIMs[cookie] = msgID
  1090. if len(s.sentIMOrder) > sentIMCookieLimit {
  1091. delete(s.sentIMs, s.sentIMOrder[0])
  1092. s.sentIMOrder = s.sentIMOrder[1:]
  1093. }
  1094. }
  1095. // msgIDForCookie resolves an OSCAR message cookie back to the msgId handed out for
  1096. // it, or "" when the message is not one this session sent.
  1097. func (s *Session) msgIDForCookie(cookie uint64) string {
  1098. if s == nil {
  1099. return ""
  1100. }
  1101. s.sentIMMu.Lock()
  1102. defer s.sentIMMu.Unlock()
  1103. return s.sentIMs[cookie]
  1104. }
  1105. // WebAPIStoredIM is one message in a Web AIM session's in-memory IM log.
  1106. // The Web AIM client expects fetchStoredIMs entries with sender, message, msgId, and date.
  1107. type WebAPIStoredIM struct {
  1108. Sender string
  1109. Message string
  1110. MsgID string
  1111. Date int64 // Unix seconds
  1112. }
  1113. // AddStoredIM appends a message to the per-partner log for this session.
  1114. func (s *Session) AddStoredIM(partnerAimID, sender, message, msgID string, date int64) {
  1115. if s == nil || partnerAimID == "" || message == "" {
  1116. return
  1117. }
  1118. s.imLogMu.Lock()
  1119. defer s.imLogMu.Unlock()
  1120. if s.imLog == nil {
  1121. s.imLog = make(map[string][]WebAPIStoredIM)
  1122. }
  1123. s.imLog[normalizeWebAPIAimID(partnerAimID)] = append(s.imLog[normalizeWebAPIAimID(partnerAimID)], WebAPIStoredIM{
  1124. Sender: sender,
  1125. Message: message,
  1126. MsgID: msgID,
  1127. Date: date,
  1128. })
  1129. }
  1130. // StoredIM is one entry in a fetchStoredIMs reply.
  1131. type StoredIM struct {
  1132. Sender string `json:"sender" xml:"sender"`
  1133. Message string `json:"message" xml:"message"`
  1134. MsgID string `json:"msgId" xml:"msgId"`
  1135. Date int64 `json:"date" xml:"date"`
  1136. }
  1137. // StoredIMQuery describes filters for fetchStoredIMs.
  1138. type StoredIMQuery struct {
  1139. PartnerAimID string
  1140. StartTime int64
  1141. EndTime int64
  1142. NToGet int
  1143. SortOrder string
  1144. SkipMsgID string
  1145. StopMsgID string
  1146. }
  1147. // GetStoredIMs returns stored messages for a conversation partner, filtered and sorted
  1148. // per the Web AIM client's fetchStoredIMs parameters.
  1149. func (s *Session) GetStoredIMs(q StoredIMQuery) []StoredIM {
  1150. if s == nil || q.PartnerAimID == "" {
  1151. return nil
  1152. }
  1153. s.imLogMu.Lock()
  1154. msgs := append([]WebAPIStoredIM(nil), s.imLog[normalizeWebAPIAimID(q.PartnerAimID)]...)
  1155. s.imLogMu.Unlock()
  1156. if len(msgs) == 0 {
  1157. return []StoredIM{}
  1158. }
  1159. filtered := make([]WebAPIStoredIM, 0, len(msgs))
  1160. for _, msg := range msgs {
  1161. if q.StartTime > 0 && msg.Date < q.StartTime {
  1162. continue
  1163. }
  1164. if q.EndTime > 0 && msg.Date > q.EndTime {
  1165. continue
  1166. }
  1167. filtered = append(filtered, msg)
  1168. }
  1169. descending := strings.EqualFold(q.SortOrder, "descendingDate")
  1170. sort.Slice(filtered, func(i, j int) bool {
  1171. if descending {
  1172. return filtered[i].Date > filtered[j].Date
  1173. }
  1174. return filtered[i].Date < filtered[j].Date
  1175. })
  1176. if q.SkipMsgID != "" {
  1177. for i, msg := range filtered {
  1178. if msg.MsgID == q.SkipMsgID {
  1179. filtered = filtered[i+1:]
  1180. break
  1181. }
  1182. }
  1183. }
  1184. if q.StopMsgID != "" {
  1185. for i, msg := range filtered {
  1186. if msg.MsgID == q.StopMsgID {
  1187. filtered = filtered[:i]
  1188. break
  1189. }
  1190. }
  1191. }
  1192. n := q.NToGet
  1193. if n <= 0 {
  1194. n = 100
  1195. }
  1196. if len(filtered) > n {
  1197. filtered = filtered[:n]
  1198. }
  1199. out := make([]StoredIM, len(filtered))
  1200. for i, msg := range filtered {
  1201. out[i] = StoredIM(msg)
  1202. }
  1203. return out
  1204. }
  1205. func (s *Session) Caps() [][16]byte {
  1206. s.capsMu.RLock()
  1207. defer s.capsMu.RUnlock()
  1208. return slices.Clone(s.capabilities)
  1209. }
  1210. // ClearMood removes the mood capability the session advertises, if any. The
  1211. // user then presents whatever presence state they are in.
  1212. func (s *Session) ClearMood() {
  1213. s.capsMu.Lock()
  1214. defer s.capsMu.Unlock()
  1215. s.clearMood()
  1216. }
  1217. // clearMood drops every mood capability the session advertises. The caller must
  1218. // hold s.capsMu.
  1219. func (s *Session) clearMood() {
  1220. s.capabilities = slices.DeleteFunc(s.capabilities, func(cap [16]byte) bool {
  1221. return wire.IsMoodCap(cap)
  1222. })
  1223. }
  1224. // SetMood replaces the mood capability the session advertises. A client shows
  1225. // one mood at a time, so whichever mood was set before is dropped.
  1226. //
  1227. // It panics when mood is not a mood capability: the caller resolves it from the
  1228. // mood table, so anything else is a programming error rather than bad input.
  1229. func (s *Session) SetMood(mood uuid.UUID) {
  1230. s.capsMu.Lock()
  1231. defer s.capsMu.Unlock()
  1232. if !wire.IsMoodCap(mood) {
  1233. panic("uuid is not a mood capability")
  1234. }
  1235. s.clearMood()
  1236. s.capabilities = append(s.capabilities, mood)
  1237. }
  1238. // normalizeWebAPIAimID keys the IM log by the same normalization the web client
  1239. // applies to aimIds, so a partner stored from a display screen name is still
  1240. // found when the client queries by aimId.
  1241. func normalizeWebAPIAimID(aimID string) string {
  1242. return state.NewIdentScreenName(aimID).String()
  1243. }