common.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. )
  13. // BaseResponse is the standard response envelope for all Web API responses.
  14. // It supports both JSON and XML marshaling.
  15. type BaseResponse struct {
  16. Response ResponseBody `json:"response"`
  17. }
  18. // MarshalXML renders the envelope as the Web API's flat <response> root, where
  19. // JSON nests the same body under a "response" key. Reconciling the two shapes
  20. // here is what lets one struct describe a response in both formats.
  21. func (b BaseResponse) MarshalXML(e *xml.Encoder, _ xml.StartElement) error {
  22. return e.EncodeElement(b.Response, xml.StartElement{Name: xml.Name{Local: "response"}})
  23. }
  24. // ResponseBody contains the status and data for API responses.
  25. type ResponseBody struct {
  26. StatusCode int `json:"statusCode" xml:"statusCode"`
  27. StatusText string `json:"statusText" xml:"statusText"`
  28. RequestID string `json:"requestId,omitempty" xml:"requestId,omitempty"`
  29. // Data is never omitted. Every Web API method sends a data element even when
  30. // it carries no payload, and the client dereferences response.data on any
  31. // success; SendResponse substitutes an empty object when a handler sets none.
  32. Data interface{} `json:"data" xml:"data"`
  33. }
  34. // ErrorResponse represents an error response with proper XML/JSON support.
  35. type ErrorResponse struct {
  36. Response struct {
  37. StatusCode int `json:"statusCode" xml:"statusCode"`
  38. // StatusDetailCode names which failure of a status code this is, e.g. 3011
  39. // (bad password) under 330. Omitted when unset, which a client would
  40. // otherwise read as a detail code of its own.
  41. StatusDetailCode int `json:"statusDetailCode,omitempty" xml:"statusDetailCode,omitempty"`
  42. StatusText string `json:"statusText" xml:"statusText"`
  43. // Data carries an empty object for the same reason the JSONP error path
  44. // sends one: a client callback that reaches response.data on a failure
  45. // throws a TypeError when it is absent.
  46. Data interface{} `json:"data" xml:"data"`
  47. } `json:"response"`
  48. }
  49. // MarshalXML renders the error envelope with the same flat root as BaseResponse.
  50. func (e ErrorResponse) MarshalXML(enc *xml.Encoder, _ xml.StartElement) error {
  51. return enc.EncodeElement(e.Response, xml.StartElement{Name: xml.Name{Local: "response"}})
  52. }
  53. // newErrorResponse builds the error envelope every format shares.
  54. func newErrorResponse(statusCode int, message string) ErrorResponse {
  55. return newErrorResponseDetail(statusCode, 0, message)
  56. }
  57. // newErrorResponseDetail builds the error envelope with a statusDetailCode.
  58. func newErrorResponseDetail(statusCode, detailCode int, message string) ErrorResponse {
  59. resp := ErrorResponse{}
  60. resp.Response.StatusCode = statusCode
  61. resp.Response.StatusDetailCode = detailCode
  62. resp.Response.StatusText = message
  63. resp.Response.Data = struct{}{}
  64. return resp
  65. }
  66. // requestFormat returns the format the client asked for. A POST sends "f" in
  67. // its body, as clientLogin does.
  68. func requestFormat(r *http.Request) string {
  69. format := strings.ToLower(r.URL.Query().Get("f"))
  70. if format == "" && r.Method == http.MethodPost {
  71. _ = r.ParseForm()
  72. format = strings.ToLower(r.FormValue("f"))
  73. }
  74. return format
  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. // normalizeEnvelope fills in the envelope fields a handler does not set itself:
  85. // the request correlation id, and an empty data object for a response that
  86. // carries no payload. Both are things every encoder needs and none can infer —
  87. // and encoding/xml has no way to render a nil data at all.
  88. func normalizeEnvelope(r *http.Request, data interface{}) interface{} {
  89. br, ok := data.(BaseResponse)
  90. if !ok {
  91. return data
  92. }
  93. if br.Response.RequestID == "" {
  94. br.Response.RequestID = requestIDFromRequest(r)
  95. }
  96. if br.Response.Data == nil {
  97. br.Response.Data = struct{}{}
  98. }
  99. return br
  100. }
  101. // SendResponse sends a response in the requested format (JSON, JSONP, XML, or AMF).
  102. // This is the centralized function that all handlers should use for responses.
  103. func SendResponse(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  104. data = normalizeEnvelope(r, data)
  105. format := requestFormat(r)
  106. callback := jsonpCallback(r)
  107. // Check for AMF format first
  108. if format == "amf" || format == "amf3" {
  109. sendAMF(w, r, data, logger)
  110. return
  111. }
  112. // Check Accept header for AMF
  113. accept := strings.ToLower(r.Header.Get("Accept"))
  114. if strings.Contains(accept, "application/x-amf") ||
  115. strings.Contains(accept, "application/amf") {
  116. sendAMF(w, r, data, logger)
  117. return
  118. }
  119. // If callback is provided, it's JSONP
  120. if callback != "" {
  121. sendJSONP(w, r, callback, data, logger)
  122. return
  123. }
  124. // Check for XML format
  125. if format == "xml" {
  126. sendXML(w, data, logger)
  127. return
  128. }
  129. // Default to JSON
  130. sendJSON(w, data, logger)
  131. }
  132. // SendError sends an error response in the format the client asked for.
  133. //
  134. // When the client requested JSONP, the error must be delivered as an executable
  135. // callback: a bare JSON body inside a <script> tag is a syntax error, which the
  136. // Web AIM client reports as the generic "Failed to load script tag, probably
  137. // malformed JS at that url" instead of the real statusText.
  138. func SendError(w http.ResponseWriter, r *http.Request, statusCode int, message string) {
  139. sendErrorEnvelope(w, r, statusCode, newErrorResponse(statusCode, message))
  140. }
  141. // SendErrorDetail sends an error carrying a statusDetailCode, which is how a
  142. // client tells one failure of a status code from another. The HTTP status is
  143. // separate because the API codes are not HTTP codes: a bad clientLogin password
  144. // is 330/3011 on an HTTP 401.
  145. func SendErrorDetail(w http.ResponseWriter, r *http.Request, httpStatus, statusCode, detailCode int, message string) {
  146. sendErrorEnvelope(w, r, httpStatus, newErrorResponseDetail(statusCode, detailCode, message))
  147. }
  148. // sendErrorEnvelope writes an error envelope in the format the client asked for.
  149. func sendErrorEnvelope(w http.ResponseWriter, r *http.Request, httpStatus int, resp ErrorResponse) {
  150. if callback := jsonpCallback(r); callback != "" && isValidCallback(callback) {
  151. sendJSONPError(w, r, callback, resp)
  152. return
  153. }
  154. // A client that gets a format it cannot parse reports the failure as an
  155. // unreadable response rather than as this statusText. The Content-Type is the
  156. // fallback signal, naming the format a handler already began writing.
  157. format := requestFormat(r)
  158. contentType := w.Header().Get("Content-Type")
  159. switch {
  160. case format == "xml" || strings.Contains(contentType, "xml"):
  161. sendXMLError(w, httpStatus, resp)
  162. case format == "amf" || format == "amf3" || strings.Contains(contentType, "amf"):
  163. sendAMFError(w, r, httpStatus, resp, nil)
  164. default:
  165. sendJSONError(w, httpStatus, resp)
  166. }
  167. }
  168. // sendJSONPError writes an error envelope wrapped in the client's JSONP callback.
  169. //
  170. // The HTTP status is deliberately left at 200: browsers do not execute the body
  171. // of a <script> tag that came back with a 4xx or 5xx, so a status-carrying JSONP
  172. // error never reaches the callback at all. The real status travels in the
  173. // envelope, which is where the Web AIM client reads it from regardless.
  174. func sendJSONPError(w http.ResponseWriter, r *http.Request, callback string, resp ErrorResponse) {
  175. envelope := map[string]any{
  176. "statusCode": resp.Response.StatusCode,
  177. "statusText": resp.Response.StatusText,
  178. // Callbacks that reach response.data on a failure throw a TypeError when
  179. // it is absent, which aborts whatever the client was doing mid-startup.
  180. // Its XHR path fabricates an empty data for transport failures; JSONP
  181. // delivers the envelope verbatim, so the empty data has to come from here.
  182. "data": map[string]any{},
  183. }
  184. if resp.Response.StatusDetailCode != 0 {
  185. envelope["statusDetailCode"] = resp.Response.StatusDetailCode
  186. }
  187. // The client indexes JSONP replies by response.requestId and discards any
  188. // reply that lacks one ("Request id is missing from the server response"),
  189. // leaving the request pending until it times out.
  190. if id := requestIDFromRequest(r); id != "" {
  191. envelope["requestId"] = id
  192. }
  193. body, err := json.Marshal(map[string]any{"response": envelope})
  194. if err != nil {
  195. sendJSONError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  196. return
  197. }
  198. w.Header().Set("Content-Type", "application/javascript")
  199. _, _ = w.Write([]byte(callback))
  200. _, _ = w.Write([]byte("("))
  201. _, _ = w.Write(body)
  202. _, _ = w.Write([]byte(");"))
  203. }
  204. // sendJSONError sends a JSON error response.
  205. func sendJSONError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  206. w.Header().Set("Content-Type", "application/json")
  207. w.WriteHeader(httpStatus)
  208. _ = json.NewEncoder(w).Encode(resp)
  209. }
  210. // sendXMLError sends an XML error response.
  211. func sendXMLError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  212. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  213. w.WriteHeader(httpStatus)
  214. // Write XML declaration and marshal the response
  215. xmlData, err := xml.Marshal(resp)
  216. if err != nil {
  217. // Fall back to simple text response
  218. http.Error(w, resp.Response.StatusText, httpStatus)
  219. return
  220. }
  221. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  222. _, _ = w.Write([]byte(xmlOutput))
  223. }
  224. // sendJSON sends a JSON response.
  225. func sendJSON(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  226. w.Header().Set("Content-Type", "application/json")
  227. body, err := json.Marshal(data)
  228. if err != nil {
  229. if logger != nil {
  230. logger.Error("failed to encode JSON response", "err", err.Error())
  231. }
  232. return
  233. }
  234. if logger != nil {
  235. logger.Debug("JSON response", "body", string(body))
  236. }
  237. if _, err := w.Write(body); err != nil && logger != nil {
  238. logger.Error("failed to write JSON response", "err", err.Error())
  239. }
  240. }
  241. // sendXML sends an XML response.
  242. func sendXML(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  243. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  244. // Every payload is a struct whose xml tags name its elements, and the
  245. // envelope's MarshalXML renders the flat <response> root the Web API uses.
  246. xmlData, err := xml.Marshal(data)
  247. if err != nil {
  248. if logger != nil {
  249. logger.Error("failed to marshal XML response", "err", err.Error())
  250. }
  251. sendXMLError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  252. return
  253. }
  254. // Write XML declaration and data
  255. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  256. // Set content length for proper response handling
  257. w.Header().Set("Content-Length", strconv.Itoa(len(xmlOutput)))
  258. _, _ = w.Write([]byte(xmlOutput))
  259. }
  260. // jsonpCallback returns the JSONP callback name from the request.
  261. // Web AIM clients use the "c" query parameter; other callers may use "callback".
  262. func jsonpCallback(r *http.Request) string {
  263. if r == nil {
  264. return ""
  265. }
  266. if callback := r.URL.Query().Get("c"); callback != "" {
  267. return callback
  268. }
  269. return r.URL.Query().Get("callback")
  270. }
  271. // sendJSONP sends a JSONP response with the specified callback.
  272. func sendJSONP(w http.ResponseWriter, r *http.Request, callback string, data interface{}, logger *slog.Logger) {
  273. // Validate callback to prevent XSS. This is the one error here that cannot be
  274. // delivered as JSONP: there is no callback name safe to write.
  275. if !isValidCallback(callback) {
  276. sendJSONError(w, http.StatusBadRequest, newErrorResponse(http.StatusBadRequest, "invalid callback parameter"))
  277. return
  278. }
  279. jsonData, err := json.Marshal(data)
  280. if err != nil {
  281. if logger != nil {
  282. logger.Error("failed to marshal response", "err", err.Error())
  283. }
  284. // The client is on the <script> transport, so the error has to be
  285. // executable JS for it to see anything but a load failure.
  286. sendJSONPError(w, r, callback, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  287. return
  288. }
  289. w.Header().Set("Content-Type", "application/javascript")
  290. _, _ = w.Write([]byte(callback))
  291. _, _ = w.Write([]byte("("))
  292. _, _ = w.Write(jsonData)
  293. _, _ = w.Write([]byte(");"))
  294. }
  295. // isValidCallback validates a JSONP callback name to prevent XSS.
  296. func isValidCallback(callback string) bool {
  297. if len(callback) == 0 || len(callback) > 100 {
  298. return false
  299. }
  300. // Allow alphanumeric, underscore, dollar sign, and dot (for namespace)
  301. for _, r := range callback {
  302. if (r < 'a' || r > 'z') &&
  303. (r < 'A' || r > 'Z') &&
  304. (r < '0' || r > '9') &&
  305. r != '_' && r != '$' && r != '.' {
  306. return false
  307. }
  308. }
  309. return true
  310. }
  311. // sendAMF sends an AMF response
  312. func sendAMF(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  313. encoder := NewAMFEncoder(logger)
  314. version := DetectAMFVersion(r)
  315. amfData, err := encoder.EncodeAMF(data, version)
  316. if err != nil {
  317. if logger != nil {
  318. logger.Error("failed to encode AMF response",
  319. "err", err.Error(),
  320. "version", version,
  321. "dataType", fmt.Sprintf("%T", data))
  322. }
  323. // Fall back to JSON error
  324. sendJSONError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "AMF encoding failed"))
  325. return
  326. }
  327. w.Header().Set("Content-Type", "application/x-amf")
  328. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  329. // Debug logging if enabled
  330. if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
  331. hexPreview := ""
  332. if len(amfData) > 0 {
  333. previewLen := len(amfData)
  334. if previewLen > 64 {
  335. previewLen = 64
  336. }
  337. hexPreview = hex.EncodeToString(amfData[:previewLen])
  338. }
  339. logger.Debug("sending AMF response",
  340. "version", version,
  341. "size", len(amfData),
  342. "path", r.URL.Path,
  343. "hexPreview", hexPreview)
  344. }
  345. if _, err := w.Write(amfData); err != nil {
  346. if logger != nil {
  347. logger.Error("failed to write AMF response",
  348. "err", err.Error())
  349. }
  350. }
  351. }
  352. // sendAMFError sends an AMF error response
  353. func sendAMFError(w http.ResponseWriter, r *http.Request, httpStatus int, resp ErrorResponse, logger *slog.Logger) {
  354. encoder := NewAMFEncoder(logger)
  355. version := DetectAMFVersion(r)
  356. amfData, err := encoder.EncodeAMF(resp, version)
  357. if err != nil {
  358. // If AMF encoding fails, fall back to JSON error
  359. sendJSONError(w, httpStatus, resp)
  360. return
  361. }
  362. w.Header().Set("Content-Type", "application/x-amf")
  363. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  364. w.WriteHeader(httpStatus)
  365. _, _ = w.Write(amfData)
  366. }