cmd_client.go 52 KB

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