cmd_client.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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.InfoContext(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_chat_join 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. if _, err := s.ChatService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac); err != nil {
  556. return s.runtimeErr(ctx, fmt.Errorf("ChatService.ChannelMsgToHost: %w", err))
  557. }
  558. return fmt.Sprintf("CHAT_IN:%d:%s:F:%s", chatID, me.DisplayScreenName(), msg)
  559. }
  560. // Evil handles the toc_evil TOC command.
  561. //
  562. // From the TiK documentation:
  563. //
  564. // Evil/Warn someone else. The 2nd argument is either the string "norm" for a
  565. // normal warning, or "anon" for an anonymous warning. You can only evil
  566. // people who have recently sent you ims. The higher someones evil level, the
  567. // slower they can send message.
  568. //
  569. // Command syntax: toc_evil <User> <norm|anon>
  570. func (s OSCARProxy) Evil(ctx context.Context, me *state.Session, cmd []byte) string {
  571. var user, scope string
  572. if _, err := parseArgs(cmd, "toc_evil", &user, &scope); err != nil {
  573. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  574. }
  575. snac := wire.SNAC_0x04_0x08_ICBMEvilRequest{
  576. ScreenName: user,
  577. }
  578. switch scope {
  579. case "anon":
  580. snac.SendAs = 1
  581. case "norm":
  582. snac.SendAs = 0
  583. default:
  584. return s.runtimeErr(ctx, fmt.Errorf("incorrect warning type `%s`. allowed values: anon, norm", scope))
  585. }
  586. response, err := s.ICBMService.EvilRequest(ctx, me, wire.SNACFrame{}, snac)
  587. if err != nil {
  588. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.EvilRequest: %w", err))
  589. }
  590. switch v := response.Body.(type) {
  591. case wire.SNAC_0x04_0x09_ICBMEvilReply:
  592. return ""
  593. case wire.SNACError:
  594. s.Logger.InfoContext(ctx, "unable to warn user", "code", v.Code)
  595. default:
  596. return s.runtimeErr(ctx, errors.New("unexpected response"))
  597. }
  598. return ""
  599. }
  600. // GetDirSearchURL handles the toc_dir_search TOC command.
  601. //
  602. // From the TiK documentation:
  603. //
  604. // Perform a search of the Oscar Directory, using colon separated fields as in:
  605. //
  606. // "first name":"middle name":"last name":"maiden name":"city":"state":"country":"email"
  607. //
  608. // You can search by keyword by setting search terms in the 11th position (this
  609. // feature is not in the TiK docs but is present in the code):
  610. //
  611. // ::::::::::"search kw"
  612. //
  613. // Returns either a GOTO_URL or ERROR msg.
  614. //
  615. // Command syntax: toc_dir_search <info information>
  616. func (s OSCARProxy) GetDirSearchURL(ctx context.Context, me *state.Session, cmd []byte) string {
  617. var info string
  618. if _, err := parseArgs(cmd, "toc_dir_search", &info); err != nil {
  619. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  620. }
  621. params := strings.Split(info, ":")
  622. labels := []string{
  623. "first_name",
  624. "middle_name",
  625. "last_name",
  626. "maiden_name",
  627. "city",
  628. "state",
  629. "country",
  630. "email",
  631. "nop", // unused placeholder
  632. "nop",
  633. "keyword",
  634. }
  635. // map labels to param values at their corresponding positions
  636. p := url.Values{}
  637. i := 0
  638. for i < len(params) && i < len(labels) {
  639. if len(params[i]) > 0 {
  640. p.Add(labels[i], strings.Trim(params[i], "\""))
  641. }
  642. i++
  643. }
  644. if len(p) == 0 {
  645. return s.runtimeErr(ctx, errors.New("no search fields found"))
  646. }
  647. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  648. if err != nil {
  649. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  650. }
  651. p.Add("cookie", cookie)
  652. return fmt.Sprintf("GOTO_URL:search results:dir_search?%s", p.Encode())
  653. }
  654. // GetDirURL handles the toc_get_dir TOC command.
  655. //
  656. // From the TiK documentation:
  657. //
  658. // Gets a user's dir info a GOTO_URL or ERROR message will be sent back to the client.
  659. //
  660. // Command syntax: toc_get_dir <username>
  661. func (s OSCARProxy) GetDirURL(ctx context.Context, me *state.Session, cmd []byte) string {
  662. var user string
  663. if _, err := parseArgs(cmd, "toc_get_dir", &user); err != nil {
  664. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  665. }
  666. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  667. if err != nil {
  668. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  669. }
  670. p := url.Values{}
  671. p.Add("cookie", cookie)
  672. p.Add("user", user)
  673. return fmt.Sprintf("GOTO_URL:directory info:dir_info?%s", p.Encode())
  674. }
  675. // GetInfoURL handles the toc_get_info TOC command.
  676. //
  677. // From the TiK documentation:
  678. //
  679. // Gets a user's info a GOTO_URL or ERROR message will be sent back to the client.
  680. //
  681. // Command syntax: toc_get_info <username>
  682. func (s OSCARProxy) GetInfoURL(ctx context.Context, me *state.Session, cmd []byte) string {
  683. var user string
  684. if _, err := parseArgs(cmd, "toc_get_info", &user); err != nil {
  685. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  686. }
  687. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  688. if err != nil {
  689. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  690. }
  691. p := url.Values{}
  692. p.Add("cookie", cookie)
  693. p.Add("from", me.IdentScreenName().String())
  694. p.Add("user", user)
  695. return fmt.Sprintf("GOTO_URL:profile:info?%s", p.Encode())
  696. }
  697. // InitDone handles the toc_init_done TOC command.
  698. //
  699. // From the TiK documentation:
  700. //
  701. // Tells TOC that we are ready to go online. TOC clients should first send TOC
  702. // the buddy list and any permit/deny lists. However, toc_init_done must be
  703. // called within 30 seconds after toc_signon, or the connection will be
  704. // dropped. Remember, it can't be called until after the SIGN_ON message is
  705. // received. Calling this before or multiple times after a SIGN_ON will cause
  706. // the connection to be dropped.
  707. //
  708. // Note: The business logic described in the last 3 sentences are not yet
  709. // implemented.
  710. //
  711. // Command syntax: toc_init_done
  712. func (s OSCARProxy) InitDone(ctx context.Context, sess *state.Session, cmd []byte) string {
  713. if _, err := parseArgs(cmd, "toc_init_done"); err != nil {
  714. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  715. }
  716. if err := s.OServiceServiceBOS.ClientOnline(ctx, wire.SNAC_0x01_0x02_OServiceClientOnline{}, sess); err != nil {
  717. return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ClientOnliney: %w", err))
  718. }
  719. return ""
  720. }
  721. // RemoveBuddy handles the toc_remove_buddy TOC command.
  722. //
  723. // From the TiK documentation:
  724. //
  725. // Remove buddies from your buddy list. This does not change your saved config.
  726. //
  727. // Command syntax:
  728. func (s OSCARProxy) RemoveBuddy(ctx context.Context, me *state.Session, cmd []byte) string {
  729. users, err := parseArgs(cmd, "toc_remove_buddy")
  730. if err != nil {
  731. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  732. }
  733. snac := wire.SNAC_0x03_0x05_BuddyDelBuddies{}
  734. for _, sn := range users {
  735. snac.Buddies = append(snac.Buddies, struct {
  736. ScreenName string `oscar:"len_prefix=uint8"`
  737. }{ScreenName: sn})
  738. }
  739. if err := s.BuddyService.DelBuddies(ctx, me, snac); err != nil {
  740. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.DelBuddies: %w", err))
  741. }
  742. return ""
  743. }
  744. // SendIM handles the toc_send_im TOC command.
  745. //
  746. // From the TiK documentation:
  747. //
  748. // Send a message to a remote user. Remember to quote and encode the message.
  749. // If the optional string "auto" is the last argument, then the auto response
  750. // flag will be turned on for the IM.
  751. //
  752. // Command syntax: toc_send_im <Destination User> <Message> [auto]
  753. func (s OSCARProxy) SendIM(ctx context.Context, sender *state.Session, cmd []byte) string {
  754. var recip, msg string
  755. autoReply, err := parseArgs(cmd, "toc_send_im", &recip, &msg)
  756. if err != nil {
  757. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  758. }
  759. frags, err := wire.ICBMFragmentList(msg)
  760. if err != nil {
  761. return s.runtimeErr(ctx, fmt.Errorf("wire.ICBMFragmentList: %w", err))
  762. }
  763. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  764. ChannelID: wire.ICBMChannelIM,
  765. ScreenName: recip,
  766. TLVRestBlock: wire.TLVRestBlock{
  767. TLVList: wire.TLVList{
  768. wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags),
  769. },
  770. },
  771. }
  772. if len(autoReply) > 0 && autoReply[0] == "auto" {
  773. snac.Append(wire.NewTLVBE(wire.ICBMTLVAutoResponse, []byte{}))
  774. }
  775. // send message and ignore response since there is no TOC error code to
  776. // handle errors such as "user is offline", etc.
  777. _, err = s.ICBMService.ChannelMsgToHost(ctx, sender, wire.SNACFrame{}, snac)
  778. if err != nil {
  779. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  780. }
  781. return ""
  782. }
  783. // SetAway handles the toc_chat_join TOC command.
  784. //
  785. // From the TiK documentation:
  786. //
  787. // If the away message is present, then the unavailable status flag is set for
  788. // the user. If the away message is not present, then the unavailable status
  789. // flag is unset. The away message is basic HTML, remember to encode the
  790. // information.
  791. //
  792. // Command syntax: toc_set_away [<away message>]
  793. func (s OSCARProxy) SetAway(ctx context.Context, me *state.Session, cmd []byte) string {
  794. maybeMsg, err := parseArgs(cmd, "toc_set_away")
  795. if err != nil {
  796. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  797. }
  798. var msg string
  799. if len(maybeMsg) > 0 {
  800. msg = maybeMsg[0]
  801. }
  802. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  803. TLVRestBlock: wire.TLVRestBlock{
  804. TLVList: wire.TLVList{
  805. wire.NewTLVBE(wire.LocateTLVTagsInfoUnavailableData, msg),
  806. },
  807. },
  808. }
  809. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  810. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  811. }
  812. return ""
  813. }
  814. // SetCaps handles the toc_set_caps TOC command.
  815. //
  816. // From the TiK documentation:
  817. //
  818. // Set my capabilities. All capabilities that we support need to be sent at
  819. // the same time. Capabilities are represented by UUIDs.
  820. //
  821. // This method automatically adds the "chat" capability since it doesn't seem
  822. // to be sent explicitly by the official clients, even though they support
  823. // chat.
  824. //
  825. // Command syntax: toc_set_caps [ <Capability 1> [<Capability 2> [...]]]
  826. func (s OSCARProxy) SetCaps(ctx context.Context, me *state.Session, cmd []byte) string {
  827. params, err := parseArgs(cmd, "toc_set_caps")
  828. if err != nil {
  829. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  830. }
  831. caps := make([]uuid.UUID, 0, 16*(len(params)+1))
  832. for _, capStr := range params {
  833. uid, err := uuid.Parse(capStr)
  834. if err != nil {
  835. return s.runtimeErr(ctx, fmt.Errorf("UUID.Parse: %w", err))
  836. }
  837. caps = append(caps, uid)
  838. }
  839. caps = append(caps, capChat)
  840. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  841. TLVRestBlock: wire.TLVRestBlock{
  842. TLVList: wire.TLVList{
  843. wire.NewTLVBE(wire.LocateTLVTagsInfoCapabilities, caps),
  844. },
  845. },
  846. }
  847. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  848. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  849. }
  850. return ""
  851. }
  852. // SetConfig handles the toc_set_config TOC command.
  853. //
  854. // From the TiK documentation:
  855. //
  856. // Set the config information for this user. The config information is line
  857. // oriented with the first character being the item type, followed by a space,
  858. // with the rest of the line being the item value. Only letters, numbers, and
  859. // spaces should be used. Remember you will have to enclose the entire config
  860. // in quotes.
  861. //
  862. // Item Types:
  863. // - g - Buddy Group (All Buddies until the next g or the end of config are in this group.)
  864. // - b - A Buddy
  865. // - p - Person on permit list
  866. // - d - Person on deny list
  867. // - m - Permit/Deny Mode. Possible values are
  868. // - 1 - Permit All
  869. // - 2 - Deny All
  870. // - 3 - Permit Some
  871. // - 4 - Deny Some
  872. //
  873. // Command syntax: toc_set_config <Config Info>
  874. func (s OSCARProxy) SetConfig(ctx context.Context, me *state.Session, cmd []byte) string {
  875. // replace curly braces with quotes so that the string can be properly
  876. // split up by the space-delimited reader
  877. for i, c := range cmd {
  878. if c == '{' || c == '}' {
  879. cmd[i] = '"'
  880. }
  881. }
  882. cmd = bytes.TrimSpace(cmd)
  883. var info string
  884. if _, err := parseArgs(cmd, "toc_set_config", &info); err != nil {
  885. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  886. }
  887. config := strings.Split(info, "\n")
  888. var cfg [][2]string
  889. for _, item := range config {
  890. parts := strings.Split(item, " ")
  891. if len(parts) != 2 {
  892. s.Logger.InfoContext(ctx, "invalid config item", "item", item, "user", me.DisplayScreenName())
  893. continue
  894. }
  895. cfg = append(cfg, [2]string{parts[0], parts[1]})
  896. }
  897. mode := wire.FeedbagPDModePermitAll
  898. for _, c := range cfg {
  899. if c[0] != "m" {
  900. continue
  901. }
  902. switch c[1] {
  903. case "1":
  904. mode = wire.FeedbagPDModePermitAll
  905. case "2":
  906. mode = wire.FeedbagPDModeDenyAll
  907. case "3":
  908. mode = wire.FeedbagPDModePermitSome
  909. case "4":
  910. mode = wire.FeedbagPDModeDenySome
  911. default:
  912. return s.runtimeErr(ctx, fmt.Errorf("config: invalid mode `%s`", c[1]))
  913. }
  914. }
  915. switch mode {
  916. case wire.FeedbagPDModePermitAll:
  917. snac := wire.SNAC_0x09_0x07_PermitDenyAddDenyListEntries{
  918. Users: []struct {
  919. ScreenName string `oscar:"len_prefix=uint8"`
  920. }{
  921. {
  922. ScreenName: me.IdentScreenName().String(),
  923. },
  924. },
  925. }
  926. if err := s.PermitDenyService.AddDenyListEntries(ctx, me, snac); err != nil {
  927. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddDenyListEntries: %w", err))
  928. }
  929. case wire.FeedbagPDModeDenyAll:
  930. snac := wire.SNAC_0x09_0x05_PermitDenyAddPermListEntries{
  931. Users: []struct {
  932. ScreenName string `oscar:"len_prefix=uint8"`
  933. }{
  934. {
  935. ScreenName: me.IdentScreenName().String(),
  936. },
  937. },
  938. }
  939. if err := s.PermitDenyService.AddPermListEntries(ctx, me, snac); err != nil {
  940. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddPermListEntrie: %w", err))
  941. }
  942. case wire.FeedbagPDModePermitSome:
  943. snac := wire.SNAC_0x09_0x05_PermitDenyAddPermListEntries{}
  944. for _, c := range cfg {
  945. if c[0] != "p" {
  946. continue
  947. }
  948. snac.Users = append(snac.Users, struct {
  949. ScreenName string `oscar:"len_prefix=uint8"`
  950. }{ScreenName: c[1]})
  951. }
  952. if err := s.PermitDenyService.AddPermListEntries(ctx, me, snac); err != nil {
  953. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddPermListEntrie: %w", err))
  954. }
  955. case wire.FeedbagPDModeDenySome:
  956. snac := wire.SNAC_0x09_0x07_PermitDenyAddDenyListEntries{}
  957. for _, c := range cfg {
  958. if c[0] != "d" {
  959. continue
  960. }
  961. snac.Users = append(snac.Users, struct {
  962. ScreenName string `oscar:"len_prefix=uint8"`
  963. }{ScreenName: c[1]})
  964. }
  965. if err := s.PermitDenyService.AddDenyListEntries(ctx, me, snac); err != nil {
  966. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddDenyListEntries: %w", err))
  967. }
  968. }
  969. snac := wire.SNAC_0x03_0x04_BuddyAddBuddies{}
  970. for _, c := range cfg {
  971. if c[0] != "b" {
  972. continue
  973. }
  974. snac.Buddies = append(snac.Buddies, struct {
  975. ScreenName string `oscar:"len_prefix=uint8"`
  976. }{ScreenName: c[1]})
  977. }
  978. if err := s.BuddyService.AddBuddies(ctx, me, snac); err != nil {
  979. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.AddBuddies: %w", err))
  980. }
  981. if err := s.TOCConfigStore.SetTOCConfig(me.IdentScreenName(), info); err != nil {
  982. return s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.SaveTOCConfig: %w", err))
  983. }
  984. return ""
  985. }
  986. // SetDir handles the toc_set_dir TOC command.
  987. //
  988. // From the TiK documentation:
  989. //
  990. // Set the DIR user information. This is a colon separated fields as in:
  991. //
  992. // "first name":"middle name":"last name":"maiden name":"city":"state":"country":"email":"allow web searches".
  993. //
  994. // Should return a DIR_STATUS msg. Having anything in the "allow web searches"
  995. // field allows people to use web-searches to find your directory info.
  996. // Otherwise, they'd have to use the client.
  997. //
  998. // The fields "email" and "allow web searches" are ignored by this method.
  999. //
  1000. // Command syntax: toc_set_dir <info information>
  1001. func (s OSCARProxy) SetDir(ctx context.Context, me *state.Session, cmd []byte) string {
  1002. var info string
  1003. if _, err := parseArgs(cmd, "toc_set_dir", &info); err != nil {
  1004. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1005. }
  1006. rawFields := strings.Split(info, ":")
  1007. var finalFields [9]string
  1008. if len(rawFields) > len(finalFields) {
  1009. return s.runtimeErr(ctx, fmt.Errorf("expected at most %d params, got %d", len(finalFields), len(rawFields)))
  1010. }
  1011. for i, a := range rawFields {
  1012. finalFields[i] = strings.Trim(a, "\"")
  1013. }
  1014. snac := wire.SNAC_0x02_0x09_LocateSetDirInfo{
  1015. TLVRestBlock: wire.TLVRestBlock{
  1016. TLVList: wire.TLVList{
  1017. wire.NewTLVBE(wire.ODirTLVFirstName, finalFields[0]),
  1018. wire.NewTLVBE(wire.ODirTLVMiddleName, finalFields[1]),
  1019. wire.NewTLVBE(wire.ODirTLVLastName, finalFields[2]),
  1020. wire.NewTLVBE(wire.ODirTLVMaidenName, finalFields[3]),
  1021. wire.NewTLVBE(wire.ODirTLVCountry, finalFields[6]),
  1022. wire.NewTLVBE(wire.ODirTLVState, finalFields[5]),
  1023. wire.NewTLVBE(wire.ODirTLVCity, finalFields[4]),
  1024. },
  1025. },
  1026. }
  1027. if _, err := s.LocateService.SetDirInfo(ctx, me, wire.SNACFrame{}, snac); err != nil {
  1028. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetDirInfo: %w", err))
  1029. }
  1030. return ""
  1031. }
  1032. // SetIdle handles the toc_set_idle TOC command.
  1033. //
  1034. // From the TiK documentation:
  1035. //
  1036. // Set idle information. If <idle secs> is 0 then the user isn't idle at all.
  1037. // If <idle secs> is greater than 0 then the user has already been idle for
  1038. // <idle secs> number of seconds. The server will automatically keep
  1039. // incrementing this number, so do not repeatedly call with new idle times.
  1040. //
  1041. // Command syntax: toc_set_idle <idle secs>
  1042. func (s OSCARProxy) SetIdle(ctx context.Context, me *state.Session, cmd []byte) string {
  1043. var idleTimeStr string
  1044. if _, err := parseArgs(cmd, "toc_set_idle", &idleTimeStr); err != nil {
  1045. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1046. }
  1047. time, err := strconv.Atoi(idleTimeStr)
  1048. if err != nil {
  1049. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  1050. }
  1051. snac := wire.SNAC_0x01_0x11_OServiceIdleNotification{
  1052. IdleTime: uint32(time),
  1053. }
  1054. if err := s.OServiceServiceBOS.IdleNotification(ctx, me, snac); err != nil {
  1055. return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.IdleNotification: %w", err))
  1056. }
  1057. return ""
  1058. }
  1059. // SetInfo handles the toc_set_info TOC command.
  1060. //
  1061. // From the TiK documentation:
  1062. //
  1063. // Set the LOCATE user information. This is basic HTML. Remember to encode the info.
  1064. //
  1065. // Command syntax: toc_set_info <info information>
  1066. func (s OSCARProxy) SetInfo(ctx context.Context, me *state.Session, cmd []byte) string {
  1067. var info string
  1068. if _, err := parseArgs(cmd, "toc_set_info", &info); err != nil {
  1069. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1070. }
  1071. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  1072. TLVRestBlock: wire.TLVRestBlock{
  1073. TLVList: wire.TLVList{
  1074. wire.NewTLVBE(wire.LocateTLVTagsInfoSigData, info),
  1075. },
  1076. },
  1077. }
  1078. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  1079. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  1080. }
  1081. return ""
  1082. }
  1083. // Signon handles the toc_signon TOC command.
  1084. //
  1085. // From the TiK documentation:
  1086. //
  1087. // The password needs to be roasted with the Roasting String if coming over a
  1088. // FLAP connection, CP connections don't use roasted passwords. The language
  1089. // specified will be used when generating web pages, such as the get info
  1090. // pages. Currently, the only supported language is "english". If the language
  1091. // sent isn't found, the default "english" language will be used. The version
  1092. // string will be used for the client identity, and must be less than 50
  1093. // characters.
  1094. //
  1095. // Passwords are roasted when sent to the host. This is done so they aren't
  1096. // sent in "clear text" over the wire, although they are still trivial to
  1097. // decode. Roasting is performed by first xoring each byte in the password
  1098. // with the equivalent modulo byte in the roasting string. The result is then
  1099. // converted to ascii hex, and prepended with "0x". So for example the
  1100. // password "password" roasts to "0x2408105c23001130".
  1101. //
  1102. // The Roasting String is Tic/Toc.
  1103. //
  1104. // Command syntax: toc_signon <authorizer host> <authorizer port> <User Name> <Password> <language> <version>
  1105. func (s OSCARProxy) Signon(ctx context.Context, cmd []byte) (*state.Session, []string) {
  1106. var userName, password string
  1107. if _, err := parseArgs(cmd, "toc_signon", nil, nil, &userName, &password); err != nil {
  1108. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))}
  1109. }
  1110. passwordHash, err := hex.DecodeString(password[2:])
  1111. if err != nil {
  1112. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("hex.DecodeString: %w", err))}
  1113. }
  1114. signonFrame := wire.FLAPSignonFrame{}
  1115. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsScreenName, userName))
  1116. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsRoastedTOCPassword, passwordHash))
  1117. block, err := s.AuthService.FLAPLogin(signonFrame, state.NewStubUser)
  1118. if err != nil {
  1119. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("AuthService.FLAPLogin: %w", err))}
  1120. }
  1121. if block.HasTag(wire.LoginTLVTagsErrorSubcode) {
  1122. s.Logger.DebugContext(ctx, "login failed")
  1123. return nil, []string{"ERROR:980"} // bad username/password
  1124. }
  1125. authCookie, ok := block.Bytes(wire.OServiceTLVTagsLoginCookie)
  1126. if !ok {
  1127. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("unable to get session id from payload"))}
  1128. }
  1129. sess, err := s.AuthService.RegisterBOSSession(ctx, authCookie)
  1130. if err != nil {
  1131. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterBOSSession: %w", err))}
  1132. }
  1133. // set chat capability so that... tk
  1134. sess.SetCaps([][16]byte{capChat})
  1135. if err := s.BuddyListRegistry.RegisterBuddyList(sess.IdentScreenName()); err != nil {
  1136. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("BuddyListRegistry.RegisterBuddyList: %w", err))}
  1137. }
  1138. u, err := s.TOCConfigStore.User(sess.IdentScreenName())
  1139. if err != nil {
  1140. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.User: %w", err))}
  1141. }
  1142. if u == nil {
  1143. return nil, []string{s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.User: user not found"))}
  1144. }
  1145. return sess, []string{"SIGN_ON:TOC1.0", fmt.Sprintf("CONFIG:%s", u.TOCConfig)}
  1146. }
  1147. // Signout terminates a TOC session. It sends departure notifications to
  1148. // buddies, de-registers buddy list and session.
  1149. func (s OSCARProxy) Signout(ctx context.Context, me *state.Session) {
  1150. if err := s.BuddyService.BroadcastBuddyDeparted(ctx, me); err != nil {
  1151. s.Logger.ErrorContext(ctx, "error sending departure notifications", "err", err.Error())
  1152. }
  1153. if err := s.BuddyListRegistry.UnregisterBuddyList(me.IdentScreenName()); err != nil {
  1154. s.Logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  1155. }
  1156. s.AuthService.Signout(ctx, me)
  1157. }
  1158. // newHTTPAuthToken creates a HMAC token for authenticating TOC HTTP requests
  1159. func (s OSCARProxy) newHTTPAuthToken(me state.IdentScreenName) (string, error) {
  1160. cookie, err := s.CookieBaker.Issue([]byte(me.String()))
  1161. if err != nil {
  1162. return "", err
  1163. }
  1164. // trim padding so that gaim doesn't choke on the long value
  1165. cookie = bytes.TrimRight(cookie, "\x00")
  1166. return hex.EncodeToString(cookie), nil
  1167. }
  1168. // parseArgs extracts arguments from a TOC command. Each positional argument is
  1169. // assigned to its corresponding args pointer. It returns the remaining
  1170. // arguments as varargs.
  1171. func parseArgs(payload []byte, cmd string, args ...*string) (varArgs []string, err error) {
  1172. reader := csv.NewReader(bytes.NewReader(payload))
  1173. reader.Comma = ' '
  1174. reader.LazyQuotes = true
  1175. reader.TrimLeadingSpace = true
  1176. segs, err := reader.Read()
  1177. if err != nil {
  1178. return nil, fmt.Errorf("CSV reader error: %w", err)
  1179. }
  1180. // sanity check the command name
  1181. if segs[0] != cmd {
  1182. return nil, fmt.Errorf("command mismatch. expected %s, got %s", cmd, segs[0])
  1183. }
  1184. // all elements after the command are arguments
  1185. segs = segs[1:]
  1186. if len(segs) < len(args) {
  1187. return nil, fmt.Errorf("command contains fewer arguments than expected")
  1188. }
  1189. i := 0
  1190. // populate placeholder pointers with their corresponding values
  1191. for ; i < len(args); i++ {
  1192. if args[i] == nil {
  1193. // ignore argument, don't populate its corresponding pointer
  1194. continue
  1195. }
  1196. *args[i] = strings.TrimSpace(segs[i])
  1197. }
  1198. // dump remaining arguments as varargs
  1199. for _, param := range segs[i:] {
  1200. varArgs = append(varArgs, param)
  1201. }
  1202. return varArgs, err
  1203. }
  1204. // runtimeErr is a convenience function that logs an error and returns a TOC
  1205. // internal server error.
  1206. func (s OSCARProxy) runtimeErr(ctx context.Context, err error) string {
  1207. s.Logger.ErrorContext(ctx, "internal service error", "err", err.Error())
  1208. return cmdInternalSvcErr
  1209. }