cmd_client.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. package toc
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/csv"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "log/slog"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "github.com/google/uuid"
  15. "github.com/mk6i/retro-aim-server/state"
  16. "github.com/mk6i/retro-aim-server/wire"
  17. )
  18. var (
  19. // capChat is the UUID that represents an OSCAR client's ability to chat
  20. capChat = uuid.MustParse("748F2420-6287-11D1-8222-444553540000")
  21. )
  22. // NewChatRegistry creates a new ChatRegistry instances.
  23. func NewChatRegistry() *ChatRegistry {
  24. chatRegistry := &ChatRegistry{
  25. lookup: make(map[int]wire.ICBMRoomInfo),
  26. sessions: make(map[int]*state.Session),
  27. m: sync.RWMutex{},
  28. }
  29. return chatRegistry
  30. }
  31. // ChatRegistry manages the chat rooms that a user is connected to during a TOC
  32. // session. It maintains mappings between chat room identifiers, metadata, and
  33. // active chat sessions.
  34. //
  35. // This struct provides thread-safe operations for adding, retrieving, and managing
  36. // chat room metadata and associated sessions.
  37. type ChatRegistry struct {
  38. lookup map[int]wire.ICBMRoomInfo // Maps chat room IDs to their metadata.
  39. sessions map[int]*state.Session // Tracks active chat sessions by chat room ID.
  40. nextID int // Incremental identifier for newly added chat rooms.
  41. m sync.RWMutex // Synchronization primitive for concurrent access.
  42. }
  43. // Add registers metadata for a newly joined chat room and returns a unique
  44. // identifier for it. If the room is already registered, it returns the existing ID.
  45. func (c *ChatRegistry) Add(room wire.ICBMRoomInfo) int {
  46. c.m.Lock()
  47. defer c.m.Unlock()
  48. for chatID, r := range c.lookup {
  49. if r == room {
  50. return chatID
  51. }
  52. }
  53. id := c.nextID
  54. c.lookup[id] = room
  55. c.nextID++
  56. return id
  57. }
  58. // LookupRoom retrieves metadata for the chat room registered with chatID.
  59. // It returns the room metadata and a boolean indicating whether the chat ID
  60. // was found.
  61. func (c *ChatRegistry) LookupRoom(chatID int) (wire.ICBMRoomInfo, bool) {
  62. c.m.RLock()
  63. defer c.m.RUnlock()
  64. room, found := c.lookup[chatID]
  65. return room, found
  66. }
  67. // RegisterSess associates a chat session with a chat room. If a session is
  68. // already registered for the given chat ID, it will be overwritten.
  69. func (c *ChatRegistry) RegisterSess(chatID int, sess *state.Session) {
  70. c.m.Lock()
  71. defer c.m.Unlock()
  72. c.sessions[chatID] = sess
  73. }
  74. // RetrieveSess retrieves the chat session associated with the given chat ID.
  75. // If no session is registered for the chat ID, it returns nil.
  76. func (c *ChatRegistry) RetrieveSess(chatID int) *state.Session {
  77. c.m.RLock()
  78. defer c.m.RUnlock()
  79. return c.sessions[chatID]
  80. }
  81. // OSCARProxy acts as a bridge between TOC clients and the OSCAR server,
  82. // translating protocol messages between the two.
  83. //
  84. // It performs the following functions:
  85. // - Receives TOC messages from the client, converts them into SNAC messages,
  86. // and forwards them to the OSCAR server. The SNAC response is then converted
  87. // back into a TOC response for the client.
  88. // - Receives incoming messages from the OSCAR server and translates them into
  89. // TOC responses for the client.
  90. type OSCARProxy struct {
  91. AdminService AdminService
  92. AuthService AuthService
  93. BuddyListRegistry BuddyListRegistry
  94. BuddyService BuddyService
  95. ChatNavService ChatNavService
  96. ChatService ChatService
  97. CookieBaker CookieBaker
  98. DirSearchService DirSearchService
  99. ICBMService ICBMService
  100. LocateService LocateService
  101. Logger *slog.Logger
  102. OServiceServiceBOS OServiceService
  103. OServiceServiceChat OServiceService
  104. PermitDenyService PermitDenyService
  105. TOCConfigStore TOCConfigStore
  106. }
  107. // RecvClientCmd processes a client TOC command and returns a server reply.
  108. //
  109. // * sessBOS is the current user's session.
  110. // * chatRegistry manages the current user's chat sessions
  111. // * payload is the command + arguments
  112. // * toCh is the channel that transports messages to client
  113. // * doAsync performs async tasks, is auto-cleaned up by caller
  114. //
  115. // It returns true if the server can continue processing commands.
  116. func (s OSCARProxy) RecvClientCmd(
  117. ctx context.Context,
  118. sessBOS *state.Session,
  119. chatRegistry *ChatRegistry,
  120. payload []byte,
  121. toCh chan<- []byte,
  122. doAsync func(f func() error),
  123. ) (reply string, ok bool) {
  124. cmd := payload
  125. if idx := bytes.IndexByte(payload, ' '); idx > -1 {
  126. cmd = cmd[:idx]
  127. }
  128. if s.Logger.Enabled(ctx, slog.LevelDebug) {
  129. s.Logger.DebugContext(ctx, "client request", "command", payload)
  130. } else {
  131. s.Logger.InfoContext(ctx, "client request", "command", cmd)
  132. }
  133. switch string(cmd) {
  134. case "toc_send_im":
  135. return s.SendIM(ctx, sessBOS, payload), true
  136. case "toc_init_done":
  137. return s.InitDone(ctx, sessBOS, payload), true
  138. case "toc_add_buddy":
  139. return s.AddBuddy(ctx, sessBOS, payload), true
  140. case "toc_get_status":
  141. return s.GetStatus(ctx, sessBOS, payload), true
  142. case "toc_remove_buddy":
  143. return s.RemoveBuddy(ctx, sessBOS, payload), true
  144. case "toc_add_permit":
  145. return s.AddPermit(ctx, sessBOS, payload), true
  146. case "toc_add_deny":
  147. return s.AddDeny(ctx, sessBOS, payload), true
  148. case "toc_set_away":
  149. return s.SetAway(ctx, sessBOS, payload), true
  150. case "toc_set_caps":
  151. return s.SetCaps(ctx, sessBOS, payload), true
  152. case "toc_evil":
  153. return s.Evil(ctx, sessBOS, payload), true
  154. case "toc_get_info":
  155. return s.GetInfoURL(ctx, sessBOS, payload), true
  156. case "toc_change_passwd":
  157. return s.ChangePassword(ctx, sessBOS, payload), true
  158. case "toc_format_nickname":
  159. return s.FormatNickname(ctx, sessBOS, payload), true
  160. case "toc_chat_join", "toc_chat_accept":
  161. var chatID int
  162. var msg string
  163. if string(cmd) == "toc_chat_join" {
  164. chatID, msg = s.ChatJoin(ctx, sessBOS, chatRegistry, payload)
  165. } else {
  166. chatID, msg = s.ChatAccept(ctx, sessBOS, chatRegistry, payload)
  167. }
  168. if msg == cmdInternalSvcErr {
  169. // todo idk if this is worth cancelling the connection over
  170. return "", false
  171. }
  172. doAsync(func() error {
  173. sess := chatRegistry.RetrieveSess(chatID)
  174. s.RecvChat(ctx, sess, chatID, toCh)
  175. return nil
  176. })
  177. return msg, true
  178. case "toc_chat_send":
  179. return s.ChatSend(ctx, chatRegistry, payload), true
  180. case "toc_chat_leave":
  181. return s.ChatLeave(ctx, chatRegistry, payload), true
  182. case "toc_set_info":
  183. return s.SetInfo(ctx, sessBOS, payload), true
  184. case "toc_set_dir":
  185. return s.SetDir(ctx, sessBOS, payload), true
  186. case "toc_set_idle":
  187. return s.SetIdle(ctx, sessBOS, payload), true
  188. case "toc_set_config":
  189. return s.SetConfig(ctx, sessBOS, payload), true
  190. case "toc_chat_invite":
  191. return s.ChatInvite(ctx, sessBOS, chatRegistry, payload), true
  192. case "toc_dir_search":
  193. return s.GetDirSearchURL(ctx, sessBOS, payload), true
  194. case "toc_get_dir":
  195. return s.GetDirURL(ctx, sessBOS, payload), true
  196. }
  197. s.Logger.ErrorContext(ctx, fmt.Sprintf("unsupported TOC command %s", cmd))
  198. return "", true
  199. }
  200. // AddBuddy handles the toc_add_buddy TOC command.
  201. //
  202. // From the TiK documentation:
  203. //
  204. // Add buddies to your buddy list. This does not change your saved config.
  205. //
  206. // Command syntax: toc_add_buddy <Buddy User 1> [<Buddy User2> [<Buddy User 3> [...]]]
  207. func (s OSCARProxy) AddBuddy(ctx context.Context, me *state.Session, cmd []byte) string {
  208. users, err := parseArgs(cmd, "toc_add_buddy")
  209. if err != nil {
  210. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  211. }
  212. snac := wire.SNAC_0x03_0x04_BuddyAddBuddies{}
  213. for _, sn := range users {
  214. snac.Buddies = append(snac.Buddies, struct {
  215. ScreenName string `oscar:"len_prefix=uint8"`
  216. }{ScreenName: sn})
  217. }
  218. if err := s.BuddyService.AddBuddies(ctx, me, snac); err != nil {
  219. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.AddBuddies: %w", err))
  220. }
  221. return ""
  222. }
  223. // AddPermit handles the toc_add_permit TOC command.
  224. //
  225. // From the TiK documentation:
  226. //
  227. // ADD the following people to your permit mode. If you are in deny mode it
  228. // will switch you to permit mode first. With no arguments and in deny mode
  229. // this will switch you to permit none. If already in permit mode, no
  230. // arguments does nothing and your permit list remains the same.
  231. //
  232. // Command syntax: toc_add_permit [ <User 1> [<User 2> [...]]]
  233. func (s OSCARProxy) AddPermit(ctx context.Context, me *state.Session, cmd []byte) string {
  234. users, err := parseArgs(cmd, "toc_add_permit")
  235. if err != nil {
  236. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  237. }
  238. snac := wire.SNAC_0x09_0x05_PermitDenyAddPermListEntries{}
  239. for _, sn := range users {
  240. snac.Users = append(snac.Users, struct {
  241. ScreenName string `oscar:"len_prefix=uint8"`
  242. }{ScreenName: sn})
  243. }
  244. if err := s.PermitDenyService.AddPermListEntries(ctx, me, snac); err != nil {
  245. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddPermListEntries: %w", err))
  246. }
  247. return ""
  248. }
  249. // AddDeny handles the toc_add_deny TOC command.
  250. //
  251. // From the TiK documentation:
  252. //
  253. // ADD the following people to your deny mode. If you are in permit mode it
  254. // will switch you to deny mode first. With no arguments and in permit mode,
  255. // this will switch you to deny none. If already in deny mode, no arguments
  256. // does nothing and your deny list remains unchanged.
  257. //
  258. // Command syntax: toc_add_deny [ <User 1> [<User 2> [...]]]
  259. func (s OSCARProxy) AddDeny(ctx context.Context, me *state.Session, cmd []byte) string {
  260. users, err := parseArgs(cmd, "toc_add_deny")
  261. if err != nil {
  262. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  263. }
  264. snac := wire.SNAC_0x09_0x07_PermitDenyAddDenyListEntries{}
  265. for _, sn := range users {
  266. snac.Users = append(snac.Users, struct {
  267. ScreenName string `oscar:"len_prefix=uint8"`
  268. }{ScreenName: sn})
  269. }
  270. if err := s.PermitDenyService.AddDenyListEntries(ctx, me, snac); err != nil {
  271. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddDenyListEntries: %w", err))
  272. }
  273. return ""
  274. }
  275. // ChangePassword handles the toc_change_passwd TOC command.
  276. //
  277. // From the TiK documentation:
  278. //
  279. // Change a user's password. An ADMIN_PASSWD_STATUS or ERROR message will be
  280. // sent back to the client.
  281. //
  282. // Command syntax: toc_change_passwd <existing_passwd> <new_passwd>
  283. func (s OSCARProxy) ChangePassword(ctx context.Context, me *state.Session, cmd []byte) string {
  284. var oldPass, newPass string
  285. if _, err := parseArgs(cmd, "toc_change_passwd", &oldPass, &newPass); err != nil {
  286. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  287. }
  288. reqSNAC := wire.SNAC_0x07_0x04_AdminInfoChangeRequest{
  289. TLVRestBlock: wire.TLVRestBlock{
  290. TLVList: wire.TLVList{
  291. wire.NewTLVBE(wire.AdminTLVOldPassword, oldPass),
  292. wire.NewTLVBE(wire.AdminTLVNewPassword, newPass),
  293. },
  294. },
  295. }
  296. reply, err := s.AdminService.InfoChangeRequest(ctx, me, wire.SNACFrame{}, reqSNAC)
  297. if err != nil {
  298. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: %w", err))
  299. }
  300. replyBody, ok := reply.Body.(wire.SNAC_0x07_0x05_AdminChangeReply)
  301. if !ok {
  302. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: unexpected response type %v", replyBody))
  303. }
  304. code, ok := replyBody.Uint16BE(wire.AdminTLVErrorCode)
  305. if ok {
  306. switch code {
  307. case wire.AdminInfoErrorInvalidPasswordLength:
  308. return "ERROR:911"
  309. case wire.AdminInfoErrorValidatePassword:
  310. return "ERROR:912"
  311. default:
  312. return "ERROR:913"
  313. }
  314. }
  315. return "ADMIN_PASSWD_STATUS:0"
  316. }
  317. // ChatAccept handles the toc_chat_accept TOC command.
  318. //
  319. // From the TiK documentation:
  320. //
  321. // Accept a CHAT_INVITE message from TOC. The server will send a CHAT_JOIN in
  322. // response.
  323. //
  324. // Command syntax: toc_chat_accept <Chat Room ID>
  325. func (s OSCARProxy) ChatAccept(
  326. ctx context.Context,
  327. me *state.Session,
  328. chatRegistry *ChatRegistry,
  329. cmd []byte,
  330. ) (int, string) {
  331. var chatIDStr string
  332. if _, err := parseArgs(cmd, "toc_chat_accept", &chatIDStr); err != nil {
  333. return 0, s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  334. }
  335. chatID, err := strconv.Atoi(chatIDStr)
  336. if err != nil {
  337. return 0, s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  338. }
  339. chatInfo, found := chatRegistry.LookupRoom(chatID)
  340. if !found {
  341. return 0, s.runtimeErr(ctx, fmt.Errorf("chatRegistry.LookupRoom: no chat found for ID %d", chatID))
  342. }
  343. reqRoomSNAC := wire.SNAC_0x0D_0x04_ChatNavRequestRoomInfo{
  344. Cookie: chatInfo.Cookie,
  345. Exchange: chatInfo.Exchange,
  346. InstanceNumber: chatInfo.Instance,
  347. }
  348. reqRoomReply, err := s.ChatNavService.RequestRoomInfo(ctx, wire.SNACFrame{}, reqRoomSNAC)
  349. if err != nil {
  350. return 0, s.runtimeErr(ctx, fmt.Errorf("ChatNavService.RequestRoomInfo: %w", err))
  351. }
  352. reqRoomReplyBody, ok := reqRoomReply.Body.(wire.SNAC_0x0D_0x09_ChatNavNavInfo)
  353. if !ok {
  354. return 0, s.runtimeErr(ctx, fmt.Errorf("chatNavService.RequestRoomInfo: unexpected response type %v", reqRoomReplyBody))
  355. }
  356. b, hasInfo := reqRoomReplyBody.Bytes(wire.ChatNavTLVRoomInfo)
  357. if !hasInfo {
  358. return 0, s.runtimeErr(ctx, errors.New("reqRoomReplyBody.Bytes: missing wire.ChatNavTLVRoomInfo"))
  359. }
  360. roomInfo := wire.SNAC_0x0E_0x02_ChatRoomInfoUpdate{}
  361. if err := wire.UnmarshalBE(&roomInfo, bytes.NewReader(b)); err != nil {
  362. return 0, s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  363. }
  364. roomName, hasName := roomInfo.Bytes(wire.ChatRoomTLVRoomName)
  365. if !hasName {
  366. return 0, s.runtimeErr(ctx, errors.New("roomInfo.Bytes: missing wire.ChatRoomTLVRoomName"))
  367. }
  368. svcReqSNAC := wire.SNAC_0x01_0x04_OServiceServiceRequest{
  369. FoodGroup: wire.Chat,
  370. TLVRestBlock: wire.TLVRestBlock{
  371. TLVList: wire.TLVList{
  372. wire.NewTLVBE(0x01, wire.SNAC_0x01_0x04_TLVRoomInfo{
  373. Cookie: chatInfo.Cookie,
  374. }),
  375. },
  376. },
  377. }
  378. svcReqReply, err := s.OServiceServiceBOS.ServiceRequest(ctx, me, wire.SNACFrame{}, svcReqSNAC)
  379. if err != nil {
  380. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ServiceRequest: %w", err))
  381. }
  382. svcReqReplyBody, ok := svcReqReply.Body.(wire.SNAC_0x01_0x05_OServiceServiceResponse)
  383. if !ok {
  384. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ServiceRequest: unexpected response type %v", svcReqReplyBody))
  385. }
  386. loginCookie, hasCookie := svcReqReplyBody.Bytes(wire.OServiceTLVTagsLoginCookie)
  387. if !hasCookie {
  388. return 0, s.runtimeErr(ctx, errors.New("missing wire.OServiceTLVTagsLoginCookie"))
  389. }
  390. chatSess, err := s.AuthService.RegisterChatSession(ctx, loginCookie)
  391. if err != nil {
  392. return 0, s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterChatSession: %w", err))
  393. }
  394. chatRegistry.RegisterSess(chatID, chatSess)
  395. if err := s.OServiceServiceChat.ClientOnline(ctx, wire.SNAC_0x01_0x02_OServiceClientOnline{}, chatSess); err != nil {
  396. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceChat.ClientOnline: %w", err))
  397. }
  398. return chatID, fmt.Sprintf("CHAT_JOIN:%d:%s", chatID, roomName)
  399. }
  400. // ChatInvite handles the toc_chat_invite TOC command.
  401. //
  402. // From the TiK documentation:
  403. //
  404. // Once you are inside a chat room you can invite other people into that room.
  405. // Remember to quote and encode the invite message.
  406. //
  407. // Command syntax: toc_chat_invite <Chat Room ID> <Invite Msg> <buddy1> [<buddy2> [<buddy3> [...]]]
  408. func (s OSCARProxy) ChatInvite(ctx context.Context, me *state.Session, chatRegistry *ChatRegistry, cmd []byte) string {
  409. var chatRoomIDStr, msg string
  410. users, err := parseArgs(cmd, "toc_chat_invite", &chatRoomIDStr, &msg)
  411. if err != nil {
  412. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  413. }
  414. chatID, err := strconv.Atoi(chatRoomIDStr)
  415. if err != nil {
  416. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  417. }
  418. roomInfo, found := chatRegistry.LookupRoom(chatID)
  419. if !found {
  420. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.LookupRoom: chat ID `%d` not found", chatID))
  421. }
  422. for _, guest := range users {
  423. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  424. ChannelID: wire.ICBMChannelRendezvous,
  425. ScreenName: guest,
  426. TLVRestBlock: wire.TLVRestBlock{
  427. TLVList: wire.TLVList{
  428. wire.NewTLVBE(0x05, wire.ICBMCh2Fragment{
  429. Type: 0,
  430. Capability: capChat,
  431. TLVRestBlock: wire.TLVRestBlock{
  432. TLVList: wire.TLVList{
  433. wire.NewTLVBE(10, uint16(1)),
  434. wire.NewTLVBE(12, msg),
  435. wire.NewTLVBE(13, "us-ascii"),
  436. wire.NewTLVBE(14, "en"),
  437. wire.NewTLVBE(10001, roomInfo),
  438. },
  439. },
  440. }),
  441. },
  442. },
  443. }
  444. if _, err := s.ICBMService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac); err != nil {
  445. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  446. }
  447. }
  448. return ""
  449. }
  450. // ChatJoin handles the toc_chat_join TOC command.
  451. //
  452. // From the TiK documentation:
  453. //
  454. // Join a chat room in the given exchange. Exchange is an integer that
  455. // represents a group of chat rooms. Different exchanges have different
  456. // properties. For example some exchanges might have room replication (ie a
  457. // room never fills up, there are just multiple instances.) and some exchanges
  458. // might have navigational information. Currently, exchange should always be
  459. // 4, however this may change in the future. You will either receive an ERROR
  460. // if the room couldn't be joined or a CHAT_JOIN message. The Chat Room Name
  461. // is case-insensitive and consecutive spaces are removed.
  462. //
  463. // Command syntax: toc_chat_join <Exchange> <Chat Room Name>
  464. func (s OSCARProxy) ChatJoin(
  465. ctx context.Context,
  466. me *state.Session,
  467. chatRegistry *ChatRegistry,
  468. cmd []byte,
  469. ) (int, string) {
  470. var exchangeStr, roomName string
  471. if _, err := parseArgs(cmd, "toc_chat_join", &exchangeStr, &roomName); err != nil {
  472. return 0, s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  473. }
  474. // create room or retrieve the room if it already exists
  475. exchange, err := strconv.Atoi(exchangeStr)
  476. if err != nil {
  477. return 0, s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  478. }
  479. mkRoomReq := wire.SNAC_0x0E_0x02_ChatRoomInfoUpdate{
  480. Exchange: uint16(exchange),
  481. Cookie: "create",
  482. TLVBlock: wire.TLVBlock{
  483. TLVList: wire.TLVList{
  484. wire.NewTLVBE(wire.ChatRoomTLVRoomName, roomName),
  485. },
  486. },
  487. }
  488. mkRoomReply, err := s.ChatNavService.CreateRoom(ctx, me, wire.SNACFrame{}, mkRoomReq)
  489. if err != nil {
  490. return 0, s.runtimeErr(ctx, fmt.Errorf("ChatNavService.CreateRoom: %w", err))
  491. }
  492. mkRoomReplyBody, ok := mkRoomReply.Body.(wire.SNAC_0x0D_0x09_ChatNavNavInfo)
  493. if !ok {
  494. return 0, s.runtimeErr(ctx, fmt.Errorf("chatNavService.CreateRoom: unexpected response type %v", mkRoomReplyBody))
  495. }
  496. buf, ok := mkRoomReplyBody.Bytes(wire.ChatNavTLVRoomInfo)
  497. if !ok {
  498. return 0, s.runtimeErr(ctx, errors.New("mkRoomReplyBody.Bytes: missing wire.ChatNavTLVRoomInfo"))
  499. }
  500. inBody := wire.SNAC_0x0E_0x02_ChatRoomInfoUpdate{}
  501. if err := wire.UnmarshalBE(&inBody, bytes.NewReader(buf)); err != nil {
  502. return 0, s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  503. }
  504. svcReqSNAC := wire.SNAC_0x01_0x04_OServiceServiceRequest{
  505. FoodGroup: wire.Chat,
  506. TLVRestBlock: wire.TLVRestBlock{
  507. TLVList: wire.TLVList{
  508. wire.NewTLVBE(0x01, wire.SNAC_0x01_0x04_TLVRoomInfo{
  509. Cookie: inBody.Cookie,
  510. }),
  511. },
  512. },
  513. }
  514. svcReqReply, err := s.OServiceServiceBOS.ServiceRequest(ctx, me, wire.SNACFrame{}, svcReqSNAC)
  515. if err != nil {
  516. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ServiceRequest: %w", err))
  517. }
  518. svcReqReplyBody, ok := svcReqReply.Body.(wire.SNAC_0x01_0x05_OServiceServiceResponse)
  519. if !ok {
  520. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ServiceRequest: unexpected response type %v", svcReqReplyBody))
  521. }
  522. loginCookie, hasCookie := svcReqReplyBody.Bytes(wire.OServiceTLVTagsLoginCookie)
  523. if !hasCookie {
  524. return 0, s.runtimeErr(ctx, errors.New("svcReqReplyBody.Bytes: missing wire.OServiceTLVTagsLoginCookie"))
  525. }
  526. chatSess, err := s.AuthService.RegisterChatSession(ctx, loginCookie)
  527. if err != nil {
  528. return 0, s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterChatSession: %w", err))
  529. }
  530. roomInfo := wire.ICBMRoomInfo{
  531. Exchange: inBody.Exchange,
  532. Cookie: inBody.Cookie,
  533. Instance: inBody.InstanceNumber,
  534. }
  535. chatID := chatRegistry.Add(roomInfo)
  536. chatRegistry.RegisterSess(chatID, chatSess)
  537. if err := s.OServiceServiceChat.ClientOnline(ctx, wire.SNAC_0x01_0x02_OServiceClientOnline{}, chatSess); err != nil {
  538. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceChat.ClientOnline: %w", err))
  539. }
  540. return chatID, fmt.Sprintf("CHAT_JOIN:%d:%s", chatID, roomName)
  541. }
  542. // ChatLeave handles the toc_chat_leave TOC command.
  543. //
  544. // From the TiK documentation:
  545. //
  546. // Leave the chat room.
  547. //
  548. // Command syntax: toc_chat_leave <Chat Room ID>
  549. func (s OSCARProxy) ChatLeave(ctx context.Context, chatRegistry *ChatRegistry, cmd []byte) string {
  550. var chatIDStr string
  551. if _, err := parseArgs(cmd, "toc_chat_leave", &chatIDStr); err != nil {
  552. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  553. }
  554. chatID, err := strconv.Atoi(chatIDStr)
  555. if err != nil {
  556. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  557. }
  558. me := chatRegistry.RetrieveSess(chatID)
  559. if me == nil {
  560. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.RetrieveSess: chat session `%d` not found", chatID))
  561. }
  562. s.AuthService.SignoutChat(ctx, me)
  563. me.Close() // stop async server SNAC reply handler for this chat room
  564. return fmt.Sprintf("CHAT_LEFT:%d", chatID)
  565. }
  566. // ChatSend handles the toc_chat_send TOC command.
  567. //
  568. // From the TiK documentation:
  569. //
  570. // Send a message in a chat room using the chat room id from CHAT_JOIN. Since
  571. // reflection is always on in TOC, you do not need to add the message to your
  572. // chat UI, since you will get a CHAT_IN with the message. Remember to quote
  573. // and encode the message.
  574. //
  575. // Command syntax: toc_chat_send <Chat Room ID> <Message>
  576. func (s OSCARProxy) ChatSend(ctx context.Context, chatRegistry *ChatRegistry, cmd []byte) string {
  577. var chatIDStr, msg string
  578. if _, err := parseArgs(cmd, "toc_chat_send", &chatIDStr, &msg); err != nil {
  579. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  580. }
  581. chatID, err := strconv.Atoi(chatIDStr)
  582. if err != nil {
  583. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  584. }
  585. me := chatRegistry.RetrieveSess(chatID)
  586. if me == nil {
  587. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.RetrieveSess: session for chat ID `%d` not found", chatID))
  588. }
  589. block := wire.TLVRestBlock{}
  590. // the order of these TLVs matters for AIM 2.x. if out of order, screen
  591. // names do not appear with each chat message.
  592. block.Append(wire.NewTLVBE(wire.ChatTLVEnableReflectionFlag, uint8(1)))
  593. block.Append(wire.NewTLVBE(wire.ChatTLVSenderInformation, me.TLVUserInfo()))
  594. block.Append(wire.NewTLVBE(wire.ChatTLVPublicWhisperFlag, []byte{}))
  595. block.Append(wire.NewTLVBE(wire.ChatTLVMessageInfo, wire.TLVRestBlock{
  596. TLVList: wire.TLVList{
  597. wire.NewTLVBE(wire.ChatTLVMessageInfoText, msg),
  598. },
  599. }))
  600. snac := wire.SNAC_0x0E_0x05_ChatChannelMsgToHost{
  601. Channel: wire.ICBMChannelMIME,
  602. TLVRestBlock: block,
  603. }
  604. reply, err := s.ChatService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac)
  605. if err != nil {
  606. return s.runtimeErr(ctx, fmt.Errorf("ChatService.ChannelMsgToHost: %w", err))
  607. }
  608. if reply == nil {
  609. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: missing response "))
  610. }
  611. switch v := reply.Body.(type) {
  612. case wire.SNAC_0x0E_0x06_ChatChannelMsgToClient:
  613. msgInfo, ok := v.Bytes(wire.ChatTLVMessageInfo)
  614. if !ok {
  615. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: missing wire.ChatTLVMessageInfo"))
  616. }
  617. reflectMsg, err := wire.UnmarshalChatMessageText(msgInfo)
  618. if err != nil {
  619. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalChatMessageText: %w", err))
  620. }
  621. senderInfo, ok := v.Bytes(wire.ChatTLVSenderInformation)
  622. if !ok {
  623. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: missing wire.ChatTLVSenderInformation"))
  624. }
  625. var userInfo wire.TLVUserInfo
  626. if err := wire.UnmarshalBE(&userInfo, bytes.NewReader(senderInfo)); err != nil {
  627. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  628. }
  629. return fmt.Sprintf("CHAT_IN:%d:%s:F:%s", chatID, userInfo.ScreenName, reflectMsg)
  630. default:
  631. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: unexpected response"))
  632. }
  633. }
  634. // Evil handles the toc_evil TOC command.
  635. //
  636. // From the TiK documentation:
  637. //
  638. // Evil/Warn someone else. The 2nd argument is either the string "norm" for a
  639. // normal warning, or "anon" for an anonymous warning. You can only evil
  640. // people who have recently sent you ims. The higher someones evil level, the
  641. // slower they can send message.
  642. //
  643. // Command syntax: toc_evil <User> <norm|anon>
  644. func (s OSCARProxy) Evil(ctx context.Context, me *state.Session, cmd []byte) string {
  645. var user, scope string
  646. if _, err := parseArgs(cmd, "toc_evil", &user, &scope); err != nil {
  647. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  648. }
  649. snac := wire.SNAC_0x04_0x08_ICBMEvilRequest{
  650. ScreenName: user,
  651. }
  652. switch scope {
  653. case "anon":
  654. snac.SendAs = 1
  655. case "norm":
  656. snac.SendAs = 0
  657. default:
  658. return s.runtimeErr(ctx, fmt.Errorf("incorrect warning type `%s`. allowed values: anon, norm", scope))
  659. }
  660. response, err := s.ICBMService.EvilRequest(ctx, me, wire.SNACFrame{}, snac)
  661. if err != nil {
  662. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.EvilRequest: %w", err))
  663. }
  664. switch v := response.Body.(type) {
  665. case wire.SNAC_0x04_0x09_ICBMEvilReply:
  666. return ""
  667. case wire.SNACError:
  668. s.Logger.InfoContext(ctx, "unable to warn user", "code", v.Code)
  669. default:
  670. return s.runtimeErr(ctx, errors.New("unexpected response"))
  671. }
  672. return ""
  673. }
  674. // FormatNickname handles the toc_format_nickname TOC command.
  675. //
  676. // From the TiK documentation:
  677. //
  678. // Reformat a user's nickname. An ADMIN_NICK_STATUS or ERROR message will be
  679. // sent back to the client.
  680. //
  681. // Command syntax: toc_format_nickname <new_format>
  682. func (s OSCARProxy) FormatNickname(ctx context.Context, me *state.Session, cmd []byte) string {
  683. var newFormat string
  684. if _, err := parseArgs(cmd, "toc_format_nickname", &newFormat); err != nil {
  685. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  686. }
  687. // remove curly braces added by TiK
  688. newFormat = strings.Trim(newFormat, "{}")
  689. reqSNAC := wire.SNAC_0x07_0x04_AdminInfoChangeRequest{
  690. TLVRestBlock: wire.TLVRestBlock{
  691. TLVList: wire.TLVList{
  692. wire.NewTLVBE(wire.AdminTLVScreenNameFormatted, newFormat),
  693. },
  694. },
  695. }
  696. reply, err := s.AdminService.InfoChangeRequest(ctx, me, wire.SNACFrame{}, reqSNAC)
  697. if err != nil {
  698. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: %w", err))
  699. }
  700. replyBody, ok := reply.Body.(wire.SNAC_0x07_0x05_AdminChangeReply)
  701. if !ok {
  702. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: unexpected response type %v", replyBody))
  703. }
  704. code, ok := replyBody.Uint16BE(wire.AdminTLVErrorCode)
  705. if ok {
  706. switch code {
  707. case wire.AdminInfoErrorInvalidNickNameLength, wire.AdminInfoErrorInvalidNickName:
  708. return "ERROR:911"
  709. default:
  710. return "ERROR:913"
  711. }
  712. }
  713. return "ADMIN_NICK_STATUS:0"
  714. }
  715. // GetDirSearchURL handles the toc_dir_search TOC command.
  716. //
  717. // From the TiK documentation:
  718. //
  719. // Perform a search of the Oscar Directory, using colon separated fields as in:
  720. //
  721. // "first name":"middle name":"last name":"maiden name":"city":"state":"country":"email"
  722. //
  723. // You can search by keyword by setting search terms in the 11th position (this
  724. // feature is not in the TiK docs but is present in the code):
  725. //
  726. // ::::::::::"search kw"
  727. //
  728. // Returns either a GOTO_URL or ERROR msg.
  729. //
  730. // Command syntax: toc_dir_search <info information>
  731. func (s OSCARProxy) GetDirSearchURL(ctx context.Context, me *state.Session, cmd []byte) string {
  732. var info string
  733. if _, err := parseArgs(cmd, "toc_dir_search", &info); err != nil {
  734. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  735. }
  736. params := strings.Split(info, ":")
  737. labels := []string{
  738. "first_name",
  739. "middle_name",
  740. "last_name",
  741. "maiden_name",
  742. "city",
  743. "state",
  744. "country",
  745. "email",
  746. "nop", // unused placeholder
  747. "nop",
  748. "keyword",
  749. }
  750. // map labels to param values at their corresponding positions
  751. p := url.Values{}
  752. for i, param := range params {
  753. if i >= len(labels) {
  754. break
  755. }
  756. if param != "" {
  757. p.Add(labels[i], strings.Trim(param, "\""))
  758. }
  759. }
  760. if len(p) == 0 {
  761. return s.runtimeErr(ctx, errors.New("no search fields found"))
  762. }
  763. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  764. if err != nil {
  765. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  766. }
  767. p.Add("cookie", cookie)
  768. return fmt.Sprintf("GOTO_URL:search results:dir_search?%s", p.Encode())
  769. }
  770. // GetDirURL handles the toc_get_dir TOC command.
  771. //
  772. // From the TiK documentation:
  773. //
  774. // Gets a user's dir info a GOTO_URL or ERROR message will be sent back to the client.
  775. //
  776. // Command syntax: toc_get_dir <username>
  777. func (s OSCARProxy) GetDirURL(ctx context.Context, me *state.Session, cmd []byte) string {
  778. var user string
  779. if _, err := parseArgs(cmd, "toc_get_dir", &user); err != nil {
  780. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  781. }
  782. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  783. if err != nil {
  784. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  785. }
  786. p := url.Values{}
  787. p.Add("cookie", cookie)
  788. p.Add("user", user)
  789. return fmt.Sprintf("GOTO_URL:directory info:dir_info?%s", p.Encode())
  790. }
  791. // GetInfoURL handles the toc_get_info TOC command.
  792. //
  793. // From the TiK documentation:
  794. //
  795. // Gets a user's info a GOTO_URL or ERROR message will be sent back to the client.
  796. //
  797. // Command syntax: toc_get_info <username>
  798. func (s OSCARProxy) GetInfoURL(ctx context.Context, me *state.Session, cmd []byte) string {
  799. var user string
  800. if _, err := parseArgs(cmd, "toc_get_info", &user); err != nil {
  801. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  802. }
  803. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  804. if err != nil {
  805. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  806. }
  807. p := url.Values{}
  808. p.Add("cookie", cookie)
  809. p.Add("from", me.IdentScreenName().String())
  810. p.Add("user", user)
  811. return fmt.Sprintf("GOTO_URL:profile:info?%s", p.Encode())
  812. }
  813. // GetStatus handles the toc_get_status TOC command.
  814. //
  815. // From the TOC2 documentation:
  816. //
  817. // This useful command wasn't ever really documented. It returns either an
  818. // UPDATE_BUDDY message or an ERROR message depending on whether or not the
  819. // guy appears to be online.
  820. //
  821. // Command syntax: toc_get_status <screenname>
  822. func (s OSCARProxy) GetStatus(ctx context.Context, me *state.Session, cmd []byte) string {
  823. var them string
  824. if _, err := parseArgs(cmd, "toc_get_status", &them); err != nil {
  825. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  826. }
  827. inBody := wire.SNAC_0x02_0x05_LocateUserInfoQuery{
  828. ScreenName: them,
  829. }
  830. info, err := s.LocateService.UserInfoQuery(ctx, me, wire.SNACFrame{}, inBody)
  831. if err != nil {
  832. return s.runtimeErr(ctx, fmt.Errorf("LocateService.UserInfoQuery: %w", err))
  833. }
  834. switch v := info.Body.(type) {
  835. case wire.SNACError:
  836. if v.Code == wire.ErrorCodeNotLoggedOn {
  837. return fmt.Sprintf("ERROR:901:%s", them)
  838. } else {
  839. return s.runtimeErr(ctx, fmt.Errorf("LocateService.UserInfoQuery error code: %d", v.Code))
  840. }
  841. case wire.SNAC_0x02_0x06_LocateUserInfoReply:
  842. return userInfoToUpdateBuddy(v.TLVUserInfo)
  843. default:
  844. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: unexpected response type %v", v))
  845. }
  846. }
  847. // InitDone handles the toc_init_done TOC command.
  848. //
  849. // From the TiK documentation:
  850. //
  851. // Tells TOC that we are ready to go online. TOC clients should first send TOC
  852. // the buddy list and any permit/deny lists. However, toc_init_done must be
  853. // called within 30 seconds after toc_signon, or the connection will be
  854. // dropped. Remember, it can't be called until after the SIGN_ON message is
  855. // received. Calling this before or multiple times after a SIGN_ON will cause
  856. // the connection to be dropped.
  857. //
  858. // Note: The business logic described in the last 3 sentences are not yet
  859. // implemented.
  860. //
  861. // Command syntax: toc_init_done
  862. func (s OSCARProxy) InitDone(ctx context.Context, sess *state.Session, cmd []byte) string {
  863. if _, err := parseArgs(cmd, "toc_init_done"); err != nil {
  864. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  865. }
  866. if err := s.OServiceServiceBOS.ClientOnline(ctx, wire.SNAC_0x01_0x02_OServiceClientOnline{}, sess); err != nil {
  867. return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ClientOnliney: %w", err))
  868. }
  869. return ""
  870. }
  871. // RemoveBuddy handles the toc_remove_buddy TOC command.
  872. //
  873. // From the TiK documentation:
  874. //
  875. // Remove buddies from your buddy list. This does not change your saved config.
  876. //
  877. // Command syntax:
  878. func (s OSCARProxy) RemoveBuddy(ctx context.Context, me *state.Session, cmd []byte) string {
  879. users, err := parseArgs(cmd, "toc_remove_buddy")
  880. if err != nil {
  881. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  882. }
  883. snac := wire.SNAC_0x03_0x05_BuddyDelBuddies{}
  884. for _, sn := range users {
  885. snac.Buddies = append(snac.Buddies, struct {
  886. ScreenName string `oscar:"len_prefix=uint8"`
  887. }{ScreenName: sn})
  888. }
  889. if err := s.BuddyService.DelBuddies(ctx, me, snac); err != nil {
  890. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.DelBuddies: %w", err))
  891. }
  892. return ""
  893. }
  894. // SendIM handles the toc_send_im TOC command.
  895. //
  896. // From the TiK documentation:
  897. //
  898. // Send a message to a remote user. Remember to quote and encode the message.
  899. // If the optional string "auto" is the last argument, then the auto response
  900. // flag will be turned on for the IM.
  901. //
  902. // Command syntax: toc_send_im <Destination User> <Message> [auto]
  903. func (s OSCARProxy) SendIM(ctx context.Context, sender *state.Session, cmd []byte) string {
  904. var recip, msg string
  905. autoReply, err := parseArgs(cmd, "toc_send_im", &recip, &msg)
  906. if err != nil {
  907. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  908. }
  909. frags, err := wire.ICBMFragmentList(msg)
  910. if err != nil {
  911. return s.runtimeErr(ctx, fmt.Errorf("wire.ICBMFragmentList: %w", err))
  912. }
  913. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  914. ChannelID: wire.ICBMChannelIM,
  915. ScreenName: recip,
  916. TLVRestBlock: wire.TLVRestBlock{
  917. TLVList: wire.TLVList{
  918. wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags),
  919. },
  920. },
  921. }
  922. if len(autoReply) > 0 && autoReply[0] == "auto" {
  923. snac.Append(wire.NewTLVBE(wire.ICBMTLVAutoResponse, []byte{}))
  924. }
  925. // send message and ignore response since there is no TOC error code to
  926. // handle errors such as "user is offline", etc.
  927. _, err = s.ICBMService.ChannelMsgToHost(ctx, sender, wire.SNACFrame{}, snac)
  928. if err != nil {
  929. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  930. }
  931. return ""
  932. }
  933. // SetAway handles the toc_chat_join TOC command.
  934. //
  935. // From the TiK documentation:
  936. //
  937. // If the away message is present, then the unavailable status flag is set for
  938. // the user. If the away message is not present, then the unavailable status
  939. // flag is unset. The away message is basic HTML, remember to encode the
  940. // information.
  941. //
  942. // Command syntax: toc_set_away [<away message>]
  943. func (s OSCARProxy) SetAway(ctx context.Context, me *state.Session, cmd []byte) string {
  944. maybeMsg, err := parseArgs(cmd, "toc_set_away")
  945. if err != nil {
  946. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  947. }
  948. var msg string
  949. if len(maybeMsg) > 0 {
  950. msg = maybeMsg[0]
  951. }
  952. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  953. TLVRestBlock: wire.TLVRestBlock{
  954. TLVList: wire.TLVList{
  955. wire.NewTLVBE(wire.LocateTLVTagsInfoUnavailableData, msg),
  956. },
  957. },
  958. }
  959. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  960. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  961. }
  962. return ""
  963. }
  964. // SetCaps handles the toc_set_caps TOC command.
  965. //
  966. // From the TiK documentation:
  967. //
  968. // Set my capabilities. All capabilities that we support need to be sent at
  969. // the same time. Capabilities are represented by UUIDs.
  970. //
  971. // This method automatically adds the "chat" capability since it doesn't seem
  972. // to be sent explicitly by the official clients, even though they support
  973. // chat.
  974. //
  975. // Command syntax: toc_set_caps [ <Capability 1> [<Capability 2> [...]]]
  976. func (s OSCARProxy) SetCaps(ctx context.Context, me *state.Session, cmd []byte) string {
  977. params, err := parseArgs(cmd, "toc_set_caps")
  978. if err != nil {
  979. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  980. }
  981. caps := make([]uuid.UUID, 0, 16*(len(params)+1))
  982. for _, capStr := range params {
  983. uid, err := uuid.Parse(capStr)
  984. if err != nil {
  985. return s.runtimeErr(ctx, fmt.Errorf("UUID.Parse: %w", err))
  986. }
  987. caps = append(caps, uid)
  988. }
  989. caps = append(caps, capChat)
  990. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  991. TLVRestBlock: wire.TLVRestBlock{
  992. TLVList: wire.TLVList{
  993. wire.NewTLVBE(wire.LocateTLVTagsInfoCapabilities, caps),
  994. },
  995. },
  996. }
  997. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  998. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  999. }
  1000. return ""
  1001. }
  1002. // SetConfig handles the toc_set_config TOC command.
  1003. //
  1004. // From the TiK documentation:
  1005. //
  1006. // Set the config information for this user. The config information is line
  1007. // oriented with the first character being the item type, followed by a space,
  1008. // with the rest of the line being the item value. Only letters, numbers, and
  1009. // spaces should be used. Remember you will have to enclose the entire config
  1010. // in quotes.
  1011. //
  1012. // Item Types:
  1013. // - g - Buddy Group (All Buddies until the next g or the end of config are in this group.)
  1014. // - b - A Buddy
  1015. // - p - Person on permit list
  1016. // - d - Person on deny list
  1017. // - m - Permit/Deny Mode. Possible values are
  1018. // - 1 - Permit All
  1019. // - 2 - Deny All
  1020. // - 3 - Permit Some
  1021. // - 4 - Deny Some
  1022. //
  1023. // Command syntax: toc_set_config <Config Info>
  1024. func (s OSCARProxy) SetConfig(ctx context.Context, me *state.Session, cmd []byte) string {
  1025. // replace curly braces with quotes so that the string can be properly
  1026. // split up by the space-delimited reader
  1027. for i, c := range cmd {
  1028. if c == '{' || c == '}' {
  1029. cmd[i] = '"'
  1030. }
  1031. }
  1032. cmd = bytes.TrimSpace(cmd)
  1033. var info string
  1034. if _, err := parseArgs(cmd, "toc_set_config", &info); err != nil {
  1035. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1036. }
  1037. config := strings.Split(info, "\n")
  1038. var cfg [][2]string
  1039. for _, item := range config {
  1040. parts := strings.Split(item, " ")
  1041. if len(parts) != 2 {
  1042. s.Logger.InfoContext(ctx, "invalid config item", "item", item, "user", me.DisplayScreenName())
  1043. continue
  1044. }
  1045. cfg = append(cfg, [2]string{parts[0], parts[1]})
  1046. }
  1047. mode := wire.FeedbagPDModePermitAll
  1048. for _, c := range cfg {
  1049. if c[0] != "m" {
  1050. continue
  1051. }
  1052. switch c[1] {
  1053. case "1":
  1054. mode = wire.FeedbagPDModePermitAll
  1055. case "2":
  1056. mode = wire.FeedbagPDModeDenyAll
  1057. case "3":
  1058. mode = wire.FeedbagPDModePermitSome
  1059. case "4":
  1060. mode = wire.FeedbagPDModeDenySome
  1061. default:
  1062. return s.runtimeErr(ctx, fmt.Errorf("config: invalid mode `%s`", c[1]))
  1063. }
  1064. }
  1065. switch mode {
  1066. case wire.FeedbagPDModePermitAll:
  1067. snac := wire.SNAC_0x09_0x07_PermitDenyAddDenyListEntries{
  1068. Users: []struct {
  1069. ScreenName string `oscar:"len_prefix=uint8"`
  1070. }{
  1071. {
  1072. ScreenName: me.IdentScreenName().String(),
  1073. },
  1074. },
  1075. }
  1076. if err := s.PermitDenyService.AddDenyListEntries(ctx, me, snac); err != nil {
  1077. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddDenyListEntries: %w", err))
  1078. }
  1079. case wire.FeedbagPDModeDenyAll:
  1080. snac := wire.SNAC_0x09_0x05_PermitDenyAddPermListEntries{
  1081. Users: []struct {
  1082. ScreenName string `oscar:"len_prefix=uint8"`
  1083. }{
  1084. {
  1085. ScreenName: me.IdentScreenName().String(),
  1086. },
  1087. },
  1088. }
  1089. if err := s.PermitDenyService.AddPermListEntries(ctx, me, snac); err != nil {
  1090. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddPermListEntrie: %w", err))
  1091. }
  1092. case wire.FeedbagPDModePermitSome:
  1093. snac := wire.SNAC_0x09_0x05_PermitDenyAddPermListEntries{}
  1094. for _, c := range cfg {
  1095. if c[0] != "p" {
  1096. continue
  1097. }
  1098. snac.Users = append(snac.Users, struct {
  1099. ScreenName string `oscar:"len_prefix=uint8"`
  1100. }{ScreenName: c[1]})
  1101. }
  1102. if err := s.PermitDenyService.AddPermListEntries(ctx, me, snac); err != nil {
  1103. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddPermListEntrie: %w", err))
  1104. }
  1105. case wire.FeedbagPDModeDenySome:
  1106. snac := wire.SNAC_0x09_0x07_PermitDenyAddDenyListEntries{}
  1107. for _, c := range cfg {
  1108. if c[0] != "d" {
  1109. continue
  1110. }
  1111. snac.Users = append(snac.Users, struct {
  1112. ScreenName string `oscar:"len_prefix=uint8"`
  1113. }{ScreenName: c[1]})
  1114. }
  1115. if err := s.PermitDenyService.AddDenyListEntries(ctx, me, snac); err != nil {
  1116. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddDenyListEntries: %w", err))
  1117. }
  1118. }
  1119. snac := wire.SNAC_0x03_0x04_BuddyAddBuddies{}
  1120. for _, c := range cfg {
  1121. if c[0] != "b" {
  1122. continue
  1123. }
  1124. snac.Buddies = append(snac.Buddies, struct {
  1125. ScreenName string `oscar:"len_prefix=uint8"`
  1126. }{ScreenName: c[1]})
  1127. }
  1128. if err := s.BuddyService.AddBuddies(ctx, me, snac); err != nil {
  1129. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.AddBuddies: %w", err))
  1130. }
  1131. if err := s.TOCConfigStore.SetTOCConfig(me.IdentScreenName(), info); err != nil {
  1132. return s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.SaveTOCConfig: %w", err))
  1133. }
  1134. return ""
  1135. }
  1136. // SetDir handles the toc_set_dir TOC command.
  1137. //
  1138. // From the TiK documentation:
  1139. //
  1140. // Set the DIR user information. This is a colon separated fields as in:
  1141. //
  1142. // "first name":"middle name":"last name":"maiden name":"city":"state":"country":"email":"allow web searches".
  1143. //
  1144. // Should return a DIR_STATUS msg. Having anything in the "allow web searches"
  1145. // field allows people to use web-searches to find your directory info.
  1146. // Otherwise, they'd have to use the client.
  1147. //
  1148. // The fields "email" and "allow web searches" are ignored by this method.
  1149. //
  1150. // Command syntax: toc_set_dir <info information>
  1151. func (s OSCARProxy) SetDir(ctx context.Context, me *state.Session, cmd []byte) string {
  1152. var info string
  1153. if _, err := parseArgs(cmd, "toc_set_dir", &info); err != nil {
  1154. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1155. }
  1156. rawFields := strings.Split(info, ":")
  1157. var finalFields [9]string
  1158. if len(rawFields) > len(finalFields) {
  1159. return s.runtimeErr(ctx, fmt.Errorf("expected at most %d params, got %d", len(finalFields), len(rawFields)))
  1160. }
  1161. for i, a := range rawFields {
  1162. finalFields[i] = strings.Trim(a, "\"")
  1163. }
  1164. snac := wire.SNAC_0x02_0x09_LocateSetDirInfo{
  1165. TLVRestBlock: wire.TLVRestBlock{
  1166. TLVList: wire.TLVList{
  1167. wire.NewTLVBE(wire.ODirTLVFirstName, finalFields[0]),
  1168. wire.NewTLVBE(wire.ODirTLVMiddleName, finalFields[1]),
  1169. wire.NewTLVBE(wire.ODirTLVLastName, finalFields[2]),
  1170. wire.NewTLVBE(wire.ODirTLVMaidenName, finalFields[3]),
  1171. wire.NewTLVBE(wire.ODirTLVCountry, finalFields[6]),
  1172. wire.NewTLVBE(wire.ODirTLVState, finalFields[5]),
  1173. wire.NewTLVBE(wire.ODirTLVCity, finalFields[4]),
  1174. },
  1175. },
  1176. }
  1177. if _, err := s.LocateService.SetDirInfo(ctx, me, wire.SNACFrame{}, snac); err != nil {
  1178. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetDirInfo: %w", err))
  1179. }
  1180. return ""
  1181. }
  1182. // SetIdle handles the toc_set_idle TOC command.
  1183. //
  1184. // From the TiK documentation:
  1185. //
  1186. // Set idle information. If <idle secs> is 0 then the user isn't idle at all.
  1187. // If <idle secs> is greater than 0 then the user has already been idle for
  1188. // <idle secs> number of seconds. The server will automatically keep
  1189. // incrementing this number, so do not repeatedly call with new idle times.
  1190. //
  1191. // Command syntax: toc_set_idle <idle secs>
  1192. func (s OSCARProxy) SetIdle(ctx context.Context, me *state.Session, cmd []byte) string {
  1193. var idleTimeStr string
  1194. if _, err := parseArgs(cmd, "toc_set_idle", &idleTimeStr); err != nil {
  1195. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1196. }
  1197. time, err := strconv.Atoi(idleTimeStr)
  1198. if err != nil {
  1199. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  1200. }
  1201. snac := wire.SNAC_0x01_0x11_OServiceIdleNotification{
  1202. IdleTime: uint32(time),
  1203. }
  1204. if err := s.OServiceServiceBOS.IdleNotification(ctx, me, snac); err != nil {
  1205. return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.IdleNotification: %w", err))
  1206. }
  1207. return ""
  1208. }
  1209. // SetInfo handles the toc_set_info TOC command.
  1210. //
  1211. // From the TiK documentation:
  1212. //
  1213. // Set the LOCATE user information. This is basic HTML. Remember to encode the info.
  1214. //
  1215. // Command syntax: toc_set_info <info information>
  1216. func (s OSCARProxy) SetInfo(ctx context.Context, me *state.Session, cmd []byte) string {
  1217. var info string
  1218. if _, err := parseArgs(cmd, "toc_set_info", &info); err != nil {
  1219. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1220. }
  1221. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  1222. TLVRestBlock: wire.TLVRestBlock{
  1223. TLVList: wire.TLVList{
  1224. wire.NewTLVBE(wire.LocateTLVTagsInfoSigData, info),
  1225. },
  1226. },
  1227. }
  1228. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  1229. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  1230. }
  1231. return ""
  1232. }
  1233. // Signon handles the toc_signon TOC command.
  1234. //
  1235. // From the TiK documentation:
  1236. //
  1237. // The password needs to be roasted with the Roasting String if coming over a
  1238. // FLAP connection, CP connections don't use roasted passwords. The language
  1239. // specified will be used when generating web pages, such as the get info
  1240. // pages. Currently, the only supported language is "english". If the language
  1241. // sent isn't found, the default "english" language will be used. The version
  1242. // string will be used for the client identity, and must be less than 50
  1243. // characters.
  1244. //
  1245. // Passwords are roasted when sent to the host. This is done so they aren't
  1246. // sent in "clear text" over the wire, although they are still trivial to
  1247. // decode. Roasting is performed by first xoring each byte in the password
  1248. // with the equivalent modulo byte in the roasting string. The result is then
  1249. // converted to ascii hex, and prepended with "0x". So for example the
  1250. // password "password" roasts to "0x2408105c23001130".
  1251. //
  1252. // The Roasting String is Tic/Toc.
  1253. //
  1254. // Command syntax: toc_signon <authorizer host> <authorizer port> <User Name> <Password> <language> <version>
  1255. func (s OSCARProxy) Signon(ctx context.Context, cmd []byte) (*state.Session, []string) {
  1256. var userName, password string
  1257. if _, err := parseArgs(cmd, "toc_signon", nil, nil, &userName, &password); err != nil {
  1258. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))}
  1259. }
  1260. passwordHash, err := hex.DecodeString(password[2:])
  1261. if err != nil {
  1262. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("hex.DecodeString: %w", err))}
  1263. }
  1264. signonFrame := wire.FLAPSignonFrame{}
  1265. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsScreenName, userName))
  1266. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsRoastedTOCPassword, passwordHash))
  1267. block, err := s.AuthService.FLAPLogin(signonFrame, state.NewStubUser)
  1268. if err != nil {
  1269. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("AuthService.FLAPLogin: %w", err))}
  1270. }
  1271. if block.HasTag(wire.LoginTLVTagsErrorSubcode) {
  1272. s.Logger.DebugContext(ctx, "login failed")
  1273. return nil, []string{"ERROR:980"} // bad username/password
  1274. }
  1275. authCookie, ok := block.Bytes(wire.OServiceTLVTagsLoginCookie)
  1276. if !ok {
  1277. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("unable to get session id from payload"))}
  1278. }
  1279. sess, err := s.AuthService.RegisterBOSSession(ctx, authCookie)
  1280. if err != nil {
  1281. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterBOSSession: %w", err))}
  1282. }
  1283. // set chat capability so that... tk
  1284. sess.SetCaps([][16]byte{capChat})
  1285. if err := s.BuddyListRegistry.RegisterBuddyList(sess.IdentScreenName()); err != nil {
  1286. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("BuddyListRegistry.RegisterBuddyList: %w", err))}
  1287. }
  1288. u, err := s.TOCConfigStore.User(sess.IdentScreenName())
  1289. if err != nil {
  1290. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.User: %w", err))}
  1291. }
  1292. if u == nil {
  1293. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.User: user not found"))}
  1294. }
  1295. return sess, []string{"SIGN_ON:TOC1.0", fmt.Sprintf("CONFIG:%s", u.TOCConfig)}
  1296. }
  1297. // Signout terminates a TOC session. It sends departure notifications to
  1298. // buddies, de-registers buddy list and session.
  1299. func (s OSCARProxy) Signout(ctx context.Context, me *state.Session) {
  1300. if err := s.BuddyService.BroadcastBuddyDeparted(ctx, me); err != nil {
  1301. s.Logger.ErrorContext(ctx, "error sending departure notifications", "err", err.Error())
  1302. }
  1303. if err := s.BuddyListRegistry.UnregisterBuddyList(me.IdentScreenName()); err != nil {
  1304. s.Logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  1305. }
  1306. s.AuthService.Signout(ctx, me)
  1307. }
  1308. // newHTTPAuthToken creates a HMAC token for authenticating TOC HTTP requests
  1309. func (s OSCARProxy) newHTTPAuthToken(me state.IdentScreenName) (string, error) {
  1310. cookie, err := s.CookieBaker.Issue([]byte(me.String()))
  1311. if err != nil {
  1312. return "", err
  1313. }
  1314. // trim padding so that gaim doesn't choke on the long value
  1315. cookie = bytes.TrimRight(cookie, "\x00")
  1316. return hex.EncodeToString(cookie), nil
  1317. }
  1318. // parseArgs extracts arguments from a TOC command. Each positional argument is
  1319. // assigned to its corresponding args pointer. It returns the remaining
  1320. // arguments as varargs.
  1321. func parseArgs(payload []byte, cmd string, args ...*string) (varArgs []string, err error) {
  1322. reader := csv.NewReader(bytes.NewReader(payload))
  1323. reader.Comma = ' '
  1324. reader.LazyQuotes = true
  1325. reader.TrimLeadingSpace = true
  1326. segs, err := reader.Read()
  1327. if err != nil {
  1328. return []string{}, fmt.Errorf("CSV reader error: %w", err)
  1329. }
  1330. // sanity check the command name
  1331. if segs[0] != cmd {
  1332. return []string{}, fmt.Errorf("command mismatch. expected %s, got %s", cmd, segs[0])
  1333. }
  1334. // all elements after the command are arguments
  1335. segs = segs[1:]
  1336. if len(segs) < len(args) {
  1337. return []string{}, fmt.Errorf("command contains fewer arguments than expected")
  1338. }
  1339. // populate placeholder pointers with their corresponding values
  1340. for i, arg := range args {
  1341. if arg != nil {
  1342. *arg = strings.TrimSpace(segs[i])
  1343. }
  1344. }
  1345. // dump remaining arguments as varargs
  1346. return segs[len(args):], err
  1347. }
  1348. // runtimeErr is a convenience function that logs an error and returns a TOC
  1349. // internal server error.
  1350. func (s OSCARProxy) runtimeErr(ctx context.Context, err error) string {
  1351. s.Logger.ErrorContext(ctx, "internal service error", "err", err.Error())
  1352. return cmdInternalSvcErr
  1353. }