session.go 27 KB

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