4
0

session.go 34 KB

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