cmd_server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. package toc
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "net"
  10. "strings"
  11. "github.com/google/uuid"
  12. "github.com/mk6i/open-oscar-server/state"
  13. "github.com/mk6i/open-oscar-server/wire"
  14. )
  15. var (
  16. // cmdInternalSvcErr indicates a general failure. Use wire.TOCErrorAdminProcessingRequest
  17. // error code as this is the closest applicable code as per TiK, Tameclone, phptoclib.
  18. cmdInternalSvcErr = "ERROR:" + wire.TOCErrorAdminProcessingRequest + ":internal server error"
  19. rateLimitExceededErr = "ERROR:" + wire.TOCErrorGeneralRateLimitHit
  20. errDisconnect = errors.New("got booted by another session")
  21. )
  22. // RecvBOS routes incoming SNAC messages from the BOS server to their
  23. // corresponding TOC handlers. It ignores any SNAC messages for which there is
  24. // no TOC response.
  25. func (s OSCARProxy) RecvBOS(ctx context.Context, me *state.SessionInstance, chatRegistry *ChatRegistry, ch chan<- []string) error {
  26. for {
  27. select {
  28. case <-ctx.Done():
  29. me.CloseInstance()
  30. return nil
  31. case <-me.Closed():
  32. return errDisconnect
  33. case snac := <-me.ReceiveMessage():
  34. switch v := snac.Body.(type) {
  35. case wire.SNAC_0x03_0x0B_BuddyArrived:
  36. sendOrCancel(ctx, ch, s.UpdateBuddyArrival(v, me))
  37. case wire.SNAC_0x03_0x0C_BuddyDeparted:
  38. sendOrCancel(ctx, ch, s.UpdateBuddyDeparted(v, me))
  39. case wire.SNAC_0x04_0x07_ICBMChannelMsgToClient:
  40. sendOrCancel(ctx, ch, s.IMIn(ctx, chatRegistry, me, v))
  41. case wire.SNAC_0x01_0x10_OServiceEvilNotification:
  42. sendOrCancel(ctx, ch, s.Eviled(v))
  43. case wire.SNAC_0x04_0x14_ICBMClientEvent:
  44. if me.IsTOC2() {
  45. sendOrCancel(ctx, ch, s.ClientEvent(v))
  46. }
  47. case wire.SNAC_0x13_0x09_FeedbagUpdateItem:
  48. if me.IsTOC2() {
  49. sendOrCancel(ctx, ch, s.Inserted2(ctx, me, v))
  50. }
  51. case wire.SNAC_0x13_0x0A_FeedbagDeleteItem:
  52. if me.IsTOC2() {
  53. sendOrCancel(ctx, ch, s.Deleted2(ctx, me, v))
  54. }
  55. default:
  56. s.Logger.DebugContext(ctx, fmt.Sprintf("unsupported snac. foodgroup: %s subgroup: %s",
  57. wire.FoodGroupName(snac.Frame.FoodGroup),
  58. wire.SubGroupName(snac.Frame.FoodGroup, snac.Frame.SubGroup)))
  59. }
  60. }
  61. }
  62. }
  63. // RecvChat routes incoming SNAC messages from the chat server to their
  64. // corresponding TOC handlers. It ignores any SNAC messages for which there is
  65. // no TOC response.
  66. func (s OSCARProxy) RecvChat(ctx context.Context, me *state.SessionInstance, chatID int, ch chan<- []string) {
  67. for {
  68. select {
  69. case <-ctx.Done():
  70. return
  71. case <-me.Closed():
  72. return
  73. case snac := <-me.ReceiveMessage():
  74. switch v := snac.Body.(type) {
  75. case wire.SNAC_0x0E_0x04_ChatUsersLeft:
  76. sendOrCancel(ctx, ch, s.ChatUpdateBuddyLeft(v, chatID))
  77. case wire.SNAC_0x0E_0x03_ChatUsersJoined:
  78. sendOrCancel(ctx, ch, s.ChatUpdateBuddyArrived(v, chatID))
  79. case wire.SNAC_0x0E_0x06_ChatChannelMsgToClient:
  80. sendOrCancel(ctx, ch, s.ChatIn(ctx, me, v, chatID))
  81. default:
  82. s.Logger.DebugContext(ctx, fmt.Sprintf("unsupported snac. foodgroup: %s subgroup: %s",
  83. wire.FoodGroupName(snac.Frame.FoodGroup),
  84. wire.SubGroupName(snac.Frame.FoodGroup, snac.Frame.SubGroup)))
  85. }
  86. }
  87. }
  88. }
  89. // ChatIn handles the CHAT_IN and ENC_CHAT_IN TOC commands.
  90. //
  91. // From the TiK documentation:
  92. //
  93. // A chat message was sent in a chat room.
  94. //
  95. // From the BlueTOC documentation:
  96. //
  97. // This command received instead of CHAT_IN. It is similar to TOC 1.0 except there are a two new parameters.
  98. // One of them is language; the other is unknown but is usually "A"
  99. //
  100. // Command syntax: CHAT_IN:<Chat Room Id>:<Source User>:<Whisper? T/F>:<Message>
  101. // Command syntax: CHAT_IN_ENC:<chatroom id>:<user>:<whisper T/F>:<???>:en:<message>
  102. func (s OSCARProxy) ChatIn(ctx context.Context, me *state.SessionInstance, snac wire.SNAC_0x0E_0x06_ChatChannelMsgToClient, chatID int) []string {
  103. b, ok := snac.Bytes(wire.ChatTLVSenderInformation)
  104. if !ok {
  105. return s.runtimeErr(ctx, errors.New("snac.Bytes: missing wire.ChatTLVSenderInformation"))
  106. }
  107. u := wire.TLVUserInfo{}
  108. err := wire.UnmarshalBE(&u, bytes.NewReader(b))
  109. if err != nil {
  110. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))
  111. }
  112. b, ok = snac.Bytes(wire.ChatTLVMessageInfo)
  113. if !ok {
  114. return s.runtimeErr(ctx, errors.New("snac.Bytes: missing wire.ChatTLVMessageInfo"))
  115. }
  116. text, err := wire.UnmarshalChatMessageText(b)
  117. if err != nil {
  118. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalChatMessageText: %w", err))
  119. }
  120. if me.SupportsTOC2MsgEnc() {
  121. return []string{fmt.Sprintf("CHAT_IN_ENC:%d:%s:F:A:en:%s", chatID, u.ScreenName, text)}
  122. }
  123. return []string{fmt.Sprintf("CHAT_IN:%d:%s:F:%s", chatID, u.ScreenName, text)}
  124. }
  125. // ChatUpdateBuddyArrived handles the CHAT_UPDATE_BUDDY TOC command for chat
  126. // room arrival events.
  127. //
  128. // From the TiK documentation:
  129. //
  130. // This one command handles arrival/departs from a chat room. The very first
  131. // message of this type for each chat room contains the users already in the
  132. // room.
  133. //
  134. // Command syntax: CHAT_UPDATE_BUDDY:<Chat Room Id>:<Inside? T/F>:<User 1>:<User 2>...
  135. func (s OSCARProxy) ChatUpdateBuddyArrived(snac wire.SNAC_0x0E_0x03_ChatUsersJoined, chatID int) []string {
  136. users := make([]string, 0, len(snac.Users))
  137. for _, u := range snac.Users {
  138. users = append(users, u.ScreenName)
  139. }
  140. return []string{fmt.Sprintf("CHAT_UPDATE_BUDDY:%d:T:%s", chatID, strings.Join(users, ":"))}
  141. }
  142. // ChatUpdateBuddyLeft handles the CHAT_UPDATE_BUDDY TOC command for chat
  143. // room departure events.
  144. //
  145. // From the TiK documentation:
  146. //
  147. // This one command handles arrival/departs from a chat room. The very first
  148. // message of this type for each chat room contains the users already in the
  149. // room.
  150. //
  151. // Command syntax: CHAT_UPDATE_BUDDY:<Chat Room Id>:<Inside? T/F>:<User 1>:<User 2>...
  152. func (s OSCARProxy) ChatUpdateBuddyLeft(snac wire.SNAC_0x0E_0x04_ChatUsersLeft, chatID int) []string {
  153. users := make([]string, 0, len(snac.Users))
  154. for _, u := range snac.Users {
  155. users = append(users, u.ScreenName)
  156. }
  157. return []string{fmt.Sprintf("CHAT_UPDATE_BUDDY:%d:F:%s", chatID, strings.Join(users, ":"))}
  158. }
  159. // Eviled handles the EVILED TOC command.
  160. //
  161. // From the TiK documentation:
  162. //
  163. // The user was just eviled.
  164. //
  165. // Command syntax: EVILED:<new evil>:<name of eviler, blank if anonymous>
  166. func (s OSCARProxy) Eviled(snac wire.SNAC_0x01_0x10_OServiceEvilNotification) []string {
  167. warning := fmt.Sprintf("%d", snac.NewEvil/10)
  168. who := ""
  169. if snac.Snitcher != nil {
  170. who = snac.Snitcher.ScreenName
  171. }
  172. return []string{fmt.Sprintf("EVILED:%s:%s", warning, who)}
  173. }
  174. // IMIn handles incoming ICBM channel messages and returns one of: IM_IN (TOC1), IM_IN2 or
  175. // IM_IN_ENC2 (TOC2), or for rendezvous channel CHAT_INVITE or RVOUS_PROPOSE.
  176. //
  177. // From the TiK documentation (TOC1 IM_IN):
  178. //
  179. // Receive an IM from someone. Everything after the third colon is the
  180. // incoming message, including other colons.
  181. //
  182. // TOC2 clients receive IM_IN2 (same structure as IM_IN with an extra field) or
  183. // IM_IN_ENC2 when the client supports encoded messages (BlueTOC/BizTOCSock documentation).
  184. // For ICBM rendezvous (chat invite, file transfer), this returns CHAT_INVITE or RVOUS_PROPOSE
  185. // instead (see convertICBMRendezvous).
  186. //
  187. // Command syntax: IM_IN:<Source User>:<Auto Response T/F?>:<Message>
  188. // Command syntax: IM_IN2:<Source User>:<Auto Response T/F?>:<Whisper?>:<Message>
  189. // Command syntax: IM_IN_ENC2:<User>:<Auto>:<???>:<???>:<User Class>:<???>:<???>:<Language>:<Message>
  190. func (s OSCARProxy) IMIn(ctx context.Context, chatRegistry *ChatRegistry, me *state.SessionInstance, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) []string {
  191. switch snac.ChannelID {
  192. case wire.ICBMChannelIM:
  193. return []string{s.convertICBMInstantMsg(ctx, me, snac)}
  194. case wire.ICBMChannelRendezvous:
  195. return []string{s.convertICBMRendezvous(ctx, chatRegistry, snac)}
  196. default:
  197. s.Logger.DebugContext(ctx, "received unsupported ICBM channel message", "channel_id", snac.ChannelID)
  198. return []string{}
  199. }
  200. }
  201. // convertICBMInstantMsg converts an ICBM instant message SNAC to a TOC IM_IN or TOC2 IM_IN2, or TOC2Enhanced IM_IN_ENC2 response.
  202. func (s OSCARProxy) convertICBMInstantMsg(ctx context.Context, me *state.SessionInstance, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) string {
  203. buf, ok := snac.Bytes(wire.ICBMTLVAOLIMData)
  204. if !ok {
  205. return s.runtimeErr(ctx, errors.New("TLVRestBlock.Bytes: missing wire.ICBMTLVAOLIMData"))[0]
  206. }
  207. txt, err := wire.UnmarshalICBMMessageText(buf)
  208. if err != nil {
  209. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalICBMMessageText: %w", err))[0]
  210. }
  211. autoResp := "F"
  212. if _, isAutoReply := snac.Bytes(wire.ICBMTLVAutoResponse); isAutoReply {
  213. autoResp = "T"
  214. }
  215. if me.SupportsTOC2MsgEnc() {
  216. uFlags, _ := snac.TLVUserInfo.Uint16BE(wire.OServiceUserInfoUserFlags)
  217. classStr := userClassString(uFlags, snac.IsAway())
  218. // from a packet dump found in this russian zine: https://xn--lcss68aj21b.xn--w8je.xn--tckwe/books/xakep/spec65.pdf
  219. // interesting that "L" is a value, not sure what it's for.
  220. return fmt.Sprintf("IM_IN_ENC2:%s:%s:F:T:%s:F:L:en:%s", snac.ScreenName, autoResp, classStr, txt)
  221. }
  222. if me.IsTOC2() {
  223. return fmt.Sprintf("IM_IN2:%s:%s:%s:%s", snac.ScreenName, autoResp, "F", txt)
  224. }
  225. return fmt.Sprintf("IM_IN:%s:%s:%s", snac.ScreenName, autoResp, txt)
  226. }
  227. // convertICBMRendezvous converts an ICBM rendezvous SNAC to a TOC response.
  228. // - if chat, return CHAT_INVITE
  229. // - file transfer, return RVOUS_PROPOSE
  230. // - don't respond for other rendezvous types
  231. func (s OSCARProxy) convertICBMRendezvous(ctx context.Context, chatRegistry *ChatRegistry, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) string {
  232. rdinfo, has := snac.Bytes(wire.ICBMTLVData)
  233. if !has {
  234. return s.runtimeErr(ctx, errors.New("TLVRestBlock.Bytes: missing rendezvous block"))[0]
  235. }
  236. frag := wire.ICBMCh2Fragment{}
  237. if err := wire.UnmarshalBE(&frag, bytes.NewReader(rdinfo)); err != nil {
  238. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))[0]
  239. }
  240. if frag.Type != wire.ICBMRdvMessagePropose {
  241. s.Logger.DebugContext(ctx, "can't convert ICBM rendezvous message to TOC response", "rdv_type", frag.Type)
  242. return ""
  243. }
  244. switch uuid.UUID(frag.Capability) {
  245. case wire.CapChat:
  246. prompt, ok := frag.Bytes(wire.ICBMRdvTLVTagsInvitation)
  247. if !ok {
  248. return s.runtimeErr(ctx, errors.New("frag.Bytes: missing chat invite prompt"))[0]
  249. }
  250. svcData, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData)
  251. if !ok || svcData == nil {
  252. return s.runtimeErr(ctx, errors.New("frag.Bytes: missing room info"))[0]
  253. }
  254. roomInfo := wire.ICBMRoomInfo{}
  255. if err := wire.UnmarshalBE(&roomInfo, bytes.NewReader(svcData)); err != nil {
  256. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))[0]
  257. }
  258. cookie := strings.Split(roomInfo.Cookie, "-") // make this safe
  259. if len(cookie) < 3 {
  260. return s.runtimeErr(ctx, errors.New("roomInfo.Cookie: malformed cookie, could not get room name"))[0]
  261. }
  262. roomName := cookie[2]
  263. chatID := chatRegistry.Add(roomInfo)
  264. return fmt.Sprintf("CHAT_INVITE:%s:%d:%s:%s", roomName, chatID, snac.ScreenName, prompt)
  265. case wire.CapFileTransfer:
  266. user := snac.ScreenName
  267. capability := strings.ToUpper(wire.CapFileTransfer.String()) // TiK requires upper-case UUID characters
  268. cookie := base64.StdEncoding.EncodeToString(frag.Cookie[:])
  269. seq, _ := frag.Uint16BE(wire.ICBMRdvTLVTagsSeqNum)
  270. rvousIP := "0.0.0.0"
  271. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsRdvIP); ok && len(ip) == 4 {
  272. rvousIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  273. }
  274. proposerIP := "0.0.0.0"
  275. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsRequesterIP); ok && len(ip) == 4 {
  276. proposerIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  277. }
  278. verifiedIP := "0.0.0.0"
  279. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsVerifiedIP); ok && len(ip) == 4 {
  280. verifiedIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  281. }
  282. rvousPort, _ := frag.Uint16BE(wire.ICBMRdvTLVTagsPort)
  283. var fileMetadata string
  284. if f, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData); ok {
  285. // remove sequence of null bytes from the end that causes TiK file open
  286. // dialog to crash
  287. f = bytes.TrimRight(f, "\x00")
  288. fileMetadata = base64.StdEncoding.EncodeToString(f)
  289. }
  290. return fmt.Sprintf("RVOUS_PROPOSE:%s:%s:%s:%d:%s:%s:%s:%d:%d:%s",
  291. user, capability, cookie, seq, rvousIP, proposerIP, verifiedIP, rvousPort, wire.ICBMRdvTLVTagsSvcData, fileMetadata)
  292. default:
  293. s.Logger.DebugContext(ctx, "received rendezvous ICBM for unsupported capability", "capability", wire.CapChat)
  294. return ""
  295. }
  296. }
  297. // UpdateBuddyArrival handles the UPDATE_BUDDY TOC command for buddy arrival events.
  298. //
  299. // From the TiK documentation:
  300. //
  301. // This one command handles arrival/depart/updates. Evil Amount is a percentage, Signon Time is UNIX epoc, idle time is in minutes, UC (User Class) is a two/three character string.
  302. // - uc[0]
  303. // - ' ' - Ignore
  304. // - 'A' - On AOL
  305. // - uc[1]
  306. // - ' ' - Ignore
  307. // - 'A' - Oscar Admin
  308. // - 'U' - Oscar Unconfirmed
  309. // - 'O' - Oscar Normal
  310. // - uc[2]
  311. // - '\0' - Ignore
  312. // - ' ' - Ignore
  313. // - 'U' - The user has set their unavailable flag.
  314. //
  315. // Command syntax: UPDATE_BUDDY:<Buddy User>:<Online? T/F>:<Evil Amount>:<Signon Time>:<IdleTime>:<UC>
  316. //
  317. // For TOC2 this sends UPDATE_BUDDY2 with the same fields (plus a trailing field). When
  318. // the buddy has capabilities, BUDDY_CAPS2 is also sent (see userInfoToBuddyCaps).
  319. func (s OSCARProxy) UpdateBuddyArrival(snac wire.SNAC_0x03_0x0B_BuddyArrived, me *state.SessionInstance) []string {
  320. msgs := []string{userInfoToUpdateBuddy(snac.TLVUserInfo, me)}
  321. if caps := userInfoToBuddyCaps(snac.TLVUserInfo, me, s.Logger); caps != "" {
  322. msgs = append(msgs, caps)
  323. }
  324. return msgs
  325. }
  326. // UpdateBuddyDeparted handles the UPDATE_BUDDY TOC command for buddy departure events.
  327. //
  328. // From the TiK documentation:
  329. //
  330. // This one command handles arrival/depart/updates. Evil Amount is a
  331. // percentage, Signon Time is UNIX epoc, idle time is in minutes, UC (User
  332. // Class) is a two/three character string.
  333. // - uc[0]
  334. // - ' ' - Ignore
  335. // - 'A' - On AOL
  336. // - uc[1]
  337. // - ' ' - Ignore
  338. // - 'A' - Oscar Admin
  339. // - 'U' - Oscar Unconfirmed
  340. // - 'O' - Oscar Normal
  341. // - uc[2]
  342. // - '\0' - Ignore
  343. // - ' ' - Ignore
  344. // - 'U' - The user has set their unavailable flag.
  345. //
  346. // Command syntax: UPDATE_BUDDY:<Buddy User>:<Online? T/F>:<Evil Amount>:<Signon Time>:<IdleTime>:<UC>
  347. // TOC2 uses UPDATE_BUDDY2 with the same fields.
  348. func (s OSCARProxy) UpdateBuddyDeparted(snac wire.SNAC_0x03_0x0C_BuddyDeparted, me *state.SessionInstance) []string {
  349. if me.IsTOC2() {
  350. return []string{fmt.Sprintf("UPDATE_BUDDY2:%s:F:0:0:0: :", snac.ScreenName)}
  351. }
  352. return []string{fmt.Sprintf("UPDATE_BUDDY:%s:F:0:0:0: ", snac.ScreenName)}
  353. }
  354. // Inserted2 handles the INSERTED2 TOC2 server-to-client notifications.
  355. //
  356. // From the BlueTOC documentation:
  357. //
  358. // Sent whenever the buddy list is modified from a different location (e.g. logged
  359. // in twice). Dynamic updates when items are added to the buddy list.
  360. //
  361. // INSERTED2:g:<group name>
  362. // A new group has been added to the buddy list.
  363. //
  364. // INSERTED2:b:<alias>:<username>:<group>
  365. // A new screenname has been added.
  366. //
  367. // INSERTED2:d:<username>
  368. // Somebody has been added to the deny list.
  369. //
  370. // INSERTED2:p:<username>
  371. // Somebody has been added to the permit list.
  372. //
  373. // Inserted2 is invoked when this session receives FeedbagUpdateItem (e.g. list
  374. // modified from another client). The feedbag is queried when adding buddies to
  375. // resolve GroupID to group name; buddy alias comes from TLV.
  376. func (s OSCARProxy) Inserted2(ctx context.Context, me *state.SessionInstance, snac wire.SNAC_0x13_0x09_FeedbagUpdateItem) []string {
  377. var out []string
  378. groupNameByID := make(map[uint16]string)
  379. hasBuddy := false
  380. for _, item := range snac.Items {
  381. if item.ClassID == wire.FeedbagClassIdBuddy {
  382. hasBuddy = true
  383. break
  384. }
  385. }
  386. if hasBuddy {
  387. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  388. if err != nil {
  389. s.Logger.DebugContext(ctx, "Inserted2: feedbag lookup failed", "err", err)
  390. return nil
  391. }
  392. for _, item := range fb {
  393. if item.ClassID == wire.FeedbagClassIdGroup {
  394. groupNameByID[item.GroupID] = item.Name
  395. }
  396. }
  397. }
  398. for _, item := range snac.Items {
  399. switch item.ClassID {
  400. case wire.FeedbagClassIdGroup:
  401. out = append(out, fmt.Sprintf("INSERTED2:g:%s", item.Name))
  402. case wire.FeedbagClassIdBuddy:
  403. group := groupNameByID[item.GroupID]
  404. if group == "" {
  405. group = "Buddies"
  406. }
  407. alias := ""
  408. if b, ok := item.Bytes(wire.FeedbagAttributesAlias); ok {
  409. alias = string(b)
  410. }
  411. out = append(out, fmt.Sprintf("INSERTED2:b:%s:%s:%s", alias, item.Name, group))
  412. case wire.FeedbagClassIDDeny:
  413. out = append(out, fmt.Sprintf("INSERTED2:d:%s", item.Name))
  414. case wire.FeedbagClassIDPermit:
  415. out = append(out, fmt.Sprintf("INSERTED2:p:%s", item.Name))
  416. }
  417. }
  418. return out
  419. }
  420. // Deleted2 handles the DELETED2 TOC2 server-to-client notifications.
  421. //
  422. // From the BlueTOC documentation:
  423. //
  424. // Sent whenever the buddy list is modified from a different location. Dynamic
  425. // updates when items are removed from the buddy list.
  426. //
  427. // DELETED2:g:<group name>
  428. // A group has been deleted from the buddy list.
  429. //
  430. // DELETED2:b:<username>:<group>
  431. // A user has been deleted from the buddy list.
  432. //
  433. // DELETED2:d:<username>
  434. // A user has been removed from the deny list.
  435. //
  436. // DELETED2:p:<username>
  437. // A user has been removed from the permit list.
  438. //
  439. // Deleted2 is invoked when this session receives FeedbagDeleteItem (e.g. list
  440. // modified from another client). The feedbag is queried when deleting buddies to
  441. // resolve GroupID to group name.
  442. func (s OSCARProxy) Deleted2(ctx context.Context, me *state.SessionInstance, snac wire.SNAC_0x13_0x0A_FeedbagDeleteItem) []string {
  443. var out []string
  444. groupNameByID := make(map[uint16]string)
  445. hasBuddy := false
  446. for _, item := range snac.Items {
  447. if item.ClassID == wire.FeedbagClassIdBuddy {
  448. hasBuddy = true
  449. break
  450. }
  451. }
  452. if hasBuddy {
  453. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  454. if err != nil {
  455. s.Logger.DebugContext(ctx, "Deleted2: feedbag lookup failed", "err", err)
  456. return nil
  457. }
  458. for _, item := range fb {
  459. if item.ClassID == wire.FeedbagClassIdGroup {
  460. groupNameByID[item.GroupID] = item.Name
  461. }
  462. }
  463. }
  464. for _, item := range snac.Items {
  465. switch item.ClassID {
  466. case wire.FeedbagClassIdGroup:
  467. out = append(out, fmt.Sprintf("DELETED2:g:%s", item.Name))
  468. case wire.FeedbagClassIdBuddy:
  469. group := groupNameByID[item.GroupID]
  470. if group == "" {
  471. group = "Buddies"
  472. }
  473. out = append(out, fmt.Sprintf("DELETED2:b:%s:%s", item.Name, group))
  474. case wire.FeedbagClassIDDeny:
  475. out = append(out, fmt.Sprintf("DELETED2:d:%s", item.Name))
  476. case wire.FeedbagClassIDPermit:
  477. out = append(out, fmt.Sprintf("DELETED2:p:%s", item.Name))
  478. }
  479. }
  480. return out
  481. }
  482. // ClientEvent handles the CLIENT_EVENT2 TOC2 command.
  483. //
  484. // From BizTOCSock documentation:
  485. //
  486. // I discovered this a while ago, but this is the typing status of a user in IMs, much
  487. // like what AIM does. It is only sent while you're currently being IMed by someone.
  488. // There are only three codes as I know of, but I believe there is one for "User is
  489. // recording..." If it were one, it would probably be code 3.
  490. // 0 = User is doing nothing
  491. // 1 = User has entered text
  492. // 2 = User is currently typing
  493. //
  494. // Command syntax: CLIENT_EVENT2:<Buddy User>:<Typing Status>
  495. func (s OSCARProxy) ClientEvent(snac wire.SNAC_0x04_0x14_ICBMClientEvent) []string {
  496. return []string{fmt.Sprintf("CLIENT_EVENT2:%s:%d", snac.ScreenName, snac.Event)}
  497. }
  498. // userClassString generates the 3-character user class (UC) string based on user flags and away status.
  499. func userClassString(uFlags uint16, isAway bool) string {
  500. uc := [3]string{" ", " ", " "}
  501. if hasFlag(uFlags, wire.OServiceUserFlagAOL) {
  502. uc[0] = "A"
  503. }
  504. if hasFlag(uFlags, wire.OServiceUserFlagAdministrator) {
  505. uc[1] = "A"
  506. } else if hasFlag(uFlags, wire.OServiceUserFlagWireless) {
  507. uc[1] = "C"
  508. } else if hasFlag(uFlags, wire.OServiceUserFlagUnconfirmed) {
  509. uc[1] = "U"
  510. } else if hasFlag(uFlags, wire.OServiceUserFlagOSCARFree) {
  511. uc[1] = "O"
  512. }
  513. if isAway {
  514. uc[2] = "U"
  515. }
  516. return strings.Join(uc[:], "")
  517. }
  518. func sendOrCancel(ctx context.Context, ch chan<- []string, msg []string) {
  519. select {
  520. case <-ctx.Done():
  521. return
  522. case ch <- msg:
  523. return
  524. }
  525. }
  526. // userInfoToUpdateBuddy creates an UPDATE_BUDDY or UPDATE_BUDDY2 server reply from a User
  527. // Info TLV.
  528. func userInfoToUpdateBuddy(snac wire.TLVUserInfo, me *state.SessionInstance) string {
  529. online, _ := snac.Uint32BE(wire.OServiceUserInfoSignonTOD)
  530. idle, _ := snac.Uint16BE(wire.OServiceUserInfoIdleTime)
  531. uFlags, _ := snac.Uint16BE(wire.OServiceUserInfoUserFlags)
  532. uc := userClassString(uFlags, snac.IsAway())
  533. warning := fmt.Sprintf("%d", snac.WarningLevel/10)
  534. if me.IsTOC2() {
  535. return fmt.Sprintf("UPDATE_BUDDY2:%s:%s:%s:%d:%d:%s:", snac.ScreenName, "T", warning, online, idle, uc)
  536. }
  537. return fmt.Sprintf("UPDATE_BUDDY:%s:%s:%s:%d:%d:%s", snac.ScreenName, "T", warning, online, idle, uc)
  538. }
  539. // hasFlag checks if a specific flag is set in the bitmask.
  540. func hasFlag[T ~uint16 | ~uint8](bitmask, flag T) bool {
  541. return (bitmask & flag) == flag
  542. }
  543. // userInfoToBuddyCaps creates a BUDDY_CAPS2 server-to-client message from a User Info TLV.
  544. //
  545. // From the BizTOCSock documentation:
  546. //
  547. // These are the buddies capabilities, such as Chat, Live Video, Direct Connect, etc.
  548. // They are sent with every UPDATE_BUDDY2. If a user updates to where they can use
  549. // Direct Connect, you will get sent both packets.
  550. //
  551. // Format: BUDDY_CAPS2:<User>:<Cap1>,<Cap2>,...
  552. func userInfoToBuddyCaps(snac wire.TLVUserInfo, me *state.SessionInstance, logger *slog.Logger) string {
  553. if !me.IsTOC2() {
  554. return ""
  555. }
  556. b, hasCaps := snac.Bytes(wire.OServiceUserInfoOscarCaps)
  557. if !hasCaps {
  558. logger.DebugContext(context.Background(), "userInfoToBuddyCaps: no buddy caps found")
  559. return ""
  560. }
  561. if len(b)%16 != 0 {
  562. logger.DebugContext(context.Background(), "userInfoToBuddyCaps: buddy caps length not divisible by 16")
  563. return ""
  564. }
  565. var capStrings []string
  566. for i := 0; i < len(b); i += 16 {
  567. var c [16]byte
  568. copy(c[:], b[i:i+16])
  569. uid := uuid.UUID(c)
  570. capStrings = append(capStrings, uid.String())
  571. }
  572. clientCaps := strings.Join(capStrings, ",")
  573. return fmt.Sprintf("BUDDY_CAPS2:%s:%s", snac.ScreenName, clientCaps)
  574. }