aim_handler.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. SendOK(w, r, data, h.Logger)
  536. if len(events) > 0 {
  537. h.Logger.DebugContext(ctx, "events fetched",
  538. "aimsid", aimsid,
  539. "count", len(events),
  540. "last_seq", newLastSeqNum,
  541. )
  542. }
  543. }
  544. // AddTempBuddy handles GET /aim/addTempBuddy requests.
  545. // This adds temporary buddies to the session without persisting them to the feedbag.
  546. // The temporary buddies are only visible for the duration of the session.
  547. func (h *AimHandler) AddTempBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  548. ctx := r.Context()
  549. aimsid := r.URL.Query().Get("aimsid")
  550. buddyNames := r.URL.Query()["t"]
  551. if len(buddyNames) == 0 {
  552. SendError(w, r, http.StatusBadRequest, "missing buddy names (t parameter)")
  553. return
  554. }
  555. // Store temporary buddies in the session
  556. // Note: These are not persisted to the feedbag database
  557. if session.TempBuddies == nil {
  558. session.TempBuddies = make(map[string]bool)
  559. }
  560. for _, buddyName := range buddyNames {
  561. buddyName = strings.TrimSpace(buddyName)
  562. if buddyName != "" {
  563. session.TempBuddies[buddyName] = true
  564. }
  565. }
  566. // Prepare response
  567. responseData := &ResultCodeData{ResultCode: "success", BuddyNames: buddyNames}
  568. SendOK(w, r, responseData, h.Logger)
  569. // Do not push buddylist events for temp buddies. The Web AIM client handles
  570. // addTempBuddy via the API response; a buddylist event without "groups" causes
  571. // the client to clear the entire contact list (zC always calls clear() first).
  572. h.Logger.InfoContext(ctx, "temporary buddies added",
  573. "aimsid", aimsid,
  574. "buddies", buddyNames,
  575. "count", len(buddyNames),
  576. )
  577. }
  578. // RemoveTempBuddy handles GET /aim/removeTempBuddy requests.
  579. // This removes temporary session buddies added via addTempBuddy.
  580. func (h *AimHandler) RemoveTempBuddy(w http.ResponseWriter, r *http.Request, session *Session) {
  581. ctx := r.Context()
  582. aimsid := r.URL.Query().Get("aimsid")
  583. buddyNames := r.URL.Query()["t"]
  584. if len(buddyNames) == 0 {
  585. SendError(w, r, http.StatusBadRequest, "missing buddy names (t parameter)")
  586. return
  587. }
  588. removed := make([]string, 0, len(buddyNames))
  589. for _, buddyName := range buddyNames {
  590. buddyName = strings.TrimSpace(buddyName)
  591. if buddyName == "" {
  592. continue
  593. }
  594. if session.TempBuddies != nil {
  595. delete(session.TempBuddies, buddyName)
  596. }
  597. removed = append(removed, buddyName)
  598. }
  599. SendOK(w, r, &ResultCodeData{ResultCode: "success", BuddyNames: removed}, h.Logger)
  600. h.Logger.InfoContext(ctx, "temporary buddies removed",
  601. "aimsid", aimsid,
  602. "buddies", removed,
  603. "count", len(removed),
  604. )
  605. }
  606. // SetForwardDomain acknowledges the client's forward-domain registration.
  607. // The Web AIM client fires this once when the session goes online; name may be
  608. // the literal string "null" for local/dev servers.
  609. func (h *AimHandler) SetForwardDomain(w http.ResponseWriter, r *http.Request) {
  610. SendOK(w, r, nil, h.Logger)
  611. }
  612. // ReportAction acknowledges a client-side UI telemetry ping. The Web AIM client
  613. // fires this on menu clicks and similar interactions with an action param of the
  614. // form "type=click,id=block-user-chatmenu"; it ignores the response.
  615. func (h *AimHandler) ReportAction(w http.ResponseWriter, r *http.Request) {
  616. SendOK(w, r, nil, h.Logger)
  617. }
  618. // StoredDataItems is the client-side data blob store, which this server does
  619. // not keep, so it always answers with an empty items list.
  620. type StoredDataItems struct {
  621. Items []string `json:"items" xml:"items>item"`
  622. }
  623. // GetData returns empty client-side data blobs (buddy list favorites, etc.).
  624. func (h *AimHandler) GetData(w http.ResponseWriter, r *http.Request) {
  625. SendOK(w, r, &StoredDataItems{Items: []string{}}, h.Logger)
  626. }
  627. // StartOSCARSessionResponse represents the response for startOSCARSession endpoint.
  628. type StartOSCARSessionResponse struct {
  629. Response struct {
  630. StatusCode int `json:"statusCode" xml:"statusCode"`
  631. StatusText string `json:"statusText" xml:"statusText"`
  632. Data struct {
  633. Host string `json:"host" xml:"host"`
  634. Port int `json:"port" xml:"port"`
  635. Cookie string `json:"cookie" xml:"cookie"`
  636. // TLSCertName is the certificate name the client verifies BOS against.
  637. // Omitted rather than sent empty: its absence means connect in the clear.
  638. TLSCertName string `json:"tlsCertName,omitempty" xml:"tlsCertName,omitempty"`
  639. } `json:"data" xml:"data"`
  640. } `json:"response"`
  641. }
  642. // MarshalXML renders the envelope with the same flat root as BaseResponse.
  643. func (s StartOSCARSessionResponse) MarshalXML(e *xml.Encoder, _ xml.StartElement) error {
  644. return e.EncodeElement(s.Response, xml.StartElement{Name: xml.Name{Local: "response"}})
  645. }
  646. // StartOSCARSession handles GET /aim/startOSCARSession requests, which hand a
  647. // client that authenticated over HTTP the address of a BOS server and the
  648. // cookie to sign on with. The token in "a" is the auth cookie clientLogin
  649. // minted, already what BOS expects, so it is handed straight back.
  650. //
  651. // The sig_sha256 the client computes over the query string is not checked: that
  652. // signature is keyed by HMAC(password, sessionSecret), and clientLogin keeps
  653. // neither past the response.
  654. func (h *AimHandler) StartOSCARSession(w http.ResponseWriter, r *http.Request) {
  655. ctx := r.Context()
  656. h.Logger.InfoContext(ctx, "startOSCARSession requested",
  657. "method", r.Method,
  658. "remote_addr", r.RemoteAddr,
  659. "user_agent", r.UserAgent())
  660. // Get API key info from context (set by auth middleware)
  661. apiKey, ok := ctx.Value(ContextKeyAPIKey).(*state.WebAPIKey)
  662. if !ok {
  663. h.Logger.Error("API key not found in context")
  664. SendError(w, r, http.StatusInternalServerError, "internal server error")
  665. return
  666. }
  667. // Verify that this API key has permission to create OSCAR sessions
  668. if !hasOSCARBridgeCapability(apiKey) {
  669. h.Logger.Warn("API key lacks OSCAR bridge capability",
  670. "dev_id", apiKey.DevID)
  671. SendError(w, r, http.StatusForbidden, "OSCAR bridge not enabled for this application")
  672. return
  673. }
  674. params := r.URL.Query()
  675. token := params.Get("a")
  676. if token == "" {
  677. h.Logger.Warn("missing authentication token")
  678. SendError(w, r, http.StatusUnauthorized, "authentication token required")
  679. return
  680. }
  681. rawCookie, err := base64.URLEncoding.DecodeString(strings.TrimSpace(token))
  682. if err != nil {
  683. h.Logger.WarnContext(ctx, "invalid authentication token (base64)", "err", err.Error())
  684. SendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  685. return
  686. }
  687. cookie, _, err := h.AuthService.CrackCookie(rawCookie)
  688. if err != nil {
  689. h.Logger.WarnContext(ctx, "invalid authentication token", "err", err.Error())
  690. SendError(w, r, http.StatusUnauthorized, "invalid or expired token")
  691. return
  692. }
  693. // Encryption the server cannot provide degrades to a plaintext host, which a
  694. // client doing opportunistic encryption expects when no certificate is named.
  695. // The sign-on cookie then crosses the wire in the clear, so the downgrade is
  696. // logged rather than left to be inferred from the absent tlsCertName.
  697. useTLS := parseBoolParam(params.Get("useTLS"))
  698. endpoint := h.BOSListener.PlainEndpoint()
  699. if useTLS {
  700. ssl, ok := h.BOSListener.SSLEndpoint()
  701. if !ok {
  702. h.Logger.WarnContext(ctx, "TLS requested but no SSL listener is configured, advertising a plaintext BOS host",
  703. "screen_name", cookie.ScreenName)
  704. useTLS = false
  705. } else {
  706. endpoint = ssl
  707. }
  708. }
  709. host, portStr, err := net.SplitHostPort(endpoint.AdvertisedHost())
  710. if err != nil {
  711. h.Logger.ErrorContext(ctx, "unable to split advertised BOS host", "err", err.Error())
  712. SendError(w, r, http.StatusInternalServerError, "internal server error")
  713. return
  714. }
  715. port, _ := strconv.Atoi(portStr)
  716. resp := &StartOSCARSessionResponse{}
  717. resp.Response.StatusCode = 200
  718. resp.Response.StatusText = "OK"
  719. resp.Response.Data.Host = host
  720. resp.Response.Data.Port = port
  721. // Base64, the encoding the client decodes the cookie with.
  722. resp.Response.Data.Cookie = base64.StdEncoding.EncodeToString(rawCookie)
  723. if useTLS {
  724. // The advertised SSL host is the name the certificate is issued to.
  725. resp.Response.Data.TLSCertName = host
  726. }
  727. SendResponse(w, r, resp, h.Logger)
  728. h.Logger.InfoContext(ctx, "OSCAR session bridge created",
  729. "screen_name", cookie.ScreenName,
  730. "bos_host", host,
  731. "bos_port", port,
  732. "use_tls", useTLS)
  733. }
  734. // hasOSCARBridgeCapability checks if the API key has permission to create OSCAR bridges.
  735. func hasOSCARBridgeCapability(apiKey *state.WebAPIKey) bool {
  736. if len(apiKey.Capabilities) == 0 {
  737. return true // No restrictions if capabilities not specified
  738. }
  739. // Check if OSCAR bridge is explicitly enabled
  740. for _, cap := range apiKey.Capabilities {
  741. if cap == "oscar_bridge" || cap == "*" {
  742. return true
  743. }
  744. }
  745. return false
  746. }
  747. // parseBoolParam parses a boolean parameter from query string.
  748. func parseBoolParam(value string) bool {
  749. value = strings.ToLower(value)
  750. return value == "true" || value == "1" || value == "yes"
  751. }
  752. // seedRateLimitAlert raises the client's rate limit alert when a session starts
  753. // on an account that is already rate limited.
  754. //
  755. // The monitor broadcasts transitions, not current state, so a session signing on
  756. // mid-limit missed the one that raised the alert — and the client's alert is
  757. // sticky, so the eventual "clear" would arrive with nothing to dismiss. An OSCAR
  758. // client learns the current state from the rate params it gets at handshake; this
  759. // is the Web API's equivalent.
  760. //
  761. // Only the limited state is seeded: alert is a warning the user cannot act on,
  762. // and seeding clear would render nothing.
  763. func seedRateLimitAlert(session *Session, classID wire.RateLimitClassID) {
  764. if classID == 0 {
  765. return
  766. }
  767. status := session.OSCARSession.Session().RateLimitStates()[classID-1].CurrentStatus
  768. if status != wire.RateLimitStatusLimited {
  769. return
  770. }
  771. session.EventQueue.Push(EventTypeRateLimit, RateLimitEvent{
  772. Classes: []RateLimitClass{
  773. {
  774. ID: int(classID),
  775. Status: rateLimitStatusName(status),
  776. },
  777. },
  778. })
  779. }
  780. // buildMyInfo assembles the shared base of a myInfo payload — the user's own
  781. // identity blob that the AIM client renders in its identity badge.
  782. //
  783. // It carries only fields that are safe to repeat on every myInfo: the client's
  784. // user-object merge deletes friendly and capabilities before merging, so both
  785. // must be present on each push or the badge loses them. Time-sensitive fields
  786. // (onlineTime, memberSince) are intentionally excluded — a mid-session refresh
  787. // omits them so the client keeps the signon time it already has; the startSession
  788. // builders add them explicitly. buddyIcon is included only when non-empty; an
  789. // empty value would be dropped by the client merge anyway, and the placeholder
  790. // URL (not "") is what clears an icon.
  791. func buildMyInfo(screenName state.DisplayScreenName, webState, buddyIcon string) *MyInfo {
  792. // The web client compares userType/service case-sensitively; a UIN account must
  793. // report ICQ so it renders as an ICQ contact rather than AIM.
  794. userType, service := "aim", "AIM"
  795. if screenName.IsUIN() {
  796. userType, service = "icq", "ICQ"
  797. }
  798. return &MyInfo{
  799. AimID: screenName.IdentScreenName().String(),
  800. DisplayID: screenName.String(),
  801. Friendly: screenName.String(),
  802. State: webState,
  803. UserType: userType,
  804. // Never nil: the client iterates capabilities unconditionally.
  805. Capabilities: []string{},
  806. Bot: false,
  807. Service: service,
  808. BuddyIcon: buddyIcon,
  809. }
  810. }
  811. func requestScheme(r *http.Request) string {
  812. if r.TLS != nil {
  813. return "https"
  814. }
  815. if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  816. return proto
  817. }
  818. return "http"
  819. }
  820. // baseURLFromRequest returns the absolute base URL the client reached this
  821. // server on, used to build asset URLs that the client loads directly.
  822. func baseURLFromRequest(r *http.Request) string {
  823. return fmt.Sprintf("%s://%s", requestScheme(r), r.Host)
  824. }