cmd_client.go 51 KB

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