aim_handler.go 35 KB

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