cmd_client.go 57 KB

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