messaging.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package handlers
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "fmt"
  7. "log/slog"
  8. "net/http"
  9. "time"
  10. "github.com/mk6i/open-oscar-server/server/webapi/types"
  11. "github.com/mk6i/open-oscar-server/state"
  12. "github.com/mk6i/open-oscar-server/wire"
  13. )
  14. // ICBMService defines methods for ICBM operations
  15. type ICBMService interface {
  16. ChannelMsgToHost(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame, inBody wire.SNAC_0x04_0x06_ICBMChannelMsgToHost) (*wire.SNACMessage, error)
  17. ClientEvent(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame, inBody wire.SNAC_0x04_0x14_ICBMClientEvent) error
  18. OfflineRetrieve(ctx context.Context, instance *state.SessionInstance, inFrame wire.SNACFrame) (wire.SNACMessage, error)
  19. }
  20. // MessagingHandler handles Web AIM API messaging endpoints
  21. type MessagingHandler struct {
  22. SessionManager *state.WebAPISessionManager
  23. ICBMService ICBMService
  24. LocateService LocateService
  25. FeedbagService FeedbagService
  26. Logger *slog.Logger
  27. }
  28. // queryOrFormParam returns a request parameter from the query string or, for POST
  29. // requests, from application/x-www-form-urlencoded body fields. The Web AIM client
  30. // sends t/offlineIM/etc. on the query string and puts message in the POST body.
  31. func queryOrFormParam(r *http.Request, key string) string {
  32. if v := r.URL.Query().Get(key); v != "" {
  33. return v
  34. }
  35. if r.Method == http.MethodPost {
  36. if err := r.ParseForm(); err == nil {
  37. return r.FormValue(key)
  38. }
  39. }
  40. return ""
  41. }
  42. // SendIM handles the /im/sendIM endpoint for sending instant messages
  43. func (h *MessagingHandler) SendIM(w http.ResponseWriter, r *http.Request, sess *state.WebAPISession) {
  44. ctx := r.Context()
  45. // Parse parameters
  46. recipient := queryOrFormParam(r, "t")
  47. if recipient == "" {
  48. h.sendErrorResponse(w, r, http.StatusBadRequest, "missing required parameter: t (recipient)")
  49. return
  50. }
  51. message := queryOrFormParam(r, "message")
  52. if message == "" {
  53. h.sendErrorResponse(w, r, http.StatusBadRequest, "missing required parameter: message")
  54. return
  55. }
  56. // Parse optional parameters
  57. autoResponse := queryOrFormParam(r, "autoResponse") == "1"
  58. // The client sets offlineIM once it believes the recipient is offline and
  59. // storable; it sends the literal "true" rather than "1".
  60. offlineIM := queryOrFormParam(r, "offlineIM") == "true" || queryOrFormParam(r, "offlineIM") == "1"
  61. // Generate message cookie
  62. var cookie [8]byte
  63. if _, err := rand.Read(cookie[:]); err != nil {
  64. h.Logger.ErrorContext(ctx, "failed to generate message cookie", "error", err)
  65. h.sendErrorResponse(w, r, http.StatusInternalServerError, "internal server error")
  66. return
  67. }
  68. cookieUint64 := binary.BigEndian.Uint64(cookie[:])
  69. // Create message ID for response (UUID format like working implementation)
  70. // Using the cookie bytes to generate a UUID-like string
  71. messageID := fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",
  72. binary.BigEndian.Uint32(cookie[:4]),
  73. binary.BigEndian.Uint16(cookie[4:6]),
  74. binary.BigEndian.Uint16(cookie[6:8]),
  75. binary.BigEndian.Uint16([]byte{0x80, 0x00}), // Version bits
  76. time.Now().UnixNano()&0xffffffffffff)
  77. now := float64(time.Now().Unix())
  78. nowSec := time.Now().Unix()
  79. // The client sends t as the normalized aimId it keys the conversation by, so
  80. // it is never a source of display names.
  81. recipientIdent := state.NewIdentScreenName(recipient)
  82. clientIM := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  83. Cookie: cookieUint64,
  84. ChannelID: wire.ICBMChannelIM,
  85. ScreenName: recipient,
  86. TLVRestBlock: wire.TLVRestBlock{},
  87. }
  88. // Add message data
  89. frags, err := wire.ICBMFragmentList(message)
  90. if err != nil {
  91. h.sendErrorResponse(w, r, http.StatusInternalServerError, "failed to send message")
  92. return
  93. }
  94. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags))
  95. // Add auto-response flag if applicable
  96. if autoResponse {
  97. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVAutoResponse, []byte{}))
  98. }
  99. // Without this directive the ICBM service rejects messages to offline
  100. // recipients instead of storing them.
  101. if offlineIM {
  102. clientIM.Append(wire.NewTLVBE(wire.ICBMTLVStore, []byte{}))
  103. }
  104. frame := wire.SNACFrame{
  105. FoodGroup: wire.ICBM,
  106. SubGroup: wire.ICBMChannelMsgToHost,
  107. RequestID: wire.ReqIDFromServer,
  108. }
  109. resp, err := h.ICBMService.ChannelMsgToHost(r.Context(), sess.OSCARSession, frame, clientIM)
  110. if err != nil {
  111. h.sendErrorResponse(w, r, http.StatusInternalServerError, "failed to send message")
  112. return
  113. }
  114. if resp != nil {
  115. switch {
  116. case resp.Frame.FoodGroup == wire.ICBM && resp.Frame.SubGroup == wire.ICBMErr:
  117. if errSn, ok := resp.Body.(wire.SNACError); ok {
  118. switch errSn.Code {
  119. case wire.ErrorCodeNotLoggedOn:
  120. subCode, hasSubCode := errSn.Uint16BE(wire.ErrorTLVErrorSubcode)
  121. if hasSubCode && subCode == wire.ICBMSubErrOfflineIMExceedMax {
  122. h.Logger.DebugContext(ctx, "user's offline messages full")
  123. h.sendUndeliverable(w, r, "recipient's offline message store is full")
  124. } else {
  125. h.Logger.DebugContext(ctx, "recipient offline")
  126. h.sendUndeliverable(w, r, "recipient is offline and cannot receive offline messages")
  127. }
  128. return
  129. case wire.ErrorCodeInLocalPermitDeny:
  130. h.Logger.DebugContext(ctx, "you blocked this user")
  131. h.sendUndeliverable(w, r, "you have blocked this user")
  132. return
  133. }
  134. }
  135. h.Logger.DebugContext(ctx, "message rejected by ICBM service")
  136. h.sendUndeliverable(w, r, "failed to send message")
  137. return
  138. case resp.Frame.FoodGroup == wire.ICBM && resp.Frame.SubGroup == wire.ICBMHostAck:
  139. h.Logger.DebugContext(ctx, "received host ack")
  140. }
  141. }
  142. sess.AddStoredIM(recipientIdent.String(), sess.ScreenName.IdentScreenName().String(), message, messageID, nowSec)
  143. recipientDisplay := h.resolveDisplayName(ctx, sess.OSCARSession, recipientIdent)
  144. // The alias lives in the sender's feedbag, so unlike the display name it cannot
  145. // be read off a locate reply.
  146. recipientAlias := sess.Aliases(ctx)[recipientIdent.String()]
  147. h.pushSenderWebAPIEvents(sess, recipientIdent, recipientDisplay, recipientAlias, message, messageID, now, autoResponse)
  148. h.Logger.DebugContext(ctx, "queued sentIM event for sender",
  149. "from", sess.ScreenName.String(),
  150. "to", recipient,
  151. "eventType", types.EventTypeSentIM,
  152. )
  153. // Send success response
  154. responseData := &SendIMData{MsgID: messageID, State: "delivered"}
  155. response := BaseResponse{}
  156. response.Response.StatusCode = 200
  157. response.Response.StatusText = "OK"
  158. response.Response.Data = responseData
  159. SendResponse(w, r, response, h.Logger)
  160. }
  161. // sendUndeliverable reports an IM the server accepted but could not deliver.
  162. //
  163. // The status travels in the envelope with HTTP 200, because the web client reads
  164. // response.statusCode and only recognizes 602/603 as "recipient offline or
  165. // blocked". Any other code, and an empty body most of all, falls through to its
  166. // generic "Bummer. Your message failed." alert.
  167. func (h *MessagingHandler) sendUndeliverable(w http.ResponseWriter, r *http.Request, statusText string) {
  168. response := BaseResponse{}
  169. response.Response.StatusCode = 602
  170. response.Response.StatusText = statusText
  171. SendResponse(w, r, response, h.Logger)
  172. }
  173. // resolveDisplayName returns the recipient's screen name as they formatted it,
  174. // or "" when it cannot be determined because they are offline or blocked.
  175. func (h *MessagingHandler) resolveDisplayName(ctx context.Context, instance *state.SessionInstance, recipient state.IdentScreenName) string {
  176. reply, err := h.LocateService.UserInfoQuery(ctx, instance, wire.SNACFrame{},
  177. wire.SNAC_0x02_0x05_LocateUserInfoQuery{
  178. Type: uint16(wire.LocateTypeUnavailable),
  179. ScreenName: recipient.String(),
  180. })
  181. if err != nil {
  182. h.Logger.DebugContext(ctx, "failed to resolve recipient display name",
  183. "screenName", recipient.String(), "error", err)
  184. return ""
  185. }
  186. info, ok := reply.Body.(wire.SNAC_0x02_0x06_LocateUserInfoReply)
  187. if !ok {
  188. return ""
  189. }
  190. return info.ScreenName
  191. }
  192. // pushSenderWebAPIEvents echoes a just-sent IM back to the sender's own event
  193. // queue. recipientDisplay is the recipient's own formatting of their screen name,
  194. // or "" when it could not be resolved; recipientAlias is the sender's private name
  195. // for them, or "" when unaliased.
  196. //
  197. // The web client merges every user map it receives onto the single user object it
  198. // keys by aimId, so a displayId here overwrites the name the buddy list already
  199. // rendered. Echoing the normalized aimId as a displayId would reduce a buddy named
  200. // "Mike Lee" to "mikelee" the moment you message him. Omitting displayId leaves the
  201. // client's existing name untouched. The merge also deletes any alias it holds, so
  202. // friendly has to be repeated here even though the buddy list already sent it.
  203. func (h *MessagingHandler) pushSenderWebAPIEvents(sess *state.WebAPISession, recipient state.IdentScreenName, recipientDisplay, recipientAlias, message, messageID string, now float64, autoResponse bool) {
  204. senderAimID := sess.ScreenName.IdentScreenName().String()
  205. recipientAimID := recipient.String()
  206. senderEventData := types.SentIMEvent{
  207. Sender: types.UserInfo{
  208. AimID: senderAimID,
  209. DisplayID: sess.ScreenName.String(),
  210. UserType: "aim",
  211. },
  212. Dest: types.UserInfo{
  213. AimID: recipientAimID,
  214. DisplayID: recipientDisplay,
  215. Friendly: recipientAlias,
  216. UserType: "aim",
  217. },
  218. Message: message,
  219. MsgID: messageID,
  220. Timestamp: now,
  221. AutoResp: autoResponse,
  222. }
  223. sess.EventQueue.Push(types.EventTypeSentIM, senderEventData)
  224. if sess.IsSubscribedTo("conversation") {
  225. sess.EventQueue.Push(types.EventTypeConversation, types.ConversationEventData("update", []types.ConversationEntryData{
  226. types.ConversationEntry(recipientAimID, recipientDisplay, message, messageID, senderAimID, true, 0),
  227. }))
  228. }
  229. }
  230. // sendErrorResponse sends an error response in Web AIM API format
  231. func (h *MessagingHandler) sendErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, errorText string) {
  232. SendError(w, r, statusCode, errorText)
  233. }
  234. // SetTyping handles the /im/setTyping endpoint for typing indicators
  235. func (h *MessagingHandler) SetTyping(w http.ResponseWriter, r *http.Request, sess *state.WebAPISession) {
  236. ctx := r.Context()
  237. // Parse parameters
  238. recipient := r.URL.Query().Get("t")
  239. if recipient == "" {
  240. h.sendErrorResponse(w, r, http.StatusBadRequest, "missing required parameter: t (recipient)")
  241. return
  242. }
  243. typingStatus := r.URL.Query().Get("typingStatus")
  244. if typingStatus == "" {
  245. typingStatus = "none"
  246. }
  247. var event uint16
  248. switch typingStatus {
  249. case "typing":
  250. event = 0x0002
  251. case "typed":
  252. event = 0x0001
  253. default:
  254. event = 0x0000
  255. }
  256. inBody := wire.SNAC_0x04_0x14_ICBMClientEvent{
  257. ChannelID: wire.ICBMChannelIM,
  258. ScreenName: recipient,
  259. Event: event,
  260. }
  261. if err := h.ICBMService.ClientEvent(ctx, sess.OSCARSession, wire.SNACFrame{}, inBody); err != nil {
  262. h.Logger.ErrorContext(ctx, "failed to send typing notification", "error", err)
  263. h.sendErrorResponse(w, r, http.StatusInternalServerError, "internal server error")
  264. return
  265. }
  266. h.sendSuccessResponse(w, r, nil)
  267. }
  268. // SendIMData reports the fate of an accepted IM.
  269. type SendIMData struct {
  270. MsgID string `json:"msgId" xml:"msgId"`
  271. State string `json:"state" xml:"state"`
  272. }
  273. // sendSuccessResponse sends a success response in Web AIM API format
  274. func (h *MessagingHandler) sendSuccessResponse(w http.ResponseWriter, r *http.Request, data interface{}) {
  275. response := BaseResponse{}
  276. response.Response.StatusCode = 200
  277. response.Response.StatusText = "OK"
  278. response.Response.Data = data
  279. SendResponse(w, r, response, h.Logger)
  280. }