session.go 34 KB

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