4
0

cmd_server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package toc
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "strings"
  10. "github.com/google/uuid"
  11. "github.com/mk6i/retro-aim-server/state"
  12. "github.com/mk6i/retro-aim-server/wire"
  13. )
  14. var (
  15. cmdInternalSvcErr = "ERROR:989:internal server error"
  16. rateLimitExceededErr = "ERROR:903"
  17. errDisconnect = errors.New("got booted by another session")
  18. )
  19. // RecvBOS routes incoming SNAC messages from the BOS server to their
  20. // corresponding TOC handlers. It ignores any SNAC messages for which there is
  21. // no TOC response.
  22. func (s OSCARProxy) RecvBOS(ctx context.Context, me *state.Session, chatRegistry *ChatRegistry, ch chan<- []byte) error {
  23. for {
  24. select {
  25. case <-ctx.Done():
  26. return nil
  27. case <-me.Closed():
  28. return errDisconnect
  29. case snac := <-me.ReceiveMessage():
  30. switch v := snac.Body.(type) {
  31. case wire.SNAC_0x03_0x0B_BuddyArrived:
  32. sendOrCancel(ctx, ch, s.UpdateBuddyArrival(v))
  33. case wire.SNAC_0x03_0x0C_BuddyDeparted:
  34. sendOrCancel(ctx, ch, s.UpdateBuddyDeparted(v))
  35. case wire.SNAC_0x04_0x07_ICBMChannelMsgToClient:
  36. sendOrCancel(ctx, ch, s.IMIn(ctx, chatRegistry, v))
  37. case wire.SNAC_0x01_0x10_OServiceEvilNotification:
  38. sendOrCancel(ctx, ch, s.Eviled(v))
  39. default:
  40. s.Logger.DebugContext(ctx, fmt.Sprintf("unsupported snac. foodgroup: %s subgroup: %s",
  41. wire.FoodGroupName(snac.Frame.FoodGroup),
  42. wire.SubGroupName(snac.Frame.FoodGroup, snac.Frame.SubGroup)))
  43. }
  44. }
  45. }
  46. }
  47. // RecvChat routes incoming SNAC messages from the chat server to their
  48. // corresponding TOC handlers. It ignores any SNAC messages for which there is
  49. // no TOC response.
  50. func (s OSCARProxy) RecvChat(ctx context.Context, me *state.Session, chatID int, ch chan<- []byte) {
  51. for {
  52. select {
  53. case <-ctx.Done():
  54. return
  55. case <-me.Closed():
  56. return
  57. case snac := <-me.ReceiveMessage():
  58. switch v := snac.Body.(type) {
  59. case wire.SNAC_0x0E_0x04_ChatUsersLeft:
  60. sendOrCancel(ctx, ch, s.ChatUpdateBuddyLeft(v, chatID))
  61. case wire.SNAC_0x0E_0x03_ChatUsersJoined:
  62. sendOrCancel(ctx, ch, s.ChatUpdateBuddyArrived(v, chatID))
  63. case wire.SNAC_0x0E_0x06_ChatChannelMsgToClient:
  64. sendOrCancel(ctx, ch, s.ChatIn(ctx, v, chatID))
  65. default:
  66. s.Logger.DebugContext(ctx, fmt.Sprintf("unsupported snac. foodgroup: %s subgroup: %s",
  67. wire.FoodGroupName(snac.Frame.FoodGroup),
  68. wire.SubGroupName(snac.Frame.FoodGroup, snac.Frame.SubGroup)))
  69. }
  70. }
  71. }
  72. }
  73. // ChatIn handles the CHAT_IN TOC command.
  74. //
  75. // From the TiK documentation:
  76. //
  77. // A chat message was sent in a chat room.
  78. //
  79. // Command syntax: CHAT_IN:<Chat Room Id>:<Source User>:<Whisper? T/F>:<Message>
  80. func (s OSCARProxy) ChatIn(ctx context.Context, snac wire.SNAC_0x0E_0x06_ChatChannelMsgToClient, chatID int) string {
  81. b, ok := snac.Bytes(wire.ChatTLVSenderInformation)
  82. if !ok {
  83. return s.runtimeErr(ctx, errors.New("snac.Bytes: missing wire.ChatTLVSenderInformation"))
  84. }
  85. u := wire.TLVUserInfo{}
  86. err := wire.UnmarshalBE(&u, bytes.NewReader(b))
  87. if err != nil {
  88. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  89. }
  90. b, ok = snac.Bytes(wire.ChatTLVMessageInfo)
  91. if !ok {
  92. return s.runtimeErr(ctx, errors.New("snac.Bytes: missing wire.ChatTLVMessageInfo"))
  93. }
  94. text, err := wire.UnmarshalChatMessageText(b)
  95. if err != nil {
  96. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalChatMessageText: %w", err))
  97. }
  98. return fmt.Sprintf("CHAT_IN:%d:%s:F:%s", chatID, u.ScreenName, text)
  99. }
  100. // ChatUpdateBuddyArrived handles the CHAT_UPDATE_BUDDY TOC command for chat
  101. // room arrival events.
  102. //
  103. // From the TiK documentation:
  104. //
  105. // This one command handles arrival/departs from a chat room. The very first
  106. // message of this type for each chat room contains the users already in the
  107. // room.
  108. //
  109. // Command syntax: CHAT_UPDATE_BUDDY:<Chat Room Id>:<Inside? T/F>:<User 1>:<User 2>...
  110. func (s OSCARProxy) ChatUpdateBuddyArrived(snac wire.SNAC_0x0E_0x03_ChatUsersJoined, chatID int) string {
  111. users := make([]string, 0, len(snac.Users))
  112. for _, u := range snac.Users {
  113. users = append(users, u.ScreenName)
  114. }
  115. return fmt.Sprintf("CHAT_UPDATE_BUDDY:%d:T:%s", chatID, strings.Join(users, ":"))
  116. }
  117. // ChatUpdateBuddyLeft handles the CHAT_UPDATE_BUDDY TOC command for chat
  118. // room departure events.
  119. //
  120. // From the TiK documentation:
  121. //
  122. // This one command handles arrival/departs from a chat room. The very first
  123. // message of this type for each chat room contains the users already in the
  124. // room.
  125. //
  126. // Command syntax: CHAT_UPDATE_BUDDY:<Chat Room Id>:<Inside? T/F>:<User 1>:<User 2>...
  127. func (s OSCARProxy) ChatUpdateBuddyLeft(snac wire.SNAC_0x0E_0x04_ChatUsersLeft, chatID int) string {
  128. users := make([]string, 0, len(snac.Users))
  129. for _, u := range snac.Users {
  130. users = append(users, u.ScreenName)
  131. }
  132. return fmt.Sprintf("CHAT_UPDATE_BUDDY:%d:F:%s", chatID, strings.Join(users, ":"))
  133. }
  134. // Eviled handles the EVILED TOC command.
  135. //
  136. // From the TiK documentation:
  137. //
  138. // The user was just eviled.
  139. //
  140. // Command syntax: EVILED:<new evil>:<name of eviler, blank if anonymous>
  141. func (s OSCARProxy) Eviled(snac wire.SNAC_0x01_0x10_OServiceEvilNotification) string {
  142. warning := fmt.Sprintf("%d", snac.NewEvil/10)
  143. who := ""
  144. if snac.Snitcher != nil {
  145. who = snac.Snitcher.ScreenName
  146. }
  147. return fmt.Sprintf("EVILED:%s:%s", warning, who)
  148. }
  149. // IMIn handles the IM_IN TOC command.
  150. //
  151. // From the TiK documentation:
  152. //
  153. // Receive an IM from someone. Everything after the third colon is the
  154. // incoming message, including other colons.
  155. //
  156. // Command syntax: IM_IN:<Source User>:<Auto Response T/F?>:<Message>
  157. func (s OSCARProxy) IMIn(ctx context.Context, chatRegistry *ChatRegistry, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) string {
  158. switch snac.ChannelID {
  159. case wire.ICBMChannelIM:
  160. return s.convertICBMInstantMsg(ctx, snac)
  161. case wire.ICBMChannelRendezvous:
  162. return s.convertICBMRendezvous(ctx, chatRegistry, snac)
  163. default:
  164. s.Logger.DebugContext(ctx, "received unsupported ICBM channel message", "channel_id", snac.ChannelID)
  165. return ""
  166. }
  167. }
  168. // convertICBMInstantMsg converts an ICBM instant message SNAC to a TOC IM_IN response.
  169. func (s OSCARProxy) convertICBMInstantMsg(ctx context.Context, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) string {
  170. buf, ok := snac.TLVRestBlock.Bytes(wire.ICBMTLVAOLIMData)
  171. if !ok {
  172. return s.runtimeErr(ctx, errors.New("TLVRestBlock.Bytes: missing wire.ICBMTLVAOLIMData"))
  173. }
  174. txt, err := wire.UnmarshalICBMMessageText(buf)
  175. if err != nil {
  176. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalICBMMessageText: %w", err))
  177. }
  178. autoResp := "F"
  179. if _, isAutoReply := snac.TLVRestBlock.Bytes(wire.ICBMTLVAutoResponse); isAutoReply {
  180. autoResp = "T"
  181. }
  182. return fmt.Sprintf("IM_IN:%s:%s:%s", snac.ScreenName, autoResp, txt)
  183. }
  184. // convertICBMRendezvous converts an ICBM rendezvous SNAC to a TOC response.
  185. // - if chat, return CHAT_INVITE
  186. // - file transfer, return RVOUS_PROPOSE
  187. // - don't respond for other rendezvous types
  188. func (s OSCARProxy) convertICBMRendezvous(ctx context.Context, chatRegistry *ChatRegistry, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) string {
  189. rdinfo, has := snac.TLVRestBlock.Bytes(wire.ICBMTLVData)
  190. if !has {
  191. return s.runtimeErr(ctx, errors.New("TLVRestBlock.Bytes: missing rendezvous block"))
  192. }
  193. frag := wire.ICBMCh2Fragment{}
  194. if err := wire.UnmarshalBE(&frag, bytes.NewReader(rdinfo)); err != nil {
  195. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  196. }
  197. if frag.Type != wire.ICBMRdvMessagePropose {
  198. s.Logger.DebugContext(ctx, "can't convert ICBM rendezvous message to TOC response", "rdv_type", frag.Type)
  199. return ""
  200. }
  201. switch uuid.UUID(frag.Capability) {
  202. case wire.CapChat:
  203. prompt, ok := frag.Bytes(wire.ICBMRdvTLVTagsInvitation)
  204. if !ok {
  205. return s.runtimeErr(ctx, errors.New("frag.Bytes: missing chat invite prompt"))
  206. }
  207. svcData, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData)
  208. if !ok || svcData == nil {
  209. return s.runtimeErr(ctx, errors.New("frag.Bytes: missing room info"))
  210. }
  211. roomInfo := wire.ICBMRoomInfo{}
  212. if err := wire.UnmarshalBE(&roomInfo, bytes.NewReader(svcData)); err != nil {
  213. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  214. }
  215. cookie := strings.Split(roomInfo.Cookie, "-") // make this safe
  216. if len(cookie) < 3 {
  217. return s.runtimeErr(ctx, errors.New("roomInfo.Cookie: malformed cookie, could not get room name"))
  218. }
  219. roomName := cookie[2]
  220. chatID := chatRegistry.Add(roomInfo)
  221. return fmt.Sprintf("CHAT_INVITE:%s:%d:%s:%s", roomName, chatID, snac.ScreenName, prompt)
  222. case wire.CapFileTransfer:
  223. user := snac.TLVUserInfo.ScreenName
  224. capability := strings.ToUpper(wire.CapFileTransfer.String()) // TiK requires upper-case UUID characters
  225. cookie := base64.StdEncoding.EncodeToString(frag.Cookie[:])
  226. seq, _ := frag.Uint16BE(wire.ICBMRdvTLVTagsSeqNum)
  227. rvousIP := "0.0.0.0"
  228. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsRdvIP); ok && len(ip) == 4 {
  229. rvousIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  230. }
  231. proposerIP := "0.0.0.0"
  232. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsRequesterIP); ok && len(ip) == 4 {
  233. proposerIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  234. }
  235. verifiedIP := "0.0.0.0"
  236. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsVerifiedIP); ok && len(ip) == 4 {
  237. verifiedIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  238. }
  239. rvousPort, _ := frag.Uint16BE(wire.ICBMRdvTLVTagsPort)
  240. var fileMetadata string
  241. if f, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData); ok {
  242. // remove sequence of null bytes from the end that causes TiK file open
  243. // dialog to crash
  244. f = bytes.TrimRight(f, "\x00")
  245. fileMetadata = base64.StdEncoding.EncodeToString(f)
  246. }
  247. return fmt.Sprintf("RVOUS_PROPOSE:%s:%s:%s:%d:%s:%s:%s:%d:%d:%s",
  248. user, capability, cookie, seq, rvousIP, proposerIP, verifiedIP, rvousPort, wire.ICBMRdvTLVTagsSvcData, fileMetadata)
  249. default:
  250. s.Logger.DebugContext(ctx, "received rendezvous ICBM for unsupported capability", "capability", wire.CapChat)
  251. return ""
  252. }
  253. }
  254. // UpdateBuddyArrival handles the UPDATE_BUDDY TOC command for buddy arrival events.
  255. //
  256. // From the TiK documentation:
  257. //
  258. // This one command handles arrival/depart/updates. Evil Amount is a percentage, Signon Time is UNIX epoc, idle time is in minutes, UC (User Class) is a two/three character string.
  259. // - uc[0]
  260. // - ' ' - Ignore
  261. // - 'A' - On AOL
  262. // - uc[1]
  263. // - ' ' - Ignore
  264. // - 'A' - Oscar Admin
  265. // - 'U' - Oscar Unconfirmed
  266. // - 'O' - Oscar Normal
  267. // - uc[2]
  268. // - '\0' - Ignore
  269. // - ' ' - Ignore
  270. // - 'U' - The user has set their unavailable flag.
  271. //
  272. // Command syntax: UPDATE_BUDDY:<Buddy User>:<Online? T/F>:<Evil Amount>:<Signon Time>:<IdleTime>:<UC>
  273. func (s OSCARProxy) UpdateBuddyArrival(snac wire.SNAC_0x03_0x0B_BuddyArrived) string {
  274. return userInfoToUpdateBuddy(snac.TLVUserInfo)
  275. }
  276. // UpdateBuddyDeparted handles the UPDATE_BUDDY TOC command for buddy departure events.
  277. //
  278. // From the TiK documentation:
  279. //
  280. // This one command handles arrival/depart/updates. Evil Amount is a
  281. // percentage, Signon Time is UNIX epoc, idle time is in minutes, UC (User
  282. // Class) is a two/three character string.
  283. // - uc[0]
  284. // - ' ' - Ignore
  285. // - 'A' - On AOL
  286. // - uc[1]
  287. // - ' ' - Ignore
  288. // - 'A' - Oscar Admin
  289. // - 'U' - Oscar Unconfirmed
  290. // - 'O' - Oscar Normal
  291. // - uc[2]
  292. // - '\0' - Ignore
  293. // - ' ' - Ignore
  294. // - 'U' - The user has set their unavailable flag.
  295. //
  296. // Command syntax: UPDATE_BUDDY:<Buddy User>:<Online? T/F>:<Evil Amount>:<Signon Time>:<IdleTime>:<UC>
  297. func (s OSCARProxy) UpdateBuddyDeparted(snac wire.SNAC_0x03_0x0C_BuddyDeparted) string {
  298. return fmt.Sprintf("UPDATE_BUDDY:%s:F:0:0:0: ", snac.ScreenName)
  299. }
  300. func sendOrCancel(ctx context.Context, ch chan<- []byte, msg string) {
  301. select {
  302. case <-ctx.Done():
  303. return
  304. case ch <- []byte(msg):
  305. return
  306. }
  307. }
  308. // userInfoToUpdateBuddy creates an UPDATE_BUDDY server reply from a User
  309. // Info TLV.
  310. func userInfoToUpdateBuddy(snac wire.TLVUserInfo) string {
  311. online, _ := snac.Uint32BE(wire.OServiceUserInfoSignonTOD)
  312. idle, _ := snac.Uint16BE(wire.OServiceUserInfoIdleTime)
  313. uc := [3]string{" ", "O", " "}
  314. if snac.IsAway() {
  315. uc[2] = "U"
  316. }
  317. warning := fmt.Sprintf("%d", snac.WarningLevel/10)
  318. class := strings.Join(uc[:], "")
  319. return fmt.Sprintf("UPDATE_BUDDY:%s:%s:%s:%d:%d:%s", snac.ScreenName, "T", warning, online, idle, class)
  320. }