cmd_client.go 44 KB

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