cmd_client.go 46 KB

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