common.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package handlers
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "encoding/json"
  6. "encoding/xml"
  7. "fmt"
  8. "log/slog"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "github.com/mk6i/open-oscar-server/state"
  13. )
  14. // SessionRetriever provides methods to retrieve OSCAR sessions.
  15. type SessionRetriever interface {
  16. AllSessions() []*state.Session
  17. RetrieveSession(screenName state.IdentScreenName) *state.Session
  18. }
  19. // CommonHandler provides shared utilities for all Web API handlers.
  20. type CommonHandler struct {
  21. Logger *slog.Logger
  22. }
  23. // BaseResponse is the standard response envelope for all Web API responses.
  24. // It supports both JSON and XML marshaling.
  25. type BaseResponse struct {
  26. XMLName xml.Name `xml:"response" json:"-"`
  27. Response ResponseBody `json:"response"`
  28. }
  29. // ResponseBody contains the status and data for API responses.
  30. type ResponseBody struct {
  31. StatusCode int `json:"statusCode" xml:"statusCode"`
  32. StatusText string `json:"statusText" xml:"statusText"`
  33. RequestID string `json:"requestId,omitempty" xml:"requestId,omitempty"`
  34. Data interface{} `json:"data,omitempty" xml:"data,omitempty"`
  35. }
  36. // ErrorResponse represents an error response with proper XML/JSON support.
  37. type ErrorResponse struct {
  38. XMLName xml.Name `xml:"response" json:"-"`
  39. Response struct {
  40. StatusCode int `json:"statusCode" xml:"statusCode"`
  41. StatusText string `json:"statusText" xml:"statusText"`
  42. } `json:"response" xml:"-"`
  43. // For XML responses, flatten the structure
  44. StatusCode int `json:"-" xml:"statusCode"`
  45. StatusText string `json:"-" xml:"statusText"`
  46. }
  47. // XMLMapResponse is a helper struct for converting map-based responses to XML
  48. type XMLMapResponse struct {
  49. XMLName xml.Name `xml:"response"`
  50. StatusCode int `xml:"statusCode"`
  51. StatusText string `xml:"statusText"`
  52. Data XMLData `xml:"data,omitempty"`
  53. }
  54. // XMLData wraps the data for XML responses
  55. type XMLData struct {
  56. // Auth response fields
  57. Token *XMLToken `xml:"token,omitempty"`
  58. LoginID string `xml:"loginId,omitempty"`
  59. ScreenName string `xml:"screenName,omitempty"`
  60. SessionSecret string `xml:"sessionSecret,omitempty"`
  61. HostTime int64 `xml:"hostTime,omitempty"`
  62. TokenExpiresIn int `xml:"tokenExpiresIn,omitempty"`
  63. // Generic fields for other responses
  64. AimSID string `xml:"aimsid,omitempty"`
  65. FetchURL string `xml:"fetchUrl,omitempty"`
  66. MsgID string `xml:"msgId,omitempty"`
  67. State string `xml:"state,omitempty"`
  68. // For any other data, we'll encode as string
  69. Raw string `xml:",chardata"`
  70. }
  71. // XMLToken represents the token structure in XML
  72. type XMLToken struct {
  73. A string `xml:"a"`
  74. ExpiresIn int `xml:"expiresIn"`
  75. }
  76. // requestIDFromRequest returns the Web AIM client request correlation id from the
  77. // "r" query parameter. JSONP callbacks require this echoed in response.requestId.
  78. func requestIDFromRequest(r *http.Request) string {
  79. if r == nil {
  80. return ""
  81. }
  82. return r.URL.Query().Get("r")
  83. }
  84. // attachRequestID copies the request's "r" parameter into BaseResponse.requestId
  85. // when the handler did not set one explicitly.
  86. func attachRequestID(r *http.Request, data interface{}) interface{} {
  87. id := requestIDFromRequest(r)
  88. if id == "" {
  89. return data
  90. }
  91. br, ok := data.(BaseResponse)
  92. if !ok || br.Response.RequestID != "" {
  93. return data
  94. }
  95. br.Response.RequestID = id
  96. return br
  97. }
  98. // SendResponse sends a response in the requested format (JSON, JSONP, XML, or AMF).
  99. // This is the centralized function that all handlers should use for responses.
  100. func SendResponse(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  101. data = attachRequestID(r, data)
  102. // Check for format parameter (f for format or callback for JSONP)
  103. // First check URL query parameters
  104. format := strings.ToLower(r.URL.Query().Get("f"))
  105. callback := JSONPCallback(r)
  106. // If format not in URL query, check form values (for POST requests)
  107. if format == "" && r.Method == "POST" {
  108. _ = r.ParseForm()
  109. format = strings.ToLower(r.FormValue("f"))
  110. if callback == "" {
  111. callback = JSONPCallback(r)
  112. }
  113. }
  114. // Check for AMF format first
  115. if format == "amf" || format == "amf3" {
  116. SendAMF(w, r, data, logger)
  117. return
  118. }
  119. // Check Accept header for AMF
  120. accept := strings.ToLower(r.Header.Get("Accept"))
  121. if strings.Contains(accept, "application/x-amf") ||
  122. strings.Contains(accept, "application/amf") {
  123. SendAMF(w, r, data, logger)
  124. return
  125. }
  126. // If callback is provided, it's JSONP
  127. if callback != "" {
  128. SendJSONP(w, callback, data, logger)
  129. return
  130. }
  131. // Check for XML format
  132. if format == "xml" {
  133. SendXML(w, data, logger)
  134. return
  135. }
  136. // Default to JSON
  137. SendJSON(w, data, logger)
  138. }
  139. // SendError sends an error response in the appropriate format.
  140. func SendError(w http.ResponseWriter, statusCode int, message string) {
  141. // Try to detect format from Content-Type header if already set
  142. contentType := w.Header().Get("Content-Type")
  143. if strings.Contains(contentType, "amf") {
  144. SendAMFError(w, nil, statusCode, message, nil)
  145. } else if strings.Contains(contentType, "xml") {
  146. SendXMLError(w, statusCode, message)
  147. } else {
  148. SendJSONError(w, statusCode, message)
  149. }
  150. }
  151. // SendJSONError sends a JSON error response.
  152. func SendJSONError(w http.ResponseWriter, statusCode int, message string) {
  153. resp := ErrorResponse{}
  154. resp.Response.StatusCode = statusCode
  155. resp.Response.StatusText = message
  156. w.Header().Set("Content-Type", "application/json")
  157. w.WriteHeader(statusCode)
  158. _ = json.NewEncoder(w).Encode(resp)
  159. }
  160. // SendXMLError sends an XML error response.
  161. func SendXMLError(w http.ResponseWriter, statusCode int, message string) {
  162. resp := ErrorResponse{}
  163. resp.StatusCode = statusCode
  164. resp.StatusText = message
  165. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  166. w.WriteHeader(statusCode)
  167. // Write XML declaration and marshal the response
  168. xmlData, err := xml.Marshal(resp)
  169. if err != nil {
  170. // Fall back to simple text response
  171. http.Error(w, message, statusCode)
  172. return
  173. }
  174. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  175. _, _ = w.Write([]byte(xmlOutput))
  176. }
  177. // SendJSON sends a JSON response.
  178. func SendJSON(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  179. w.Header().Set("Content-Type", "application/json")
  180. body, err := json.Marshal(data)
  181. if err != nil {
  182. if logger != nil {
  183. logger.Error("failed to encode JSON response", "err", err.Error())
  184. }
  185. return
  186. }
  187. if logger != nil {
  188. logger.Debug("JSON response", "body", string(body))
  189. }
  190. if _, err := w.Write(body); err != nil && logger != nil {
  191. logger.Error("failed to write JSON response", "err", err.Error())
  192. }
  193. }
  194. // SendXML sends an XML response.
  195. func SendXML(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  196. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  197. // Convert BaseResponse with map data to a format XML can handle
  198. if baseResp, ok := data.(BaseResponse); ok {
  199. data = convertBaseResponseForXML(baseResp)
  200. }
  201. // Marshal the data
  202. xmlData, err := xml.Marshal(data)
  203. if err != nil {
  204. if logger != nil {
  205. logger.Error("failed to marshal XML response", "err", err.Error())
  206. }
  207. SendXMLError(w, http.StatusInternalServerError, "internal server error")
  208. return
  209. }
  210. // Write XML declaration and data
  211. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  212. // Set content length for proper response handling
  213. w.Header().Set("Content-Length", strconv.Itoa(len(xmlOutput)))
  214. _, _ = w.Write([]byte(xmlOutput))
  215. }
  216. // JSONPCallback returns the JSONP callback name from the request.
  217. // Web AIM clients use the "c" query parameter; other callers may use "callback".
  218. func JSONPCallback(r *http.Request) string {
  219. if callback := r.URL.Query().Get("c"); callback != "" {
  220. return callback
  221. }
  222. return r.URL.Query().Get("callback")
  223. }
  224. // SendJSONP sends a JSONP response with the specified callback.
  225. func SendJSONP(w http.ResponseWriter, callback string, data interface{}, logger *slog.Logger) {
  226. // Validate callback to prevent XSS
  227. if !IsValidCallback(callback) {
  228. SendJSONError(w, http.StatusBadRequest, "invalid callback parameter")
  229. return
  230. }
  231. jsonData, err := json.Marshal(data)
  232. if err != nil {
  233. if logger != nil {
  234. logger.Error("failed to marshal response", "err", err.Error())
  235. }
  236. SendJSONError(w, http.StatusInternalServerError, "internal server error")
  237. return
  238. }
  239. w.Header().Set("Content-Type", "application/javascript")
  240. _, _ = w.Write([]byte(callback))
  241. _, _ = w.Write([]byte("("))
  242. _, _ = w.Write(jsonData)
  243. _, _ = w.Write([]byte(");"))
  244. }
  245. // IsValidCallback validates a JSONP callback name to prevent XSS.
  246. func IsValidCallback(callback string) bool {
  247. if len(callback) == 0 || len(callback) > 100 {
  248. return false
  249. }
  250. // Allow alphanumeric, underscore, dollar sign, and dot (for namespace)
  251. for _, r := range callback {
  252. if (r < 'a' || r > 'z') &&
  253. (r < 'A' || r > 'Z') &&
  254. (r < '0' || r > '9') &&
  255. r != '_' && r != '$' && r != '.' {
  256. return false
  257. }
  258. }
  259. return true
  260. }
  261. // SendAMF sends an AMF response
  262. func SendAMF(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  263. encoder := NewAMFEncoder(logger)
  264. version := DetectAMFVersion(r)
  265. amfData, err := encoder.EncodeAMF(data, version)
  266. if err != nil {
  267. if logger != nil {
  268. logger.Error("failed to encode AMF response",
  269. "err", err.Error(),
  270. "version", version,
  271. "dataType", fmt.Sprintf("%T", data))
  272. }
  273. // Fall back to JSON error
  274. SendJSONError(w, http.StatusInternalServerError, "AMF encoding failed")
  275. return
  276. }
  277. w.Header().Set("Content-Type", "application/x-amf")
  278. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  279. // Debug logging if enabled
  280. if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
  281. hexPreview := ""
  282. if len(amfData) > 0 {
  283. previewLen := len(amfData)
  284. if previewLen > 64 {
  285. previewLen = 64
  286. }
  287. hexPreview = hex.EncodeToString(amfData[:previewLen])
  288. }
  289. logger.Debug("sending AMF response",
  290. "version", version,
  291. "size", len(amfData),
  292. "path", r.URL.Path,
  293. "hexPreview", hexPreview)
  294. }
  295. if _, err := w.Write(amfData); err != nil {
  296. if logger != nil {
  297. logger.Error("failed to write AMF response",
  298. "err", err.Error())
  299. }
  300. }
  301. }
  302. // convertBaseResponseForXML converts a BaseResponse with map data to XMLMapResponse
  303. func convertBaseResponseForXML(resp BaseResponse) XMLMapResponse {
  304. xmlResp := XMLMapResponse{
  305. StatusCode: resp.Response.StatusCode,
  306. StatusText: resp.Response.StatusText,
  307. }
  308. // Convert map data to XMLData struct
  309. if dataMap, ok := resp.Response.Data.(map[string]interface{}); ok {
  310. xmlData := XMLData{}
  311. // Handle auth response fields
  312. if tokenData, ok := dataMap["token"].(map[string]interface{}); ok {
  313. xmlData.Token = &XMLToken{}
  314. if a, ok := tokenData["a"].(string); ok {
  315. xmlData.Token.A = a
  316. }
  317. if expiresIn, ok := tokenData["expiresIn"].(int); ok {
  318. xmlData.Token.ExpiresIn = expiresIn
  319. }
  320. }
  321. if loginId, ok := dataMap["loginId"].(string); ok {
  322. xmlData.LoginID = loginId
  323. }
  324. if screenName, ok := dataMap["screenName"].(string); ok {
  325. xmlData.ScreenName = screenName
  326. }
  327. if sessionSecret, ok := dataMap["sessionSecret"].(string); ok {
  328. xmlData.SessionSecret = sessionSecret
  329. }
  330. if hostTime, ok := dataMap["hostTime"].(int64); ok {
  331. xmlData.HostTime = hostTime
  332. }
  333. if tokenExpiresIn, ok := dataMap["tokenExpiresIn"].(int); ok {
  334. xmlData.TokenExpiresIn = tokenExpiresIn
  335. }
  336. // Handle session response fields
  337. if aimsid, ok := dataMap["aimsid"].(string); ok {
  338. xmlData.AimSID = aimsid
  339. }
  340. if fetchUrl, ok := dataMap["fetchUrl"].(string); ok {
  341. xmlData.FetchURL = fetchUrl
  342. }
  343. // Handle message response fields
  344. if msgId, ok := dataMap["msgId"].(string); ok {
  345. xmlData.MsgID = msgId
  346. }
  347. if state, ok := dataMap["state"].(string); ok {
  348. xmlData.State = state
  349. }
  350. xmlResp.Data = xmlData
  351. }
  352. return xmlResp
  353. }
  354. // SendAMFError sends an AMF error response
  355. func SendAMFError(w http.ResponseWriter, r *http.Request, statusCode int, message string, logger *slog.Logger) {
  356. errorResp := ErrorResponse{}
  357. errorResp.Response.StatusCode = statusCode
  358. errorResp.Response.StatusText = message
  359. encoder := NewAMFEncoder(logger)
  360. version := DetectAMFVersion(r)
  361. amfData, err := encoder.EncodeAMF(errorResp, version)
  362. if err != nil {
  363. // If AMF encoding fails, fall back to JSON error
  364. SendJSONError(w, statusCode, message)
  365. return
  366. }
  367. w.Header().Set("Content-Type", "application/x-amf")
  368. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  369. w.WriteHeader(statusCode)
  370. _, _ = w.Write(amfData)
  371. }