cmd_client.go 57 KB

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