cmd_server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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.TLVRestBlock.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.TLVRestBlock.Bytes(wire.ICBMTLVAutoResponse); isAutoReply {
  213. autoResp = "T"
  214. }
  215. if me.SupportsTOC2MsgEnc() {
  216. uFlags, hasVal := snac.TLVUserInfo.TLVList.Uint16BE(wire.OServiceUserInfoUserFlags)
  217. if !hasVal {
  218. s.Logger.DebugContext(ctx, "missing wire.OServiceUserInfoUserFlags in ICBM message")
  219. return ""
  220. }
  221. ucArray := userClassString(uFlags, snac.IsAway())
  222. // from a packet dump found in this russian zine: https://xn--lcss68aj21b.xn--w8je.xn--tckwe/books/xakep/spec65.pdf
  223. // interesting that "L" is a value, not sure what it's for.
  224. return fmt.Sprintf("IM_IN_ENC2:%s:%s:F:T:%s:F:L:en:%s", snac.ScreenName, autoResp, ucArray, txt)
  225. }
  226. if me.IsTOC2() {
  227. return fmt.Sprintf("IM_IN2:%s:%s:%s:%s", snac.ScreenName, autoResp, "F", txt)
  228. }
  229. return fmt.Sprintf("IM_IN:%s:%s:%s", snac.ScreenName, autoResp, txt)
  230. }
  231. // convertICBMRendezvous converts an ICBM rendezvous SNAC to a TOC response.
  232. // - if chat, return CHAT_INVITE
  233. // - file transfer, return RVOUS_PROPOSE
  234. // - don't respond for other rendezvous types
  235. func (s OSCARProxy) convertICBMRendezvous(ctx context.Context, chatRegistry *ChatRegistry, snac wire.SNAC_0x04_0x07_ICBMChannelMsgToClient) string {
  236. rdinfo, has := snac.TLVRestBlock.Bytes(wire.ICBMTLVData)
  237. if !has {
  238. return s.runtimeErr(ctx, errors.New("TLVRestBlock.Bytes: missing rendezvous block"))[0]
  239. }
  240. frag := wire.ICBMCh2Fragment{}
  241. if err := wire.UnmarshalBE(&frag, bytes.NewReader(rdinfo)); err != nil {
  242. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))[0]
  243. }
  244. if frag.Type != wire.ICBMRdvMessagePropose {
  245. s.Logger.DebugContext(ctx, "can't convert ICBM rendezvous message to TOC response", "rdv_type", frag.Type)
  246. return ""
  247. }
  248. switch uuid.UUID(frag.Capability) {
  249. case wire.CapChat:
  250. prompt, ok := frag.Bytes(wire.ICBMRdvTLVTagsInvitation)
  251. if !ok {
  252. return s.runtimeErr(ctx, errors.New("frag.Bytes: missing chat invite prompt"))[0]
  253. }
  254. svcData, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData)
  255. if !ok || svcData == nil {
  256. return s.runtimeErr(ctx, errors.New("frag.Bytes: missing room info"))[0]
  257. }
  258. roomInfo := wire.ICBMRoomInfo{}
  259. if err := wire.UnmarshalBE(&roomInfo, bytes.NewReader(svcData)); err != nil {
  260. return s.runtimeErr(ctx, fmt.Errorf("wire.UnmarshalBE: %w", err))[0]
  261. }
  262. cookie := strings.Split(roomInfo.Cookie, "-") // make this safe
  263. if len(cookie) < 3 {
  264. return s.runtimeErr(ctx, errors.New("roomInfo.Cookie: malformed cookie, could not get room name"))[0]
  265. }
  266. roomName := cookie[2]
  267. chatID := chatRegistry.Add(roomInfo)
  268. return fmt.Sprintf("CHAT_INVITE:%s:%d:%s:%s", roomName, chatID, snac.ScreenName, prompt)
  269. case wire.CapFileTransfer:
  270. user := snac.TLVUserInfo.ScreenName
  271. capability := strings.ToUpper(wire.CapFileTransfer.String()) // TiK requires upper-case UUID characters
  272. cookie := base64.StdEncoding.EncodeToString(frag.Cookie[:])
  273. seq, _ := frag.Uint16BE(wire.ICBMRdvTLVTagsSeqNum)
  274. rvousIP := "0.0.0.0"
  275. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsRdvIP); ok && len(ip) == 4 {
  276. rvousIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  277. }
  278. proposerIP := "0.0.0.0"
  279. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsRequesterIP); ok && len(ip) == 4 {
  280. proposerIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  281. }
  282. verifiedIP := "0.0.0.0"
  283. if ip, ok := frag.Bytes(wire.ICBMRdvTLVTagsVerifiedIP); ok && len(ip) == 4 {
  284. verifiedIP = net.IPv4(ip[0], ip[1], ip[2], ip[3]).String()
  285. }
  286. rvousPort, _ := frag.Uint16BE(wire.ICBMRdvTLVTagsPort)
  287. var fileMetadata string
  288. if f, ok := frag.Bytes(wire.ICBMRdvTLVTagsSvcData); ok {
  289. // remove sequence of null bytes from the end that causes TiK file open
  290. // dialog to crash
  291. f = bytes.TrimRight(f, "\x00")
  292. fileMetadata = base64.StdEncoding.EncodeToString(f)
  293. }
  294. return fmt.Sprintf("RVOUS_PROPOSE:%s:%s:%s:%d:%s:%s:%s:%d:%d:%s",
  295. user, capability, cookie, seq, rvousIP, proposerIP, verifiedIP, rvousPort, wire.ICBMRdvTLVTagsSvcData, fileMetadata)
  296. default:
  297. s.Logger.DebugContext(ctx, "received rendezvous ICBM for unsupported capability", "capability", wire.CapChat)
  298. return ""
  299. }
  300. }
  301. // UpdateBuddyArrival handles the UPDATE_BUDDY TOC command for buddy arrival events.
  302. //
  303. // From the TiK documentation:
  304. //
  305. // 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.
  306. // - uc[0]
  307. // - ' ' - Ignore
  308. // - 'A' - On AOL
  309. // - uc[1]
  310. // - ' ' - Ignore
  311. // - 'A' - Oscar Admin
  312. // - 'U' - Oscar Unconfirmed
  313. // - 'O' - Oscar Normal
  314. // - uc[2]
  315. // - '\0' - Ignore
  316. // - ' ' - Ignore
  317. // - 'U' - The user has set their unavailable flag.
  318. //
  319. // Command syntax: UPDATE_BUDDY:<Buddy User>:<Online? T/F>:<Evil Amount>:<Signon Time>:<IdleTime>:<UC>
  320. //
  321. // For TOC2 this sends UPDATE_BUDDY2 with the same fields (plus a trailing field). When
  322. // the buddy has capabilities, BUDDY_CAPS2 is also sent (see userInfoToBuddyCaps).
  323. func (s OSCARProxy) UpdateBuddyArrival(snac wire.SNAC_0x03_0x0B_BuddyArrived, me *state.SessionInstance) []string {
  324. msgs := []string{userInfoToUpdateBuddy(snac.TLVUserInfo, me)}
  325. if caps := userInfoToBuddyCaps(snac.TLVUserInfo, me, s.Logger); caps != "" {
  326. msgs = append(msgs, caps)
  327. }
  328. return msgs
  329. }
  330. // UpdateBuddyDeparted handles the UPDATE_BUDDY TOC command for buddy departure events.
  331. //
  332. // From the TiK documentation:
  333. //
  334. // This one command handles arrival/depart/updates. Evil Amount is a
  335. // percentage, Signon Time is UNIX epoc, idle time is in minutes, UC (User
  336. // Class) is a two/three character string.
  337. // - uc[0]
  338. // - ' ' - Ignore
  339. // - 'A' - On AOL
  340. // - uc[1]
  341. // - ' ' - Ignore
  342. // - 'A' - Oscar Admin
  343. // - 'U' - Oscar Unconfirmed
  344. // - 'O' - Oscar Normal
  345. // - uc[2]
  346. // - '\0' - Ignore
  347. // - ' ' - Ignore
  348. // - 'U' - The user has set their unavailable flag.
  349. //
  350. // Command syntax: UPDATE_BUDDY:<Buddy User>:<Online? T/F>:<Evil Amount>:<Signon Time>:<IdleTime>:<UC>
  351. // TOC2 uses UPDATE_BUDDY2 with the same fields.
  352. func (s OSCARProxy) UpdateBuddyDeparted(snac wire.SNAC_0x03_0x0C_BuddyDeparted, me *state.SessionInstance) []string {
  353. if me.IsTOC2() {
  354. return []string{fmt.Sprintf("UPDATE_BUDDY2:%s:F:0:0:0: :", snac.ScreenName)}
  355. }
  356. return []string{fmt.Sprintf("UPDATE_BUDDY:%s:F:0:0:0: ", snac.ScreenName)}
  357. }
  358. // Inserted2 handles the INSERTED2 TOC2 server-to-client notifications.
  359. //
  360. // From the BlueTOC documentation:
  361. //
  362. // Sent whenever the buddy list is modified from a different location (e.g. logged
  363. // in twice). Dynamic updates when items are added to the buddy list.
  364. //
  365. // INSERTED2:g:<group name>
  366. // A new group has been added to the buddy list.
  367. //
  368. // INSERTED2:b:<alias>:<username>:<group>
  369. // A new screenname has been added.
  370. //
  371. // INSERTED2:d:<username>
  372. // Somebody has been added to the deny list.
  373. //
  374. // INSERTED2:p:<username>
  375. // Somebody has been added to the permit list.
  376. //
  377. // Inserted2 is invoked when this session receives FeedbagUpdateItem (e.g. list
  378. // modified from another client). The feedbag is queried when adding buddies to
  379. // resolve GroupID to group name; buddy alias comes from TLV.
  380. func (s OSCARProxy) Inserted2(ctx context.Context, me *state.SessionInstance, snac wire.SNAC_0x13_0x09_FeedbagUpdateItem) []string {
  381. var out []string
  382. groupNameByID := make(map[uint16]string)
  383. hasBuddy := false
  384. for _, item := range snac.Items {
  385. if item.ClassID == wire.FeedbagClassIdBuddy {
  386. hasBuddy = true
  387. break
  388. }
  389. }
  390. if hasBuddy {
  391. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  392. if err != nil {
  393. s.Logger.DebugContext(ctx, "Inserted2: feedbag lookup failed", "err", err)
  394. return nil
  395. }
  396. for _, item := range fb {
  397. if item.ClassID == wire.FeedbagClassIdGroup {
  398. groupNameByID[item.GroupID] = item.Name
  399. }
  400. }
  401. }
  402. for _, item := range snac.Items {
  403. switch item.ClassID {
  404. case wire.FeedbagClassIdGroup:
  405. out = append(out, fmt.Sprintf("INSERTED2:g:%s", item.Name))
  406. case wire.FeedbagClassIdBuddy:
  407. group := groupNameByID[item.GroupID]
  408. if group == "" {
  409. group = "Buddies"
  410. }
  411. alias := ""
  412. if b, ok := item.Bytes(wire.FeedbagAttributesAlias); ok {
  413. alias = string(b)
  414. }
  415. out = append(out, fmt.Sprintf("INSERTED2:b:%s:%s:%s", alias, item.Name, group))
  416. case wire.FeedbagClassIDDeny:
  417. out = append(out, fmt.Sprintf("INSERTED2:d:%s", item.Name))
  418. case wire.FeedbagClassIDPermit:
  419. out = append(out, fmt.Sprintf("INSERTED2:p:%s", item.Name))
  420. }
  421. }
  422. return out
  423. }
  424. // Deleted2 handles the DELETED2 TOC2 server-to-client notifications.
  425. //
  426. // From the BlueTOC documentation:
  427. //
  428. // Sent whenever the buddy list is modified from a different location. Dynamic
  429. // updates when items are removed from the buddy list.
  430. //
  431. // DELETED2:g:<group name>
  432. // A group has been deleted from the buddy list.
  433. //
  434. // DELETED2:b:<username>:<group>
  435. // A user has been deleted from the buddy list.
  436. //
  437. // DELETED2:d:<username>
  438. // A user has been removed from the deny list.
  439. //
  440. // DELETED2:p:<username>
  441. // A user has been removed from the permit list.
  442. //
  443. // Deleted2 is invoked when this session receives FeedbagDeleteItem (e.g. list
  444. // modified from another client). The feedbag is queried when deleting buddies to
  445. // resolve GroupID to group name.
  446. func (s OSCARProxy) Deleted2(ctx context.Context, me *state.SessionInstance, snac wire.SNAC_0x13_0x0A_FeedbagDeleteItem) []string {
  447. var out []string
  448. groupNameByID := make(map[uint16]string)
  449. hasBuddy := false
  450. for _, item := range snac.Items {
  451. if item.ClassID == wire.FeedbagClassIdBuddy {
  452. hasBuddy = true
  453. break
  454. }
  455. }
  456. if hasBuddy {
  457. fb, err := s.FeedbagManager.Feedbag(ctx, me.IdentScreenName())
  458. if err != nil {
  459. s.Logger.DebugContext(ctx, "Deleted2: feedbag lookup failed", "err", err)
  460. return nil
  461. }
  462. for _, item := range fb {
  463. if item.ClassID == wire.FeedbagClassIdGroup {
  464. groupNameByID[item.GroupID] = item.Name
  465. }
  466. }
  467. }
  468. for _, item := range snac.Items {
  469. switch item.ClassID {
  470. case wire.FeedbagClassIdGroup:
  471. out = append(out, fmt.Sprintf("DELETED2:g:%s", item.Name))
  472. case wire.FeedbagClassIdBuddy:
  473. group := groupNameByID[item.GroupID]
  474. if group == "" {
  475. group = "Buddies"
  476. }
  477. out = append(out, fmt.Sprintf("DELETED2:b:%s:%s", item.Name, group))
  478. case wire.FeedbagClassIDDeny:
  479. out = append(out, fmt.Sprintf("DELETED2:d:%s", item.Name))
  480. case wire.FeedbagClassIDPermit:
  481. out = append(out, fmt.Sprintf("DELETED2:p:%s", item.Name))
  482. }
  483. }
  484. return out
  485. }
  486. // ClientEvent handles the CLIENT_EVENT2 TOC2 command.
  487. //
  488. // From BizTOCSock documentation:
  489. //
  490. // I discovered this a while ago, but this is the typing status of a user in IMs, much
  491. // like what AIM does. It is only sent while you're currently being IMed by someone.
  492. // There are only three codes as I know of, but I believe there is one for "User is
  493. // recording..." If it were one, it would probably be code 3.
  494. // 0 = User is doing nothing
  495. // 1 = User has entered text
  496. // 2 = User is currently typing
  497. //
  498. // Command syntax: CLIENT_EVENT2:<Buddy User>:<Typing Status>
  499. func (s OSCARProxy) ClientEvent(snac wire.SNAC_0x04_0x14_ICBMClientEvent) []string {
  500. return []string{fmt.Sprintf("CLIENT_EVENT2:%s:%d", snac.ScreenName, snac.Event)}
  501. }
  502. // userClassString generates the 3-character user class (UC) string based on user flags and away status.
  503. func userClassString(uFlags uint16, isAway bool) string {
  504. uc := [3]string{" ", " ", " "}
  505. if hasFlag(uFlags, wire.OServiceUserFlagAOL) {
  506. uc[0] = "A"
  507. }
  508. if hasFlag(uFlags, wire.OServiceUserFlagAdministrator) {
  509. uc[1] = "A"
  510. } else if hasFlag(uFlags, wire.OServiceUserFlagWireless) {
  511. uc[1] = "C"
  512. } else if hasFlag(uFlags, wire.OServiceUserFlagUnconfirmed) {
  513. uc[1] = "U"
  514. } else if hasFlag(uFlags, wire.OServiceUserFlagOSCARFree) {
  515. uc[1] = "O"
  516. }
  517. if isAway {
  518. uc[2] = "U"
  519. }
  520. return strings.Join(uc[:], "")
  521. }
  522. func sendOrCancel(ctx context.Context, ch chan<- []string, msg []string) {
  523. select {
  524. case <-ctx.Done():
  525. return
  526. case ch <- msg:
  527. return
  528. }
  529. }
  530. // userInfoToUpdateBuddy creates an UPDATE_BUDDY or UPDATE_BUDDY2 server reply from a User
  531. // Info TLV.
  532. func userInfoToUpdateBuddy(snac wire.TLVUserInfo, me *state.SessionInstance) string {
  533. online, _ := snac.Uint32BE(wire.OServiceUserInfoSignonTOD)
  534. idle, _ := snac.Uint16BE(wire.OServiceUserInfoIdleTime)
  535. uFlags, _ := snac.TLVList.Uint16BE(wire.OServiceUserInfoUserFlags)
  536. uc := userClassString(uFlags, snac.IsAway())
  537. warning := fmt.Sprintf("%d", snac.WarningLevel/10)
  538. if me.IsTOC2() {
  539. return fmt.Sprintf("UPDATE_BUDDY2:%s:%s:%s:%d:%d:%s:", snac.ScreenName, "T", warning, online, idle, uc)
  540. }
  541. return fmt.Sprintf("UPDATE_BUDDY:%s:%s:%s:%d:%d:%s", snac.ScreenName, "T", warning, online, idle, uc)
  542. }
  543. // hasFlag checks if a specific flag is set in the bitmask.
  544. func hasFlag[T ~uint16 | ~uint8](bitmask, flag T) bool {
  545. return (bitmask & flag) == flag
  546. }
  547. // userInfoToBuddyCaps creates a BUDDY_CAPS2 server-to-client message from a User Info TLV.
  548. //
  549. // From the BizTOCSock documentation:
  550. //
  551. // These are the buddies capabilities, such as Chat, Live Video, Direct Connect, etc.
  552. // They are sent with every UPDATE_BUDDY2. If a user updates to where they can use
  553. // Direct Connect, you will get sent both packets.
  554. //
  555. // Format: BUDDY_CAPS2:<User>:<Cap1>,<Cap2>,...
  556. func userInfoToBuddyCaps(snac wire.TLVUserInfo, me *state.SessionInstance, logger *slog.Logger) string {
  557. if !me.IsTOC2() {
  558. return ""
  559. }
  560. b, hasCaps := snac.TLVList.Bytes(wire.OServiceUserInfoOscarCaps)
  561. if !hasCaps {
  562. logger.DebugContext(context.Background(), "userInfoToBuddyCaps: no buddy caps found")
  563. return ""
  564. }
  565. if len(b)%16 != 0 {
  566. logger.DebugContext(context.Background(), "userInfoToBuddyCaps: buddy caps length not divisible by 16")
  567. return ""
  568. }
  569. var capStrings []string
  570. for i := 0; i < len(b); i += 16 {
  571. var c [16]byte
  572. copy(c[:], b[i:i+16])
  573. uid := uuid.UUID(c)
  574. capStrings = append(capStrings, uid.String())
  575. }
  576. clientCaps := strings.Join(capStrings, ",")
  577. return fmt.Sprintf("BUDDY_CAPS2:%s:%s", snac.ScreenName, clientCaps)
  578. }