cmd_client.go 55 KB

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