4
0

session.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. package handlers
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/google/uuid"
  13. "github.com/mk6i/open-oscar-server/config"
  14. "github.com/mk6i/open-oscar-server/server/webapi/middleware"
  15. "github.com/mk6i/open-oscar-server/server/webapi/types"
  16. "github.com/mk6i/open-oscar-server/state"
  17. "github.com/mk6i/open-oscar-server/wire"
  18. )
  19. // SessionHandler handles Web AIM API session management endpoints.
  20. type SessionHandler struct {
  21. SessionManager *state.WebAPISessionManager
  22. OSCARAuthService AuthService
  23. FeedbagService FeedbagService
  24. ICBMService ICBMService
  25. BuddyListManager *BuddyListManager
  26. IconSource BuddyIconSource
  27. Logger *slog.Logger
  28. OServiceService OServiceService
  29. // the same SNAC-to-rate-class mapping RateLimitMiddleware enforces against, so
  30. // the class a session alerts on cannot drift from the one it is charged
  31. SNACRateLimits wire.SNACRateLimits
  32. FnSessCfg func(sess *state.Session)
  33. FnSessInit func(instance *state.SessionInstance) func() error
  34. FnInstanceClose func(instance *state.SessionInstance) func()
  35. }
  36. // AuthService defines methods needed for authentication.
  37. type AuthService interface {
  38. BUCPChallenge(ctx context.Context, bodyIn wire.SNAC_0x17_0x06_BUCPChallengeRequest, newUUID func() uuid.UUID) (wire.SNACMessage, error)
  39. BUCPLogin(ctx context.Context, bodyIn wire.SNAC_0x17_0x02_BUCPLoginRequest, endpointCfg config.Endpoint) (wire.SNACMessage, error)
  40. CrackCookie(authCookie []byte) (state.ServerCookie, error)
  41. RegisterBOSSession(ctx context.Context, authCookie state.ServerCookie, conf func(sess *state.Session)) (*state.SessionInstance, error)
  42. FLAPLogin(ctx context.Context, inFrame wire.FLAPSignonFrame, endpointCfg config.Endpoint) (wire.TLVRestBlock, error)
  43. Signout(ctx context.Context, session *state.Session)
  44. SignoutChat(ctx context.Context, sess *state.Session)
  45. }
  46. // SessionManager defines methods for OSCAR session management.
  47. type SessionManager interface {
  48. AddSession(ctx context.Context, screenName state.DisplayScreenName, doMultiSess bool, cfg ...func(sess *state.Session)) (*state.SessionInstance, error)
  49. RemoveSession(session *state.Session)
  50. RelayToScreenName(ctx context.Context, screenName state.IdentScreenName, msg wire.SNACMessage)
  51. }
  52. // BuddyListRegistry defines methods for buddy list management.
  53. type BuddyListRegistry interface {
  54. RegisterBuddyList(ctx context.Context, screenName state.IdentScreenName) error
  55. UnregisterBuddyList(ctx context.Context, screenName state.IdentScreenName) error
  56. }
  57. type ChatSessionManager interface {
  58. RemoveUserFromAllChats(user state.IdentScreenName)
  59. }
  60. // MyInfo is the user's own identity blob, which the Web AIM client renders in
  61. // its identity badge. It is both the startSession payload's myInfo and the
  62. // myInfo event's data.
  63. type MyInfo struct {
  64. AimID string `json:"aimId" xml:"aimId"`
  65. DisplayID string `json:"displayId" xml:"displayId"`
  66. Friendly string `json:"friendly" xml:"friendly"`
  67. State string `json:"state" xml:"state"`
  68. UserType string `json:"userType" xml:"userType"` // "aim", "icq"
  69. Bot bool `json:"bot" xml:"bot"`
  70. Service string `json:"service" xml:"service"` // "AIM", "ICQ" (compared case-sensitively)
  71. // Capabilities is always sent, empty included, because the client iterates it
  72. // unconditionally.
  73. Capabilities []string `json:"capabilities" xml:"capabilities>capability"`
  74. // BuddyIcon is omitted when empty so the client's merge preserves the icon it
  75. // already holds.
  76. BuddyIcon string `json:"buddyIcon,omitempty" xml:"buddyIcon,omitempty"`
  77. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  78. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  79. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  80. MemberSince int64 `json:"memberSince,omitempty" xml:"memberSince,omitempty"`
  81. Self *MyInfoSelf `json:"self,omitempty" xml:"self,omitempty"`
  82. }
  83. // MyInfoSelf carries the session-scoped half of myInfo: the instance the client
  84. // is talking to and the limits it must respect.
  85. type MyInfoSelf struct {
  86. InstNum int `json:"instNum" xml:"instNum"`
  87. LoginTime int64 `json:"loginTime" xml:"loginTime"`
  88. SessionTimeout int `json:"sessionTimeout" xml:"sessionTimeout"`
  89. Events []string `json:"events" xml:"events>event"`
  90. AssertCaps []string `json:"assertCaps" xml:"assertCaps>capability"`
  91. RightsInfo RightsInfo `json:"rightsInfo" xml:"rightsInfo"`
  92. }
  93. // RightsInfo reports the account limits the client enforces client-side.
  94. type RightsInfo struct {
  95. MaxDenies int `json:"maxDenies" xml:"maxDenies"`
  96. MaxPermits int `json:"maxPermits" xml:"maxPermits"`
  97. MaxWatchers int `json:"maxWatchers" xml:"maxWatchers"`
  98. MaxBuddies int `json:"maxBuddies" xml:"maxBuddies"`
  99. MaxTempBuddies int `json:"maxTempBuddies" xml:"maxTempBuddies"`
  100. MaxIMSize int `json:"maxIMSize" xml:"maxIMSize"`
  101. MinInterIcbmInterval int `json:"minInterIcbmInterval" xml:"minInterIcbmInterval"`
  102. MaxSourceEvil int `json:"maxSourceEvil" xml:"maxSourceEvil"`
  103. MaxDstEvil int `json:"maxDstEvil" xml:"maxDstEvil"`
  104. MaxSigLen int `json:"maxSigLen" xml:"maxSigLen"`
  105. }
  106. // WellKnownUrls advertises the API roots to clients that discover them rather
  107. // than deriving them.
  108. type WellKnownUrls struct {
  109. WebApiBase string `json:"webApiBase" xml:"webApiBase"`
  110. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  111. LifestreamApiBase string `json:"lifestreamApiBase" xml:"lifestreamApiBase"`
  112. }
  113. // StartSessionEvents seeds the client with the first value of each event it
  114. // subscribed to, so it renders a populated UI before its first fetchEvents.
  115. // Each field is absent unless the client asked for that event.
  116. type StartSessionEvents struct {
  117. MyInfo *MyInfo `json:"myInfo,omitempty" xml:"myInfo,omitempty"`
  118. BuddyList *BuddyListData `json:"buddylist,omitempty" xml:"buddylist,omitempty"`
  119. Preference *PreferenceData `json:"preference,omitempty" xml:"preference,omitempty"`
  120. PermitDeny interface{} `json:"permitDeny,omitempty" xml:"permitDeny,omitempty"`
  121. }
  122. // BuddyListData is the buddylist event payload and the buddy list half of the
  123. // startSession seed.
  124. type BuddyListData struct {
  125. Groups []WebAPIBuddyGroup `json:"groups" xml:"groups>group"`
  126. }
  127. // StartSessionData is the startSession payload.
  128. type StartSessionData struct {
  129. AimSID string `json:"aimsid" xml:"aimsid"`
  130. Ts int64 `json:"ts" xml:"ts"`
  131. FetchTimeout int `json:"fetchTimeout" xml:"fetchTimeout"`
  132. TimeToNextFetch int `json:"timeToNextFetch" xml:"timeToNextFetch"`
  133. // FetchBaseURL sits directly in data, not in wellKnownUrls: it is where the
  134. // client reads its poll URL from.
  135. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  136. MyInfo *MyInfo `json:"myInfo,omitempty" xml:"myInfo,omitempty"`
  137. Events *StartSessionEvents `json:"events,omitempty" xml:"events,omitempty"`
  138. WellKnownUrls *WellKnownUrls `json:"wellKnownUrls,omitempty" xml:"wellKnownUrls,omitempty"`
  139. }
  140. // StartSession handles GET /aim/startSession requests.
  141. func (h *SessionHandler) StartSession(w http.ResponseWriter, r *http.Request) {
  142. ctx := r.Context()
  143. // Get API key info from context (set by auth middleware)
  144. apiKey, ok := ctx.Value(middleware.ContextKeyAPIKey).(*state.WebAPIKey)
  145. if !ok {
  146. h.sendError(w, r, http.StatusInternalServerError, "internal server error")
  147. return
  148. }
  149. // Parse parameters
  150. params := r.URL.Query()
  151. // Get authentication token if provided
  152. authToken := params.Get("a")
  153. // Get client info
  154. clientName := params.Get("clientName")
  155. if clientName == "" {
  156. clientName = "WebAIM"
  157. }
  158. clientVersion := params.Get("clientVersion")
  159. if clientVersion == "" {
  160. clientVersion = "1.0"
  161. }
  162. // Get events to subscribe to
  163. eventsParam := params.Get("events")
  164. var events []string
  165. if eventsParam != "" {
  166. events = strings.Split(eventsParam, ",")
  167. h.Logger.DebugContext(ctx, "parsing events from request",
  168. "eventsParam", eventsParam,
  169. "parsedEvents", events,
  170. )
  171. } else {
  172. // Default events if none specified
  173. events = []string{"buddylist", "presence", "im", "sentIM"}
  174. h.Logger.DebugContext(ctx, "using default events",
  175. "events", events,
  176. )
  177. }
  178. // Get timeout settings
  179. timeout := 60000 // Default 60 seconds for better stability with Gromit
  180. if t := params.Get("timeout"); t != "" {
  181. if val, err := strconv.Atoi(t); err == nil && val > 0 {
  182. timeout = val * 1000 // Convert to milliseconds
  183. }
  184. }
  185. // A Web API session must be bridged to an authenticated OSCAR session;
  186. // anonymous guests are not supported.
  187. if authToken == "" {
  188. h.sendError(w, r, http.StatusUnauthorized, "authentication token required")
  189. return
  190. }
  191. rawCookie, err := base64.URLEncoding.DecodeString(strings.TrimSpace(authToken))
  192. if err != nil {
  193. h.Logger.Warn("invalid authentication token (base64)", "error", err)
  194. h.sendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  195. return
  196. }
  197. cookie, err := h.OSCARAuthService.CrackCookie(rawCookie)
  198. if err != nil {
  199. h.Logger.Warn("invalid authentication token", "error", err)
  200. h.sendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  201. return
  202. }
  203. screenName := cookie.ScreenName
  204. tokenPreview := authToken
  205. if len(tokenPreview) > 8 {
  206. tokenPreview = tokenPreview[:8] + "..."
  207. }
  208. h.Logger.Info("authenticated session requested",
  209. "token", tokenPreview,
  210. "screenName", screenName)
  211. var instance *state.SessionInstance
  212. // Create OSCAR session
  213. instance, err = h.OSCARAuthService.RegisterBOSSession(ctx, cookie, h.FnSessCfg)
  214. if err != nil {
  215. h.Logger.ErrorContext(ctx, "failed to create OSCAR session", "err", err.Error())
  216. h.sendError(w, r, http.StatusServiceUnavailable, "unable to establish session")
  217. return
  218. }
  219. if err = instance.Session().RunOnce(h.FnSessInit(instance)); err != nil {
  220. h.Logger.ErrorContext(context.Background(), "failed to init session", "err", err.Error())
  221. // RunOnce has already closed the whole session; this is belt-and-braces,
  222. // since CloseInstance is idempotent and nothing else owns the instance yet.
  223. instance.CloseInstance()
  224. h.sendError(w, r, http.StatusInternalServerError, "internal server error")
  225. return
  226. }
  227. instance.OnClose(h.FnInstanceClose(instance))
  228. if err := h.FeedbagService.Use(ctx, instance); err != nil {
  229. h.Logger.ErrorContext(ctx, "failed to use feedbag", "err", err.Error())
  230. }
  231. // A web client signals that it wants typing events through its event
  232. // subscription, not through a stored feedbag buddy pref. Reflect that
  233. // on the OSCAR session so ICBMService attaches the WantEvents TLV to
  234. // outgoing IMs, prompting recipients to send typing notifications
  235. // back. This must run after FeedbagService.Use, which otherwise
  236. // overwrites the flag from stored prefs the web user may not have set.
  237. instance.Session().SetTypingEventsEnabled(slices.Contains(events, "typing"))
  238. instance.SetSignonComplete()
  239. if err := h.OServiceService.ClientOnline(ctx, wire.BOS, wire.SNAC_0x01_0x02_OServiceClientOnline{}, instance); err != nil {
  240. h.Logger.ErrorContext(ctx, "failed to set client online", "err", err.Error())
  241. instance.CloseInstance()
  242. h.sendError(w, r, http.StatusInternalServerError, "internal server error")
  243. return
  244. }
  245. // The rate class sending an IM spends. Only its updates surface to the client's
  246. // conversation-window alert, which renders any rateLimit event as the IM
  247. // banner. A miss yields zero, which disables the alert rather than indexing a
  248. // rate class that isn't there.
  249. imRateClassID, ok := h.SNACRateLimits.RateClassLookup(wire.ICBM, wire.ICBMChannelMsgToHost)
  250. if !ok {
  251. h.Logger.ErrorContext(ctx, "no rate class maps to sending an IM, rate limit events are disabled")
  252. }
  253. // Subscribe the same way an OSCAR client does at handshake, so the per-account
  254. // monitor broadcasts this class's transitions to this session.
  255. if imRateClassID != 0 {
  256. h.OServiceService.RateParamsSubAdd(ctx, instance, wire.SNAC_0x01_0x08_OServiceRateParamsSubAdd{
  257. ClassIDs: []uint16{uint16(imRateClassID)},
  258. })
  259. }
  260. // Create WebAPI session
  261. // Record the origin the client reached us on. Asset URLs published to the
  262. // client (buddy icons) must be absolute, since the client page is served from
  263. // a different origin than this API, and they are built in places that have no
  264. // request in hand. Pinning the origin here also keeps those URLs on the same
  265. // host as the wellKnownUrls advertised below. It is passed into CreateSession
  266. // so it is set before the session is published and its listener goroutine can
  267. // read it.
  268. baseURL := baseURLFromRequest(r)
  269. session, err := h.SessionManager.CreateSession(screenName, apiKey.DevID, events, instance, baseURL, h.Logger)
  270. if err != nil {
  271. h.Logger.ErrorContext(ctx, "failed to create session", "err", err.Error())
  272. // CreateSession refuses once the manager is shut down, so this is the
  273. // path a startSession racing shutdown takes. The WebAPISession that
  274. // would have owned the instance was never created.
  275. instance.CloseInstance()
  276. h.sendError(w, r, http.StatusInternalServerError, "failed to create session")
  277. return
  278. }
  279. h.Logger.DebugContext(ctx, "session created with event subscriptions",
  280. "aimsid", session.AimSID,
  281. "events", events,
  282. )
  283. // Wire buddy list refresher so feedbag SNACs from the OSCAR bridge trigger a buddylist event.
  284. // The refresher yields the whole buddylist event payload, not just the groups,
  285. // so the session that pushes it does not have to know the payload's shape.
  286. session.BuddyListRefresher = func(ctx context.Context) (interface{}, error) {
  287. groups, err := h.BuddyListManager.GetBuddyListForUser(ctx, session)
  288. if err != nil {
  289. return nil, err
  290. }
  291. return &BuddyListData{Groups: groups}, nil
  292. }
  293. // Wire the alias loader so OSCAR-driven im/presence events can repeat the
  294. // buddy's friendly name. The client discards the alias it holds each time it
  295. // merges a user map, so an event that omits it renames the buddy. The session
  296. // caches what this returns until a feedbag change invalidates it.
  297. session.BuddyAliasLoader = func(ctx context.Context) (map[string]string, error) {
  298. return LookupBuddyAliases(ctx, h.FeedbagService, session.OSCARSession)
  299. }
  300. // Wire the buddy-icon URL formatter so presence broadcasts (BuddyArrived) can
  301. // publish a buddy's current icon from the hash carried in the SNAC, no lookup.
  302. session.BuddyIconURL = func(sn state.IdentScreenName, hash []byte) string {
  303. return h.IconSource.URLForHash(session.BaseURL, sn, hash)
  304. }
  305. // Wire the myInfo refresher so a self user-info update (icon upload/clear)
  306. // re-renders the identity badge. currentWebState reflects the user's live
  307. // presence; PublishedURL reflects the feedbag icon, already updated by the time
  308. // the OServiceUserInfoUpdate is relayed.
  309. session.MyInfoRefresher = func(ctx context.Context) (interface{}, error) {
  310. icon := h.IconSource.PublishedURL(ctx, session.BaseURL, screenName.IdentScreenName())
  311. return buildMyInfo(screenName, currentWebState(session.OSCARSession), icon), nil
  312. }
  313. // Wire permit/deny refresher so FeedbagUpdateItem SNACs trigger a permitDeny event.
  314. session.PermitDenyRefresher = func(ctx context.Context) (interface{}, error) {
  315. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  316. fb, err := h.FeedbagService.Query(ctx, session.OSCARSession, frame)
  317. if err != nil {
  318. return nil, err
  319. }
  320. reply, ok := fb.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  321. if !ok {
  322. return nil, fmt.Errorf("unexpected feedbag reply type")
  323. }
  324. return permitDenyData(reply.Items), nil
  325. }
  326. // Only IM-class rate limit updates should surface to the client alert.
  327. session.IMRateClassID = imRateClassID
  328. seedRateLimitAlert(session, imRateClassID)
  329. // Now that every refresher callback is wired, start the OSCAR listener. Doing
  330. // this inside CreateSession would race these assignments, since the goroutine
  331. // reads the callbacks as it converts SNACs into events.
  332. session.StartListeningToOSCARSession()
  333. // Store client info
  334. session.ClientName = clientName
  335. session.ClientVersion = clientVersion
  336. session.FetchTimeout = timeout
  337. session.RemoteAddr = r.RemoteAddr
  338. // The identity badge renders the user's own icon from myInfo, which is the
  339. // only event it binds its self-presence render to. PublishedURL always yields
  340. // a URL (the blank placeholder when the user has no icon) so that clearing the
  341. // icon propagates to the badge.
  342. myIconURL := h.IconSource.PublishedURL(ctx, baseURL, screenName.IdentScreenName())
  343. now := time.Now().Unix()
  344. // Prepare response
  345. data := &StartSessionData{
  346. AimSID: session.AimSID,
  347. Ts: now,
  348. FetchTimeout: session.FetchTimeout,
  349. TimeToNextFetch: session.TimeToNextFetch,
  350. // Gromit expects fetchBaseURL directly in data, not in wellKnownUrls
  351. FetchBaseURL: fmt.Sprintf("%s/aim/fetchEvents?aimsid=%s&seqNum=0", baseURL, session.AimSID),
  352. // Add wellKnownUrls for other clients that might use it.
  353. WellKnownUrls: &WellKnownUrls{
  354. WebApiBase: baseURL + "/",
  355. FetchBaseURL: baseURL + "/aim/fetchEvents",
  356. // The client appends the bare method name to this base, so it has to
  357. // carry the /lifestream/ path the routes are registered under.
  358. LifestreamApiBase: baseURL + "/lifestream/",
  359. },
  360. Events: &StartSessionEvents{},
  361. }
  362. myInfoPayload := buildMyInfo(screenName, "online", myIconURL)
  363. myInfoPayload.OnlineTime = time.Now().Unix()
  364. myInfoPayload.MemberSince = time.Now().Unix() - 86400*30 // 30 days ago
  365. myInfoPayload.Self = &MyInfoSelf{
  366. InstNum: 1,
  367. LoginTime: time.Now().Unix(),
  368. SessionTimeout: 30,
  369. Events: events,
  370. AssertCaps: []string{},
  371. RightsInfo: RightsInfo{
  372. MaxDenies: 500,
  373. MaxPermits: 500,
  374. MaxWatchers: 3000,
  375. MaxBuddies: 500,
  376. MaxTempBuddies: 160,
  377. MaxIMSize: 3987,
  378. MinInterIcbmInterval: 1000,
  379. MaxSourceEvil: 900,
  380. MaxDstEvil: 999,
  381. MaxSigLen: 4096,
  382. },
  383. }
  384. data.MyInfo = myInfoPayload
  385. data.Events.MyInfo = myInfoPayload
  386. // Seeds that only queue an event are keyed off the subscription rather than
  387. // iterated with it, so the server fixes their order and each is queued once.
  388. // myInfo and presence render the identity badge from the same payload and the
  389. // client subscribes to both, which a per-subscription loop would queue twice.
  390. if slices.Contains(events, "myInfo") || slices.Contains(events, "presence") {
  391. myInfoData := buildMyInfo(screenName, "online", myIconURL)
  392. myInfoData.OnlineTime = time.Now().Unix()
  393. myInfoData.MemberSince = time.Now().Unix() - 86400*30 // 30 days ago
  394. session.EventQueue.Push(types.EventTypeMyInfo, myInfoData)
  395. }
  396. if slices.Contains(events, "conversation") {
  397. session.EventQueue.Push(types.EventTypeConversation,
  398. types.ConversationEventData("list", nil))
  399. }
  400. // The remaining seeds also populate the response payload, so they stay keyed off
  401. // the subscription list they are rendered into.
  402. for _, event := range events {
  403. switch types.EventType(event) {
  404. case types.EventTypeBuddyList:
  405. buddyGroups := []WebAPIBuddyGroup{}
  406. if h.BuddyListManager != nil {
  407. var err error
  408. buddyGroups, err = h.BuddyListManager.GetBuddyListForUser(ctx, session)
  409. if err != nil {
  410. h.Logger.ErrorContext(ctx, "failed to get buddy list", "err", err.Error())
  411. buddyGroups = []WebAPIBuddyGroup{}
  412. }
  413. }
  414. if buddyGroups == nil {
  415. buddyGroups = []WebAPIBuddyGroup{}
  416. }
  417. blPayload := &BuddyListData{Groups: buddyGroups}
  418. data.Events.BuddyList = blPayload
  419. session.EventQueue.Push(types.EventTypeBuddyList, blPayload)
  420. case types.EventTypePreference:
  421. // Seed the client with effective preference values: the user's stored
  422. // prefs where set, and the server-side spec defaults otherwise. The
  423. // client reads its buddy-list display prefs (e.g. showGroups) only from
  424. // this event and has no default of its own for them, so an omitted pref
  425. // would silently fall back to the client's hidden default and, for
  426. // showGroups, hide group headers.
  427. prefPayload := &PreferenceData{}
  428. if item, err := buddyPrefsItem(ctx, h.FeedbagService, session.OSCARSession); err != nil {
  429. h.Logger.ErrorContext(ctx, "failed to get preferences", "err", err.Error())
  430. } else {
  431. prefPayload = effectiveBuddyPrefs(item.TLVList)
  432. }
  433. data.Events.Preference = prefPayload
  434. session.EventQueue.Push(types.EventTypePreference, prefPayload)
  435. case types.EventTypePermitDeny:
  436. // The client keeps its privacy state solely in the model this event
  437. // populates. Both the block/unblock menu action and the "blocked"
  438. // presence state read that model and no-op silently while it is
  439. // empty, so the session has to start with one.
  440. var pdPayload interface{} = PermitDenyData{PDMode: "permitAll"}
  441. if pdd, err := session.PermitDenyRefresher(ctx); err != nil {
  442. h.Logger.ErrorContext(ctx, "failed to get permit/deny settings", "err", err.Error())
  443. } else {
  444. pdPayload = pdd
  445. }
  446. data.Events.PermitDeny = pdPayload
  447. session.EventQueue.Push(types.EventTypePermitDeny, pdPayload)
  448. }
  449. }
  450. // Drain messages stored while the user was signed off. The service relays them
  451. // as ordinary ICBMChannelMsgToClient SNACs stamped with a send time, which the
  452. // listener started above turns into offlineIM events. Retrieval deletes them
  453. // from the store and the Web API has no ack, so this is the one delivery attempt.
  454. // Skip it for a client that did not subscribe, which leaves the messages stored
  455. // for a session that wants them rather than spending them on one that does not.
  456. //
  457. // This trails every event queued above because the listener pushes from its own
  458. // goroutine, so anything drained here can overtake a later push. An offlineIM
  459. // names its sender by bare aimId and leaves the client to resolve the display
  460. // name against the buddy list it holds, and the conversation list is rebuilt from
  461. // scratch on the first "list" the client sees. Both of those events are queued in
  462. // the loop above, so the drain has to come after it.
  463. if slices.Contains(events, "offlineIM") {
  464. frame := wire.SNACFrame{
  465. FoodGroup: wire.ICBM,
  466. SubGroup: wire.ICBMOfflineRetrieve,
  467. RequestID: wire.ReqIDFromServer,
  468. }
  469. if _, err := h.ICBMService.OfflineRetrieve(ctx, instance, frame); err != nil {
  470. h.Logger.ErrorContext(ctx, "failed to retrieve offline messages", "err", err.Error())
  471. }
  472. }
  473. resp := BaseResponse{}
  474. resp.Response.StatusCode = 200
  475. resp.Response.StatusText = "OK"
  476. resp.Response.Data = data
  477. // Send response in requested format (JSON, JSONP, XML, or AMF)
  478. SendResponse(w, r, resp, h.Logger)
  479. h.Logger.DebugContext(ctx, "session started",
  480. "aimsid", session.AimSID,
  481. "screen_name", screenName,
  482. "dev_id", apiKey.DevID,
  483. "events", events,
  484. "format", r.URL.Query().Get("f"),
  485. )
  486. }
  487. // EndSession handles GET /aim/endSession requests.
  488. func (h *SessionHandler) EndSession(w http.ResponseWriter, r *http.Request, session *state.WebAPISession) {
  489. ctx := r.Context()
  490. // RemoveSession evicts the session from the manager and tears it down
  491. // (closes the event queue and the OSCAR instance). Without this the aimsid
  492. // stays resolvable until the reaper sweeps it, and RequireSession would keep
  493. // handing handlers a session whose OSCAR instance is already closed.
  494. if err := h.SessionManager.RemoveSession(ctx, session.AimSID); err != nil {
  495. h.Logger.ErrorContext(ctx, "failed to remove session", "err", err.Error())
  496. }
  497. // Send response
  498. resp := BaseResponse{}
  499. resp.Response.StatusCode = 200
  500. resp.Response.StatusText = "OK"
  501. // Send response in requested format (JSON, JSONP, or AMF)
  502. SendResponse(w, r, resp, h.Logger)
  503. h.Logger.DebugContext(ctx, "session ended",
  504. "aimsid", session.AimSID,
  505. "screen_name", session.ScreenName,
  506. )
  507. }
  508. // sendError sends a Web AIM API error envelope, honoring JSONP when requested.
  509. func (h *SessionHandler) sendError(w http.ResponseWriter, r *http.Request, statusCode int, message string) {
  510. resp := BaseResponse{}
  511. resp.Response.StatusCode = statusCode
  512. resp.Response.StatusText = message
  513. SendResponse(w, r, resp, h.Logger)
  514. }
  515. // buildMyInfo assembles the shared base of a myInfo payload — the user's own
  516. // identity blob that the AIM client renders in its identity badge.
  517. //
  518. // It carries only fields that are safe to repeat on every myInfo: the client's
  519. // user-object merge deletes friendly and capabilities before merging, so both
  520. // must be present on each push or the badge loses them. Time-sensitive fields
  521. // (onlineTime, memberSince) are intentionally excluded — a mid-session refresh
  522. // omits them so the client keeps the signon time it already has; the startSession
  523. // builders add them explicitly. buddyIcon is included only when non-empty; an
  524. // empty value would be dropped by the client merge anyway, and the placeholder
  525. // URL (not "") is what clears an icon.
  526. func buildMyInfo(screenName state.DisplayScreenName, webState, buddyIcon string) *MyInfo {
  527. // The web client compares userType/service case-sensitively; a UIN account must
  528. // report ICQ so it renders as an ICQ contact rather than AIM.
  529. userType, service := "aim", "AIM"
  530. if screenName.IsUIN() {
  531. userType, service = "icq", "ICQ"
  532. }
  533. return &MyInfo{
  534. AimID: screenName.IdentScreenName().String(),
  535. DisplayID: screenName.String(),
  536. Friendly: screenName.String(),
  537. State: webState,
  538. UserType: userType,
  539. // Never nil: the client iterates capabilities unconditionally.
  540. Capabilities: []string{},
  541. Bot: false,
  542. Service: service,
  543. BuddyIcon: buddyIcon,
  544. }
  545. }
  546. func requestScheme(r *http.Request) string {
  547. if r.TLS != nil {
  548. return "https"
  549. }
  550. if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  551. return proto
  552. }
  553. return "http"
  554. }
  555. // baseURLFromRequest returns the absolute base URL the client reached this
  556. // server on, used to build asset URLs that the client loads directly.
  557. func baseURLFromRequest(r *http.Request) string {
  558. return fmt.Sprintf("%s://%s", requestScheme(r), r.Host)
  559. }