cmd_server.go 12 KB

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