session.go 44 KB

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