1use anyhow::{ensure, Result};
2use serde::{Deserialize, Serialize};
3
4use crate::GameDialect;
5
6const TITANIUM_CHANNEL_MESSAGE_HEADER: usize = 148;
7const MAC_CHANNEL_MESSAGE_HEADER: usize = 136;
8const MAX_OUTBOUND_MESSAGE: usize = 4095;
9const MAX_MAC_OUTBOUND_MESSAGE: usize = 2043;
10const STML_ENTITIES: &[(&[u8], char)] = &[
11 (b"&", '&'),
12 (b"&PCT;", '%'),
13 (b"<", '<'),
14 (b">", '>'),
15 (b""", '"'),
16 (b"&NBSP;", ' '),
17];
18
19#[must_use]
23pub fn server_filters() -> [u8; 116] {
24 let mut filters = [0; 116];
25 for index in (1..=7).chain(14..=17) {
26 filters[index * 4] = 1;
27 }
28 filters
29}
30
31#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
33#[serde(rename_all = "snake_case")]
34#[non_exhaustive]
35pub enum ChannelName {
36 #[serde(alias = "gu", alias = "/gu")]
38 Guild,
39 Group,
41 Shout,
43 #[serde(alias = "auc", alias = "/auc")]
45 Auction,
46 #[serde(alias = "/ooc")]
48 Ooc,
49 Broadcast,
51 Tell,
53 Say,
55 GmSay,
57 Raid,
59 Emote,
61 Motd,
63 System,
65 GuildMotd,
67 Unknown,
69}
70
71#[derive(Clone, Debug, Eq, PartialEq)]
74#[non_exhaustive]
75pub enum OutboundChat {
76 Guild(String),
78 Group(String),
80 Shout(String),
82 Auction(String),
84 Ooc(String),
86 Tell {
88 recipient: String,
90 message: String,
92 },
93 Say(String),
95 Raid(String),
97}
98
99impl OutboundChat {
100 const fn channel(&self) -> u16 {
101 match self {
102 Self::Guild(_) => 0,
103 Self::Group(_) => 2,
104 Self::Shout(_) => 3,
105 Self::Auction(_) => 4,
106 Self::Ooc(_) => 5,
107 Self::Tell { .. } => 7,
108 Self::Say(_) => 8,
109 Self::Raid(_) => 15,
110 }
111 }
112
113 fn message(&self) -> &str {
114 match self {
115 Self::Guild(message)
116 | Self::Group(message)
117 | Self::Shout(message)
118 | Self::Auction(message)
119 | Self::Ooc(message)
120 | Self::Say(message)
121 | Self::Raid(message)
122 | Self::Tell { message, .. } => message,
123 }
124 }
125
126 fn recipient(&self) -> Option<&str> {
127 match self {
128 Self::Tell { recipient, .. } => Some(recipient),
129 _ => None,
130 }
131 }
132}
133
134fn encode_chat_text(text: &str) -> String {
137 let mut encoded = String::with_capacity(text.len());
138 for character in text.chars() {
139 if character == '%' {
140 encoded.push_str("&PCT;");
141 } else {
142 encoded.push(character);
143 }
144 }
145 encoded
146}
147
148#[must_use]
153pub fn outbound_text_len(dialect: GameDialect, text: &str) -> usize {
154 match dialect {
155 GameDialect::TitaniumP99 => encode_chat_text(text).len(),
156 GameDialect::EqMac => text.len(),
157 }
158}
159
160#[must_use]
162pub const fn outbound_text_limit(dialect: GameDialect) -> usize {
163 match dialect {
164 GameDialect::TitaniumP99 => MAX_OUTBOUND_MESSAGE,
165 GameDialect::EqMac => MAX_MAC_OUTBOUND_MESSAGE,
168 }
169}
170
171pub fn encode_outbound_for(
178 protocol: GameDialect,
179 message: &OutboundChat,
180 sender: &str,
181) -> Result<Vec<u8>> {
182 let message_text = message.message();
183 ensure!(!message_text.is_empty(), "chat message must not be empty");
184 ensure!(
185 !message_text.contains('\0'),
186 "chat message must not contain NUL"
187 );
188 let wire_text = match protocol {
189 GameDialect::TitaniumP99 => encode_chat_text(message_text),
190 GameDialect::EqMac => message_text.to_owned(),
191 };
192 ensure!(
193 wire_text.len() <= outbound_text_limit(protocol),
194 "chat message exceeds server field size"
195 );
196 ensure!(
197 !sender.is_empty() && sender.len() < 64 && !sender.contains('\0'),
198 "sender exceeds protocol field size"
199 );
200
201 let header = match protocol {
202 GameDialect::TitaniumP99 => TITANIUM_CHANNEL_MESSAGE_HEADER,
203 GameDialect::EqMac => MAC_CHANNEL_MESSAGE_HEADER,
204 };
205 let trailer = usize::from(protocol == GameDialect::EqMac) * 4;
207 let mut body = vec![0; header + wire_text.len() + 1 + trailer];
208 if let Some(recipient) = message.recipient() {
209 ensure!(
210 !recipient.is_empty() && recipient.len() < 64 && !recipient.contains('\0'),
211 "tell recipient exceeds protocol field size"
212 );
213 body[..recipient.len()].copy_from_slice(recipient.as_bytes());
214 }
215 body[64..64 + sender.len()].copy_from_slice(sender.as_bytes());
216 match protocol {
218 GameDialect::TitaniumP99 => {
219 body[132..136].copy_from_slice(&u32::from(message.channel()).to_le_bytes());
220 body[144..148].copy_from_slice(&100u32.to_le_bytes());
221 }
222 GameDialect::EqMac => {
223 body[130..132].copy_from_slice(&message.channel().to_le_bytes());
224 body[134..136].copy_from_slice(&100u16.to_le_bytes());
225 }
226 }
227 body[header..header + wire_text.len()].copy_from_slice(wire_text.as_bytes());
228 Ok(body)
229}
230
231pub fn encode_outbound(message: &OutboundChat, sender: &str) -> Result<Vec<u8>> {
238 encode_outbound_for(GameDialect::TitaniumP99, message, sender)
239}
240
241#[derive(Clone, Copy, Debug, Eq, PartialEq)]
242enum CommunicationOpcode {
243 Motd,
244 ChannelMessage,
245 Emote,
246 SpecialMessage,
247 FormattedMessage,
248 SimpleMessage,
249 GuildMotd,
250 Unknown(u16),
251}
252
253impl CommunicationOpcode {
254 const fn for_protocol(protocol: GameDialect, value: u16) -> Self {
255 match protocol {
256 GameDialect::TitaniumP99 => match value {
257 0x024d => Self::Motd,
258 0x1004 => Self::ChannelMessage,
259 0x547a => Self::Emote,
260 0x2372 => Self::SpecialMessage,
261 0x5a48 => Self::FormattedMessage,
262 0x673c => Self::SimpleMessage,
263 0x475a => Self::GuildMotd,
264 value => Self::Unknown(value),
265 },
266 GameDialect::EqMac => match value {
267 0xdd41 => Self::Motd,
268 0x0741 => Self::ChannelMessage,
269 0x1540 => Self::Emote,
270 0x8041 => Self::SpecialMessage,
271 0x3642 => Self::FormattedMessage,
272 0x0442 => Self::GuildMotd,
273 value => Self::Unknown(value),
274 },
275 }
276 }
277}
278
279#[must_use]
281pub const fn channel_name(id: u32) -> ChannelName {
282 match id {
283 0 => ChannelName::Guild,
284 2 => ChannelName::Group,
285 3 => ChannelName::Shout,
286 4 => ChannelName::Auction,
287 5 => ChannelName::Ooc,
288 6 => ChannelName::Broadcast,
289 7 => ChannelName::Tell,
290 8 => ChannelName::Say,
291 11 => ChannelName::GmSay,
292 15 => ChannelName::Raid,
293 22 => ChannelName::Emote,
294 _ => ChannelName::Unknown,
295 }
296}
297
298fn u32_at(body: &[u8], offset: usize) -> u32 {
299 u32::from_le_bytes(body[offset..offset + 4].try_into().unwrap())
300}
301
302fn u16_at(body: &[u8], offset: usize) -> u16 {
303 u16::from_le_bytes(body[offset..offset + 2].try_into().unwrap())
304}
305
306fn cstr(bytes: &[u8]) -> &[u8] {
307 &bytes[..bytes.iter().position(|&v| v == 0).unwrap_or(bytes.len())]
308}
309
310fn text(bytes: &[u8]) -> String {
311 String::from_utf8_lossy(cstr(bytes)).into_owned()
312}
313
314fn nonempty_text(bytes: &[u8]) -> Option<String> {
315 match text(bytes) {
316 value if value.is_empty() => None,
317 value => Some(value),
318 }
319}
320
321fn display_text(bytes: &[u8]) -> String {
324 let mut readable = String::new();
325 let mut plain_start = 0;
326 let mut position = 0;
327 while position < bytes.len() {
328 let entity = if bytes[position] == b'&' {
329 STML_ENTITIES.iter().find_map(|&(entity, replacement)| {
330 let end = position + entity.len();
331 (bytes
332 .get(position..end)
333 .is_some_and(|candidate| candidate.eq_ignore_ascii_case(entity)))
334 .then_some((end, replacement))
335 })
336 } else {
337 None
338 };
339
340 if let Some((end, replacement)) = entity {
341 readable.push_str(&String::from_utf8_lossy(&bytes[plain_start..position]));
342 readable.push(replacement);
343 position = end;
344 plain_start = end;
345 } else {
346 position += 1;
347 }
348 }
349 readable.push_str(&String::from_utf8_lossy(&bytes[plain_start..]));
350 readable
351}
352
353fn hex_number(bytes: &[u8]) -> u32 {
354 bytes.iter().fold(0, |value, byte| {
355 let digit = match byte {
356 b'0'..=b'9' => byte - b'0',
357 b'a'..=b'f' => byte - b'a' + 10,
358 b'A'..=b'F' => byte - b'A' + 10,
359 _ => 0,
360 };
361 value * 16 + u32::from(digit)
362 })
363}
364
365fn item_id(protocol: GameDialect, body: &[u8]) -> u32 {
366 let digits = &body[1..];
367 match protocol {
368 GameDialect::TitaniumP99 => hex_number(&digits[..5]),
369 GameDialect::EqMac => std::str::from_utf8(digits)
370 .ok()
371 .and_then(|value| value.parse().ok())
372 .unwrap_or_else(|| hex_number(digits)),
373 }
374}
375
376#[derive(Clone, Debug, Serialize)]
378pub struct ItemLink {
379 pub body: String,
381 pub text: String,
383 pub start: usize,
385 pub end: usize,
387 pub text_start: usize,
389 pub text_end: usize,
391 pub item_id: u32,
393}
394
395#[derive(Clone, Debug, Serialize)]
397pub struct Message {
398 #[serde(skip_serializing_if = "Option::is_none")]
400 pub message: Option<String>,
401 #[serde(skip_serializing_if = "Option::is_none")]
403 pub message_hex: Option<String>,
404 pub text: String,
406 #[serde(skip_serializing_if = "Vec::is_empty")]
408 pub item_links: Vec<ItemLink>,
409}
410
411#[derive(Clone, Debug, Serialize)]
413pub struct ChatEvent {
414 #[serde(rename = "type")]
415 kind: &'static str,
416 pub opcode: u16,
418 #[serde(skip_serializing_if = "Option::is_none")]
420 pub payload_hex: Option<String>,
421 pub channel_name: ChannelName,
423 #[serde(flatten, skip_serializing_if = "Option::is_none")]
425 pub message: Option<Message>,
426 #[serde(skip_serializing_if = "Option::is_none")]
428 pub channel: Option<u32>,
429 #[serde(skip_serializing_if = "Option::is_none")]
431 pub sender: Option<String>,
432 #[serde(skip_serializing_if = "Option::is_none")]
434 pub target: Option<String>,
435 #[serde(skip_serializing_if = "Option::is_none")]
437 pub string_id: Option<u32>,
438 #[serde(skip_serializing_if = "Option::is_none")]
440 pub arguments: Option<Vec<Message>>,
441}
442
443impl ChatEvent {
444 fn new(opcode: u16, payload: &[u8], channel_name: ChannelName, include_raw: bool) -> Self {
445 Self {
446 kind: "chat",
447 opcode,
448 payload_hex: include_raw.then(|| hex::encode(payload)),
449 channel_name,
450 message: None,
451 channel: None,
452 sender: None,
453 target: None,
454 string_id: None,
455 arguments: None,
456 }
457 }
458
459 fn with_message(mut self, message: Message) -> Self {
460 self.message = Some(message);
461 self
462 }
463}
464
465fn message_for(protocol: GameDialect, bytes: &[u8], include_raw: bool) -> Message {
469 let bytes = cstr(bytes);
470 let mut links = Vec::new();
471 let mut readable = String::new();
472 let mut plain_start = 0;
473 let mut pos = 0;
474 while pos < bytes.len() {
475 let body_size = match protocol {
476 GameDialect::TitaniumP99 => 45,
477 GameDialect::EqMac => 7,
478 };
479 if bytes[pos] == 0x12 && pos + body_size + 1 < bytes.len() {
480 let body = &bytes[pos + 1..pos + 1 + body_size];
481 if body.iter().all(u8::is_ascii_hexdigit) {
482 let label_start = pos + 1 + body_size;
483 if let Some(tail) = bytes[label_start..].iter().position(|&b| b == 0x12) {
484 let end = label_start + tail;
485 let label = display_text(&bytes[label_start..end]);
486 readable.push_str(&display_text(&bytes[plain_start..pos]));
487 let text_start = readable.len();
488 readable.push_str(&label);
489 let text_end = readable.len();
490 links.push(ItemLink {
491 body: String::from_utf8_lossy(body).into_owned(),
492 text: label,
493 start: pos,
494 end: end + 1,
495 text_start,
496 text_end,
497 item_id: item_id(protocol, body),
498 });
499 pos = end + 1;
500 plain_start = pos;
501 continue;
502 }
503 }
504 }
505 pos += 1;
506 }
507 readable.push_str(&display_text(&bytes[plain_start..]));
508 Message {
509 message: include_raw.then(|| String::from_utf8_lossy(bytes).into_owned()),
510 message_hex: include_raw.then(|| hex::encode(bytes)),
511 text: readable,
512 item_links: links,
513 }
514}
515
516#[must_use]
518pub fn message(bytes: &[u8], include_raw: bool) -> Message {
519 message_for(GameDialect::TitaniumP99, bytes, include_raw)
520}
521
522pub fn parse(opcode: u16, body: &[u8], include_raw: bool) -> Result<Option<ChatEvent>> {
529 parse_for(GameDialect::TitaniumP99, opcode, body, include_raw)
530}
531
532pub fn parse_for(
538 protocol: GameDialect,
539 opcode: u16,
540 body: &[u8],
541 include_raw: bool,
542) -> Result<Option<ChatEvent>> {
543 let event = match CommunicationOpcode::for_protocol(protocol, opcode) {
544 CommunicationOpcode::Motd => ChatEvent::new(opcode, body, ChannelName::Motd, include_raw)
545 .with_message(message_for(protocol, body, include_raw)),
546 CommunicationOpcode::ChannelMessage => {
547 let header = match protocol {
548 GameDialect::TitaniumP99 => TITANIUM_CHANNEL_MESSAGE_HEADER,
549 GameDialect::EqMac => MAC_CHANNEL_MESSAGE_HEADER,
550 };
551 ensure!(body.len() > header, "truncated ChannelMessage");
552 ensure!(body[header..].contains(&0), "unterminated ChannelMessage");
553 let channel = match protocol {
554 GameDialect::TitaniumP99 => u32_at(body, 132),
555 GameDialect::EqMac => u32::from(u16::from_le_bytes([body[130], body[131]])),
556 };
557 let mut event = ChatEvent::new(opcode, body, channel_name(channel), include_raw)
558 .with_message(message_for(protocol, &body[header..], include_raw));
559 event.channel = Some(channel);
560 event.sender = Some(text(&body[64..128]));
561 event.target = nonempty_text(&body[..64]);
562 event
563 }
564 CommunicationOpcode::Emote => {
565 let text_offset = match protocol {
566 GameDialect::TitaniumP99 => 4,
567 GameDialect::EqMac => 2,
568 };
569 ensure!(body.len() > text_offset, "truncated Emote");
570 ChatEvent::new(opcode, body, ChannelName::Emote, include_raw).with_message(message_for(
571 protocol,
572 &body[text_offset..],
573 include_raw,
574 ))
575 }
576 CommunicationOpcode::SpecialMessage => {
577 if protocol == GameDialect::EqMac {
578 ensure!(body.len() > 4, "truncated SpecialMesg");
579 ChatEvent::new(opcode, body, ChannelName::System, include_raw)
580 .with_message(message_for(protocol, &body[4..], include_raw))
581 } else {
582 ensure!(body.len() >= 24, "truncated SpecialMesg");
583 let sender = cstr(&body[11..]);
584 let offset = 11 + sender.len() + 1 + 12;
585 ensure!(offset < body.len(), "truncated SpecialMesg text");
586 let mut event = ChatEvent::new(opcode, body, ChannelName::System, include_raw)
587 .with_message(message_for(protocol, &body[offset..], include_raw));
588 event.sender = Some(String::from_utf8_lossy(sender).into_owned());
589 event
590 }
591 }
592 CommunicationOpcode::FormattedMessage => {
593 let arguments_offset = match protocol {
594 GameDialect::TitaniumP99 => 12,
595 GameDialect::EqMac => 6,
596 };
597 ensure!(body.len() >= arguments_offset, "truncated FormattedMessage");
598 let arguments = body[arguments_offset..]
599 .split(|&b| b == 0)
600 .take_while(|arg| !arg.is_empty())
601 .map(|argument| message_for(protocol, argument, include_raw))
602 .collect();
603 let mut event = ChatEvent::new(opcode, body, ChannelName::System, include_raw);
604 event.string_id = Some(match protocol {
605 GameDialect::TitaniumP99 => u32_at(body, 4),
606 GameDialect::EqMac => u32::from(u16_at(body, 2)),
607 });
608 event.arguments = Some(arguments);
609 event
610 }
611 CommunicationOpcode::SimpleMessage => {
612 ensure!(body.len() >= 12, "truncated SimpleMessage");
613 let mut event = ChatEvent::new(opcode, body, ChannelName::System, include_raw);
614 event.string_id = Some(u32_at(body, 0));
615 event
616 }
617 CommunicationOpcode::GuildMotd => {
618 if protocol == GameDialect::EqMac {
619 ensure!(body.len() > 68, "truncated guild MOTD");
620 let mut event = ChatEvent::new(opcode, body, ChannelName::GuildMotd, include_raw)
621 .with_message(message_for(protocol, &body[68..], include_raw));
622 event.sender = nonempty_text(&body[..64]);
623 event
624 } else {
625 ensure!(body.len() >= 137, "truncated guild MOTD");
626 let mut event = ChatEvent::new(opcode, body, ChannelName::GuildMotd, include_raw)
627 .with_message(message_for(protocol, &body[136..], include_raw));
628 event.sender = Some(text(&body[68..132]));
629 event.target = nonempty_text(&body[4..68]);
630 event
631 }
632 }
633 CommunicationOpcode::Unknown(_) => return Ok(None),
634 };
635 Ok(Some(event))
636}
637
638#[cfg(test)]
639mod tests {
640 use super::*;
641
642 #[test]
643 fn all_channel_ids_are_logged_including_unknown() {
644 for channel in [0, 2, 3, 4, 5, 6, 7, 8, 11, 15, 22, 999] {
645 let mut body = vec![0; 148];
646 body[64..70].copy_from_slice(b"Trader");
647 body[132..136].copy_from_slice(&u32::to_le_bytes(channel));
648 body.extend_from_slice(b"hello\0");
649 let event = parse(0x1004, &body, false).unwrap().unwrap();
650 assert_eq!(event.channel, Some(channel));
651 assert_eq!(event.sender.as_deref(), Some("Trader"));
652 assert_eq!(event.message.as_ref().unwrap().text, "hello");
653 let json = serde_json::to_value(&event).unwrap();
654 assert_eq!(json["text"], "hello");
655 for field in [
656 "payload_hex",
657 "message",
658 "message_hex",
659 "item_links",
660 "target",
661 "language",
662 "language_skill",
663 ] {
664 assert!(json.get(field).is_none());
665 }
666 }
667 assert!(parse(0xffff, &[], false).unwrap().is_none());
668 }
669
670 #[test]
671 fn outbound_chat_matches_the_titanium_channel_message_layout() {
672 let cases = [
673 (OutboundChat::Guild("guild".into()), 0, None),
674 (OutboundChat::Group("group".into()), 2, None),
675 (OutboundChat::Shout("shout".into()), 3, None),
676 (OutboundChat::Auction("auction".into()), 4, None),
677 (OutboundChat::Ooc("ooc".into()), 5, None),
678 (
679 OutboundChat::Tell {
680 recipient: "Recipient".into(),
681 message: "tell".into(),
682 },
683 7,
684 Some("Recipient"),
685 ),
686 (OutboundChat::Say("say".into()), 8, None),
687 (OutboundChat::Raid("raid".into()), 15, None),
688 ];
689
690 for (message, channel, recipient) in cases {
691 let expected_message = message.message().as_bytes().to_vec();
692 let body = encode_outbound(&message, "ExampleCharacter").unwrap();
693 assert_eq!(
694 body.len(),
695 TITANIUM_CHANNEL_MESSAGE_HEADER + expected_message.len() + 1
696 );
697 assert_eq!(text(&body[..64]), recipient.unwrap_or_default());
698 assert_eq!(text(&body[64..128]), "ExampleCharacter");
699 assert_eq!(u32_at(&body, 128), 0);
700 assert_eq!(u32_at(&body, 132), channel);
701 assert_eq!(&body[136..144], &[0; 8]);
702 assert_eq!(u32_at(&body, 144), 100);
703 assert_eq!(
704 &body[TITANIUM_CHANNEL_MESSAGE_HEADER..body.len() - 1],
705 expected_message
706 );
707 assert_eq!(body.last(), Some(&0));
708 }
709 }
710
711 #[test]
712 fn outbound_chat_uses_titanium_percent_escaping() {
713 let input = "95% & < > \" a b Épée";
714 let body = encode_outbound(&OutboundChat::Say(input.into()), "ExampleCharacter").unwrap();
715 let wire_text = &body[TITANIUM_CHANNEL_MESSAGE_HEADER..body.len() - 1];
716 assert_eq!(wire_text, b"95&PCT; & < > \" a b \xC3\x89p\xC3\xA9e");
717 assert_eq!(display_text(wire_text), input);
718
719 let maximum = encode_outbound(
720 &OutboundChat::Say("%".repeat(MAX_OUTBOUND_MESSAGE / b"&PCT;".len())),
721 "ExampleCharacter",
722 )
723 .unwrap();
724 assert_eq!(
725 maximum.len(),
726 TITANIUM_CHANNEL_MESSAGE_HEADER + MAX_OUTBOUND_MESSAGE + 1
727 );
728 assert!(encode_outbound(
729 &OutboundChat::Say("%".repeat(MAX_OUTBOUND_MESSAGE / b"&PCT;".len() + 1)),
730 "ExampleCharacter",
731 )
732 .is_err());
733 }
734
735 #[test]
736 fn quarm_channel_messages_use_the_eqmac_layout() {
737 let mut body = vec![0; MAC_CHANNEL_MESSAGE_HEADER];
738 body[..9].copy_from_slice(b"Recipient");
739 body[64..70].copy_from_slice(b"Trader");
740 body[128..130].copy_from_slice(&1u16.to_le_bytes());
741 body[130..132].copy_from_slice(&4u16.to_le_bytes());
742 body[134..136].copy_from_slice(&100u16.to_le_bytes());
743 body.extend_from_slice(b"WTS \x121000042Bronze Sword\x12\0");
744
745 let event = parse_for(GameDialect::EqMac, 0x0741, &body, false)
746 .unwrap()
747 .unwrap();
748 assert_eq!(event.channel_name, ChannelName::Auction);
749 assert_eq!(event.channel, Some(4));
750 assert_eq!(event.sender.as_deref(), Some("Trader"));
751 assert_eq!(event.target.as_deref(), Some("Recipient"));
752 let message = event.message.unwrap();
753 assert_eq!(message.text, "WTS Bronze Sword");
754 assert_eq!(message.item_links.len(), 1);
755 assert_eq!(message.item_links[0].body, "1000042");
756 assert_eq!(message.item_links[0].item_id, 42);
757 }
758
759 #[test]
760 fn quarm_outbound_chat_keeps_percent_text_and_adds_the_eqmac_trailer() {
761 let message = OutboundChat::Tell {
762 recipient: "Recipient".into(),
763 message: "95% ready".into(),
764 };
765 let body = encode_outbound_for(GameDialect::EqMac, &message, "ExampleCharacter").unwrap();
766 assert_eq!(body.len(), MAC_CHANNEL_MESSAGE_HEADER + 9 + 5);
767 assert_eq!(text(&body[..64]), "Recipient");
768 assert_eq!(text(&body[64..128]), "ExampleCharacter");
769 assert_eq!(u16_at(&body, 128), 0);
770 assert_eq!(u16_at(&body, 130), 7);
771 assert_eq!(u16_at(&body, 132), 0);
772 assert_eq!(u16_at(&body, 134), 100);
773 assert_eq!(
774 &body[MAC_CHANNEL_MESSAGE_HEADER..MAC_CHANNEL_MESSAGE_HEADER + 9],
775 b"95% ready"
776 );
777 assert_eq!(&body[body.len() - 5..], &[0; 5]);
778 assert!(encode_outbound_for(
779 GameDialect::EqMac,
780 &OutboundChat::Say("x".repeat(MAX_MAC_OUTBOUND_MESSAGE + 1)),
781 "ExampleCharacter"
782 )
783 .is_err());
784 }
785
786 #[test]
787 fn quarm_communication_structs_use_eqmac_offsets() {
788 let mut formatted = vec![0; 6];
789 formatted[2..4].copy_from_slice(&1234u16.to_le_bytes());
790 formatted.extend_from_slice(b"Sword\0Target\0\0");
791 let event = parse_for(GameDialect::EqMac, 0x3642, &formatted, false)
792 .unwrap()
793 .unwrap();
794 assert_eq!(event.string_id, Some(1234));
795 assert_eq!(event.arguments.unwrap()[0].text, "Sword");
796
797 let mut special = 7u32.to_le_bytes().to_vec();
798 special.extend_from_slice(b"System text\0");
799 let event = parse_for(GameDialect::EqMac, 0x8041, &special, false)
800 .unwrap()
801 .unwrap();
802 assert_eq!(event.message.unwrap().text, "System text");
803 assert_eq!(event.sender, None);
804
805 let mut motd = vec![0; 68];
806 motd[..6].copy_from_slice(b"Leader");
807 motd.extend_from_slice(b"Welcome\0");
808 let event = parse_for(GameDialect::EqMac, 0x0442, &motd, false)
809 .unwrap()
810 .unwrap();
811 assert_eq!(event.sender.as_deref(), Some("Leader"));
812 assert_eq!(event.message.unwrap().text, "Welcome");
813 }
814
815 #[test]
816 fn outbound_chat_rejects_values_the_wire_or_server_cannot_represent() {
817 for message in [
818 OutboundChat::Say(String::new()),
819 OutboundChat::Say("bad\0message".into()),
820 OutboundChat::Say("x".repeat(MAX_OUTBOUND_MESSAGE + 1)),
821 OutboundChat::Tell {
822 recipient: String::new(),
823 message: "hello".into(),
824 },
825 OutboundChat::Tell {
826 recipient: "x".repeat(64),
827 message: "hello".into(),
828 },
829 ] {
830 assert!(encode_outbound(&message, "ExampleCharacter").is_err());
831 }
832 assert!(
833 encode_outbound(&OutboundChat::Say("hello".into()), "x".repeat(64).as_str()).is_err()
834 );
835 }
836
837 #[test]
838 fn links_keep_their_body_and_wire_offsets() {
839 let link = b"00002A0000000000000000000000000000000ABCDEF12";
840 assert_eq!(link.len(), 45);
841 let mut input = b"WTS \x12".to_vec();
842 input.extend(link);
843 input.extend_from_slice(b"Item\x12 \xff");
844 let event = message(&input, false);
845 assert_eq!(event.message, None);
846 assert_eq!(event.message_hex, None);
847 assert_eq!(event.text, "WTS Item �");
848 assert_eq!(event.item_links[0].item_id, 42);
849 assert_eq!(event.item_links[0].start, 4);
850 assert_eq!(event.item_links[0].end, 55);
851 assert_eq!(event.item_links[0].text_start, 4);
852 assert_eq!(event.item_links[0].text_end, 8);
853 assert_eq!(event.item_links[0].body, std::str::from_utf8(link).unwrap());
854 let json = serde_json::to_value(&event).unwrap();
855 for field in ["action_id", "hash", "augment_ids", "is_evolving"] {
856 assert!(json["item_links"][0].get(field).is_none());
857 }
858 assert!(message(b"bad \x12short\x12", false).item_links.is_empty());
859 }
860
861 #[test]
862 fn stml_entities_decode_only_in_display_text() {
863 let input = b"95&PCT; & < > " a&NBSP; b &pct; & < > " &PCT; &&PCT; ' % &PCT";
864 let decoded = message(input, true);
865 assert_eq!(
866 decoded.text,
867 "95% & < > \" a b % & < > \" &PCT; &% ' % &PCT"
868 );
869 assert_eq!(decoded.message.as_deref(), std::str::from_utf8(input).ok());
870 assert_eq!(
871 decoded.message_hex.as_deref(),
872 Some(hex::encode(input).as_str())
873 );
874 }
875
876 #[test]
877 fn percent_entities_preserve_link_wire_offsets_and_update_display_ranges() {
878 let body = b"00002A0000000000000000000000000000000ABCDEF12";
879 let mut input = "é&PCT; ".as_bytes().to_vec();
880 for (label, suffix) in [
881 (b"Sword&PCT;".as_slice(), b" &pct; ".as_slice()),
882 ("Épée".as_bytes(), b" &PCT;".as_slice()),
883 ] {
884 input.push(0x12);
885 input.extend(body);
886 input.extend(label);
887 input.push(0x12);
888 input.extend(suffix);
889 }
890
891 let decoded = message(&input, true);
892 assert_eq!(decoded.text, "é% Sword% % Épée %");
893 assert_eq!(decoded.message.as_deref(), std::str::from_utf8(&input).ok());
894 assert_eq!(
895 decoded.message_hex.as_deref(),
896 Some(hex::encode(&input).as_str())
897 );
898 assert_eq!(decoded.item_links.len(), 2);
899 assert_eq!(decoded.item_links[0].text, "Sword%");
900 assert_eq!(decoded.item_links[1].text, "Épée");
901 for link in &decoded.item_links {
902 assert_eq!(&decoded.text[link.text_start..link.text_end], link.text);
903 assert_eq!(input[link.start], 0x12);
904 assert_eq!(input[link.end - 1], 0x12);
905 assert_eq!(link.body, std::str::from_utf8(body).unwrap());
906 }
907 }
908
909 #[test]
910 fn display_ranges_address_decoded_text_with_unicode_and_replacement_characters() {
911 let body = b"00002A0000000000000000000000000000000ABCDEF12";
912 let mut input = "é 🗡 unlinked Item ".as_bytes().to_vec();
913 input.push(0xff);
914 for label in [b"Item".as_slice(), "Épée".as_bytes(), b"I\xfftem"] {
915 input.push(b' ');
916 input.push(0x12);
917 input.extend(body);
918 input.extend(label);
919 input.push(0x12);
920 }
921 input.extend(b" end");
922 let decoded = message(&input, false);
923 assert_eq!(decoded.text, "é 🗡 unlinked Item � Item Épée I�tem end");
924 assert_eq!(decoded.item_links.len(), 3);
925 let mut previous_end = 0;
926 for link in &decoded.item_links {
927 assert_eq!(&decoded.text[link.text_start..link.text_end], link.text);
928 assert!(link.text_start >= previous_end);
929 assert_eq!(input[link.start], 0x12);
930 assert_eq!(input[link.end - 1], 0x12);
931 previous_end = link.text_end;
932 }
933 let json = serde_json::to_value(decoded).unwrap();
934 assert!(json["item_links"][0]["text_start"].is_u64());
935 assert!(json.get("message_hex").is_none());
936 }
937
938 #[test]
939 fn raw_mode_preserves_packet_and_message_bytes() {
940 let mut body = vec![0; 148];
941 body[64..70].copy_from_slice(b"Trader");
942 body[132..136].copy_from_slice(&4_u32.to_le_bytes());
943 body.extend_from_slice(b"hello\0");
944 let event = parse(0x1004, &body, true).unwrap().unwrap();
945 let message = event.message.as_ref().unwrap();
946 assert_eq!(event.payload_hex, Some(hex::encode(&body)));
947 assert_eq!(message.message.as_deref(), Some("hello"));
948 assert_eq!(message.message_hex.as_deref(), Some("68656c6c6f"));
949 }
950}