aim_handler.go 36 KB

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