4
0

server.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log/slog"
  8. "net/http"
  9. "time"
  10. "golang.org/x/sync/errgroup"
  11. "github.com/mk6i/open-oscar-server/config"
  12. "github.com/mk6i/open-oscar-server/state"
  13. "github.com/mk6i/open-oscar-server/wire"
  14. )
  15. func NewServer(listeners []string, logger *slog.Logger, handler Handler, apiKeyValidator APIKeyValidator, sessionManager *SessionManager) *Server {
  16. servers := make([]*http.Server, 0, len(listeners))
  17. authMiddleware := NewAuthMiddleware(apiKeyValidator, logger)
  18. rateLimiter := NewRateLimitMiddleware(handler.SNACRateLimits, logger)
  19. authHandler := &AuthHandler{
  20. AuthService: handler.AuthService,
  21. Logger: logger,
  22. }
  23. aimHandler := &AimHandler{
  24. SessionManager: sessionManager,
  25. AuthService: handler.AuthService,
  26. FeedbagService: handler.FeedbagService,
  27. ICBMService: handler.ICBMService,
  28. OServiceService: handler.OServiceService,
  29. BuddyListManager: handler.BuddyListManager,
  30. IconSource: handler.IconSource,
  31. BOSListener: handler.BOSListener,
  32. SNACRateLimits: handler.SNACRateLimits,
  33. Logger: logger,
  34. }
  35. presenceHandler := &PresenceHandler{
  36. SessionManager: sessionManager,
  37. FeedbagService: handler.FeedbagService,
  38. BuddyBroadcaster: handler.BuddyBroadcaster,
  39. LocateService: handler.LocateService,
  40. IconSource: handler.IconSource,
  41. Logger: logger,
  42. }
  43. buddyListHandler := &BuddyListHandler{
  44. BuddyListManager: handler.BuddyListManager,
  45. Logger: logger,
  46. FeedbagService: handler.FeedbagService,
  47. }
  48. messagingHandler := &MessagingHandler{
  49. ICBMService: handler.ICBMService,
  50. LocateService: handler.LocateService,
  51. FeedbagService: handler.FeedbagService,
  52. Logger: logger,
  53. }
  54. preferenceHandler := &PreferenceHandler{
  55. SessionManager: sessionManager,
  56. FeedbagService: handler.FeedbagService,
  57. Logger: logger,
  58. }
  59. memberDirHandler := &MemberDirHandler{
  60. DirSearchService: handler.DirSearchService,
  61. LocateService: handler.LocateService,
  62. Logger: logger,
  63. }
  64. shutdownCtx, shutdownCancel := context.WithCancel(context.Background())
  65. for _, l := range listeners {
  66. mux := http.NewServeMux()
  67. // CORSMiddleware wraps the auth layer rather than the other way around, so
  68. // that responses the auth layer rejects (400 missing key, 403 bad key, 429
  69. // rate limited) still carry Access-Control-Allow-Origin. A browser blocks a
  70. // cross-origin response without that header, and the Web AIM client reads
  71. // the resulting status-0 empty response as a CORS failure and permanently
  72. // switches its whole request pipeline to JSONP.
  73. //
  74. // oscarRoute charges the request against the rate class for (foodGroup,
  75. // subGroup) before the handler runs; sessionRoute and stubRoute reach no
  76. // food group and so are not rate limited here.
  77. oscarRoute := func(foodGroup uint16, subGroup uint16, h SessionHandlerFunc) http.Handler {
  78. return authMiddleware.CORSMiddleware(
  79. authMiddleware.AuthenticateFlexible(
  80. authMiddleware.RequireSession(sessionManager,
  81. rateLimiter.OSCAR(foodGroup, subGroup)(h))))
  82. }
  83. sessionRoute := func(h SessionHandlerFunc) http.Handler {
  84. return authMiddleware.CORSMiddleware(
  85. authMiddleware.AuthenticateFlexible(
  86. authMiddleware.RequireSession(sessionManager, h)))
  87. }
  88. stubRoute := func(h http.HandlerFunc) http.Handler {
  89. return authMiddleware.CORSMiddleware(
  90. authMiddleware.AuthenticateFlexible(h))
  91. }
  92. // Exact root only. Pattern "GET /" matches every GET path in Go 1.22+ (prefix /), which
  93. // would steal /getAggregated and other lifestream URLs before stubs/404.
  94. mux.Handle("GET /{$}", http.HandlerFunc(handler.GetHelloWorldHandler))
  95. // Unauthenticated and outside every middleware: Flash Player fetches the
  96. // policy before it has a session, and refuses to look at a redirect or an
  97. // error envelope.
  98. mux.Handle("GET /crossdomain.xml", &CrossDomainPolicyHandler{Logger: logger})
  99. // Authentication endpoint (public - no API key required for user login)
  100. // Using pattern with explicit method for Go 1.22+ routing.
  101. mux.Handle("POST /auth/clientLogin", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  102. // Set CORS headers for public endpoint
  103. w.Header().Set("Access-Control-Allow-Origin", "*")
  104. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  105. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  106. authHandler.ClientLogin(w, r)
  107. }))
  108. // Handle OPTIONS for CORS preflight
  109. mux.HandleFunc("OPTIONS /auth/clientLogin", func(w http.ResponseWriter, r *http.Request) {
  110. w.Header().Set("Access-Control-Allow-Origin", "*")
  111. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  112. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  113. w.WriteHeader(http.StatusNoContent)
  114. })
  115. mux.Handle("GET /auth/getToken", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  116. w.Header().Set("Access-Control-Allow-Origin", "*")
  117. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  118. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  119. authHandler.GetToken(w, r)
  120. }))
  121. mux.HandleFunc("OPTIONS /auth/getToken", func(w http.ResponseWriter, r *http.Request) {
  122. w.Header().Set("Access-Control-Allow-Origin", "*")
  123. w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
  124. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  125. w.WriteHeader(http.StatusNoContent)
  126. })
  127. // No SSO cookie is involved, so this sits outside the session middleware.
  128. // Both methods, since clients differ on which they use.
  129. getInfo := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  130. w.Header().Set("Access-Control-Allow-Origin", "*")
  131. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
  132. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  133. authHandler.GetInfo(w, r)
  134. })
  135. mux.Handle("GET /auth/getInfo", getInfo)
  136. mux.Handle("POST /auth/getInfo", getInfo)
  137. mux.HandleFunc("OPTIONS /auth/getInfo", func(w http.ResponseWriter, r *http.Request) {
  138. w.Header().Set("Access-Control-Allow-Origin", "*")
  139. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
  140. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  141. w.WriteHeader(http.StatusNoContent)
  142. })
  143. // Web AIM navigates the browser here on File > Logout; clear SSO state
  144. // and redirect to the login screen.
  145. mux.Handle("GET /auth/logout", http.HandlerFunc(authHandler.Logout))
  146. // Wrapped in CORS: besides the browser navigation that renders the form,
  147. // the client fetches this cross-origin for its client2Web SSO handoff, and
  148. // a response without Access-Control-Allow-Origin reaches it as an ioError.
  149. loginPSP := authMiddleware.CORSMiddleware(http.HandlerFunc(authHandler.LoginPSP))
  150. mux.Handle("GET /_cqr/login/login.psp", loginPSP)
  151. mux.Handle("POST /_cqr/login/login.psp", loginPSP)
  152. // Authenticated Web AIM API endpoints
  153. // SessionInstance management - supports multiple auth methods (k, a, ts+sig_sha256).
  154. //
  155. // Both methods: Go 1.22 patterns are method-exact and clients differ.
  156. startSession := authMiddleware.CORSMiddleware(
  157. authMiddleware.AuthenticateFlexible(
  158. http.HandlerFunc(aimHandler.StartSession)))
  159. mux.Handle("GET /aim/startSession", startSession)
  160. mux.Handle("POST /aim/startSession", startSession)
  161. // End session - uses aimsid for auth, no k required
  162. mux.Handle("GET /aim/endSession", sessionRoute(aimHandler.EndSession))
  163. // Event fetching - uses aimsid for auth, no k required. This is the
  164. // long-poll loop the client runs continuously.
  165. mux.Handle("GET /aim/fetchEvents", sessionRoute(aimHandler.FetchEvents))
  166. // Temp buddies are session-local rather than feedbag-backed, but they
  167. // are the Web API's equivalent of the BUDDY temp buddy SNACs and are
  168. // charged as such.
  169. mux.Handle("GET /aim/addTempBuddy", oscarRoute(wire.Buddy, wire.BuddyAddTempBuddies, aimHandler.AddTempBuddy))
  170. mux.Handle("GET /aim/removeTempBuddy", oscarRoute(wire.Buddy, wire.BuddyDelTempBuddies, aimHandler.RemoveTempBuddy))
  171. mux.Handle("GET /aim/setForwardDomain", stubRoute(aimHandler.SetForwardDomain))
  172. mux.Handle("GET /aim/getData", stubRoute(aimHandler.GetData))
  173. mux.Handle("GET /aim/reportAction", stubRoute(aimHandler.ReportAction))
  174. // OSCAR Bridge endpoint. Hands off to a BOS session rather than reaching
  175. // a food group, so there is no OSCAR budget to charge.
  176. mux.Handle("GET /aim/startOSCARSession",
  177. authMiddleware.CORSMiddleware(
  178. authMiddleware.Authenticate(
  179. http.HandlerFunc(aimHandler.StartOSCARSession))))
  180. conversationStub := &ConversationStubHandler{
  181. Logger: logger,
  182. }
  183. mux.Handle("GET /conversation/update", stubRoute(conversationStub.Update))
  184. mux.Handle("GET /conversation/close", stubRoute(conversationStub.Close))
  185. mux.Handle("GET /imlog/markRead", stubRoute(conversationStub.MarkRead))
  186. mux.Handle("GET /imlog/fetchStoredIMs", sessionRoute(conversationStub.FetchStoredIMs))
  187. // Presence and buddy list
  188. // GetPresence supports aimsid-based auth, so we use flexible auth
  189. mux.Handle("GET /presence/get", oscarRoute(wire.Feedbag, wire.FeedbagQuery, presenceHandler.GetPresence))
  190. mux.Handle("GET /buddylist/addBuddy", oscarRoute(wire.Feedbag, wire.FeedbagInsertItem, buddyListHandler.AddBuddy))
  191. mux.Handle("GET /buddylist/addGroup", oscarRoute(wire.Feedbag, wire.FeedbagInsertItem, buddyListHandler.AddGroup))
  192. mux.Handle("GET /buddylist/removeBuddy", oscarRoute(wire.Feedbag, wire.FeedbagDeleteItem, buddyListHandler.RemoveBuddy))
  193. mux.Handle("GET /buddylist/removeGroup", oscarRoute(wire.Feedbag, wire.FeedbagDeleteItem, buddyListHandler.RemoveGroup))
  194. mux.Handle("GET /buddylist/renameGroup", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.RenameGroup))
  195. mux.Handle("GET /buddylist/moveBuddy", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.MoveBuddy))
  196. mux.Handle("GET /buddylist/setBuddyAttribute", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.SetBuddyAttribute))
  197. mux.Handle("GET /buddylist/setGroupAttribute", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, buddyListHandler.SetGroupAttribute))
  198. // sendIM supports aimsid-based auth, so we use flexible auth.
  199. // The Web AIM client POSTs the message body (non-IE browsers); IE uses GET.
  200. sendIMHandler := oscarRoute(wire.ICBM, wire.ICBMChannelMsgToHost, messagingHandler.SendIM)
  201. mux.Handle("GET /im/sendIM", sendIMHandler)
  202. mux.Handle("POST /im/sendIM", sendIMHandler)
  203. mux.Handle("GET /im/setTyping", oscarRoute(wire.ICBM, wire.ICBMClientEvent, messagingHandler.SetTyping))
  204. // SetState only requires aimsid, no k parameter needed
  205. mux.Handle("GET /presence/setState", oscarRoute(wire.OService, wire.OServiceSetUserInfoFields, presenceHandler.SetState))
  206. // These presence endpoints support aimsid-based auth where k is not required
  207. mux.Handle("GET /presence/setStatus", oscarRoute(wire.OService, wire.OServiceSetUserInfoFields, presenceHandler.SetStatus))
  208. mux.Handle("GET /presence/setProfile", oscarRoute(wire.Locate, wire.LocateSetInfo, presenceHandler.SetProfile))
  209. mux.Handle("GET /presence/getProfile", oscarRoute(wire.Locate, wire.LocateUserInfoQuery, presenceHandler.GetProfile))
  210. // Unauthenticated, like /expressions/get below: buddy icons load as plain
  211. // <img> sources that carry no aimsid.
  212. mux.Handle("GET /presence/icon", http.HandlerFunc(presenceHandler.Icon))
  213. // Member directory search and self directory-info retrieval. Both use
  214. // aimsid-based auth, so we use flexible auth.
  215. mux.Handle("GET /memberDir/search", oscarRoute(wire.ODir, wire.ODirInfoQuery, memberDirHandler.Search))
  216. mux.Handle("GET /memberDir/get", oscarRoute(wire.Locate, wire.LocateGetDirInfo, memberDirHandler.Get))
  217. // Both methods: Go 1.22 patterns are method-exact and clients differ.
  218. memberDirUpdate := oscarRoute(wire.Locate, wire.LocateSetDirInfo, memberDirHandler.Update)
  219. mux.Handle("GET /memberDir/update", memberDirUpdate)
  220. mux.Handle("POST /memberDir/update", memberDirUpdate)
  221. // These endpoints support aimsid-based auth, so we use a flexible auth approach
  222. mux.Handle("GET /preference/set", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, preferenceHandler.SetPreferences))
  223. mux.Handle("GET /preference/get", oscarRoute(wire.Feedbag, wire.FeedbagQuery, preferenceHandler.GetPreferences))
  224. mux.Handle("GET /preference/setPermitDeny", oscarRoute(wire.Feedbag, wire.FeedbagUpdateItem, preferenceHandler.SetPermitDeny))
  225. mux.Handle("GET /preference/getPermitDeny", oscarRoute(wire.Feedbag, wire.FeedbagQuery, preferenceHandler.GetPermitDeny))
  226. // Expressions endpoint (for buddy icons, etc.).
  227. //
  228. // Unauthenticated, like /presence/icon: the buddyIcon URLs this serves are
  229. // published to the client and loaded as plain <img> sources, which carry
  230. // neither an aimsid nor an API key. Threading a session token through them
  231. // instead would leak it into the DOM and defeat caching, since these URLs
  232. // outlive the session that produced them. Buddy icons are public assets.
  233. expressionsHandler := NewExpressionsHandler(
  234. handler.IconSource, handler.BARTService, handler.FeedbagService, logger)
  235. mux.Handle("GET /expressions/get",
  236. authMiddleware.CORSMiddleware(
  237. http.HandlerFunc(expressionsHandler.Get)))
  238. // WithBinaryBody: the body is the raw image, and a missed parameter lookup
  239. // would otherwise feed it to ParseForm and consume it.
  240. mux.Handle("POST /expressions/upload",
  241. WithBinaryBody(oscarRoute(wire.BART, wire.BARTUploadQuery, expressionsHandler.Upload)))
  242. // Web AIM calls lifestream/* on the API host (e.g. /lifestream/getUserDetails).
  243. lifestreamStub := &UserInfoStubHandler{Logger: logger}
  244. // getUserDetails returns a minimal AIM identity and getServices the service
  245. // list behind it. Every other lifestream/* method is an unimplemented
  246. // social-feed feature; the subtree catch-all acknowledges them with an
  247. // empty 200 so the client doesn't error.
  248. mux.Handle("GET /lifestream/getUserDetails", stubRoute(lifestreamStub.GetUserDetails))
  249. mux.Handle("GET /lifestream/getServices", stubRoute(lifestreamStub.GetServices))
  250. mux.Handle("GET /lifestream/heyGetNotifications", stubRoute(lifestreamStub.HeyGetNotifications))
  251. mux.Handle("GET /lifestream/", stubRoute(lifestreamStub.EmptyOK))
  252. // The client probes for a linked Google Talk account as soon as the
  253. // session comes up, and its callback dereferences response.data unless
  254. // the status says the service is absent.
  255. serviceStub := &ServiceStubHandler{Logger: logger}
  256. mux.Handle("GET /service/getAttributes", stubRoute(serviceStub.GetAttributes))
  257. // Go 1.22 patterns are method-exact, so an OPTIONS preflight matches none of
  258. // the "GET /x" routes above and would otherwise fall through to the 404
  259. // handler, failing the preflight. CORSMiddleware answers OPTIONS with a 204
  260. // and the appropriate headers before ever reaching the handler below.
  261. mux.Handle("OPTIONS /", authMiddleware.CORSMiddleware(
  262. http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})))
  263. // Unmatched paths (pattern "/" matches anything not covered by routes above).
  264. //
  265. // Wrapped in CORS: the client probes endpoints this server does not
  266. // implement (/service/getAttributes, /metrics/sendIM), and a 404 without
  267. // Access-Control-Allow-Origin is blocked by the browser rather than read as
  268. // a 404, which latches the client into JSONP for the rest of the session.
  269. mux.Handle("/", authMiddleware.CORSMiddleware(
  270. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  271. logger.Debug("webapi 404", "method", r.Method, "path", r.URL.Path)
  272. SendError(w, r, http.StatusNotFound, "not found")
  273. })))
  274. servers = append(servers, &http.Server{
  275. Addr: l,
  276. Handler: RequestLogger(logger, mux),
  277. })
  278. }
  279. aimHandler.FnSessCfg = func(sess *state.Session) {
  280. sess.OnSessionClose(func() {
  281. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  282. defer cancel()
  283. if !shuttingDown(shutdownCtx) {
  284. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(ctx, sess.IdentScreenName()); err != nil {
  285. logger.ErrorContext(ctx, "error sending buddy departure notifications", "err", err.Error())
  286. }
  287. }
  288. // buddy list must be cleared before session is closed, otherwise
  289. // there will be a race condition that could cause the buddy list
  290. // be prematurely deleted.
  291. if err := handler.BuddyListRegistry.UnregisterBuddyList(ctx, sess.IdentScreenName()); err != nil {
  292. logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  293. }
  294. handler.ChatSessionManager.RemoveUserFromAllChats(sess.IdentScreenName())
  295. handler.AuthService.Signout(ctx, sess)
  296. })
  297. }
  298. aimHandler.FnSessInit = func(instance *state.SessionInstance) func() error {
  299. return func() error {
  300. // make buddy list visible to other users
  301. if err := handler.BuddyListRegistry.RegisterBuddyList(shutdownCtx, instance.IdentScreenName()); err != nil {
  302. return fmt.Errorf("unable to init buddy list: %w", err)
  303. }
  304. // restore warning level from last session
  305. if err := handler.RecalcWarning(shutdownCtx, instance); err != nil {
  306. return fmt.Errorf("failed to recalculate warning level: %w", err)
  307. }
  308. // periodically decay warning level
  309. go handler.LowerWarnLevel(shutdownCtx, instance)
  310. // broadcast rate limit transitions to every instance on the account
  311. go handler.OServiceService.MonitorRateLimits(shutdownCtx, instance.Session())
  312. return nil
  313. }
  314. }
  315. aimHandler.FnInstanceClose = func(instance *state.SessionInstance) func() {
  316. return func() {
  317. if shuttingDown(shutdownCtx) {
  318. return
  319. }
  320. if instance.Session().Invisible() {
  321. if err := handler.BuddyBroadcaster.BroadcastBuddyDeparted(shutdownCtx, instance.IdentScreenName()); err != nil {
  322. logger.ErrorContext(shutdownCtx, "error sending buddy departure notifications", "err", err.Error())
  323. }
  324. } else {
  325. if err := handler.BuddyBroadcaster.BroadcastBuddyArrived(shutdownCtx, instance.IdentScreenName(), instance.Session().TLVUserInfo()); err != nil {
  326. logger.ErrorContext(shutdownCtx, "error sending buddy arrival notifications", "err", err.Error())
  327. }
  328. }
  329. }
  330. }
  331. return &Server{
  332. servers: servers,
  333. logger: logger,
  334. sessionManager: sessionManager,
  335. shutdownCtx: shutdownCtx,
  336. shutdownCancel: shutdownCancel,
  337. }
  338. }
  339. // Server hosts an HTTP endpoint capable of handling AIM-style Kerberos
  340. // authentication. The messages are structured as SNACs transmitted over HTTP.
  341. //
  342. // shutdownCtx bounds the lifetime of the background session reaper: ListenAndServe
  343. // drives it, and Shutdown (or a failed listener) calls shutdownCancel to unwind.
  344. type Server struct {
  345. servers []*http.Server
  346. logger *slog.Logger
  347. sessionManager *SessionManager
  348. shutdownCtx context.Context
  349. shutdownCancel context.CancelFunc
  350. }
  351. func (s *Server) ListenAndServe() error {
  352. if len(s.servers) == 0 {
  353. s.logger.Debug("no webapi listeners defined")
  354. return nil
  355. }
  356. g, ctx := errgroup.WithContext(s.shutdownCtx)
  357. g.Go(func() error {
  358. s.sessionManager.Run(ctx)
  359. return nil
  360. })
  361. for _, server := range s.servers {
  362. g.Go(func() error {
  363. s.logger.Info("starting server", "addr", server.Addr)
  364. if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
  365. s.shutdownCancel()
  366. return fmt.Errorf("unable to start webapi server: %w", err)
  367. }
  368. return nil
  369. })
  370. }
  371. return g.Wait()
  372. }
  373. func (s *Server) Shutdown(ctx context.Context) error {
  374. s.logger.Debug("Initiating graceful shutdown...")
  375. s.shutdownCancel() // stop the session reaper so ListenAndServe's errgroup can drain
  376. var errs []error
  377. if err := s.sessionManager.Shutdown(ctx); err != nil {
  378. errs = append(errs, fmt.Errorf("draining webapi sessions: %w", err))
  379. }
  380. for _, srv := range s.servers {
  381. if err := srv.Shutdown(ctx); err != nil {
  382. errs = append(errs, fmt.Errorf("stopping webapi listener %s: %w", srv.Addr, err))
  383. }
  384. }
  385. if err := errors.Join(errs...); err != nil {
  386. s.logger.Error("shutdown incomplete", "err", err.Error())
  387. return err
  388. }
  389. s.logger.Info("shutdown complete")
  390. return nil
  391. }
  392. func shuttingDown(ctx context.Context) bool {
  393. select {
  394. case <-ctx.Done():
  395. // server is shutting down, don't send buddy notifications
  396. return true
  397. default:
  398. }
  399. return false
  400. }
  401. type Handler struct {
  402. AuthService AuthService
  403. BuddyListRegistry BuddyListRegistry
  404. ICBMService ICBMService
  405. LocateService LocateService
  406. Logger *slog.Logger
  407. OServiceService OServiceService
  408. BuddyBroadcaster BuddyBroadcaster
  409. BOSListener config.ListenerGroup
  410. BuddyListManager *BuddyListManager
  411. RecalcWarning func(ctx context.Context, instance *state.SessionInstance) error
  412. LowerWarnLevel func(ctx context.Context, instance *state.SessionInstance)
  413. ChatSessionManager ChatSessionManager
  414. FeedbagService FeedbagService
  415. DirSearchService DirSearchService
  416. IconSource BuddyIconSource
  417. BARTService BARTService
  418. SNACRateLimits wire.SNACRateLimits
  419. }
  420. func (h Handler) GetHelloWorldHandler(w http.ResponseWriter, r *http.Request) {
  421. _, _ = fmt.Fprintf(w, "WebAPI Server Running\n")
  422. // Must return the same JSON envelope as other Web AIM APIs.
  423. h.Logger.Info("webapi root GET", "remote", r.RemoteAddr, "host", r.Host, "path", r.URL.Path)
  424. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  425. resp := map[string]interface{}{
  426. "response": map[string]interface{}{
  427. "statusCode": 200,
  428. "statusText": "Ok",
  429. "data": map[string]interface{}{},
  430. },
  431. }
  432. _ = json.NewEncoder(w).Encode(resp)
  433. }