cmd_client.go 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646
  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. "sort"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/google/uuid"
  18. "github.com/mk6i/open-oscar-server/config"
  19. "github.com/mk6i/open-oscar-server/state"
  20. "github.com/mk6i/open-oscar-server/wire"
  21. )
  22. // NewChatRegistry creates a new ChatRegistry instance.
  23. func NewChatRegistry() *ChatRegistry {
  24. chatRegistry := &ChatRegistry{
  25. lookup: make(map[int]wire.ICBMRoomInfo),
  26. sessions: make(map[int]*state.SessionInstance),
  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.SessionInstance // 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, instance *state.SessionInstance) {
  70. c.m.Lock()
  71. defer c.m.Unlock()
  72. c.sessions[chatID] = instance
  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.SessionInstance {
  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.SessionInstance {
  89. c.m.RLock()
  90. defer c.m.RUnlock()
  91. sessions := make([]*state.SessionInstance, 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. OServiceService OServiceService
  119. PermitDenyService PermitDenyService
  120. TOCConfigStore TOCConfigStore
  121. SessionRetriever SessionRetriever
  122. FeedbagService FeedbagService
  123. FeedbagManager FeedbagManager
  124. SNACRateLimits wire.SNACRateLimits
  125. HTTPIPRateLimiter *IPRateLimiter
  126. // RandIntn is the source for feedbag item ID generation.
  127. // Inject a deterministic func in tests to assert exact feedbag item slices.
  128. RandIntn func(n int) int
  129. }
  130. // RecvClientCmd processes a client TOC command and returns a server reply.
  131. //
  132. // * sessBOS is the current user's session.
  133. // * chatRegistry manages the current user's chat sessions
  134. // * payload is the command + arguments
  135. // * toCh is the channel that transports messages to client
  136. // * doAsync performs async tasks, is auto-cleaned up by caller
  137. //
  138. // It returns true if the server can continue processing commands.
  139. func (s OSCARProxy) RecvClientCmd(
  140. ctx context.Context,
  141. sessBOS *state.SessionInstance,
  142. chatRegistry *ChatRegistry,
  143. payload []byte,
  144. toCh chan<- []string,
  145. doAsync func(f func() error),
  146. ) (replies []string) {
  147. cmd := payload
  148. var args []byte
  149. if idx := bytes.IndexByte(payload, ' '); idx > -1 {
  150. cmd, args = payload[:idx], payload[idx:]
  151. }
  152. if s.Logger.Enabled(ctx, slog.LevelDebug) {
  153. s.Logger.DebugContext(ctx, "client request", "command", payload)
  154. } else {
  155. s.Logger.InfoContext(ctx, "client request", "command", cmd)
  156. }
  157. switch string(cmd) {
  158. case "toc_send_im", "toc2_send_im":
  159. return s.SendIM(ctx, sessBOS, args)
  160. case "toc_init_done":
  161. return s.InitDone(ctx, sessBOS)
  162. case "toc_add_buddy":
  163. return s.AddBuddy(ctx, sessBOS, args)
  164. case "toc_get_status":
  165. return s.GetStatus(ctx, sessBOS, args)
  166. case "toc_remove_buddy":
  167. return s.RemoveBuddy(ctx, sessBOS, args)
  168. case "toc_add_permit":
  169. return s.AddPermit(ctx, sessBOS, args)
  170. case "toc_add_deny":
  171. return s.AddDeny(ctx, sessBOS, args)
  172. case "toc_set_away":
  173. return s.SetAway(ctx, sessBOS, args)
  174. case "toc_set_caps":
  175. return s.SetCaps(ctx, sessBOS, args)
  176. case "toc_evil":
  177. return s.Evil(ctx, sessBOS, args)
  178. case "toc_get_info":
  179. return s.GetInfoURL(ctx, sessBOS, args)
  180. case "toc_change_passwd":
  181. return s.ChangePassword(ctx, sessBOS, args)
  182. case "toc_format_nickname":
  183. return s.FormatNickname(ctx, sessBOS, args)
  184. case "toc_chat_join", "toc_chat_accept":
  185. var chatID int
  186. var msg []string
  187. if string(cmd) == "toc_chat_join" {
  188. chatID, msg = s.ChatJoin(ctx, sessBOS, chatRegistry, args)
  189. } else {
  190. chatID, msg = s.ChatAccept(ctx, sessBOS, chatRegistry, args)
  191. }
  192. if len(msg) > 0 && msg[0] == cmdInternalSvcErr {
  193. return msg
  194. }
  195. doAsync(func() error {
  196. sess := chatRegistry.RetrieveSess(chatID)
  197. s.RecvChat(ctx, sess, chatID, toCh)
  198. return nil
  199. })
  200. return msg
  201. case "toc_chat_send":
  202. return s.ChatSend(ctx, chatRegistry, args)
  203. case "toc_chat_whisper":
  204. return s.ChatWhisper(ctx, chatRegistry, args)
  205. case "toc_chat_leave":
  206. return s.ChatLeave(ctx, chatRegistry, args)
  207. case "toc_set_info":
  208. return s.SetInfo(ctx, sessBOS, args)
  209. case "toc_set_dir":
  210. return s.SetDir(ctx, sessBOS, args)
  211. case "toc_set_idle":
  212. return s.SetIdle(ctx, sessBOS, args)
  213. case "toc_set_config":
  214. return s.SetConfig(ctx, sessBOS, args)
  215. case "toc_chat_invite":
  216. return s.ChatInvite(ctx, sessBOS, chatRegistry, args)
  217. case "toc_dir_search":
  218. return s.GetDirSearchURL(ctx, sessBOS, args)
  219. case "toc_get_dir":
  220. return s.GetDirURL(ctx, sessBOS, args)
  221. case "toc_rvous_accept":
  222. return s.RvousAccept(ctx, sessBOS, args)
  223. case "toc_rvous_cancel":
  224. return s.RvousCancel(ctx, sessBOS, args)
  225. case "toc2_set_pdmode":
  226. return s.SetPDMode(ctx, sessBOS, args)
  227. case "toc2_send_im_enc":
  228. return s.SendIMEnc(ctx, sessBOS, args)
  229. case "toc2_remove_buddy":
  230. return s.RemoveBuddy2(ctx, sessBOS, args)
  231. case "toc2_new_group":
  232. return s.NewGroup(ctx, sessBOS, args)
  233. case "toc2_del_group":
  234. return s.DelGroup(ctx, sessBOS, args)
  235. case "toc2_new_buddies":
  236. return s.NewBuddies(ctx, sessBOS, args)
  237. case "toc2_add_permit":
  238. return s.AddPermit2(ctx, sessBOS, args)
  239. case "toc2_remove_permit":
  240. return s.RemovePermit2(ctx, sessBOS, args)
  241. case "toc2_add_deny":
  242. return s.AddDeny2(ctx, sessBOS, args)
  243. case "toc2_remove_deny":
  244. return s.RemoveDeny2(ctx, sessBOS, args)
  245. case "toc2_client_event":
  246. return s.SendClientEvent(ctx, sessBOS, args)
  247. }
  248. s.Logger.ErrorContext(ctx, fmt.Sprintf("unsupported TOC command %s", cmd))
  249. return []string{cmdInternalSvcErr}
  250. }
  251. // AddBuddy handles the toc_add_buddy TOC command.
  252. //
  253. // From the TiK documentation:
  254. //
  255. // Add buddies to your buddy list. This does not change your saved config.
  256. //
  257. // Command syntax: toc_add_buddy <Buddy User 1> [<Buddy User2> [<Buddy User 3> [...]]]
  258. func (s OSCARProxy) AddBuddy(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  259. if msg, isLimited := s.checkRateLimit(ctx, me, wire.Buddy, wire.BuddyAddBuddies); 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_0x03_0x04_BuddyAddBuddies{}
  267. for _, sn := range users {
  268. snac.Buddies = append(snac.Buddies, struct {
  269. ScreenName string `oscar:"len_prefix=uint8"`
  270. }{ScreenName: sn})
  271. }
  272. if err := s.BuddyService.AddBuddies(ctx, me, snac); err != nil {
  273. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.AddBuddies: %w", err))
  274. }
  275. return []string{}
  276. }
  277. // AddPermit handles the toc_add_permit TOC command.
  278. //
  279. // From the TiK documentation:
  280. //
  281. // ADD the following people to your permit mode. If you are in deny mode it
  282. // will switch you to permit mode first. With no arguments and in deny mode
  283. // this will switch you to permit none. If already in permit mode, no
  284. // arguments does nothing and your permit list remains the same.
  285. //
  286. // Command syntax: toc_add_permit [ <User 1> [<User 2> [...]]]
  287. func (s OSCARProxy) AddPermit(ctx context.Context, me *state.SessionInstance, 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_0x05_PermitDenyAddPermListEntries{}
  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.AddPermListEntries(ctx, me, snac); err != nil {
  302. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddPermListEntries: %w", err))
  303. }
  304. return []string{}
  305. }
  306. // AddDeny handles the toc_add_deny TOC command.
  307. //
  308. // From the TiK documentation:
  309. //
  310. // ADD the following people to your deny mode. If you are in permit mode it
  311. // will switch you to deny mode first. With no arguments and in permit mode,
  312. // this will switch you to deny none. If already in deny mode, no arguments
  313. // does nothing and your deny list remains unchanged.
  314. //
  315. // Command syntax: toc_add_deny [ <User 1> [<User 2> [...]]]
  316. func (s OSCARProxy) AddDeny(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  317. if msg, isLimited := s.checkRateLimit(ctx, me, wire.PermitDeny, wire.PermitDenyAddDenyListEntries); isLimited {
  318. return msg
  319. }
  320. users, err := parseArgs(args)
  321. if err != nil {
  322. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  323. }
  324. snac := wire.SNAC_0x09_0x07_PermitDenyAddDenyListEntries{}
  325. for _, sn := range users {
  326. snac.Users = append(snac.Users, struct {
  327. ScreenName string `oscar:"len_prefix=uint8"`
  328. }{ScreenName: sn})
  329. }
  330. if err := s.PermitDenyService.AddDenyListEntries(ctx, me, snac); err != nil {
  331. return s.runtimeErr(ctx, fmt.Errorf("PermitDenyService.AddDenyListEntries: %w", err))
  332. }
  333. return []string{}
  334. }
  335. // ChangePassword handles the toc_change_passwd TOC command.
  336. //
  337. // From the TiK documentation:
  338. //
  339. // Change a user's password. An ADMIN_PASSWD_STATUS or ERROR message will be
  340. // sent back to the client.
  341. //
  342. // Command syntax: toc_change_passwd <existing_passwd> <new_passwd>
  343. func (s OSCARProxy) ChangePassword(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  344. if msg, isLimited := s.checkRateLimit(ctx, me, wire.Admin, wire.AdminInfoChangeRequest); isLimited {
  345. return msg
  346. }
  347. var oldPass, newPass string
  348. if _, err := parseArgs(args, &oldPass, &newPass); err != nil {
  349. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  350. }
  351. oldPass = unescape(oldPass)
  352. newPass = unescape(newPass)
  353. reqSNAC := wire.SNAC_0x07_0x04_AdminInfoChangeRequest{
  354. TLVRestBlock: wire.TLVRestBlock{
  355. TLVList: wire.TLVList{
  356. wire.NewTLVBE(wire.AdminTLVOldPassword, oldPass),
  357. wire.NewTLVBE(wire.AdminTLVNewPassword, newPass),
  358. },
  359. },
  360. }
  361. reply, err := s.AdminService.InfoChangeRequest(ctx, me, wire.SNACFrame{}, reqSNAC)
  362. if err != nil {
  363. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: %w", err))
  364. }
  365. replyBody, ok := reply.Body.(wire.SNAC_0x07_0x05_AdminChangeReply)
  366. if !ok {
  367. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: unexpected response type %v", replyBody))
  368. }
  369. code, ok := replyBody.Uint16BE(wire.AdminTLVErrorCode)
  370. if ok {
  371. switch code {
  372. case wire.AdminInfoErrorInvalidPasswordLength:
  373. return []string{"ERROR:" + wire.TOCErrorAdminInvalidInput}
  374. case wire.AdminInfoErrorValidatePassword:
  375. return []string{"ERROR:" + wire.TOCErrorAuthIncorrectNickOrPassword}
  376. default:
  377. return []string{"ERROR:" + wire.TOCErrorAdminProcessingRequest}
  378. }
  379. }
  380. return []string{"ADMIN_PASSWD_STATUS:0"}
  381. }
  382. // ChatAccept handles the toc_chat_accept TOC command.
  383. //
  384. // From the TiK documentation:
  385. //
  386. // Accept a CHAT_INVITE message from TOC. The server will send a CHAT_JOIN in
  387. // response.
  388. //
  389. // Command syntax: toc_chat_accept <Chat Room ID>
  390. func (s OSCARProxy) ChatAccept(
  391. ctx context.Context,
  392. me *state.SessionInstance,
  393. chatRegistry *ChatRegistry,
  394. args []byte,
  395. ) (int, []string) {
  396. var chatIDStr string
  397. if _, err := parseArgs(args, &chatIDStr); err != nil {
  398. return 0, s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  399. }
  400. chatID, err := strconv.Atoi(chatIDStr)
  401. if err != nil {
  402. return 0, s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  403. }
  404. chatInfo, found := chatRegistry.LookupRoom(chatID)
  405. if !found {
  406. return 0, s.runtimeErr(ctx, fmt.Errorf("chatRegistry.LookupRoom: no chat found for ID %d", chatID))
  407. }
  408. if msg, isLimited := s.checkRateLimit(ctx, me, wire.ChatNav, wire.ChatNavRequestRoomInfo); isLimited {
  409. return 0, msg
  410. }
  411. reqRoomSNAC := wire.SNAC_0x0D_0x04_ChatNavRequestRoomInfo{
  412. Cookie: chatInfo.Cookie,
  413. Exchange: chatInfo.Exchange,
  414. InstanceNumber: chatInfo.Instance,
  415. }
  416. reqRoomReply, err := s.ChatNavService.RequestRoomInfo(ctx, wire.SNACFrame{}, reqRoomSNAC)
  417. if err != nil {
  418. return 0, s.runtimeErr(ctx, fmt.Errorf("ChatNavService.RequestRoomInfo: %w", err))
  419. }
  420. reqRoomReplyBody, ok := reqRoomReply.Body.(wire.SNAC_0x0D_0x09_ChatNavNavInfo)
  421. if !ok {
  422. return 0, s.runtimeErr(
  423. ctx,
  424. fmt.Errorf("chatNavService.RequestRoomInfo: unexpected response type %v", reqRoomReplyBody),
  425. )
  426. }
  427. b, hasInfo := reqRoomReplyBody.Bytes(wire.ChatNavTLVRoomInfo)
  428. if !hasInfo {
  429. return 0, s.runtimeErr(ctx, errors.New("reqRoomReplyBody.Bytes: missing wire.ChatNavTLVRoomInfo"))
  430. }
  431. roomInfo := wire.SNAC_0x0E_0x02_ChatRoomInfoUpdate{}
  432. if err := wire.UnmarshalBE(&roomInfo, bytes.NewReader(b)); err != nil {
  433. return 0, s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  434. }
  435. roomName, hasName := roomInfo.Bytes(wire.ChatRoomTLVRoomName)
  436. if !hasName {
  437. return 0, s.runtimeErr(ctx, errors.New("roomInfo.Bytes: missing wire.ChatRoomTLVRoomName"))
  438. }
  439. if msg, isLimited := s.checkRateLimit(ctx, me, wire.OService, wire.OServiceServiceRequest); isLimited {
  440. return 0, msg
  441. }
  442. svcReqSNAC := wire.SNAC_0x01_0x04_OServiceServiceRequest{
  443. FoodGroup: wire.Chat,
  444. TLVRestBlock: wire.TLVRestBlock{
  445. TLVList: wire.TLVList{
  446. wire.NewTLVBE(0x01, wire.SNAC_0x01_0x04_TLVRoomInfo{
  447. Cookie: chatInfo.Cookie,
  448. }),
  449. },
  450. },
  451. }
  452. svcReqReply, err := s.OServiceService.ServiceRequest(ctx, wire.BOS, me, wire.SNACFrame{}, svcReqSNAC, config.Listener{})
  453. if err != nil {
  454. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ServiceRequest: %w", err))
  455. }
  456. svcReqReplyBody, ok := svcReqReply.Body.(wire.SNAC_0x01_0x05_OServiceServiceResponse)
  457. if !ok {
  458. return 0, s.runtimeErr(
  459. ctx,
  460. fmt.Errorf("OServiceServiceBOS.ServiceRequest: unexpected response type %v", svcReqReplyBody),
  461. )
  462. }
  463. loginCookie, hasCookie := svcReqReplyBody.Bytes(wire.OServiceTLVTagsLoginCookie)
  464. if !hasCookie {
  465. return 0, s.runtimeErr(ctx, errors.New("missing wire.OServiceTLVTagsLoginCookie"))
  466. }
  467. // todo: naming for cookie: login cookie, server cookie, or auth cookie?
  468. serverCookie, err := s.AuthService.CrackCookie(loginCookie)
  469. if err != nil {
  470. return 0, s.runtimeErr(ctx, fmt.Errorf("AuthService.CrackCookie: %w", err))
  471. }
  472. chatSess, err := s.AuthService.RegisterChatSession(ctx, serverCookie)
  473. if err != nil {
  474. return 0, s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterChatSession: %w", err))
  475. }
  476. if msg, isLimited := s.checkRateLimit(ctx, me, wire.OService, wire.OServiceClientOnline); isLimited {
  477. return 0, msg
  478. }
  479. if err := s.OServiceService.ClientOnline(ctx, wire.Chat, wire.SNAC_0x01_0x02_OServiceClientOnline{}, chatSess); err != nil {
  480. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceChat.ClientOnline: %w", err))
  481. }
  482. chatRegistry.RegisterSess(chatID, chatSess)
  483. return chatID, []string{fmt.Sprintf("CHAT_JOIN:%d:%s", chatID, roomName)}
  484. }
  485. // ChatInvite handles the toc_chat_invite TOC command.
  486. //
  487. // From the TiK documentation:
  488. //
  489. // Once you are inside a chat room you can invite other people into that room.
  490. // Remember to quote and encode the invite message.
  491. //
  492. // Command syntax: toc_chat_invite <Chat Room ID> <Invite Msg> <buddy1> [<buddy2> [<buddy3> [...]]]
  493. func (s OSCARProxy) ChatInvite(ctx context.Context, me *state.SessionInstance, chatRegistry *ChatRegistry, args []byte) []string {
  494. var chatRoomIDStr, msg string
  495. users, err := parseArgs(args, &chatRoomIDStr, &msg)
  496. if err != nil {
  497. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  498. }
  499. msg = unescape(msg)
  500. chatID, err := strconv.Atoi(chatRoomIDStr)
  501. if err != nil {
  502. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  503. }
  504. roomInfo, found := chatRegistry.LookupRoom(chatID)
  505. if !found {
  506. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.LookupRoom: chat ID `%d` not found", chatID))
  507. }
  508. for _, guest := range users {
  509. if msg, isLimited := s.checkRateLimit(ctx, me, wire.ICBM, wire.ICBMChannelMsgToHost); isLimited {
  510. return msg
  511. }
  512. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  513. ChannelID: wire.ICBMChannelRendezvous,
  514. ScreenName: guest,
  515. TLVRestBlock: wire.TLVRestBlock{
  516. TLVList: wire.TLVList{
  517. wire.NewTLVBE(wire.ICBMTLVData, wire.ICBMCh2Fragment{
  518. Type: wire.ICBMRdvMessagePropose,
  519. Capability: wire.CapChat,
  520. TLVRestBlock: wire.TLVRestBlock{
  521. TLVList: wire.TLVList{
  522. wire.NewTLVBE(wire.ICBMRdvTLVTagsSeqNum, uint16(1)),
  523. wire.NewTLVBE(wire.ICBMRdvTLVTagsInvitation, msg),
  524. wire.NewTLVBE(wire.ICBMRdvTLVTagsInviteMIMECharset, "us-ascii"),
  525. wire.NewTLVBE(wire.ICBMRdvTLVTagsInviteMIMELang, "en"),
  526. wire.NewTLVBE(wire.ICBMRdvTLVTagsSvcData, roomInfo),
  527. },
  528. },
  529. }),
  530. },
  531. },
  532. }
  533. if _, err := s.ICBMService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac); err != nil {
  534. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  535. }
  536. }
  537. return []string{}
  538. }
  539. // ChatJoin handles the toc_chat_join TOC command.
  540. //
  541. // From the TiK documentation:
  542. //
  543. // Join a chat room in the given exchange. Exchange is an integer that
  544. // represents a group of chat rooms. Different exchanges have different
  545. // properties. For example some exchanges might have room replication (ie a
  546. // room never fills up, there are just multiple instances.) and some exchanges
  547. // might have navigational information. Currently, exchange should always be
  548. // 4, however this may change in the future. You will either receive an ERROR
  549. // if the room couldn't be joined or a CHAT_JOIN message. The Chat Room Name
  550. // is case-insensitive and consecutive spaces are removed.
  551. //
  552. // Command syntax: toc_chat_join <Exchange> <Chat Room Name>
  553. func (s OSCARProxy) ChatJoin(
  554. ctx context.Context,
  555. me *state.SessionInstance,
  556. chatRegistry *ChatRegistry,
  557. args []byte,
  558. ) (int, []string) {
  559. var exchangeStr, roomName string
  560. if _, err := parseArgs(args, &exchangeStr, &roomName); err != nil {
  561. return 0, s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  562. }
  563. roomName = unescape(roomName)
  564. // create room or retrieve the room if it already exists
  565. exchange, err := strconv.Atoi(exchangeStr)
  566. if err != nil {
  567. return 0, s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  568. }
  569. if msg, isLimited := s.checkRateLimit(ctx, me, wire.Chat, wire.ChatRoomInfoUpdate); isLimited {
  570. return 0, msg
  571. }
  572. mkRoomReq := wire.SNAC_0x0E_0x02_ChatRoomInfoUpdate{
  573. Exchange: uint16(exchange),
  574. Cookie: "create",
  575. TLVBlock: wire.TLVBlock{
  576. TLVList: wire.TLVList{
  577. wire.NewTLVBE(wire.ChatRoomTLVRoomName, roomName),
  578. },
  579. },
  580. }
  581. mkRoomReply, err := s.ChatNavService.CreateRoom(ctx, me, wire.SNACFrame{}, mkRoomReq)
  582. if err != nil {
  583. return 0, s.runtimeErr(ctx, fmt.Errorf("ChatNavService.CreateRoom: %w", err))
  584. }
  585. mkRoomReplyBody, ok := mkRoomReply.Body.(wire.SNAC_0x0D_0x09_ChatNavNavInfo)
  586. if !ok {
  587. return 0, s.runtimeErr(
  588. ctx,
  589. fmt.Errorf("chatNavService.CreateRoom: unexpected response type %v", mkRoomReplyBody),
  590. )
  591. }
  592. buf, ok := mkRoomReplyBody.Bytes(wire.ChatNavTLVRoomInfo)
  593. if !ok {
  594. return 0, s.runtimeErr(ctx, errors.New("mkRoomReplyBody.Bytes: missing wire.ChatNavTLVRoomInfo"))
  595. }
  596. inBody := wire.SNAC_0x0E_0x02_ChatRoomInfoUpdate{}
  597. if err := wire.UnmarshalBE(&inBody, bytes.NewReader(buf)); err != nil {
  598. return 0, s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  599. }
  600. if msg, isLimited := s.checkRateLimit(ctx, me, wire.OService, wire.OServiceServiceRequest); isLimited {
  601. return 0, msg
  602. }
  603. svcReqSNAC := wire.SNAC_0x01_0x04_OServiceServiceRequest{
  604. FoodGroup: wire.Chat,
  605. TLVRestBlock: wire.TLVRestBlock{
  606. TLVList: wire.TLVList{
  607. wire.NewTLVBE(0x01, wire.SNAC_0x01_0x04_TLVRoomInfo{
  608. Cookie: inBody.Cookie,
  609. }),
  610. },
  611. },
  612. }
  613. svcReqReply, err := s.OServiceService.ServiceRequest(ctx, wire.BOS, me, wire.SNACFrame{}, svcReqSNAC, config.Listener{})
  614. if err != nil {
  615. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ServiceRequest: %w", err))
  616. }
  617. svcReqReplyBody, ok := svcReqReply.Body.(wire.SNAC_0x01_0x05_OServiceServiceResponse)
  618. if !ok {
  619. return 0, s.runtimeErr(
  620. ctx,
  621. fmt.Errorf("OServiceServiceBOS.ServiceRequest: unexpected response type %v", svcReqReplyBody),
  622. )
  623. }
  624. loginCookie, hasCookie := svcReqReplyBody.Bytes(wire.OServiceTLVTagsLoginCookie)
  625. if !hasCookie {
  626. return 0, s.runtimeErr(ctx, errors.New("svcReqReplyBody.Bytes: missing wire.OServiceTLVTagsLoginCookie"))
  627. }
  628. // todo: naming for cookie: login cookie, server cookie, or auth cookie?
  629. serverCookie, err := s.AuthService.CrackCookie(loginCookie)
  630. if err != nil {
  631. return 0, s.runtimeErr(ctx, fmt.Errorf("AuthService.CrackCookie: %w", err))
  632. }
  633. chatSess, err := s.AuthService.RegisterChatSession(ctx, serverCookie)
  634. if err != nil {
  635. return 0, s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterChatSession: %w", err))
  636. }
  637. if msg, isLimited := s.checkRateLimit(ctx, me, wire.OService, wire.OServiceClientOnline); isLimited {
  638. return 0, msg
  639. }
  640. if err := s.OServiceService.ClientOnline(ctx, wire.Chat, wire.SNAC_0x01_0x02_OServiceClientOnline{}, chatSess); err != nil {
  641. return 0, s.runtimeErr(ctx, fmt.Errorf("OServiceServiceChat.ClientOnline: %w", err))
  642. }
  643. roomInfo := wire.ICBMRoomInfo{
  644. Exchange: inBody.Exchange,
  645. Cookie: inBody.Cookie,
  646. Instance: inBody.InstanceNumber,
  647. }
  648. chatID := chatRegistry.Add(roomInfo)
  649. chatRegistry.RegisterSess(chatID, chatSess)
  650. return chatID, []string{fmt.Sprintf("CHAT_JOIN:%d:%s", chatID, roomName)}
  651. }
  652. // ChatLeave handles the toc_chat_leave TOC command.
  653. //
  654. // From the TiK documentation:
  655. //
  656. // Leave the chat room.
  657. //
  658. // Command syntax: toc_chat_leave <Chat Room ID>
  659. func (s OSCARProxy) ChatLeave(ctx context.Context, chatRegistry *ChatRegistry, args []byte) []string {
  660. var chatIDStr string
  661. if _, err := parseArgs(args, &chatIDStr); err != nil {
  662. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  663. }
  664. chatID, err := strconv.Atoi(chatIDStr)
  665. if err != nil {
  666. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  667. }
  668. me := chatRegistry.RetrieveSess(chatID)
  669. if me == nil {
  670. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.RetrieveSess: chat session `%d` not found", chatID))
  671. }
  672. s.AuthService.SignoutChat(ctx, me)
  673. me.CloseInstance() // stop async server SNAC reply handler for this chat room
  674. chatRegistry.RemoveSess(chatID)
  675. return []string{fmt.Sprintf("CHAT_LEFT:%d", chatID)}
  676. }
  677. // ChatSend handles the toc_chat_send TOC command.
  678. //
  679. // From the TiK documentation:
  680. //
  681. // Send a message in a chat room using the chat room id from CHAT_JOIN. Since
  682. // reflection is always on in TOC, you do not need to add the message to your
  683. // chat UI, since you will get a CHAT_IN with the message. Remember to quote
  684. // and encode the message.
  685. //
  686. // Command syntax: toc_chat_send <Chat Room ID> <Message>
  687. func (s OSCARProxy) ChatSend(ctx context.Context, chatRegistry *ChatRegistry, args []byte) []string {
  688. var chatIDStr, msg string
  689. if _, err := parseArgs(args, &chatIDStr, &msg); err != nil {
  690. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  691. }
  692. msg = unescape(msg)
  693. chatID, err := strconv.Atoi(chatIDStr)
  694. if err != nil {
  695. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  696. }
  697. me := chatRegistry.RetrieveSess(chatID)
  698. if me == nil {
  699. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.RetrieveSess: session for chat ID `%d` not found", chatID))
  700. }
  701. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Chat, wire.ChatChannelMsgToHost); isLimited {
  702. return errMsg
  703. }
  704. block := wire.TLVRestBlock{}
  705. // the order of these TLVs matters for AIM 2.x. if out of order, screen
  706. // names do not appear with each chat message.
  707. block.Append(wire.NewTLVBE(wire.ChatTLVEnableReflectionFlag, uint8(1)))
  708. block.Append(wire.NewTLVBE(wire.ChatTLVSenderInformation, me.Session().TLVUserInfo()))
  709. block.Append(wire.NewTLVBE(wire.ChatTLVPublicWhisperFlag, []byte{}))
  710. block.Append(wire.NewTLVBE(wire.ChatTLVMessageInfo, wire.TLVRestBlock{
  711. TLVList: wire.TLVList{
  712. wire.NewTLVBE(wire.ChatTLVMessageInfoText, msg),
  713. },
  714. }))
  715. snac := wire.SNAC_0x0E_0x05_ChatChannelMsgToHost{
  716. Channel: wire.ICBMChannelMIME,
  717. TLVRestBlock: block,
  718. }
  719. reply, err := s.ChatService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac)
  720. if err != nil {
  721. return s.runtimeErr(ctx, fmt.Errorf("ChatService.ChannelMsgToHost: %w", err))
  722. }
  723. if reply == nil {
  724. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: missing response "))
  725. }
  726. switch v := reply.Body.(type) {
  727. case wire.SNAC_0x0E_0x06_ChatChannelMsgToClient:
  728. msgInfo, ok := v.Bytes(wire.ChatTLVMessageInfo)
  729. if !ok {
  730. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: missing wire.ChatTLVMessageInfo"))
  731. }
  732. reflectMsg, err := wire.UnmarshalChatMessageText(msgInfo)
  733. if err != nil {
  734. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalChatMessageText: %w", err))
  735. }
  736. senderInfo, ok := v.Bytes(wire.ChatTLVSenderInformation)
  737. if !ok {
  738. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: missing wire.ChatTLVSenderInformation"))
  739. }
  740. var userInfo wire.TLVUserInfo
  741. if err := wire.UnmarshalBE(&userInfo, bytes.NewReader(senderInfo)); err != nil {
  742. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  743. }
  744. return []string{fmt.Sprintf("CHAT_IN:%d:%s:F:%s", chatID, userInfo.ScreenName, reflectMsg)}
  745. default:
  746. return s.runtimeErr(ctx, errors.New("ChatService.ChannelMsgToHost: unexpected response"))
  747. }
  748. }
  749. // ChatWhisper handles the toc_chat_whisper TOC command.
  750. //
  751. // From the TiK documentation:
  752. //
  753. // Send a message in a chat room using the chat room id from CHAT_JOIN.
  754. // This message is directed at only one person. (Currently you DO need to add
  755. // this to your UI.) Remember to quote and encode the message. Chat whispering
  756. // is different from IMs since it is linked to a chat room, and should usually
  757. // be displayed in the chat room UI.
  758. //
  759. // Command syntax: toc_chat_whisper <Chat Room ID> <dst_user> <Message>
  760. func (s OSCARProxy) ChatWhisper(ctx context.Context, chatRegistry *ChatRegistry, args []byte) []string {
  761. var chatIDStr, recip, msg string
  762. if _, err := parseArgs(args, &chatIDStr, &recip, &msg); err != nil {
  763. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  764. }
  765. msg = unescape(msg)
  766. chatID, err := strconv.Atoi(chatIDStr)
  767. if err != nil {
  768. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  769. }
  770. me := chatRegistry.RetrieveSess(chatID)
  771. if me == nil {
  772. return s.runtimeErr(ctx, fmt.Errorf("chatRegistry.RetrieveSess: session for chat ID `%d` not found", chatID))
  773. }
  774. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Chat, wire.ChatChannelMsgToHost); isLimited {
  775. return errMsg
  776. }
  777. block := wire.TLVRestBlock{}
  778. block.Append(wire.NewTLVBE(wire.ChatTLVSenderInformation, me.Session().TLVUserInfo()))
  779. block.Append(wire.NewTLVBE(wire.ChatTLVWhisperToUser, recip))
  780. block.Append(wire.NewTLVBE(wire.ChatTLVMessageInfo, wire.TLVRestBlock{
  781. TLVList: wire.TLVList{
  782. wire.NewTLVBE(wire.ChatTLVMessageInfoText, msg),
  783. },
  784. }))
  785. snac := wire.SNAC_0x0E_0x05_ChatChannelMsgToHost{
  786. Channel: wire.ICBMChannelMIME,
  787. TLVRestBlock: block,
  788. }
  789. if _, err = s.ChatService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac); err != nil {
  790. return s.runtimeErr(ctx, fmt.Errorf("ChatService.ChannelMsgToHost: %w", err))
  791. }
  792. return []string{}
  793. }
  794. // Evil handles the toc_evil TOC command.
  795. //
  796. // From the TiK documentation:
  797. //
  798. // Evil/Warn someone else. The 2nd argument is either the string "norm" for a
  799. // normal warning, or "anon" for an anonymous warning. You can only evil
  800. // people who have recently sent you ims. The higher someones evil level, the
  801. // slower they can send message.
  802. //
  803. // An ERROR message will be sent back to the client if the warning was unsuccessful.
  804. //
  805. // Command syntax: toc_evil <User> <norm|anon>
  806. func (s OSCARProxy) Evil(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  807. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.ICBM, wire.ICBMEvilRequest); isLimited {
  808. return errMsg
  809. }
  810. var user, scope string
  811. if _, err := parseArgs(args, &user, &scope); err != nil {
  812. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  813. }
  814. snac := wire.SNAC_0x04_0x08_ICBMEvilRequest{
  815. ScreenName: user,
  816. }
  817. switch scope {
  818. case "anon":
  819. snac.SendAs = 1
  820. case "norm":
  821. snac.SendAs = 0
  822. default:
  823. return s.runtimeErr(ctx, fmt.Errorf("incorrect warning type `%s`. allowed values: anon, norm", scope))
  824. }
  825. response, err := s.ICBMService.EvilRequest(ctx, me, wire.SNACFrame{}, snac)
  826. if err != nil {
  827. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.EvilRequest: %w", err))
  828. }
  829. switch v := response.Body.(type) {
  830. case wire.SNAC_0x04_0x09_ICBMEvilReply:
  831. return []string{}
  832. case wire.SNACError:
  833. s.Logger.InfoContext(ctx, "unable to warn user", "code", v.Code)
  834. return []string{"ERROR:" + wire.TOCErrorGeneralWarningUserNotAvailable}
  835. default:
  836. return s.runtimeErr(ctx, errors.New("unexpected response"))
  837. }
  838. }
  839. // FormatNickname handles the toc_format_nickname TOC command.
  840. //
  841. // From the TiK documentation:
  842. //
  843. // Reformat a user's nickname. An ADMIN_NICK_STATUS or ERROR message will be
  844. // sent back to the client.
  845. //
  846. // From the BizTOCSock documentation:
  847. //
  848. // [NICK is also sent with ADMIN_NICK_STATUS. This gets called [...] whenever
  849. // you do a format change.
  850. //
  851. // Command syntax: toc_format_nickname <new_format>
  852. func (s OSCARProxy) FormatNickname(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  853. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Admin, wire.AdminInfoChangeRequest); isLimited {
  854. return errMsg
  855. }
  856. var newFormat string
  857. if _, err := parseArgs(args, &newFormat); err != nil {
  858. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  859. }
  860. // remove curly braces added by TiK
  861. newFormat = strings.Trim(newFormat, "{}")
  862. reqSNAC := wire.SNAC_0x07_0x04_AdminInfoChangeRequest{
  863. TLVRestBlock: wire.TLVRestBlock{
  864. TLVList: wire.TLVList{
  865. wire.NewTLVBE(wire.AdminTLVScreenNameFormatted, newFormat),
  866. },
  867. },
  868. }
  869. reply, err := s.AdminService.InfoChangeRequest(ctx, me, wire.SNACFrame{}, reqSNAC)
  870. if err != nil {
  871. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: %w", err))
  872. }
  873. replyBody, ok := reply.Body.(wire.SNAC_0x07_0x05_AdminChangeReply)
  874. if !ok {
  875. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: unexpected response type %v", replyBody))
  876. }
  877. code, ok := replyBody.Uint16BE(wire.AdminTLVErrorCode)
  878. if ok {
  879. switch code {
  880. case wire.AdminInfoErrorInvalidNickNameLength, wire.AdminInfoErrorInvalidNickName:
  881. return []string{"ERROR:" + wire.TOCErrorAdminInvalidInput}
  882. default:
  883. return []string{"ERROR:" + wire.TOCErrorAdminProcessingRequest}
  884. }
  885. }
  886. val, hasVal := replyBody.TLVBlock.String(wire.AdminTLVScreenNameFormatted)
  887. if !hasVal {
  888. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: missing AdminTLVScreenNameFormatted %v", replyBody))
  889. }
  890. return []string{"ADMIN_NICK_STATUS:0", "NICK:" + val}
  891. }
  892. // GetDirSearchURL handles the toc_dir_search TOC command.
  893. //
  894. // From the TiK documentation:
  895. //
  896. // Perform a search of the Oscar Directory, using colon separated fields as in:
  897. //
  898. // "first name":"middle name":"last name":"maiden name":"city":"state":"country":"email"
  899. //
  900. // You can search by keyword by setting search terms in the 11th position (this
  901. // feature is not in the TiK docs but is present in the code):
  902. //
  903. // ::::::::::"search kw"
  904. //
  905. // Returns either a GOTO_URL or ERROR msg.
  906. //
  907. // Command syntax: toc_dir_search <info information>
  908. func (s OSCARProxy) GetDirSearchURL(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  909. if status := me.Session().EvaluateRateLimit(time.Now(), 1); status == wire.RateLimitStatusLimited {
  910. return []string{rateLimitExceededErr}
  911. }
  912. var info string
  913. if _, err := parseArgs(args, &info); err != nil {
  914. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  915. }
  916. info = unescape(info)
  917. params := strings.Split(info, ":")
  918. labels := []string{
  919. "first_name",
  920. "middle_name",
  921. "last_name",
  922. "maiden_name",
  923. "city",
  924. "state",
  925. "country",
  926. "email",
  927. "nop", // unused placeholder
  928. "nop",
  929. "keyword",
  930. }
  931. // map labels to param values at their corresponding positions
  932. p := url.Values{}
  933. for i, param := range params {
  934. if i >= len(labels) {
  935. break
  936. }
  937. if param != "" {
  938. p.Add(labels[i], strings.Trim(param, "\""))
  939. }
  940. }
  941. if len(p) == 0 {
  942. return s.runtimeErr(ctx, errors.New("no search fields found"))
  943. }
  944. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  945. if err != nil {
  946. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  947. }
  948. p.Add("cookie", cookie)
  949. return []string{fmt.Sprintf("GOTO_URL:search results:dir_search?%s", p.Encode())}
  950. }
  951. // GetDirURL handles the toc_get_dir TOC command.
  952. //
  953. // From the TiK documentation:
  954. //
  955. // Gets a user's dir info a GOTO_URL or ERROR message will be sent back to the client.
  956. //
  957. // Command syntax: toc_get_dir <username>
  958. func (s OSCARProxy) GetDirURL(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  959. if status := me.Session().EvaluateRateLimit(time.Now(), 1); status == wire.RateLimitStatusLimited {
  960. return []string{rateLimitExceededErr}
  961. }
  962. var user string
  963. if _, err := parseArgs(args, &user); err != nil {
  964. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  965. }
  966. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  967. if err != nil {
  968. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  969. }
  970. p := url.Values{}
  971. p.Add("cookie", cookie)
  972. p.Add("user", user)
  973. return []string{fmt.Sprintf("GOTO_URL:directory info:dir_info?%s", p.Encode())}
  974. }
  975. // GetInfoURL handles the toc_get_info TOC command.
  976. //
  977. // From the TiK documentation:
  978. //
  979. // Gets a user's info a GOTO_URL or ERROR message will be sent back to the client.
  980. //
  981. // Command syntax: toc_get_info <username>
  982. func (s OSCARProxy) GetInfoURL(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  983. if status := me.Session().EvaluateRateLimit(time.Now(), 1); status == wire.RateLimitStatusLimited {
  984. return []string{rateLimitExceededErr}
  985. }
  986. var user string
  987. if _, err := parseArgs(args, &user); err != nil {
  988. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  989. }
  990. cookie, err := s.newHTTPAuthToken(me.IdentScreenName())
  991. if err != nil {
  992. return s.runtimeErr(ctx, fmt.Errorf("newHTTPAuthToken: %w", err))
  993. }
  994. p := url.Values{}
  995. p.Add("cookie", cookie)
  996. p.Add("from", me.IdentScreenName().String())
  997. p.Add("user", user)
  998. return []string{fmt.Sprintf("GOTO_URL:profile:info?%s", p.Encode())}
  999. }
  1000. // GetStatus handles the toc_get_status TOC command.
  1001. //
  1002. // From the BlueTOC documentation:
  1003. //
  1004. // This useful command wasn't ever really documented. It returns either an
  1005. // UPDATE_BUDDY message or an ERROR message depending on whether or not the
  1006. // guy appears to be online. The command is used in both TOC1 and TOC2 with
  1007. // the same syntax.
  1008. //
  1009. // Command syntax: toc_get_status <screenname>
  1010. func (s OSCARProxy) GetStatus(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1011. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Locate, wire.LocateUserInfoQuery); isLimited {
  1012. return errMsg
  1013. }
  1014. var them string
  1015. if _, err := parseArgs(args, &them); err != nil {
  1016. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1017. }
  1018. inBody := wire.SNAC_0x02_0x05_LocateUserInfoQuery{
  1019. ScreenName: them,
  1020. }
  1021. info, err := s.LocateService.UserInfoQuery(ctx, me, wire.SNACFrame{}, inBody)
  1022. if err != nil {
  1023. return s.runtimeErr(ctx, fmt.Errorf("LocateService.UserInfoQuery: %w", err))
  1024. }
  1025. switch v := info.Body.(type) {
  1026. case wire.SNACError:
  1027. if v.Code == wire.ErrorCodeNotLoggedOn {
  1028. return []string{fmt.Sprintf("ERROR:%s:%s", wire.TOCErrorGeneralUserNotAvailable, them)}
  1029. } else {
  1030. return s.runtimeErr(ctx, fmt.Errorf("LocateService.UserInfoQuery error code: %d", v.Code))
  1031. }
  1032. case wire.SNAC_0x02_0x06_LocateUserInfoReply:
  1033. return []string{userInfoToUpdateBuddy(v.TLVUserInfo, me)}
  1034. default:
  1035. return s.runtimeErr(ctx, fmt.Errorf("AdminService.InfoChangeRequest: unexpected response type %v", v))
  1036. }
  1037. }
  1038. // InitDone handles the toc_init_done TOC command.
  1039. //
  1040. // From the TiK documentation:
  1041. //
  1042. // Tells TOC that we are ready to go online. TOC clients should first send TOC
  1043. // the buddy list and any permit/deny lists. However, toc_init_done must be
  1044. // called within 30 seconds after toc_signon, or the connection will be
  1045. // dropped. Remember, it can't be called until after the SIGN_ON message is
  1046. // received. Calling this before or multiple times after a SIGN_ON will cause
  1047. // the connection to be dropped.
  1048. //
  1049. // Note: The business logic described in the last 3 sentences are not yet
  1050. // implemented.
  1051. //
  1052. // Command syntax: toc_init_done
  1053. func (s OSCARProxy) InitDone(ctx context.Context, instance *state.SessionInstance) []string {
  1054. err := s.FeedbagManager.UseFeedbag(ctx, instance.IdentScreenName())
  1055. if err != nil {
  1056. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.UseFeedbag: %w", err))
  1057. }
  1058. if errMsg, isLimited := s.checkRateLimit(ctx, instance, wire.OService, wire.OServiceClientOnline); isLimited {
  1059. return errMsg
  1060. }
  1061. if err := s.OServiceService.ClientOnline(ctx, wire.BOS, wire.SNAC_0x01_0x02_OServiceClientOnline{}, instance); err != nil {
  1062. return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.ClientOnliney: %w", err))
  1063. }
  1064. return []string{}
  1065. }
  1066. // RemoveBuddy handles the toc_remove_buddy TOC command.
  1067. //
  1068. // From the TiK documentation:
  1069. //
  1070. // Remove buddies from your buddy list. This does not change your saved config.
  1071. //
  1072. // Command syntax: toc_remove_buddy <Buddy User 1> [<Buddy User2> [<Buddy User 3> [...]]]
  1073. func (s OSCARProxy) RemoveBuddy(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1074. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Buddy, wire.BuddyDelBuddies); isLimited {
  1075. return errMsg
  1076. }
  1077. users, err := parseArgs(args)
  1078. if err != nil {
  1079. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1080. }
  1081. snac := wire.SNAC_0x03_0x05_BuddyDelBuddies{}
  1082. for _, sn := range users {
  1083. snac.Buddies = append(snac.Buddies, struct {
  1084. ScreenName string `oscar:"len_prefix=uint8"`
  1085. }{ScreenName: sn})
  1086. }
  1087. if err := s.BuddyService.DelBuddies(ctx, me, snac); err != nil {
  1088. return s.runtimeErr(ctx, fmt.Errorf("BuddyService.DelBuddies: %w", err))
  1089. }
  1090. return []string{}
  1091. }
  1092. // RvousAccept handles the toc_rvous_accept TOC command.
  1093. //
  1094. // From the TiK documentation:
  1095. //
  1096. // Accept a rendezvous proposal from the user <nick>. <cookie> is the cookie
  1097. // from the RVOUS_PROPOSE message. <service> is the UUID the proposal was for.
  1098. // <tlvlist> contains a list of tlv tags followed by base64 encoded values.
  1099. //
  1100. // Note: This method does not actually process the TLV list param, as it's not
  1101. // passed in the TiK client, the reference implementation.
  1102. //
  1103. // Command syntax: toc_rvous_accept <nick> <cookie> <service>
  1104. func (s OSCARProxy) RvousAccept(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1105. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.ICBM, wire.ICBMChannelMsgToHost); isLimited {
  1106. return errMsg
  1107. }
  1108. var nick, cookie, service string
  1109. if _, err := parseArgs(args, &nick, &cookie, &service); err != nil {
  1110. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1111. }
  1112. cbytes, err := base64.StdEncoding.DecodeString(cookie)
  1113. if err != nil {
  1114. return s.runtimeErr(ctx, fmt.Errorf("base64.Decode: %w", err))
  1115. }
  1116. var arr [8]byte
  1117. copy(arr[:], cbytes) // copy slice into array
  1118. svcUUID, err := uuid.Parse(service)
  1119. if err != nil {
  1120. return s.runtimeErr(ctx, fmt.Errorf("uuid.Parse: %w", err))
  1121. }
  1122. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  1123. ChannelID: wire.ICBMChannelRendezvous,
  1124. ScreenName: nick,
  1125. TLVRestBlock: wire.TLVRestBlock{
  1126. TLVList: wire.TLVList{
  1127. wire.NewTLVBE(wire.ICBMTLVData, wire.ICBMCh2Fragment{
  1128. Type: wire.ICBMRdvMessageAccept,
  1129. Cookie: arr,
  1130. Capability: svcUUID,
  1131. }),
  1132. },
  1133. },
  1134. }
  1135. if _, err = s.ICBMService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac); err != nil {
  1136. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  1137. }
  1138. return []string{}
  1139. }
  1140. // RvousCancel handles the toc_rvous_cancel TOC command.
  1141. //
  1142. // From the TiK documentation:
  1143. //
  1144. // Cancel a rendezvous proposal from the user <nick>. <cookie> is the cookie
  1145. // from the RVOUS_PROPOSE message. <service> is the UUID the proposal was for.
  1146. // <tlvlist> contains a list of tlv tags followed by base64 encoded values.
  1147. //
  1148. // Note: This method does not actually process the TLV list param, as it's not
  1149. // passed in the TiK client, the reference implementation.
  1150. //
  1151. // Command syntax: toc_rvous_cancel <nick> <cookie> <service>
  1152. func (s OSCARProxy) RvousCancel(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1153. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.ICBM, wire.ICBMChannelMsgToHost); isLimited {
  1154. return errMsg
  1155. }
  1156. var nick, cookie, service string
  1157. if _, err := parseArgs(args, &nick, &cookie, &service); err != nil {
  1158. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1159. }
  1160. cbytes, err := base64.StdEncoding.DecodeString(cookie)
  1161. if err != nil {
  1162. return s.runtimeErr(ctx, fmt.Errorf("base64.Decode: %w", err))
  1163. }
  1164. var arr [8]byte
  1165. copy(arr[:], cbytes) // copy slice into array
  1166. svcUUID, err := uuid.Parse(service)
  1167. if err != nil {
  1168. return s.runtimeErr(ctx, fmt.Errorf("uuid.Parse: %w", err))
  1169. }
  1170. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  1171. ChannelID: wire.ICBMChannelRendezvous,
  1172. ScreenName: nick,
  1173. TLVRestBlock: wire.TLVRestBlock{
  1174. TLVList: wire.TLVList{
  1175. wire.NewTLVBE(wire.ICBMTLVData, wire.ICBMCh2Fragment{
  1176. Type: wire.ICBMRdvMessageCancel,
  1177. Cookie: arr,
  1178. Capability: svcUUID,
  1179. TLVRestBlock: wire.TLVRestBlock{
  1180. TLVList: wire.TLVList{
  1181. wire.NewTLVBE(wire.ICBMRdvTLVTagsCancelReason, wire.ICBMRdvCancelReasonsUserCancel),
  1182. },
  1183. },
  1184. }),
  1185. },
  1186. },
  1187. }
  1188. if _, err = s.ICBMService.ChannelMsgToHost(ctx, me, wire.SNACFrame{}, snac); err != nil {
  1189. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  1190. }
  1191. return []string{}
  1192. }
  1193. // SetPDMode handles the toc2_set_pdmode TOC2 command.
  1194. //
  1195. // From the BlueTOC documentation:
  1196. //
  1197. // Set permit/deny mode. Value: 1 = Allow all (default), 2 = Block all,
  1198. // 3 = Allow "permit group" only, 4 = Block "deny group" only, 5 = Allow buddy list only.
  1199. //
  1200. // Command syntax: toc2_set_pdmode <mode>
  1201. func (s OSCARProxy) SetPDMode(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1202. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.OService, wire.FeedbagInsertItem); isLimited {
  1203. return errMsg
  1204. }
  1205. var pdModeStr string
  1206. if _, err := parseArgs(args, &pdModeStr); err != nil {
  1207. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1208. }
  1209. mode, err := strconv.Atoi(pdModeStr)
  1210. if err != nil {
  1211. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  1212. }
  1213. if mode < 1 || mode > 5 {
  1214. return s.runtimeErr(ctx, errors.New("invalid pd mode specified"))
  1215. }
  1216. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1217. if err != nil {
  1218. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1219. }
  1220. fl := newFeedbagList(fb, s.RandIntn)
  1221. fl.SetMode(uint8(mode))
  1222. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1223. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  1224. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, pending); err != nil {
  1225. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1226. }
  1227. }
  1228. return []string{}
  1229. }
  1230. // NewGroup handles the toc2_new_group TOC2 command.
  1231. //
  1232. // From the TOC2 docs by Jeffrey Rosen:
  1233. //
  1234. // This is an entirely new command that allows you to add groups. These should be
  1235. // quoted and you can't add more than one per command.
  1236. //
  1237. // Command syntax: toc2_new_group <group>
  1238. func (s OSCARProxy) NewGroup(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1239. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagInsertItem); isLimited {
  1240. return errMsg
  1241. }
  1242. var groupName string
  1243. if _, err := parseArgs(args, &groupName); err != nil {
  1244. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1245. }
  1246. groupName = unescape(groupName)
  1247. if groupName == "" {
  1248. return s.runtimeErr(ctx, fmt.Errorf("empty group name"))
  1249. }
  1250. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1251. if err != nil {
  1252. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1253. }
  1254. fl := newFeedbagList(fb, s.RandIntn)
  1255. fl.AddGroup(groupName)
  1256. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1257. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  1258. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, pending); err != nil {
  1259. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1260. }
  1261. }
  1262. return []string{}
  1263. }
  1264. // DelGroup handles the toc2_del_group TOC2 command.
  1265. //
  1266. // From the TOC2 docs by Jeffrey Rosen:
  1267. //
  1268. // Delete a group.
  1269. //
  1270. // Command syntax: toc2_del_group <group>
  1271. func (s OSCARProxy) DelGroup(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1272. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagDeleteItem); isLimited {
  1273. return errMsg
  1274. }
  1275. var groupName string
  1276. if _, err := parseArgs(args, &groupName); err != nil {
  1277. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1278. }
  1279. groupName = unescape(groupName)
  1280. if groupName == "" {
  1281. return s.runtimeErr(ctx, fmt.Errorf("empty group name"))
  1282. }
  1283. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1284. if err != nil {
  1285. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1286. }
  1287. fl := newFeedbagList(fb, s.RandIntn)
  1288. fl.DeleteGroup(groupName)
  1289. if pending := fl.PendingDeletes(); len(pending) > 0 {
  1290. deleteItem := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{
  1291. Items: pending,
  1292. }
  1293. if _, err := s.FeedbagService.DeleteItem(ctx, me, wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}, deleteItem); err != nil {
  1294. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.DeleteItem: %w", err))
  1295. }
  1296. } else {
  1297. return s.runtimeErr(ctx, fmt.Errorf("group not found: %s", groupName))
  1298. }
  1299. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1300. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  1301. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, pending); err != nil {
  1302. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1303. }
  1304. }
  1305. return []string{}
  1306. }
  1307. // NewBuddies handles the toc2_new_buddies TOC2 command.
  1308. //
  1309. // From the TOC2 docs by Jeffrey Rosen:
  1310. //
  1311. // In TOC2.0, you must add buddies in "config format". If you sent that with the
  1312. // toc2_new_buddies command, you would add the three buddies (buddytest,
  1313. // buddytest2, and buddytest3) into the group "test". Note that if the group
  1314. // doesn't already exist, it will be created.
  1315. //
  1316. // Config format: {g:group<lf>b:buddy1<lf>b:buddy2<lf>}
  1317. // Where <lf> is a linefeed character (ASCII 10).
  1318. //
  1319. // Command syntax: toc2_new_buddies <config format>
  1320. func (s OSCARProxy) NewBuddies(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1321. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagInsertItem); isLimited {
  1322. return errMsg
  1323. }
  1324. // Parse config string (handle quotes, unescape)
  1325. configStr := string(args)
  1326. configStr = strings.Trim(configStr, "'\" ")
  1327. configStr = unescape(configStr)
  1328. if configStr == "" {
  1329. return s.runtimeErr(ctx, fmt.Errorf("empty config"))
  1330. }
  1331. // Parse config format
  1332. groups, err := parseTOC2Config(configStr)
  1333. if err != nil {
  1334. return s.runtimeErr(ctx, fmt.Errorf("parseTOC2Config: %w", err))
  1335. }
  1336. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1337. if err != nil {
  1338. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1339. }
  1340. fl := newFeedbagList(fb, s.RandIntn)
  1341. var replies []string
  1342. // Process each group in config (deterministic order so tests and root Order are stable)
  1343. groupNames := make([]string, 0, len(groups))
  1344. for k := range groups {
  1345. groupNames = append(groupNames, k)
  1346. }
  1347. sort.Strings(groupNames)
  1348. for _, groupName := range groupNames {
  1349. buddies := groups[groupName]
  1350. fl.AddGroup(groupName)
  1351. for _, buddy := range buddies {
  1352. // Parse buddy entry (may contain alias/note: b:buddy:alias:::::note)
  1353. parts := strings.Split(buddy, ":")
  1354. buddyName := parts[0]
  1355. if buddyName == "" {
  1356. continue
  1357. }
  1358. var alias, note string
  1359. if len(parts) > 1 {
  1360. alias = parts[1]
  1361. }
  1362. if len(parts) > 6 {
  1363. note = parts[6]
  1364. }
  1365. inserted, err := fl.AddBuddy(groupName, buddyName, alias, note)
  1366. if err != nil {
  1367. return s.runtimeErr(ctx, fmt.Errorf("fl.AddBuddy: %w", err))
  1368. }
  1369. if inserted {
  1370. replies = append(replies, fmt.Sprintf("NEW_BUDDY_REPLY2:%s:added", buddyName))
  1371. }
  1372. }
  1373. }
  1374. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1375. buddyItems := make(map[uint16][]wire.FeedbagItem)
  1376. for _, item := range pending {
  1377. if item.ClassID == wire.FeedbagClassIdBuddy {
  1378. if _, ok := buddyItems[item.GroupID]; !ok {
  1379. buddyItems[item.GroupID] = nil
  1380. }
  1381. buddyItems[item.GroupID] = append(buddyItems[item.GroupID], item)
  1382. }
  1383. }
  1384. if len(buddyItems) == 0 {
  1385. return replies
  1386. }
  1387. for _, item := range pending {
  1388. if item.ClassID == wire.FeedbagClassIdGroup {
  1389. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem}
  1390. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, []wire.FeedbagItem{item}); err != nil {
  1391. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1392. }
  1393. }
  1394. }
  1395. for _, buddies := range buddyItems {
  1396. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  1397. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, buddies); err != nil {
  1398. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1399. }
  1400. }
  1401. }
  1402. return replies
  1403. }
  1404. // RemoveBuddy2 handles the toc2_remove_buddy command.
  1405. //
  1406. // From the TOC2 docs by Jeffrey Rosen:
  1407. //
  1408. // You can remove multiple names in the same group using the syntax <screenname> <screenname> <group>.
  1409. //
  1410. // Command syntax: toc2_remove_buddy <screenname> [screenname] ... [screenname] <group>
  1411. func (s OSCARProxy) RemoveBuddy2(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1412. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagDeleteItem); isLimited {
  1413. return errMsg
  1414. }
  1415. params, err := parseArgs(args)
  1416. if err != nil {
  1417. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1418. }
  1419. if len(params) < 2 {
  1420. return s.runtimeErr(ctx, fmt.Errorf("missing params: need at least one screenname and group"))
  1421. }
  1422. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1423. if err != nil {
  1424. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1425. }
  1426. fl := newFeedbagList(fb, s.RandIntn)
  1427. groupName := params[len(params)-1]
  1428. screenNames := params[:len(params)-1]
  1429. for _, buddyName := range screenNames {
  1430. if err := fl.DeleteBuddy(groupName, buddyName); err != nil {
  1431. return s.runtimeErr(ctx, err)
  1432. }
  1433. }
  1434. // ensure to delete buddies before groups to ensure they correctly propagate
  1435. // to concurrent sessions
  1436. if pending := fl.PendingDeletes(); len(pending) > 0 {
  1437. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}
  1438. deleteItem := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{
  1439. Items: pending,
  1440. }
  1441. if _, err := s.FeedbagService.DeleteItem(ctx, me, frame, deleteItem); err != nil {
  1442. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.DeleteItem: %w", err))
  1443. }
  1444. }
  1445. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1446. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagUpdateItem}
  1447. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, pending); err != nil {
  1448. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1449. }
  1450. }
  1451. return []string{}
  1452. }
  1453. // AddPermit2 handles the toc2_add_permit TOC2 command.
  1454. //
  1455. // From the TOC2 docs by Jeffrey Rosen:
  1456. //
  1457. // Add user(s) to permit list. <screenname> should be normalized and you can add
  1458. // multiple people at a time by separating the screennames with a space.
  1459. //
  1460. // Command syntax: toc2_add_permit <screenname> [screenname] ...
  1461. func (s OSCARProxy) AddPermit2(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1462. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagInsertItem); isLimited {
  1463. return errMsg
  1464. }
  1465. screenNames, err := parseArgs(args)
  1466. if err != nil {
  1467. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1468. }
  1469. if len(screenNames) == 0 {
  1470. return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
  1471. }
  1472. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1473. if err != nil {
  1474. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1475. }
  1476. fl := newFeedbagList(fb, s.RandIntn)
  1477. for _, sn := range screenNames {
  1478. fl.PermitUser(sn)
  1479. }
  1480. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1481. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  1482. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, pending); err != nil {
  1483. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1484. }
  1485. }
  1486. return []string{}
  1487. }
  1488. // RemovePermit2 handles the toc2_remove_permit TOC2 command.
  1489. //
  1490. // From the TOC2 docs by Jeffrey Rosen:
  1491. //
  1492. // Remove user(s) from permit list. <screenname> should be normalized and you can
  1493. // remove multiple people at a time by separating the screennames with a space.
  1494. //
  1495. // Command syntax: toc2_remove_permit <screenname> [screenname] ...
  1496. func (s OSCARProxy) RemovePermit2(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1497. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagDeleteItem); isLimited {
  1498. return errMsg
  1499. }
  1500. screenNames, err := parseArgs(args)
  1501. if err != nil {
  1502. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1503. }
  1504. if len(screenNames) == 0 {
  1505. return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
  1506. }
  1507. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1508. if err != nil {
  1509. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1510. }
  1511. fl := newFeedbagList(fb, s.RandIntn)
  1512. for _, sn := range screenNames {
  1513. fl.DeletePermit(sn)
  1514. }
  1515. if pending := fl.PendingDeletes(); len(pending) > 0 {
  1516. deleteItem := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{
  1517. Items: pending,
  1518. }
  1519. if _, err := s.FeedbagService.DeleteItem(ctx, me, wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}, deleteItem); err != nil {
  1520. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.DeleteItem: %w", err))
  1521. }
  1522. }
  1523. return []string{}
  1524. }
  1525. // AddDeny2 handles the toc2_add_deny TOC2 command.
  1526. //
  1527. // From the TOC2 docs by Jeffrey Rosen:
  1528. //
  1529. // Add user(s) to deny list. <screenname> should be normalized and you can add
  1530. // multiple people at a time by separating the screennames with a space.
  1531. //
  1532. // Command syntax: toc2_add_deny <screenname> [screenname] ...
  1533. func (s OSCARProxy) AddDeny2(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1534. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagInsertItem); isLimited {
  1535. return errMsg
  1536. }
  1537. screenNames, err := parseArgs(args)
  1538. if err != nil {
  1539. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1540. }
  1541. if len(screenNames) == 0 {
  1542. return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
  1543. }
  1544. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1545. if err != nil {
  1546. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1547. }
  1548. fl := newFeedbagList(fb, s.RandIntn)
  1549. for _, sn := range screenNames {
  1550. fl.DenyUser(sn)
  1551. }
  1552. if pending := fl.PendingUpdates(); len(pending) > 0 {
  1553. frame := wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagInsertItem}
  1554. if _, err := s.FeedbagService.UpsertItem(ctx, me, frame, pending); err != nil {
  1555. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.UpsertItem: %w", err))
  1556. }
  1557. }
  1558. return []string{}
  1559. }
  1560. // RemoveDeny2 handles the toc2_remove_deny TOC2 command.
  1561. //
  1562. // From the TOC2 docs by Jeffrey Rosen:
  1563. //
  1564. // Remove user(s) from deny list. <screenname> should be normalized and you can
  1565. // remove multiple people at a time by separating the screennames with a space.
  1566. //
  1567. // Command syntax: toc2_remove_deny <screenname> [screenname] ...
  1568. func (s OSCARProxy) RemoveDeny2(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1569. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Feedbag, wire.FeedbagDeleteItem); isLimited {
  1570. return errMsg
  1571. }
  1572. screenNames, err := parseArgs(args)
  1573. if err != nil {
  1574. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1575. }
  1576. if len(screenNames) == 0 {
  1577. return s.runtimeErr(ctx, fmt.Errorf("no screennames provided"))
  1578. }
  1579. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  1580. if err != nil {
  1581. return s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  1582. }
  1583. fl := newFeedbagList(fb, s.RandIntn)
  1584. for _, sn := range screenNames {
  1585. fl.DeleteDeny(sn)
  1586. }
  1587. if pending := fl.PendingDeletes(); len(pending) > 0 {
  1588. deleteItem := wire.SNAC_0x13_0x0A_FeedbagDeleteItem{
  1589. Items: pending,
  1590. }
  1591. if _, err := s.FeedbagService.DeleteItem(ctx, me, wire.SNACFrame{FoodGroup: wire.Feedbag, SubGroup: wire.FeedbagDeleteItem}, deleteItem); err != nil {
  1592. return s.runtimeErr(ctx, fmt.Errorf("FeedbagService.DeleteItem: %w", err))
  1593. }
  1594. }
  1595. return []string{}
  1596. }
  1597. // SendIMEnc handles the toc2_send_im_enc TOC2 command.
  1598. //
  1599. // From the BlueTOC source code:
  1600. //
  1601. // Sends an encoded instant message to a user
  1602. // Internally, this uses the "TOC3" encoded message format
  1603. // This encoded message version supports a few more variables as well as encoding
  1604. //
  1605. // Command syntax: toc2_send_im_enc <Destination user> "F" <Encoding> <Language> <Message> [auto]
  1606. func (s OSCARProxy) SendIMEnc(ctx context.Context, sender *state.SessionInstance, args []byte) []string {
  1607. if msg, isLimited := s.checkRateLimit(ctx, sender, wire.ICBM, wire.ICBMChannelMsgToHost); isLimited {
  1608. return msg
  1609. }
  1610. var recip, unknown, enc, lang, msg string
  1611. autoReply, err := parseArgs(args, &recip, &unknown, &enc, &lang, &msg)
  1612. if err != nil {
  1613. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1614. }
  1615. return s.sendIm(ctx, sender, msg, recip, autoReply)
  1616. }
  1617. // SendIM handles the toc_send_im and toc2_send_im TOC commands.
  1618. //
  1619. // From the TiK documentation (TOC1):
  1620. //
  1621. // Send a message to a remote user. Remember to quote and encode the message.
  1622. // If the optional string "auto" is the last argument, then the auto response
  1623. // flag will be turned on for the IM.
  1624. //
  1625. // TOC2 uses the same syntax as TOC1 (BlueTOC documentation).
  1626. //
  1627. // Command syntax: toc_send_im <Destination User> <Message> [auto]
  1628. // Command syntax: toc2_send_im <user> <message> [auto]
  1629. func (s OSCARProxy) SendIM(ctx context.Context, sender *state.SessionInstance, args []byte) []string {
  1630. if msg, isLimited := s.checkRateLimit(ctx, sender, wire.ICBM, wire.ICBMChannelMsgToHost); isLimited {
  1631. return msg
  1632. }
  1633. var recip, msg string
  1634. autoReply, err := parseArgs(args, &recip, &msg)
  1635. if err != nil {
  1636. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1637. }
  1638. return s.sendIm(ctx, sender, msg, recip, autoReply)
  1639. }
  1640. func (s OSCARProxy) sendIm(ctx context.Context, sender *state.SessionInstance, msg string, recip string, autoReply []string) []string {
  1641. frags, err := wire.ICBMFragmentList(unescape(msg))
  1642. if err != nil {
  1643. return s.runtimeErr(ctx, fmt.Errorf("wire.ICBMFragmentList: %w", err))
  1644. }
  1645. snac := wire.SNAC_0x04_0x06_ICBMChannelMsgToHost{
  1646. ChannelID: wire.ICBMChannelIM,
  1647. ScreenName: recip,
  1648. TLVRestBlock: wire.TLVRestBlock{
  1649. TLVList: wire.TLVList{
  1650. wire.NewTLVBE(wire.ICBMTLVAOLIMData, frags),
  1651. },
  1652. },
  1653. }
  1654. if len(autoReply) > 0 && autoReply[0] == "auto" {
  1655. snac.Append(wire.NewTLVBE(wire.ICBMTLVAutoResponse, []byte{}))
  1656. }
  1657. // send message and ignore response since there is no TOC error code to
  1658. // handle errors such as "user is offline", etc.
  1659. _, err = s.ICBMService.ChannelMsgToHost(ctx, sender, wire.SNACFrame{}, snac)
  1660. if err != nil {
  1661. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ChannelMsgToHost: %w", err))
  1662. }
  1663. return []string{}
  1664. }
  1665. // SendClientEvent handles the toc2_client_event TOC2 command.
  1666. //
  1667. // From the BlueTOC documentation:
  1668. //
  1669. // This is used to send a typing notification. Typing status: 0 for no activity,
  1670. // 1 for typing paused, 2 for currently typing.
  1671. //
  1672. // Command syntax: toc2_client_event <user> <typing status>
  1673. func (s OSCARProxy) SendClientEvent(ctx context.Context, sender *state.SessionInstance, args []byte) []string {
  1674. if msg, isLimited := s.checkRateLimit(ctx, sender, wire.ICBM, wire.ICBMClientEvent); isLimited {
  1675. return msg
  1676. }
  1677. var user, statusStr string
  1678. if _, err := parseArgs(args, &user, &statusStr); err != nil {
  1679. return s.runtimeErr(ctx, fmt.Errorf("SendClientEvent: invalid args: %w", err))
  1680. }
  1681. status, err := strconv.ParseUint(statusStr, 10, 16)
  1682. if err != nil || status > 2 {
  1683. return s.runtimeErr(ctx, fmt.Errorf("SendClientEvent: typing status must be 0, 1, or 2, got %q", statusStr))
  1684. }
  1685. inBody := wire.SNAC_0x04_0x14_ICBMClientEvent{
  1686. Cookie: 0,
  1687. ChannelID: wire.ICBMChannelIM,
  1688. ScreenName: user,
  1689. Event: uint16(status),
  1690. }
  1691. if err := s.ICBMService.ClientEvent(ctx, sender, wire.SNACFrame{}, inBody); err != nil {
  1692. return s.runtimeErr(ctx, fmt.Errorf("ICBMService.ClientEvent: %w", err))
  1693. }
  1694. return []string{}
  1695. }
  1696. // SetAway handles the toc_set_away TOC command.
  1697. //
  1698. // From the TiK documentation:
  1699. //
  1700. // If the away message is present, then the unavailable status flag is set for
  1701. // the user. If the away message is not present, then the unavailable status
  1702. // flag is unset. The away message is basic HTML, remember to encode the
  1703. // information.
  1704. //
  1705. // Command syntax: toc_set_away [<away message>]
  1706. func (s OSCARProxy) SetAway(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1707. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Locate, wire.LocateSetInfo); isLimited {
  1708. return errMsg
  1709. }
  1710. maybeMsg, err := parseArgs(args)
  1711. if err != nil {
  1712. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1713. }
  1714. var msg string
  1715. if len(maybeMsg) > 0 {
  1716. msg = unescape(maybeMsg[0])
  1717. }
  1718. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  1719. TLVRestBlock: wire.TLVRestBlock{
  1720. TLVList: wire.TLVList{
  1721. wire.NewTLVBE(wire.LocateTLVTagsInfoUnavailableData, msg),
  1722. },
  1723. },
  1724. }
  1725. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  1726. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  1727. }
  1728. return []string{}
  1729. }
  1730. // SetCaps handles the toc_set_caps TOC command.
  1731. //
  1732. // From the TiK documentation:
  1733. //
  1734. // Set my capabilities. All capabilities that we support need to be sent at
  1735. // the same time. Capabilities are represented by UUIDs.
  1736. //
  1737. // This method automatically adds the "chat" capability since it doesn't seem
  1738. // to be sent explicitly by the official clients, even though they support
  1739. // chat.
  1740. //
  1741. // Command syntax: toc_set_caps [ <Capability 1> [<Capability 2> [...]]]
  1742. func (s OSCARProxy) SetCaps(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1743. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Locate, wire.LocateSetInfo); isLimited {
  1744. return errMsg
  1745. }
  1746. params, err := parseArgs(args)
  1747. if err != nil {
  1748. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1749. }
  1750. // Clients may send capabilities as space-separated UUIDs or as a single
  1751. // comma-separated string (e.g. TameClone: "UUID,1348,134B,..."). Split each
  1752. // param on comma. Accept full UUIDs and OSCAR short caps (1–4 hex digits
  1753. // expanded to 0946XXYY-4C7F-11D1-8222-444553540000); ignore unknown tokens.
  1754. caps := make([]uuid.UUID, 0, 16)
  1755. for _, param := range params {
  1756. for _, token := range strings.Split(param, ",") {
  1757. token = strings.TrimSpace(token)
  1758. if token == "" {
  1759. continue
  1760. }
  1761. uid, err := uuid.Parse(token)
  1762. if err != nil {
  1763. uid, ok := wire.ShortCapHexToUUID(token)
  1764. if !ok {
  1765. continue
  1766. }
  1767. caps = append(caps, uid)
  1768. continue
  1769. }
  1770. caps = append(caps, uid)
  1771. }
  1772. }
  1773. // assume client supports chat, although we may want to do this according
  1774. // to client ID
  1775. caps = append(caps, wire.CapChat)
  1776. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  1777. TLVRestBlock: wire.TLVRestBlock{
  1778. TLVList: wire.TLVList{
  1779. wire.NewTLVBE(wire.LocateTLVTagsInfoCapabilities, caps),
  1780. },
  1781. },
  1782. }
  1783. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  1784. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  1785. }
  1786. return []string{}
  1787. }
  1788. // SetConfig handles the toc_set_config TOC command.
  1789. //
  1790. // From the TiK documentation:
  1791. //
  1792. // Set the config information for this user. The config information is line
  1793. // oriented with the first character being the item type, followed by a space,
  1794. // with the rest of the line being the item value. Only letters, numbers, and
  1795. // spaces should be used. Remember you will have to enclose the entire config
  1796. // in quotes.
  1797. //
  1798. // Item Types:
  1799. // - g - Buddy Group (All Buddies until the next g or the end of config are in this group.)
  1800. // - b - A Buddy
  1801. // - p - Person on permit list
  1802. // - d - Person on deny list
  1803. // - m - Permit/Deny Mode. Possible values are
  1804. // - 1 - Permit All
  1805. // - 2 - Deny All
  1806. // - 3 - Permit Some
  1807. // - 4 - Deny Some
  1808. //
  1809. // This method doesn't attempt to validate any of the configuration--it saves
  1810. // the config as received from the client.
  1811. //
  1812. // Command syntax: toc_set_config <Config Info>
  1813. func (s OSCARProxy) SetConfig(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1814. if status := me.Session().EvaluateRateLimit(time.Now(), 1); status == wire.RateLimitStatusLimited {
  1815. return []string{rateLimitExceededErr}
  1816. }
  1817. // most TOC clients don't quote the config info argument, despite what the
  1818. // documentation specifies. this makes the argument payload incompatible
  1819. // for CSV parsing. since this command takes a single argument, we can get
  1820. // away with trimming quotes and spaces from the byte slice before passing
  1821. // it to the config store.
  1822. args = bytes.Trim(args, "'\" ")
  1823. cfg := string(args)
  1824. if cfg == "" {
  1825. return s.runtimeErr(ctx, fmt.Errorf("empty config"))
  1826. }
  1827. if err := s.TOCConfigStore.SetTOCConfig(ctx, me.IdentScreenName(), cfg); err != nil {
  1828. return s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.SaveTOCConfig: %w", err))
  1829. }
  1830. return []string{}
  1831. }
  1832. // SetDir handles the toc_set_dir TOC command.
  1833. //
  1834. // From the TiK documentation:
  1835. //
  1836. // Set the DIR user information. This is a colon separated fields as in:
  1837. //
  1838. // "first name":"middle name":"last name":"maiden name":"city":"state":"country":"email":"allow web searches".
  1839. //
  1840. // Should return a DIR_STATUS msg. Having anything in the "allow web searches"
  1841. // field allows people to use web-searches to find your directory info.
  1842. // Otherwise, they'd have to use the client.
  1843. //
  1844. // The fields "email" and "allow web searches" are ignored by this method.
  1845. //
  1846. // Command syntax: toc_set_dir <info information>
  1847. func (s OSCARProxy) SetDir(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1848. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Locate, wire.LocateSetDirInfo); isLimited {
  1849. return errMsg
  1850. }
  1851. var info string
  1852. if _, err := parseArgs(args, &info); err != nil {
  1853. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1854. }
  1855. info = unescape(info)
  1856. rawFields := strings.Split(info, ":")
  1857. var finalFields [9]string
  1858. if len(rawFields) > len(finalFields) {
  1859. return s.runtimeErr(ctx, fmt.Errorf("expected at most %d params, got %d", len(finalFields), len(rawFields)))
  1860. }
  1861. for i, a := range rawFields {
  1862. finalFields[i] = strings.Trim(a, "\"")
  1863. }
  1864. snac := wire.SNAC_0x02_0x09_LocateSetDirInfo{
  1865. TLVRestBlock: wire.TLVRestBlock{
  1866. TLVList: wire.TLVList{
  1867. wire.NewTLVBE(wire.ODirTLVFirstName, finalFields[0]),
  1868. wire.NewTLVBE(wire.ODirTLVMiddleName, finalFields[1]),
  1869. wire.NewTLVBE(wire.ODirTLVLastName, finalFields[2]),
  1870. wire.NewTLVBE(wire.ODirTLVMaidenName, finalFields[3]),
  1871. wire.NewTLVBE(wire.ODirTLVCountry, finalFields[6]),
  1872. wire.NewTLVBE(wire.ODirTLVState, finalFields[5]),
  1873. wire.NewTLVBE(wire.ODirTLVCity, finalFields[4]),
  1874. },
  1875. },
  1876. }
  1877. if _, err := s.LocateService.SetDirInfo(ctx, me, wire.SNACFrame{}, snac); err != nil {
  1878. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetDirInfo: %w", err))
  1879. }
  1880. return []string{}
  1881. }
  1882. // SetIdle handles the toc_set_idle TOC command.
  1883. //
  1884. // From the TiK documentation:
  1885. //
  1886. // Set idle information. If <idle secs> is 0 then the user isn't idle at all.
  1887. // If <idle secs> is greater than 0 then the user has already been idle for
  1888. // <idle secs> number of seconds. The server will automatically keep
  1889. // incrementing this number, so do not repeatedly call with new idle times.
  1890. //
  1891. // Command syntax: toc_set_idle <idle secs>
  1892. func (s OSCARProxy) SetIdle(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1893. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.OService, wire.OServiceIdleNotification); isLimited {
  1894. return errMsg
  1895. }
  1896. var idleTimeStr string
  1897. if _, err := parseArgs(args, &idleTimeStr); err != nil {
  1898. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1899. }
  1900. t, err := strconv.Atoi(idleTimeStr)
  1901. if err != nil {
  1902. return s.runtimeErr(ctx, fmt.Errorf("strconv.Atoi: %w", err))
  1903. }
  1904. snac := wire.SNAC_0x01_0x11_OServiceIdleNotification{
  1905. IdleTime: uint32(t),
  1906. }
  1907. if err := s.OServiceService.IdleNotification(ctx, me, snac); err != nil {
  1908. return s.runtimeErr(ctx, fmt.Errorf("OServiceServiceBOS.IdleNotification: %w", err))
  1909. }
  1910. return []string{}
  1911. }
  1912. // SetInfo handles the toc_set_info TOC command.
  1913. //
  1914. // From the TiK documentation:
  1915. //
  1916. // Set the LOCATE user information. This is basic HTML. Remember to encode the info.
  1917. //
  1918. // Command syntax: toc_set_info <info information>
  1919. func (s OSCARProxy) SetInfo(ctx context.Context, me *state.SessionInstance, args []byte) []string {
  1920. if errMsg, isLimited := s.checkRateLimit(ctx, me, wire.Locate, wire.LocateSetInfo); isLimited {
  1921. return errMsg
  1922. }
  1923. var info string
  1924. if _, err := parseArgs(args, &info); err != nil {
  1925. return s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1926. }
  1927. info = unescape(info)
  1928. snac := wire.SNAC_0x02_0x04_LocateSetInfo{
  1929. TLVRestBlock: wire.TLVRestBlock{
  1930. TLVList: wire.TLVList{
  1931. wire.NewTLVBE(wire.LocateTLVTagsInfoSigData, info),
  1932. },
  1933. },
  1934. }
  1935. if err := s.LocateService.SetInfo(ctx, me, snac); err != nil {
  1936. return s.runtimeErr(ctx, fmt.Errorf("LocateService.SetInfo: %w", err))
  1937. }
  1938. return []string{}
  1939. }
  1940. // Signon handles the toc_signon, toc2_signon, and toc2_login TOC commands.
  1941. //
  1942. // From the TiK documentation (TOC1 toc_signon):
  1943. //
  1944. // The password needs to be roasted with the Roasting String if coming over a
  1945. // FLAP connection, CP connections don't use roasted passwords. The language
  1946. // specified will be used when generating web pages, such as the get info
  1947. // pages. Currently, the only supported language is "english". If the language
  1948. // sent isn't found, the default "english" language will be used. The version
  1949. // string will be used for the client identity, and must be less than 50
  1950. // characters.
  1951. //
  1952. // Passwords are roasted when sent to the host. This is done so they aren't
  1953. // sent in "clear text" over the wire, although they are still trivial to
  1954. // decode. Roasting is performed by first xoring each byte in the password
  1955. // with the equivalent modulo byte in the roasting string. The result is then
  1956. // converted to ascii hex, and prepended with "0x". So for example the
  1957. // password "password" roasts to "0x2408105c23001130".
  1958. //
  1959. // The Roasting String is Tic/Toc.
  1960. //
  1961. // toc2_signon uses the same parameters as toc_signon. toc2_login (TOC2) may
  1962. // include additional trailing parameters (e.g. agent string, code); see
  1963. // BlueTOC documentation.
  1964. //
  1965. // Command syntax: toc_signon <authorizer host> <authorizer port> <User Name> <Password> <language> <version>
  1966. // Command syntax: toc2_signon <authorizer host> <authorizer port> <User Name> <Password> <language> <version>
  1967. // Command syntax: toc2_login <authorizer host> <authorizer port> <User Name> <Password> <language> <version> [additional params...]
  1968. func (s OSCARProxy) Signon(ctx context.Context, args []byte) (*state.SessionInstance, []string) {
  1969. var cmd, userName, password string
  1970. if _, err := parseArgs(args, &cmd, nil, nil, &userName, &password); err != nil {
  1971. return nil, s.runtimeErr(ctx, fmt.Errorf("parseArgs: %w", err))
  1972. }
  1973. switch cmd {
  1974. case "toc_signon", "toc2_signon", "toc2_login":
  1975. // valid
  1976. default:
  1977. return nil, s.runtimeErr(ctx, errors.New("expected one of toc_signon, toc2_signon, toc2_login"))
  1978. }
  1979. if len(password) < 3 {
  1980. return nil, s.runtimeErr(ctx, fmt.Errorf("password too short for roasted hex (need 2-char prefix + hex)"))
  1981. }
  1982. passwordHash, err := hex.DecodeString(password[2:])
  1983. if err != nil {
  1984. return nil, s.runtimeErr(ctx, fmt.Errorf("hex.DecodeString: %w", err))
  1985. }
  1986. signonFrame := wire.FLAPSignonFrame{}
  1987. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsScreenName, userName))
  1988. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsRoastedTOCPassword, passwordHash))
  1989. if cmd == "toc2_login" || cmd == "toc2_signon" {
  1990. signonFrame.Append(wire.NewTLVBE(wire.LoginTLVTagsMultiConnFlags, wire.MultiConnFlagsRecentClient))
  1991. }
  1992. block, err := s.AuthService.FLAPLogin(ctx, signonFrame, "")
  1993. if err != nil {
  1994. return nil, s.runtimeErr(ctx, fmt.Errorf("AuthService.FLAPLogin: %w", err))
  1995. }
  1996. if block.HasTag(wire.LoginTLVTagsErrorSubcode) {
  1997. s.Logger.DebugContext(ctx, "login failed")
  1998. return nil, []string{"ERROR:" + wire.TOCErrorAuthIncorrectNickOrPassword}
  1999. }
  2000. authCookie, ok := block.Bytes(wire.OServiceTLVTagsLoginCookie)
  2001. if !ok {
  2002. return nil, s.runtimeErr(ctx, fmt.Errorf("unable to get session id from payload"))
  2003. }
  2004. // todo: naming for cookie: login cookie, server cookie, or auth cookie?
  2005. serverCookie, err := s.AuthService.CrackCookie(authCookie)
  2006. if err != nil {
  2007. return nil, s.runtimeErr(ctx, fmt.Errorf("AuthService.CrackCookie: %w", err))
  2008. }
  2009. sess, err := s.AuthService.RegisterBOSSession(ctx, serverCookie)
  2010. if err != nil {
  2011. return nil, s.runtimeErr(ctx, fmt.Errorf("AuthService.RegisterBOSSession: %w", err))
  2012. }
  2013. // set chat capability so that... tk
  2014. sess.SetCaps([][16]byte{wire.CapChat})
  2015. if err := s.BuddyListRegistry.RegisterBuddyList(ctx, sess.IdentScreenName()); err != nil {
  2016. return nil, s.runtimeErr(ctx, fmt.Errorf("BuddyListRegistry.RegisterBuddyList: %w", err))
  2017. }
  2018. u, err := s.TOCConfigStore.User(ctx, sess.IdentScreenName())
  2019. if err != nil {
  2020. return nil, s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.User: %w", err))
  2021. }
  2022. if u == nil {
  2023. return nil, s.runtimeErr(ctx, fmt.Errorf("TOCConfigStore.User: user not found"))
  2024. }
  2025. if cmd == "toc_signon" {
  2026. return sess, []string{"SIGN_ON:TOC1.0", fmt.Sprintf("CONFIG:%s", u.TOCConfig), fmt.Sprintf("NICK:%s", sess.DisplayScreenName().String())}
  2027. }
  2028. supportsTOC2MsgEnc := cmd == "toc2_login"
  2029. sess.SetTOC2(supportsTOC2MsgEnc)
  2030. if err := s.FeedbagService.Use(ctx, sess); err != nil {
  2031. return sess, s.runtimeErr(ctx, fmt.Errorf("FeedbagService.Use: %w", err))
  2032. }
  2033. fb, err := s.FeedbagManager.Feedbag(ctx, sess.IdentScreenName())
  2034. if err != nil {
  2035. return sess, s.runtimeErr(ctx, fmt.Errorf("FeedbagManager.Feedbag: %w", err))
  2036. }
  2037. signon := []string{
  2038. "SIGN_ON:TOC2.0",
  2039. fmt.Sprintf("NICK:%s", sess.DisplayScreenName().String()),
  2040. }
  2041. cfg, err := buildToc2Config(fb)
  2042. if err != nil {
  2043. return sess, s.runtimeErr(ctx, fmt.Errorf("buildToc2Config: %w", err))
  2044. }
  2045. signon = append(signon, cfg...)
  2046. return sess, signon
  2047. }
  2048. // buildToc2Config constructs configuration for CONFIG2
  2049. // - Lines are separated by LF; data between colons.
  2050. // - g: = group (before buddies in that group), b: = buddy (optionally :alias and :::::note),
  2051. // - d: = blocked, p: = private (permit), m: = privacy level (1-5), done: = end.
  2052. func buildToc2Config(fb []wire.FeedbagItem) ([]string, error) {
  2053. type buddy struct {
  2054. name string
  2055. alias string
  2056. note string
  2057. }
  2058. type group struct {
  2059. name string
  2060. buddies map[uint16]buddy
  2061. order []uint16
  2062. }
  2063. type feedbag struct {
  2064. order []uint16
  2065. groups map[uint16]group
  2066. }
  2067. buddylist := feedbag{
  2068. groups: make(map[uint16]group),
  2069. }
  2070. for _, item := range fb {
  2071. if item.ClassID == wire.FeedbagClassIdGroup {
  2072. // root group contains the order of all other groups
  2073. if item.GroupID == 0 {
  2074. val, hasVal := item.Uint16SliceBE(wire.FeedbagAttributesOrder)
  2075. if !hasVal {
  2076. return []string{}, fmt.Errorf("root group missing order attribute")
  2077. }
  2078. buddylist.order = val
  2079. continue
  2080. }
  2081. group := group{
  2082. name: item.Name,
  2083. buddies: make(map[uint16]buddy),
  2084. }
  2085. // order will be empty if the group is empty
  2086. val, _ := item.Uint16SliceBE(wire.FeedbagAttributesOrder)
  2087. group.order = val
  2088. buddylist.groups[item.GroupID] = group
  2089. }
  2090. }
  2091. var cfg []string
  2092. for _, item := range fb {
  2093. if item.ClassID == wire.FeedbagClassIdBuddy {
  2094. // Ensure group exists (handle orphaned buddies)
  2095. if _, exists := buddylist.groups[item.GroupID]; !exists {
  2096. buddylist.groups[item.GroupID] = group{
  2097. name: "", // Unknown group name
  2098. buddies: make(map[uint16]buddy),
  2099. order: []uint16{},
  2100. }
  2101. }
  2102. buddy := buddy{
  2103. name: item.Name,
  2104. }
  2105. if val, hasVal := item.String(wire.FeedbagAttributesNote); hasVal {
  2106. buddy.note = val
  2107. }
  2108. if val, hasVal := item.String(wire.FeedbagAttributesAlias); hasVal {
  2109. buddy.alias = val
  2110. }
  2111. buddylist.groups[item.GroupID].buddies[item.ItemID] = buddy
  2112. }
  2113. if item.ClassID == wire.FeedbagClassIDDeny {
  2114. cfg = append(cfg, "d:"+item.Name)
  2115. }
  2116. if item.ClassID == wire.FeedbagClassIDPermit {
  2117. cfg = append(cfg, "p:"+item.Name)
  2118. }
  2119. if item.ClassID == wire.FeedbagClassIdPdinfo {
  2120. val, hasVal := item.Uint8(wire.FeedbagAttributesPdMode)
  2121. if hasVal {
  2122. cfg = append(cfg, fmt.Sprintf("m:%d", val))
  2123. }
  2124. }
  2125. }
  2126. for _, gid := range buddylist.order {
  2127. group := buddylist.groups[gid]
  2128. cfg = append(cfg, "g:"+group.name)
  2129. for _, bid := range group.order {
  2130. buddy := group.buddies[bid]
  2131. tmpLine := "b:" + buddy.name
  2132. if buddy.alias != "" {
  2133. tmpLine += ":" + buddy.alias
  2134. }
  2135. if buddy.note != "" {
  2136. tmpLine += ":::::" + buddy.note
  2137. }
  2138. cfg = append(cfg, tmpLine)
  2139. }
  2140. }
  2141. cfg = append(cfg, "done:")
  2142. return []string{"CONFIG2:" + strings.Join(cfg, "\n") + "\n"}, nil
  2143. }
  2144. // Signout terminates a TOC session. It sends departure notifications to
  2145. // buddies, de-registers buddy list and session.
  2146. func (s OSCARProxy) Signout(ctx context.Context, me *state.SessionInstance, chatRegistry *ChatRegistry) {
  2147. if err := s.BuddyService.BroadcastBuddyDeparted(ctx, me); err != nil {
  2148. s.Logger.ErrorContext(ctx, "error sending departure notifications", "err", err.Error())
  2149. }
  2150. if err := s.BuddyListRegistry.UnregisterBuddyList(ctx, me.IdentScreenName()); err != nil {
  2151. s.Logger.ErrorContext(ctx, "error removing buddy list entry", "err", err.Error())
  2152. }
  2153. s.AuthService.Signout(ctx, me)
  2154. for _, sess := range chatRegistry.Sessions() {
  2155. s.AuthService.SignoutChat(ctx, sess)
  2156. sess.CloseInstance() // stop async server SNAC reply handler for this chat room
  2157. }
  2158. }
  2159. // newHTTPAuthToken creates a HMAC token for authenticating TOC HTTP requests
  2160. func (s OSCARProxy) newHTTPAuthToken(me state.IdentScreenName) (string, error) {
  2161. cookie, err := s.CookieBaker.Issue([]byte(me.String()))
  2162. if err != nil {
  2163. return "", err
  2164. }
  2165. // trim padding so that gaim doesn't choke on the long value
  2166. cookie = bytes.TrimRight(cookie, "\x00")
  2167. return hex.EncodeToString(cookie), nil
  2168. }
  2169. // parseArgs extracts arguments from a TOC command. Each positional argument is
  2170. // assigned to its corresponding args pointer. It returns the remaining
  2171. // arguments as varargs.
  2172. func parseArgs(payload []byte, args ...*string) (varArgs []string, err error) {
  2173. if len(payload) == 0 && len(args) == 0 {
  2174. return []string{}, nil
  2175. }
  2176. reader := csv.NewReader(bytes.NewReader(payload))
  2177. reader.Comma = ' '
  2178. reader.LazyQuotes = true
  2179. reader.TrimLeadingSpace = true
  2180. segs, err := reader.Read()
  2181. if err != nil {
  2182. return []string{}, fmt.Errorf("CSV reader error: %w", err)
  2183. }
  2184. if len(segs) < len(args) {
  2185. return []string{}, fmt.Errorf("command contains fewer arguments than expected")
  2186. }
  2187. // populate placeholder pointers with their corresponding values
  2188. for i, arg := range args {
  2189. if arg != nil {
  2190. *arg = strings.TrimSpace(segs[i])
  2191. }
  2192. }
  2193. // dump remaining arguments as varargs
  2194. return segs[len(args):], err
  2195. }
  2196. // runtimeErr is a convenience function that logs an error and returns a TOC
  2197. // internal server error.
  2198. func (s OSCARProxy) runtimeErr(ctx context.Context, err error) []string {
  2199. s.Logger.ErrorContext(ctx, "internal service error", "err", err.Error())
  2200. return []string{cmdInternalSvcErr}
  2201. }
  2202. func (s OSCARProxy) checkRateLimit(ctx context.Context, sender *state.SessionInstance, foodGroup uint16, subGroup uint16) ([]string, bool) {
  2203. rateClassID, ok := s.SNACRateLimits.RateClassLookup(foodGroup, subGroup)
  2204. if !ok {
  2205. s.Logger.ErrorContext(ctx, "rate limit not found, allowing request through")
  2206. return []string{}, false
  2207. }
  2208. if status := sender.Session().EvaluateRateLimit(time.Now(), rateClassID); status == wire.RateLimitStatusLimited {
  2209. s.Logger.DebugContext(ctx, "(toc) rate limit exceeded, dropping SNAC",
  2210. "foodgroup", wire.FoodGroupName(foodGroup),
  2211. "subgroup", wire.SubGroupName(foodGroup, subGroup))
  2212. return []string{rateLimitExceededErr}, true
  2213. }
  2214. return []string{}, false
  2215. }
  2216. // unescape removes escaping from the following TOC characters: \ { } ( ) [ ] $ "
  2217. func unescape(encoded string) string {
  2218. if !strings.ContainsRune(encoded, '\\') {
  2219. return encoded
  2220. }
  2221. var result strings.Builder
  2222. result.Grow(len(encoded))
  2223. escaped := false
  2224. for i := 0; i < len(encoded); i++ {
  2225. ch := encoded[i]
  2226. if escaped {
  2227. // append escaped character without the backslash
  2228. result.WriteByte(ch)
  2229. escaped = false
  2230. } else if ch == '\\' {
  2231. escaped = true
  2232. } else {
  2233. result.WriteByte(ch)
  2234. }
  2235. }
  2236. return result.String()
  2237. }
  2238. // parseTOC2Config parses the TOC2 config format string into a map of group names to buddy lists.
  2239. //
  2240. // Config format: {g:group<lf>b:buddy1<lf>b:buddy2<lf>}
  2241. // Where <lf> is a linefeed character (ASCII 10, \n).
  2242. //
  2243. // Extended format for buddies with alias/note:
  2244. // b:buddy:alias:::::note
  2245. //
  2246. // Returns a map where keys are group names and values are slices of buddy entries.
  2247. // Each buddy entry is a string that may contain alias/note information.
  2248. func parseTOC2Config(config string) (map[string][]string, error) {
  2249. // Remove surrounding braces
  2250. config = strings.TrimPrefix(config, "{")
  2251. config = strings.TrimSuffix(config, "}")
  2252. // Split by linefeed (ASCII 10)
  2253. lines := strings.Split(config, "\n")
  2254. result := make(map[string][]string)
  2255. var currentGroup string
  2256. for _, line := range lines {
  2257. line = strings.TrimSpace(line)
  2258. if line == "" {
  2259. continue
  2260. }
  2261. if strings.HasPrefix(line, "g:") {
  2262. // Group line: g:groupname
  2263. currentGroup = strings.TrimPrefix(line, "g:")
  2264. if currentGroup == "" {
  2265. return nil, fmt.Errorf("empty group name")
  2266. }
  2267. if result[currentGroup] == nil {
  2268. result[currentGroup] = []string{}
  2269. }
  2270. } else if strings.HasPrefix(line, "b:") {
  2271. // Buddy line: b:buddy or b:buddy:alias:::::note
  2272. if currentGroup == "" {
  2273. return nil, fmt.Errorf("buddy entry without group")
  2274. }
  2275. buddyEntry := strings.TrimPrefix(line, "b:")
  2276. if buddyEntry == "" {
  2277. return nil, fmt.Errorf("empty buddy name")
  2278. }
  2279. result[currentGroup] = append(result[currentGroup], buddyEntry)
  2280. }
  2281. }
  2282. return result, nil
  2283. }