4
0

aim_handler.go 34 KB

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