aim_handler.go 35 KB

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