aim_handler.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/xml"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "net"
  10. "net/http"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/mk6i/open-oscar-server/config"
  16. "github.com/mk6i/open-oscar-server/state"
  17. "github.com/mk6i/open-oscar-server/wire"
  18. )
  19. // AimHandler serves the /aim/* Web AIM API endpoints.
  20. type AimHandler struct {
  21. SessionManager *SessionManager
  22. AuthService AuthService
  23. FeedbagService FeedbagService
  24. ICBMService ICBMService
  25. LocateService LocateService
  26. OServiceService OServiceService
  27. BuddyListManager *BuddyListManager
  28. BuddyService BuddyService
  29. IconSource BuddyIconSource
  30. // BOSListener is the listener group startOSCARSession advertises a BOS
  31. // address from.
  32. BOSListener config.ListenerGroup
  33. // SNACRateLimits is the same SNAC-to-rate-class mapping RateLimitMiddleware
  34. // enforces against, so the class a session alerts on cannot drift from the
  35. // one it is charged.
  36. SNACRateLimits wire.SNACRateLimits
  37. Logger *slog.Logger
  38. FnSessCfg func(sess *state.Session)
  39. FnSessInit func(instance *state.SessionInstance) func() error
  40. FnInstanceClose func(instance *state.SessionInstance) func()
  41. }
  42. // MyInfo is the user's own identity blob, which the Web AIM client renders in
  43. // its identity badge. It is both the startSession payload's myInfo and the
  44. // myInfo event's data.
  45. type MyInfo struct {
  46. AimID string `json:"aimId" xml:"aimId"`
  47. DisplayID string `json:"displayId" xml:"displayId"`
  48. Friendly string `json:"friendly" xml:"friendly"`
  49. State string `json:"state" xml:"state"`
  50. UserType string `json:"userType" xml:"userType"` // "aim", "icq"
  51. Bot bool `json:"bot" xml:"bot"`
  52. Service string `json:"service,omitempty" xml:"service,omitempty"` // Non-native network; omitted for AIM
  53. // Capabilities is always sent, empty included, because the client iterates it
  54. // unconditionally.
  55. Capabilities []string `json:"capabilities" xml:"capabilities>capability"`
  56. // BuddyIcon is omitted when empty so the client's merge preserves the icon it
  57. // already holds.
  58. BuddyIcon string `json:"buddyIcon,omitempty" xml:"buddyIcon,omitempty"`
  59. MoodIcon string `json:"moodIcon,omitempty" xml:"moodIcon,omitempty"`
  60. MoodTitle string `json:"moodTitle,omitempty" xml:"moodTitle,omitempty"`
  61. AwayMsg string `json:"awayMsg,omitempty" xml:"awayMsg,omitempty"`
  62. StatusMsg string `json:"statusMsg,omitempty" xml:"statusMsg,omitempty"`
  63. OnlineTime int64 `json:"onlineTime,omitempty" xml:"onlineTime,omitempty"`
  64. MemberSince int64 `json:"memberSince,omitempty" xml:"memberSince,omitempty"`
  65. Self *MyInfoSelf `json:"self,omitempty" xml:"self,omitempty"`
  66. }
  67. // MyInfoSelf carries the session-scoped half of myInfo: the instance the client
  68. // is talking to and the limits it must respect.
  69. type MyInfoSelf struct {
  70. InstNum int `json:"instNum" xml:"instNum"`
  71. LoginTime int64 `json:"loginTime" xml:"loginTime"`
  72. SessionTimeout int `json:"sessionTimeout" xml:"sessionTimeout"`
  73. Events []string `json:"events" xml:"events>event"`
  74. AssertCaps []string `json:"assertCaps" xml:"assertCaps>capability"`
  75. RightsInfo RightsInfo `json:"rightsInfo" xml:"rightsInfo"`
  76. }
  77. // RightsInfo reports the account limits the client enforces client-side.
  78. type RightsInfo struct {
  79. MaxDenies int `json:"maxDenies" xml:"maxDenies"`
  80. MaxPermits int `json:"maxPermits" xml:"maxPermits"`
  81. MaxWatchers int `json:"maxWatchers" xml:"maxWatchers"`
  82. MaxBuddies int `json:"maxBuddies" xml:"maxBuddies"`
  83. MaxTempBuddies int `json:"maxTempBuddies" xml:"maxTempBuddies"`
  84. MaxIMSize int `json:"maxIMSize" xml:"maxIMSize"`
  85. MinInterIcbmInterval int `json:"minInterIcbmInterval" xml:"minInterIcbmInterval"`
  86. MaxSourceEvil int `json:"maxSourceEvil" xml:"maxSourceEvil"`
  87. MaxDstEvil int `json:"maxDstEvil" xml:"maxDstEvil"`
  88. MaxSigLen int `json:"maxSigLen" xml:"maxSigLen"`
  89. }
  90. // WellKnownUrls advertises the API roots to clients that discover them rather
  91. // than deriving them.
  92. type WellKnownUrls struct {
  93. WebApiBase string `json:"webApiBase" xml:"webApiBase"`
  94. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  95. LifestreamApiBase string `json:"lifestreamApiBase" xml:"lifestreamApiBase"`
  96. }
  97. // StartSessionEvents seeds the client with the first value of each event it
  98. // subscribed to, so it renders a populated UI before its first fetchEvents.
  99. // Each field is absent unless the client asked for that event.
  100. type StartSessionEvents struct {
  101. MyInfo *MyInfo `json:"myInfo,omitempty" xml:"myInfo,omitempty"`
  102. BuddyList *BuddyListData `json:"buddylist,omitempty" xml:"buddylist,omitempty"`
  103. Preference *PreferenceData `json:"preference,omitempty" xml:"preference,omitempty"`
  104. PermitDeny any `json:"permitDeny,omitempty" xml:"permitDeny,omitempty"`
  105. Service *ServiceData `json:"service,omitempty" xml:"service,omitempty"`
  106. }
  107. // BuddyListData is the buddylist event payload and the buddy list half of the
  108. // startSession seed.
  109. type BuddyListData struct {
  110. Groups []BuddyGroup `json:"groups" xml:"groups>group"`
  111. }
  112. // StartSessionData is the startSession payload.
  113. type StartSessionData struct {
  114. AimSID string `json:"aimsid" xml:"aimsid"`
  115. Ts int64 `json:"ts" xml:"ts"`
  116. FetchTimeout int `json:"fetchTimeout" xml:"fetchTimeout"`
  117. TimeToNextFetch int `json:"timeToNextFetch" xml:"timeToNextFetch"`
  118. // FetchBaseURL sits directly in data, not in wellKnownUrls: it is where the
  119. // client reads its poll URL from.
  120. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  121. MyInfo *MyInfo `json:"myInfo,omitempty" xml:"myInfo,omitempty"`
  122. Events *StartSessionEvents `json:"events,omitempty" xml:"events,omitempty"`
  123. WellKnownUrls *WellKnownUrls `json:"wellKnownUrls,omitempty" xml:"wellKnownUrls,omitempty"`
  124. }
  125. // StartSession handles GET|POST /aim/startSession requests.
  126. func (h *AimHandler) StartSession(w http.ResponseWriter, r *http.Request) {
  127. ctx := r.Context()
  128. authToken := param(r, "a")
  129. // Get client info
  130. clientName := param(r, "clientName")
  131. if clientName == "" {
  132. clientName = "WebAIM"
  133. }
  134. clientVersion := param(r, "clientVersion")
  135. if clientVersion == "" {
  136. clientVersion = "1.0"
  137. }
  138. // Get events to subscribe to
  139. eventsParam := param(r, "events")
  140. var events []string
  141. if eventsParam != "" {
  142. events = strings.Split(eventsParam, ",")
  143. h.Logger.DebugContext(ctx, "parsing events from request",
  144. "eventsParam", eventsParam,
  145. "parsedEvents", events,
  146. )
  147. } else {
  148. // Default events if none specified
  149. events = []string{"buddylist", "presence", "im", "sentIM"}
  150. h.Logger.DebugContext(ctx, "using default events",
  151. "events", events,
  152. )
  153. }
  154. // Get timeout settings
  155. timeout := 60000 // Default 60 seconds for better stability with Gromit
  156. if t := param(r, "timeout"); t != "" {
  157. if val, err := strconv.Atoi(t); err == nil && val > 0 {
  158. timeout = val * 1000 // Convert to milliseconds
  159. }
  160. }
  161. // A Web API session must be bridged to an authenticated OSCAR session;
  162. // anonymous guests are not supported.
  163. if authToken == "" {
  164. SendEnvelopeStatus(w, r, http.StatusUnauthorized, "authentication token required", h.Logger)
  165. return
  166. }
  167. rawCookie, err := base64.URLEncoding.DecodeString(strings.TrimSpace(authToken))
  168. if err != nil {
  169. h.Logger.Warn("invalid authentication token (base64)", "error", err)
  170. SendEnvelopeStatus(w, r, http.StatusUnauthorized, "invalid or expired token", h.Logger)
  171. return
  172. }
  173. cookie, _, err := h.AuthService.CrackCookie(rawCookie)
  174. if err != nil {
  175. h.Logger.Warn("invalid authentication token", "error", err)
  176. SendEnvelopeStatus(w, r, http.StatusUnauthorized, "invalid or expired token", h.Logger)
  177. return
  178. }
  179. screenName := cookie.ScreenName
  180. tokenPreview := authToken
  181. if len(tokenPreview) > 8 {
  182. tokenPreview = tokenPreview[:8] + "..."
  183. }
  184. h.Logger.Info("authenticated session requested",
  185. "token", tokenPreview,
  186. "screenName", screenName)
  187. var instance *state.SessionInstance
  188. // Create OSCAR session
  189. instance, err = h.AuthService.RegisterBOSSession(ctx, cookie, h.FnSessCfg)
  190. if err != nil {
  191. h.Logger.ErrorContext(ctx, "failed to create OSCAR session", "err", err.Error())
  192. SendEnvelopeStatus(w, r, http.StatusServiceUnavailable, "unable to establish session", h.Logger)
  193. return
  194. }
  195. if err = instance.Session().RunOnce(h.FnSessInit(instance)); err != nil {
  196. h.Logger.ErrorContext(context.Background(), "failed to init session", "err", err.Error())
  197. // RunOnce has already closed the whole session; this is belt-and-braces,
  198. // since CloseInstance is idempotent and nothing else owns the instance yet.
  199. instance.CloseInstance()
  200. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "internal server error", h.Logger)
  201. return
  202. }
  203. instance.OnClose(h.FnInstanceClose(instance))
  204. if err := h.FeedbagService.Use(ctx, instance); err != nil {
  205. h.Logger.ErrorContext(ctx, "failed to use feedbag", "err", err.Error())
  206. }
  207. // A web client signals that it wants typing events through its event
  208. // subscription, not through a stored feedbag buddy pref. Reflect that
  209. // on the OSCAR session so ICBMService attaches the WantEvents TLV to
  210. // outgoing IMs, prompting recipients to send typing notifications
  211. // back. This must run after FeedbagService.Use, which otherwise
  212. // overwrites the flag from stored prefs the web user may not have set.
  213. instance.Session().SetTypingEventsEnabled(slices.Contains(events, "typing"))
  214. instance.SetSignonComplete()
  215. setInfo := wire.SNAC_0x02_0x04_LocateSetInfo{
  216. TLVRestBlock: wire.TLVRestBlock{
  217. TLVList: wire.TLVList{
  218. wire.NewTLVBE(wire.LocateTLVTagsInfoCapabilities, webAPICaps),
  219. },
  220. },
  221. }
  222. if err := h.LocateService.SetInfo(ctx, instance, setInfo); err != nil {
  223. h.Logger.ErrorContext(ctx, "failed to set capabilities", "err", err.Error())
  224. instance.CloseInstance()
  225. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "internal server error", h.Logger)
  226. return
  227. }
  228. if err := h.OServiceService.ClientOnline(ctx, wire.BOS, wire.SNAC_0x01_0x02_OServiceClientOnline{}, instance); err != nil {
  229. h.Logger.ErrorContext(ctx, "failed to set client online", "err", err.Error())
  230. instance.CloseInstance()
  231. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "internal server error", h.Logger)
  232. return
  233. }
  234. // The rate class sending an IM spends. Only its updates surface to the client's
  235. // conversation-window alert, which renders any rateLimit event as the IM
  236. // banner. A miss yields zero, which disables the alert rather than indexing a
  237. // rate class that isn't there.
  238. imRateClassID, ok := h.SNACRateLimits.RateClassLookup(wire.ICBM, wire.ICBMChannelMsgToHost)
  239. if !ok {
  240. h.Logger.ErrorContext(ctx, "no rate class maps to sending an IM, rate limit events are disabled")
  241. }
  242. // Subscribe the same way an OSCAR client does at handshake, so the per-account
  243. // monitor broadcasts this class's transitions to this session.
  244. if imRateClassID != 0 {
  245. h.OServiceService.RateParamsSubAdd(ctx, instance, wire.SNAC_0x01_0x08_OServiceRateParamsSubAdd{
  246. ClassIDs: []uint16{uint16(imRateClassID)},
  247. })
  248. }
  249. // Create WebAPI session
  250. // Record the origin the client reached us on. Asset URLs published to the
  251. // client (buddy icons) must be absolute, since the client page is served from
  252. // a different origin than this API, and they are built in places that have no
  253. // request in hand. Pinning the origin here also keeps those URLs on the same
  254. // host as the wellKnownUrls advertised below. It is passed into CreateSession
  255. // so it is set before the session is published and its listener goroutine can
  256. // read it.
  257. baseURL := baseURLFromRequest(r)
  258. session, err := h.SessionManager.CreateSession(screenName, events, instance, baseURL, h.Logger)
  259. if err != nil {
  260. h.Logger.ErrorContext(ctx, "failed to create session", "err", err.Error())
  261. // CreateSession refuses once the manager is shut down, so this is the
  262. // path a startSession racing shutdown takes. The WebAPISession that
  263. // would have owned the instance was never created.
  264. instance.CloseInstance()
  265. SendEnvelopeStatus(w, r, http.StatusInternalServerError, "failed to create session", h.Logger)
  266. return
  267. }
  268. h.Logger.DebugContext(ctx, "session created with event subscriptions",
  269. "aimsid", session.AimSID,
  270. "events", events,
  271. )
  272. // Wire buddy list refresher so feedbag SNACs from the OSCAR bridge trigger a buddylist event.
  273. // The refresher yields the whole buddylist event payload, not just the groups,
  274. // so the session that pushes it does not have to know the payload's shape.
  275. session.BuddyListRefresher = func(ctx context.Context) (any, error) {
  276. groups, err := h.BuddyListManager.GetBuddyListForUser(ctx, session)
  277. if err != nil {
  278. return nil, err
  279. }
  280. return &BuddyListData{Groups: groups}, nil
  281. }
  282. // Wire the feedbag loader. The session caches what it returns until a feedbag
  283. // change invalidates it, and derives every read-only view of the roster from it.
  284. session.FeedbagLoader = func(ctx context.Context) ([]wire.FeedbagItem, error) {
  285. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagQuery}
  286. snac, err := h.FeedbagService.Query(ctx, session.OSCARSession, frame)
  287. if err != nil {
  288. return nil, err
  289. }
  290. reply, ok := snac.Body.(wire.SNAC_0x13_0x06_FeedbagReply)
  291. if !ok {
  292. return nil, fmt.Errorf("unexpected feedbag reply type")
  293. }
  294. return reply.Items, nil
  295. }
  296. // Wire the buddy-icon URL formatter so presence broadcasts (BuddyArrived) can
  297. // publish a buddy's current icon from the hash carried in the SNAC, no lookup.
  298. session.BuddyIconURL = func(sn state.IdentScreenName, hash []byte) string {
  299. return h.IconSource.URLForHash(session.BaseURL, sn, hash)
  300. }
  301. // Wire permit/deny refresher so FeedbagUpdateItem SNACs trigger a permitDeny event.
  302. session.PermitDenyRefresher = func(ctx context.Context) (any, error) {
  303. items, err := session.Feedbag(ctx)
  304. if err != nil {
  305. return nil, err
  306. }
  307. return permitDenyData(items), nil
  308. }
  309. // Only IM-class rate limit updates should surface to the client alert.
  310. session.IMRateClassID = imRateClassID
  311. seedRateLimitAlert(session, imRateClassID)
  312. // Now that every refresher callback is wired, start the OSCAR listener. Doing
  313. // this inside CreateSession would race these assignments, since the goroutine
  314. // reads the callbacks as it converts SNACs into events.
  315. session.StartListeningToOSCARSession()
  316. // Store client info
  317. session.ClientName = clientName
  318. session.ClientVersion = clientVersion
  319. session.FetchTimeout = timeout
  320. session.RemoteAddr = r.RemoteAddr
  321. // The identity badge renders the user's own icon from myInfo, which is the
  322. // only event it binds its self-presence render to. PublishedURL always yields
  323. // a URL (the blank placeholder when the user has no icon) so that clearing the
  324. // icon propagates to the badge.
  325. myIconURL := h.IconSource.PublishedURL(ctx, baseURL, screenName.IdentScreenName())
  326. now := time.Now().Unix()
  327. // Prepare response
  328. data := &StartSessionData{
  329. AimSID: session.AimSID,
  330. Ts: now,
  331. FetchTimeout: session.FetchTimeout,
  332. TimeToNextFetch: session.TimeToNextFetch,
  333. // Gromit expects fetchBaseURL directly in data, not in wellKnownUrls
  334. FetchBaseURL: fmt.Sprintf("%s/aim/fetchEvents?aimsid=%s&seqNum=0", baseURL, session.AimSID),
  335. // Add wellKnownUrls for other clients that might use it.
  336. WellKnownUrls: &WellKnownUrls{
  337. WebApiBase: baseURL + "/",
  338. FetchBaseURL: baseURL + "/aim/fetchEvents",
  339. // The client appends the bare method name to this base, so it has to
  340. // carry the /lifestream/ path the routes are registered under.
  341. LifestreamApiBase: baseURL + "/lifestream/",
  342. },
  343. Events: &StartSessionEvents{},
  344. }
  345. myMoodURL := moodIconURL(baseURL, "online", session.OSCARSession.Session().Caps())
  346. myInfoPayload := buildMyInfo(screenName, "online", myIconURL, myMoodURL)
  347. myInfoPayload.StatusMsg = sessionStatusMsg(session.OSCARSession)
  348. myInfoPayload.OnlineTime = time.Now().Unix()
  349. myInfoPayload.MemberSince = time.Now().Unix() - 86400*30 // 30 days ago
  350. myInfoPayload.Self = &MyInfoSelf{
  351. InstNum: 1,
  352. LoginTime: time.Now().Unix(),
  353. SessionTimeout: 30,
  354. Events: events,
  355. AssertCaps: []string{},
  356. RightsInfo: RightsInfo{
  357. MaxDenies: 500,
  358. MaxPermits: 500,
  359. MaxWatchers: 3000,
  360. MaxBuddies: 500,
  361. MaxTempBuddies: maxTempBuddies,
  362. MaxIMSize: 3987,
  363. MinInterIcbmInterval: 1000,
  364. MaxSourceEvil: 900,
  365. MaxDstEvil: 999,
  366. MaxSigLen: 4096,
  367. },
  368. }
  369. data.MyInfo = myInfoPayload
  370. data.Events.MyInfo = myInfoPayload
  371. // Seeds that only queue an event are keyed off the subscription rather than
  372. // iterated with it, so the server fixes their order and each is queued once.
  373. // myInfo and presence render the identity badge from the same payload and the
  374. // client subscribes to both, which a per-subscription loop would queue twice.
  375. if slices.Contains(events, "myInfo") || slices.Contains(events, "presence") {
  376. myInfoData := buildMyInfo(screenName, "online", myIconURL, myMoodURL)
  377. myInfoData.StatusMsg = sessionStatusMsg(session.OSCARSession)
  378. myInfoData.OnlineTime = time.Now().Unix()
  379. myInfoData.MemberSince = time.Now().Unix() - 86400*30 // 30 days ago
  380. session.EventQueue.Push(EventTypeMyInfo, myInfoData)
  381. }
  382. if slices.Contains(events, "conversation") {
  383. session.EventQueue.Push(EventTypeConversation,
  384. ConversationEventData("list", nil))
  385. }
  386. if slices.Contains(events, string(EventTypeService)) {
  387. svcPayload := newServiceData()
  388. data.Events.Service = svcPayload
  389. session.EventQueue.Push(EventTypeService, svcPayload)
  390. }
  391. // The remaining seeds also populate the response payload, so they stay keyed off
  392. // the subscription list they are rendered into.
  393. for _, event := range events {
  394. switch EventType(event) {
  395. case EventTypeBuddyList:
  396. buddyGroups, err := h.BuddyListManager.GetBuddyListForUser(ctx, session)
  397. if err != nil {
  398. h.Logger.ErrorContext(ctx, "failed to get buddy list", "err", err.Error())
  399. }
  400. if buddyGroups == nil {
  401. buddyGroups = []BuddyGroup{}
  402. }
  403. blPayload := &BuddyListData{Groups: buddyGroups}
  404. data.Events.BuddyList = blPayload
  405. session.EventQueue.Push(EventTypeBuddyList, blPayload)
  406. case EventTypePreference:
  407. // Seed the client with effective preference values: the user's stored
  408. // prefs where set, and the server-side spec defaults otherwise. The
  409. // client reads its buddy-list display prefs (e.g. showGroups) only from
  410. // this event and has no default of its own for them, so an omitted pref
  411. // would silently fall back to the client's hidden default and, for
  412. // showGroups, hide group headers.
  413. prefPayload := &PreferenceData{}
  414. if item, err := buddyPrefsItem(ctx, h.FeedbagService, session.OSCARSession); err != nil {
  415. h.Logger.ErrorContext(ctx, "failed to get preferences", "err", err.Error())
  416. } else {
  417. prefPayload = effectiveBuddyPrefs(item.TLVList)
  418. }
  419. data.Events.Preference = prefPayload
  420. session.EventQueue.Push(EventTypePreference, prefPayload)
  421. case EventTypePermitDeny:
  422. // The client keeps its privacy state solely in the model this event
  423. // populates. Both the block/unblock menu action and the "blocked"
  424. // presence state read that model and no-op silently while it is
  425. // empty, so the session has to start with one.
  426. var pdPayload any = PermitDenyData{PDMode: "permitAll"}
  427. if pdd, err := session.PermitDenyRefresher(ctx); err != nil {
  428. h.Logger.ErrorContext(ctx, "failed to get permit/deny settings", "err", err.Error())
  429. } else {
  430. pdPayload = pdd
  431. }
  432. data.Events.PermitDeny = pdPayload
  433. session.EventQueue.Push(EventTypePermitDeny, pdPayload)
  434. }
  435. }
  436. // Drain messages stored while the user was signed off. The service relays them
  437. // as ordinary ICBMChannelMsgToClient SNACs stamped with a send time, which the
  438. // listener started above turns into offlineIM events. Retrieval deletes them
  439. // from the store and the Web API has no ack, so this is the one delivery attempt.
  440. // Skip it for a client that did not subscribe, which leaves the messages stored
  441. // for a session that wants them rather than spending them on one that does not.
  442. //
  443. // This trails every event queued above because the listener pushes from its own
  444. // goroutine, so anything drained here can overtake a later push. An offlineIM
  445. // names its sender by bare aimId and leaves the client to resolve the display
  446. // name against the buddy list it holds, and the conversation list is rebuilt from
  447. // scratch on the first "list" the client sees. Both of those events are queued in
  448. // the loop above, so the drain has to come after it.
  449. if slices.Contains(events, "offlineIM") {
  450. frame := wire.SNACFrame{
  451. FoodGroup: wire.ICBM,
  452. SubGroup: wire.ICBMOfflineRetrieve,
  453. RequestID: wire.ReqIDFromServer,
  454. }
  455. if _, err := h.ICBMService.OfflineRetrieve(ctx, instance, frame); err != nil {
  456. h.Logger.ErrorContext(ctx, "failed to retrieve offline messages", "err", err.Error())
  457. }
  458. }
  459. // Send response in requested format (JSON, JSONP, XML, or AMF)
  460. SendOK(w, r, data, h.Logger)
  461. h.Logger.DebugContext(ctx, "session started",
  462. "aimsid", session.AimSID,
  463. "screen_name", screenName,
  464. "events", events,
  465. "format", r.URL.Query().Get("f"),
  466. )
  467. }
  468. // EndSession handles GET /aim/endSession requests.
  469. func (h *AimHandler) EndSession(w http.ResponseWriter, r *http.Request, session *Session) {
  470. ctx := r.Context()
  471. // RemoveSession evicts the session from the manager and tears it down
  472. // (closes the event queue and the OSCAR instance). Without this the aimsid
  473. // stays resolvable until the reaper sweeps it, and RequireSession would keep
  474. // handing handlers a session whose OSCAR instance is already closed.
  475. if err := h.SessionManager.RemoveSession(ctx, session.AimSID); err != nil {
  476. h.Logger.ErrorContext(ctx, "failed to remove session", "err", err.Error())
  477. }
  478. // Send response
  479. // Send response in requested format (JSON, JSONP, or AMF)
  480. SendOK(w, r, nil, h.Logger)
  481. h.Logger.DebugContext(ctx, "session ended",
  482. "aimsid", session.AimSID,
  483. "screen_name", session.ScreenName,
  484. )
  485. }
  486. // FetchEventsData contains the events and metadata.
  487. type FetchEventsData struct {
  488. Events []Event `json:"events" xml:"events>event"`
  489. LastSeqNum uint64 `json:"lastSeqNum" xml:"lastSeqNum"`
  490. TimeToNextFetch int `json:"timeToNextFetch" xml:"timeToNextFetch"`
  491. FetchBaseURL string `json:"fetchBaseURL" xml:"fetchBaseURL"`
  492. }
  493. // FetchEvents handles GET /aim/fetchEvents requests with long-polling support.
  494. func (h *AimHandler) FetchEvents(w http.ResponseWriter, r *http.Request, session *Session) {
  495. ctx := r.Context()
  496. aimsid := session.AimSID
  497. // Get sequence number parameter
  498. var lastSeqNum uint64
  499. if seqStr := r.URL.Query().Get("seqNum"); seqStr != "" {
  500. if val, err := strconv.ParseUint(seqStr, 10, 64); err == nil {
  501. lastSeqNum = val
  502. }
  503. }
  504. // Timeout is in milliseconds (per Web API spec and client behavior).
  505. timeout := time.Duration(session.FetchTimeout) * time.Millisecond
  506. if timeoutStr := r.URL.Query().Get("timeout"); timeoutStr != "" {
  507. if val, err := strconv.Atoi(timeoutStr); err == nil && val > 0 {
  508. timeout = time.Duration(val) * time.Millisecond
  509. }
  510. }
  511. // Limit maximum timeout to 60 seconds
  512. if timeout > 60*time.Second {
  513. timeout = 60 * time.Second
  514. }
  515. // Create a context with timeout for the fetch operation
  516. fetchCtx, cancel := context.WithTimeout(ctx, timeout)
  517. defer cancel()
  518. // Fetch events from the queue (will block until events available or timeout)
  519. events, err := session.EventQueue.Fetch(fetchCtx, lastSeqNum, timeout)
  520. if err != nil {
  521. if errors.Is(err, context.DeadlineExceeded) {
  522. // timeout is normal - return empty events array
  523. events = []Event{}
  524. } else {
  525. h.Logger.ErrorContext(ctx, "failed to fetch events", "err", err.Error())
  526. SendError(w, r, http.StatusInternalServerError, "failed to fetch events")
  527. return
  528. }
  529. }
  530. // Determine the last sequence number
  531. newLastSeqNum := lastSeqNum
  532. if len(events) > 0 {
  533. newLastSeqNum = events[len(events)-1].SeqNum
  534. }
  535. // A nil slice renders as JSON null, which a client reading data.events
  536. // strictly rejects.
  537. if events == nil {
  538. events = []Event{}
  539. }
  540. // Prepare response
  541. data := &FetchEventsData{
  542. Events: events,
  543. LastSeqNum: newLastSeqNum,
  544. TimeToNextFetch: session.TimeToNextFetch,
  545. // Include fetchBaseURL with updated sequence number for next request
  546. FetchBaseURL: fmt.Sprintf("%s/aim/fetchEvents?aimsid=%s&seqNum=%d",
  547. baseURLFromRequest(r), aimsid, newLastSeqNum),
  548. }
  549. SendOK(w, r, data, h.Logger)
  550. if len(events) > 0 {
  551. h.Logger.DebugContext(ctx, "events fetched",
  552. "aimsid", aimsid,
  553. "count", len(events),
  554. "last_seq", newLastSeqNum,
  555. )
  556. }
  557. }
  558. // maxTempBuddies caps how many screen names one addTempBuddy or removeTempBuddy
  559. // call may carry.
  560. const maxTempBuddies = 160
  561. // AddTempBuddy handles GET /aim/addTempBuddy requests.
  562. // Temporary buddies live for the duration of the OSCAR session; they are not
  563. // persisted to the feedbag.
  564. func (h *AimHandler) AddTempBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  565. ctx := r.Context()
  566. aimsid := r.URL.Query().Get("aimsid")
  567. buddyNames := targetNames(r)
  568. if len(buddyNames) == 0 {
  569. SendError(w, r, http.StatusBadRequest, "missing buddy names (t parameter)")
  570. return
  571. }
  572. if len(buddyNames) > maxTempBuddies {
  573. SendError(w, r, http.StatusBadRequest, fmt.Sprintf("too many buddy names (max %d)", maxTempBuddies))
  574. return
  575. }
  576. snac := wire.SNAC_0x03_0x0F_BuddyAddTempBuddies{}
  577. for _, buddyName := range buddyNames {
  578. snac.Buddies = append(snac.Buddies, struct {
  579. ScreenName string `oscar:"len_prefix=uint8"`
  580. }{ScreenName: buddyName})
  581. }
  582. if _, err := h.BuddyService.AddTempBuddies(ctx, session.OSCARSession, wire.SNACFrame{}, snac); err != nil {
  583. h.Logger.ErrorContext(ctx, "add temp buddies failed", "aimsid", aimsid, "err", err.Error())
  584. SendError(w, r, http.StatusInternalServerError, "unable to add temporary buddies")
  585. return
  586. }
  587. SendOK(w, r, nil, h.Logger)
  588. h.Logger.InfoContext(ctx, "temporary buddies added",
  589. "aimsid", aimsid,
  590. "buddies", buddyNames,
  591. "count", len(buddyNames),
  592. )
  593. }
  594. // RemoveTempBuddy handles GET /aim/removeTempBuddy requests.
  595. // This removes temporary session buddies added via addTempBuddy.
  596. func (h *AimHandler) RemoveTempBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  597. ctx := r.Context()
  598. aimsid := r.URL.Query().Get("aimsid")
  599. buddyNames := targetNames(r)
  600. if len(buddyNames) == 0 {
  601. SendError(w, r, http.StatusBadRequest, "missing buddy names (t parameter)")
  602. return
  603. }
  604. if len(buddyNames) > maxTempBuddies {
  605. SendError(w, r, http.StatusBadRequest, fmt.Sprintf("too many buddy names (max %d)", maxTempBuddies))
  606. return
  607. }
  608. snac := wire.SNAC_0x03_0x10_BuddyDelTempBuddies{}
  609. for _, buddyName := range buddyNames {
  610. snac.Buddies = append(snac.Buddies, struct {
  611. ScreenName string `oscar:"len_prefix=uint8"`
  612. }{ScreenName: buddyName})
  613. }
  614. if err := h.BuddyService.DelTempBuddies(ctx, session.OSCARSession, snac); err != nil {
  615. h.Logger.ErrorContext(ctx, "remove temp buddies failed", "aimsid", aimsid, "err", err.Error())
  616. SendError(w, r, http.StatusInternalServerError, "unable to remove temporary buddies")
  617. return
  618. }
  619. for _, buddyName := range buddyNames {
  620. session.forgetBuddyPresence(state.NewIdentScreenName(buddyName))
  621. }
  622. SendOK(w, r, nil, h.Logger)
  623. h.Logger.InfoContext(ctx, "temporary buddies removed",
  624. "aimsid", aimsid,
  625. "buddies", buddyNames,
  626. "count", len(buddyNames),
  627. )
  628. }
  629. // SetForwardDomain acknowledges the client's forward-domain registration.
  630. // The Web AIM client fires this once when the session goes online; name may be
  631. // the literal string "null" for local/dev servers.
  632. func (h *AimHandler) SetForwardDomain(w http.ResponseWriter, r *http.Request) {
  633. SendOK(w, r, nil, h.Logger)
  634. }
  635. // ReportAction acknowledges a client-side UI telemetry ping. The Web AIM client
  636. // fires this on menu clicks and similar interactions with an action param of the
  637. // form "type=click,id=block-user-chatmenu"; it ignores the response.
  638. func (h *AimHandler) ReportAction(w http.ResponseWriter, r *http.Request) {
  639. SendOK(w, r, nil, h.Logger)
  640. }
  641. // StoredDataItems is the client-side data blob store, which this server does
  642. // not keep, so it always answers with an empty items list.
  643. type StoredDataItems struct {
  644. Items []string `json:"items" xml:"items>item"`
  645. }
  646. // GetData returns empty client-side data blobs (buddy list favorites, etc.).
  647. func (h *AimHandler) GetData(w http.ResponseWriter, r *http.Request) {
  648. SendOK(w, r, &StoredDataItems{Items: []string{}}, h.Logger)
  649. }
  650. // StartOSCARSessionResponse represents the response for startOSCARSession endpoint.
  651. type StartOSCARSessionResponse struct {
  652. Response struct {
  653. StatusCode int `json:"statusCode" xml:"statusCode"`
  654. StatusText string `json:"statusText" xml:"statusText"`
  655. Data struct {
  656. Host string `json:"host" xml:"host"`
  657. Port int `json:"port" xml:"port"`
  658. Cookie string `json:"cookie" xml:"cookie"`
  659. // TLSCertName is the certificate name the client verifies BOS against.
  660. // Omitted rather than sent empty: its absence means connect in the clear.
  661. TLSCertName string `json:"tlsCertName,omitempty" xml:"tlsCertName,omitempty"`
  662. } `json:"data" xml:"data"`
  663. } `json:"response"`
  664. }
  665. // MarshalXML renders the envelope with the same flat root as BaseResponse.
  666. func (s StartOSCARSessionResponse) MarshalXML(e *xml.Encoder, _ xml.StartElement) error {
  667. return e.EncodeElement(s.Response, xml.StartElement{Name: xml.Name{Local: "response"}})
  668. }
  669. // StartOSCARSession handles GET /aim/startOSCARSession requests, which hand a
  670. // client that authenticated over HTTP the address of a BOS server and the
  671. // cookie to sign on with. The token in "a" is the auth cookie clientLogin
  672. // minted, already what BOS expects, so it is handed straight back.
  673. //
  674. // The sig_sha256 the client computes over the query string is not checked: that
  675. // signature is keyed by HMAC(password, sessionSecret), and clientLogin keeps
  676. // neither past the response.
  677. func (h *AimHandler) StartOSCARSession(w http.ResponseWriter, r *http.Request) {
  678. ctx := r.Context()
  679. h.Logger.InfoContext(ctx, "startOSCARSession requested",
  680. "method", r.Method,
  681. "remote_addr", r.RemoteAddr,
  682. "user_agent", r.UserAgent())
  683. params := r.URL.Query()
  684. token := params.Get("a")
  685. if token == "" {
  686. h.Logger.Warn("missing authentication token")
  687. SendError(w, r, http.StatusUnauthorized, "authentication token required")
  688. return
  689. }
  690. rawCookie, err := base64.URLEncoding.DecodeString(strings.TrimSpace(token))
  691. if err != nil {
  692. h.Logger.WarnContext(ctx, "invalid authentication token (base64)", "err", err.Error())
  693. SendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  694. return
  695. }
  696. cookie, _, err := h.AuthService.CrackCookie(rawCookie)
  697. if err != nil {
  698. h.Logger.WarnContext(ctx, "invalid authentication token", "err", err.Error())
  699. SendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  700. return
  701. }
  702. // Encryption the server cannot provide degrades to a plaintext host, which a
  703. // client doing opportunistic encryption expects when no certificate is named.
  704. // The sign-on cookie then crosses the wire in the clear, so the downgrade is
  705. // logged rather than left to be inferred from the absent tlsCertName.
  706. useTLS := parseBoolParam(params.Get("useTLS"))
  707. endpoint := h.BOSListener.PlainEndpoint()
  708. if useTLS {
  709. ssl, ok := h.BOSListener.SSLEndpoint()
  710. if !ok {
  711. h.Logger.WarnContext(ctx, "TLS requested but no SSL listener is configured, advertising a plaintext BOS host",
  712. "screen_name", cookie.ScreenName)
  713. useTLS = false
  714. } else {
  715. endpoint = ssl
  716. }
  717. }
  718. host, portStr, err := net.SplitHostPort(endpoint.AdvertisedHost())
  719. if err != nil {
  720. h.Logger.ErrorContext(ctx, "unable to split advertised BOS host", "err", err.Error())
  721. SendError(w, r, http.StatusInternalServerError, "internal server error")
  722. return
  723. }
  724. port, _ := strconv.Atoi(portStr)
  725. resp := &StartOSCARSessionResponse{}
  726. resp.Response.StatusCode = 200
  727. resp.Response.StatusText = "Ok"
  728. resp.Response.Data.Host = host
  729. resp.Response.Data.Port = port
  730. // Base64, the encoding the client decodes the cookie with.
  731. resp.Response.Data.Cookie = base64.StdEncoding.EncodeToString(rawCookie)
  732. if useTLS {
  733. // The advertised SSL host is the name the certificate is issued to.
  734. resp.Response.Data.TLSCertName = host
  735. }
  736. SendResponse(w, r, resp, h.Logger)
  737. h.Logger.InfoContext(ctx, "OSCAR session bridge created",
  738. "screen_name", cookie.ScreenName,
  739. "bos_host", host,
  740. "bos_port", port,
  741. "use_tls", useTLS)
  742. }
  743. // parseBoolParam parses a boolean parameter from query string.
  744. func parseBoolParam(value string) bool {
  745. value = strings.ToLower(value)
  746. return value == "true" || value == "1" || value == "yes"
  747. }
  748. // seedRateLimitAlert raises the client's rate limit alert when a session starts
  749. // on an account that is already rate limited.
  750. //
  751. // The monitor broadcasts transitions, not current state, so a session signing on
  752. // mid-limit missed the one that raised the alert — and the client's alert is
  753. // sticky, so the eventual "clear" would arrive with nothing to dismiss. An OSCAR
  754. // client learns the current state from the rate params it gets at handshake; this
  755. // is the Web API's equivalent.
  756. //
  757. // Only the limited state is seeded: alert is a warning the user cannot act on,
  758. // and seeding clear would render nothing.
  759. func seedRateLimitAlert(session *Session, classID wire.RateLimitClassID) {
  760. if classID == 0 {
  761. return
  762. }
  763. status := session.OSCARSession.Session().RateLimitStates()[classID-1].CurrentStatus
  764. if status != wire.RateLimitStatusLimited {
  765. return
  766. }
  767. session.EventQueue.Push(EventTypeRateLimit, RateLimitEvent{
  768. Classes: []RateLimitClass{
  769. {
  770. ID: int(classID),
  771. Status: rateLimitStatusName(status),
  772. },
  773. },
  774. })
  775. }
  776. // buildMyInfo assembles the shared base of a myInfo payload — the user's own
  777. // identity blob that the AIM client renders in its identity badge.
  778. //
  779. // It carries only fields that are safe to repeat on every myInfo: the client's
  780. // user-object merge deletes friendly and capabilities before merging, so both
  781. // must be present on each push or the badge loses them. Time-sensitive fields
  782. // (onlineTime, memberSince) are intentionally excluded — a mid-session refresh
  783. // omits them so the client keeps the signon time it already has; the
  784. // builders add them explicitly. buddyIcon is included only when non-empty; an
  785. // empty value would be dropped by the client merge anyway, and the placeholder
  786. // URL (not "") is what clears an icon. moodIcon is a parameter rather than a
  787. // field the callers set, because omitting it clears the user's mood.
  788. func buildMyInfo(screenName state.DisplayScreenName, webState, buddyIcon, moodIcon string) *MyInfo {
  789. return &MyInfo{
  790. AimID: screenName.IdentScreenName().String(),
  791. DisplayID: screenName.String(),
  792. Friendly: screenName.String(),
  793. State: webState,
  794. UserType: userTypeFor(screenName.IdentScreenName()),
  795. Service: serviceFor(screenName.IdentScreenName()),
  796. // Never nil: the client iterates capabilities unconditionally.
  797. Capabilities: []string{},
  798. Bot: false,
  799. BuddyIcon: buddyIcon,
  800. MoodIcon: moodIcon,
  801. }
  802. }
  803. func requestScheme(r *http.Request) string {
  804. if r.TLS != nil {
  805. return "https"
  806. }
  807. if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  808. return proto
  809. }
  810. return "http"
  811. }
  812. // baseURLFromRequest returns the absolute base URL the client reached this
  813. // server on, used to build asset URLs that the client loads directly.
  814. func baseURLFromRequest(r *http.Request) string {
  815. return fmt.Sprintf("%s://%s", requestScheme(r), r.Host)
  816. }