1mod quarm;
39mod session;
40
41use crate::{
42 assets::Assets,
43 chat::{ChannelName, ChatEvent},
44};
45use anyhow::{ensure, Context, Result};
46use eq_network_game::GameDialect;
47use serde::{Deserialize, Serialize};
48use std::{
49 collections::HashSet,
50 fmt,
51 str::FromStr,
52 sync::{
53 atomic::{AtomicBool, Ordering},
54 mpsc::Receiver,
55 Arc,
56 },
57 time::{Duration, Instant},
58};
59use zeroize::Zeroizing;
60
61pub use eq_network_game::command::GameCommand as ClientCommand;
63
64#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
66#[serde(rename_all = "snake_case")]
67#[non_exhaustive]
68pub enum ServerProtocol {
69 #[default]
71 #[serde(alias = "p99", alias = "project_1999")]
72 Project1999,
73 Quarm,
75}
76
77impl ServerProtocol {
78 #[must_use]
80 pub const fn default_endpoint(self) -> (&'static str, u16) {
81 match self {
82 Self::Project1999 => ("login.eqemulator.net", 5998),
83 Self::Quarm => ("loginserver.takproject.net", 6000),
84 }
85 }
86}
87
88impl From<ServerProtocol> for GameDialect {
89 fn from(protocol: ServerProtocol) -> Self {
90 match protocol {
91 ServerProtocol::Project1999 => Self::TitaniumP99,
92 ServerProtocol::Quarm => Self::EqMac,
93 }
94 }
95}
96
97impl FromStr for ServerProtocol {
98 type Err = anyhow::Error;
99
100 fn from_str(value: &str) -> Result<Self> {
101 match value.to_ascii_lowercase().as_str() {
102 "p99" | "project1999" | "project_1999" => Ok(Self::Project1999),
103 "quarm" => Ok(Self::Quarm),
104 _ => anyhow::bail!("unknown server protocol {value:?}"),
105 }
106 }
107}
108
109#[derive(Clone)]
111pub struct Credentials {
112 account: Zeroizing<String>,
113 password: Zeroizing<String>,
114}
115
116impl Credentials {
117 pub fn new(account: impl Into<String>, password: impl Into<String>) -> Self {
119 Self {
120 account: Zeroizing::new(account.into()),
121 password: Zeroizing::new(password.into()),
122 }
123 }
124
125 #[must_use]
127 pub fn account(&self) -> &str {
128 self.account.as_str()
129 }
130
131 fn password(&self) -> &str {
132 self.password.as_str()
133 }
134}
135
136impl fmt::Debug for Credentials {
137 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138 formatter
139 .debug_struct("Credentials")
140 .field("account", &"[REDACTED]")
141 .field("password", &"[REDACTED]")
142 .finish()
143 }
144}
145
146#[derive(Clone, Debug)]
148#[non_exhaustive]
149pub struct ClientConfig {
150 pub protocol: ServerProtocol,
152 pub host: String,
154 pub port: u16,
156 pub credentials: Credentials,
158 pub server: String,
160 pub character: String,
162 pub include_raw: bool,
164 pub channels: Option<HashSet<ChannelName>>,
166 pub reconnect_delay: Duration,
168}
169
170impl ClientConfig {
171 pub fn new(
173 user: impl Into<String>,
174 pass: impl Into<String>,
175 server: impl Into<String>,
176 character: impl Into<String>,
177 ) -> Self {
178 Self::for_protocol(ServerProtocol::Project1999, user, pass, server, character)
179 }
180
181 pub fn for_protocol(
183 protocol: ServerProtocol,
184 user: impl Into<String>,
185 pass: impl Into<String>,
186 server: impl Into<String>,
187 character: impl Into<String>,
188 ) -> Self {
189 let (host, port) = protocol.default_endpoint();
190 Self {
191 protocol,
192 host: host.into(),
193 port,
194 credentials: Credentials::new(user, pass),
195 server: server.into(),
196 character: character.into(),
197 include_raw: false,
198 channels: None,
199 reconnect_delay: Duration::from_secs(30),
200 }
201 }
202
203 fn validate(&self) -> Result<()> {
204 for value in [&self.host, &self.server, &self.character] {
205 ensure!(
206 !value.is_empty() && !value.contains('\0'),
207 "required connection fields must be nonempty and contain no NUL"
208 );
209 }
210 for value in [self.credentials.account(), self.credentials.password()] {
211 ensure!(
212 !value.is_empty() && !value.contains('\0'),
213 "required credentials must be nonempty and contain no NUL"
214 );
215 }
216 ensure!(self.port != 0, "login port must be nonzero");
217 if self.protocol == ServerProtocol::Quarm {
218 ensure!(
219 self.credentials.account().len() < 20 && self.credentials.password().len() < 20,
220 "Quarm login fields must fit in 19 bytes"
221 );
222 }
223 ensure!(
224 self.character.len() < 64,
225 "character name exceeds protocol field size"
226 );
227 ensure!(
228 self.reconnect_delay >= Duration::from_secs(10),
229 "reconnect delay must be at least 10 seconds"
230 );
231 Ok(())
232 }
233
234 #[must_use]
236 pub fn logs(&self, event: &ChatEvent) -> bool {
237 self.channels
238 .as_ref()
239 .is_none_or(|channels| channels.contains(&event.channel_name))
240 }
241}
242
243#[derive(Clone)]
246#[non_exhaustive]
247pub struct ClientIdentity {
248 pub hostname: String,
250 pub username: String,
252}
253
254impl ClientIdentity {
255 pub fn new(hostname: impl Into<String>, username: impl Into<String>) -> Self {
257 Self {
258 hostname: hostname.into(),
259 username: username.into(),
260 }
261 }
262}
263
264#[derive(Clone, Debug, Default)]
266pub struct CancellationToken(Arc<AtomicBool>);
267
268impl CancellationToken {
269 pub fn cancel(&self) {
271 self.0.store(true, Ordering::Relaxed);
272 }
273
274 #[must_use]
275 pub fn is_cancelled(&self) -> bool {
277 self.0.load(Ordering::Relaxed)
278 }
279
280 fn flag(&self) -> &AtomicBool {
281 &self.0
282 }
283}
284
285impl From<Arc<AtomicBool>> for CancellationToken {
286 fn from(flag: Arc<AtomicBool>) -> Self {
288 Self(flag)
289 }
290}
291
292#[derive(Clone, Copy, Debug, Eq, PartialEq)]
295#[non_exhaustive]
296pub enum LoginError {
297 InvalidCredentials,
299}
300
301impl fmt::Display for LoginError {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 match self {
304 Self::InvalidCredentials => f.write_str("Login account or password was rejected"),
305 }
306 }
307}
308
309impl std::error::Error for LoginError {}
310
311#[derive(Clone, Copy, Debug)]
313#[non_exhaustive]
314pub struct RunOptions {
315 pub reconnect: bool,
317 pub world_only: bool,
319 pub zone_duration: Option<Duration>,
321}
322
323impl Default for RunOptions {
324 fn default() -> Self {
325 Self {
326 reconnect: true,
327 world_only: false,
328 zone_duration: None,
329 }
330 }
331}
332
333#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
335#[serde(rename_all = "snake_case")]
336#[non_exhaustive]
337pub enum ConnectionState {
338 Connecting,
340 Connected,
342 Zoning,
344 Disconnected,
346 Stopped,
348}
349
350#[derive(Clone, Debug, Serialize)]
352#[non_exhaustive]
353pub struct SessionStatus {
354 pub state: ConnectionState,
356 pub timestamp: i64,
358 pub session_id: String,
360 pub zone: String,
362 pub messages: u64,
364 pub packets: u64,
366 pub last_received_seconds: Option<u64>,
368}
369
370impl SessionStatus {
371 #[must_use]
373 pub fn new(state: ConnectionState, session_id: impl Into<String>) -> Self {
374 Self {
375 state,
376 timestamp: chrono::Utc::now().timestamp(),
377 session_id: session_id.into(),
378 zone: String::new(),
379 messages: 0,
380 packets: 0,
381 last_received_seconds: None,
382 }
383 }
384
385 #[must_use]
387 pub const fn with_timestamp(mut self, timestamp: i64) -> Self {
388 self.timestamp = timestamp;
389 self
390 }
391
392 #[must_use]
394 pub fn with_zone(mut self, zone: impl Into<String>) -> Self {
395 self.zone = zone.into();
396 self
397 }
398
399 #[must_use]
401 pub const fn with_counters(mut self, messages: u64, packets: u64) -> Self {
402 self.messages = messages;
403 self.packets = packets;
404 self
405 }
406
407 #[must_use]
409 pub const fn with_last_received(mut self, seconds: Option<u64>) -> Self {
410 self.last_received_seconds = seconds;
411 self
412 }
413}
414
415#[derive(Clone, Debug, Serialize)]
417#[non_exhaustive]
418pub struct DecodeError {
419 #[serde(rename = "type")]
420 kind: &'static str,
421 pub opcode: u16,
423 pub payload_hex: String,
425 pub error: String,
427}
428
429impl DecodeError {
430 #[must_use]
432 pub fn new(opcode: u16, payload_hex: impl Into<String>, error: impl Into<String>) -> Self {
433 Self {
434 kind: "decode_error",
435 opcode,
436 payload_hex: payload_hex.into(),
437 error: error.into(),
438 }
439 }
440}
441
442#[derive(Clone, Debug, Serialize)]
444#[serde(untagged)]
445#[non_exhaustive]
446pub enum RecordEvent {
447 Chat(ChatEvent),
449 DecodeError(DecodeError),
451}
452
453#[derive(Clone, Debug, Serialize)]
455#[non_exhaustive]
456pub struct Record {
457 pub timestamp: String,
459 pub server: String,
461 pub character: String,
463 pub zone: String,
465 pub session_id: String,
467 pub message_id: u64,
469 #[serde(flatten)]
471 pub event: RecordEvent,
472}
473
474impl Record {
475 #[must_use]
477 pub fn new(
478 server: impl Into<String>,
479 character: impl Into<String>,
480 zone: impl Into<String>,
481 session_id: impl Into<String>,
482 message_id: u64,
483 event: RecordEvent,
484 ) -> Self {
485 Self {
486 timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
487 server: server.into(),
488 character: character.into(),
489 zone: zone.into(),
490 session_id: session_id.into(),
491 message_id,
492 event,
493 }
494 }
495
496 #[must_use]
498 pub fn with_timestamp(mut self, timestamp: impl Into<String>) -> Self {
499 self.timestamp = timestamp.into();
500 self
501 }
502}
503
504#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
507#[serde(rename_all = "snake_case")]
508#[non_exhaustive]
509pub enum ConnectionStage {
510 ConnectingLogin,
512 Authenticating,
514 SelectingServer,
516 ConnectingWorld,
518 SelectingCharacter,
520 ConnectingZone,
522 LoadingCharacter,
524 EnteringWorld,
526 Ready,
528}
529
530#[derive(Clone, Debug, Serialize)]
532#[serde(tag = "type", content = "data", rename_all = "snake_case")]
533#[non_exhaustive]
534pub enum ClientEvent {
535 Status(SessionStatus),
537 Progress(ConnectionStage),
539 Record(Box<Record>),
541 Diagnostic(String),
543 Reconnecting {
545 error: String,
547 delay_seconds: u64,
549 },
550}
551
552pub struct Client {
554 config: ClientConfig,
555 identity: ClientIdentity,
556 assets: Assets,
557}
558
559impl Client {
560 pub fn new(config: ClientConfig, mut identity: ClientIdentity) -> Result<Self> {
567 config.validate()?;
568 identity.hostname = identity.hostname.to_uppercase();
569 for value in [&identity.hostname, &identity.username] {
570 ensure!(
571 !value.is_empty() && value.len() < 16 && !value.contains('\0'),
572 "client identity fields must contain 1 to 15 bytes and no NUL"
573 );
574 }
575 Ok(Self {
576 config,
577 identity,
578 assets: Assets::bundled()?,
579 })
580 }
581
582 pub fn with_assets(mut self, assets: Assets) -> Result<Self> {
588 assets.spells()?;
589 self.assets = assets;
590 Ok(self)
591 }
592
593 pub fn run(
605 &self,
606 cancel: &CancellationToken,
607 options: RunOptions,
608 mut handler: impl FnMut(ClientEvent) -> Result<()>,
609 ) -> Result<()> {
610 self.run_inner(cancel, options, None, &mut handler)
611 }
612
613 pub fn run_with_commands(
622 &self,
623 cancel: &CancellationToken,
624 options: RunOptions,
625 commands: &Receiver<ClientCommand>,
626 mut handler: impl FnMut(ClientEvent) -> Result<()>,
627 ) -> Result<()> {
628 self.run_inner(cancel, options, Some(commands), &mut handler)
629 }
630
631 fn run_inner(
632 &self,
633 cancel: &CancellationToken,
634 options: RunOptions,
635 commands: Option<&Receiver<ClientCommand>>,
636 handler: &mut dyn FnMut(ClientEvent) -> Result<()>,
637 ) -> Result<()> {
638 let mut events = Events::new(&self.config, handler);
639 loop {
640 if cancel.is_cancelled() {
641 return events.status(ConnectionState::Stopped, 0, None);
642 }
643 events.reset();
644 events.status(ConnectionState::Connecting, 0, None)?;
645 events.send(ClientEvent::Progress(ConnectionStage::ConnectingLogin))?;
646 let result = session::run(
647 &self.config,
648 &self.identity,
649 &self.assets,
650 cancel,
651 &options,
652 commands,
653 &mut events,
654 );
655 if result
656 .as_ref()
657 .is_err_and(anyhow::Error::is::<EventDeliveryError>)
658 {
659 return result;
660 }
661 if result.is_ok() || cancel.is_cancelled() {
662 return events.status(ConnectionState::Stopped, 0, None);
663 }
664 events.status(ConnectionState::Disconnected, 0, None)?;
665 if !options.reconnect || result.as_ref().is_err_and(anyhow::Error::is::<LoginError>) {
666 return result;
667 }
668 events.send(ClientEvent::Reconnecting {
669 error: format!("{:#}", result.unwrap_err()),
670 delay_seconds: self.config.reconnect_delay.as_secs(),
671 })?;
672 let retry = Instant::now()
673 .checked_add(self.config.reconnect_delay)
674 .context("reconnect delay exceeds clock range")?;
675 while Instant::now() < retry && !cancel.is_cancelled() {
676 std::thread::sleep(
677 retry
678 .saturating_duration_since(Instant::now())
679 .min(Duration::from_millis(200)),
680 );
681 }
682 }
683 }
684}
685
686#[derive(Debug)]
687struct EventDeliveryError(anyhow::Error);
688
689impl fmt::Display for EventDeliveryError {
690 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
691 write!(f, "deliver client event: {}", self.0)
692 }
693}
694
695impl std::error::Error for EventDeliveryError {
696 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
697 Some(self.0.as_ref())
698 }
699}
700
701struct Events<'a> {
702 config: &'a ClientConfig,
703 handler: &'a mut dyn FnMut(ClientEvent) -> Result<()>,
704 session_id: String,
705 zone: String,
706 messages: u64,
707}
708
709impl<'a> Events<'a> {
710 fn new(
711 config: &'a ClientConfig,
712 handler: &'a mut dyn FnMut(ClientEvent) -> Result<()>,
713 ) -> Self {
714 Self {
715 config,
716 handler,
717 session_id: String::new(),
718 zone: String::new(),
719 messages: 0,
720 }
721 }
722
723 fn reset(&mut self) {
724 self.session_id = format!("{:016x}", rand::random::<u64>());
725 self.zone.clear();
726 self.messages = 0;
727 }
728
729 fn send(&mut self, event: ClientEvent) -> Result<()> {
730 (self.handler)(event).map_err(|error| EventDeliveryError(error).into())
731 }
732
733 fn diagnostic(&mut self, message: String) -> Result<()> {
734 self.send(ClientEvent::Diagnostic(message))
735 }
736
737 fn status(
738 &mut self,
739 state: ConnectionState,
740 packets: u64,
741 last_received_seconds: Option<u64>,
742 ) -> Result<()> {
743 self.send(ClientEvent::Status(SessionStatus {
744 state,
745 timestamp: chrono::Utc::now().timestamp(),
746 session_id: self.session_id.clone(),
747 zone: self.zone.clone(),
748 messages: self.messages,
749 packets,
750 last_received_seconds,
751 }))
752 }
753
754 fn record(&mut self, zone: &str, event: RecordEvent) -> Result<()> {
755 if let RecordEvent::Chat(chat) = &event {
756 if !self.config.logs(chat) {
757 return Ok(());
758 }
759 }
760 self.messages += 1;
761 self.send(ClientEvent::Record(Box::new(Record {
762 timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
763 server: self.config.server.clone(),
764 character: self.config.character.clone(),
765 zone: zone.to_owned(),
766 session_id: self.session_id.clone(),
767 message_id: self.messages,
768 event,
769 })))
770 }
771}
772
773#[cfg(test)]
774mod tests {
775 use super::*;
776 use crate::chat;
777
778 #[test]
779 fn protocol_names_are_stable_and_p99_aliases_remain_readable() {
780 assert_eq!(
781 serde_json::to_string(&ServerProtocol::Project1999).unwrap(),
782 r#""project1999""#
783 );
784 for name in [r#""project1999""#, r#""p99""#, r#""project_1999""#] {
785 assert_eq!(
786 serde_json::from_str::<ServerProtocol>(name).unwrap(),
787 ServerProtocol::Project1999
788 );
789 }
790 assert_eq!(
791 "QUARM".parse::<ServerProtocol>().unwrap(),
792 ServerProtocol::Quarm
793 );
794 }
795
796 fn chat(channel: u32) -> ChatEvent {
797 let mut packet = vec![0; 148];
798 packet[64..70].copy_from_slice(b"Sender");
799 packet[132..136].copy_from_slice(&channel.to_le_bytes());
800 packet.extend(b"Example message\0");
801 chat::parse(0x1004, &packet, false).unwrap().unwrap()
802 }
803
804 #[test]
805 fn records_preserve_flat_json_filtering_and_per_session_ids() {
806 let mut config = ClientConfig::new(
807 "EXAMPLE_ACCOUNT",
808 "EXAMPLE_PASSWORD",
809 "Test Server",
810 "ExampleCharacter",
811 );
812 config.channels = Some(HashSet::from([ChannelName::Auction]));
813 let mut received = Vec::new();
814 let mut handler = |event| {
815 received.push(event);
816 Ok(())
817 };
818 let mut events = Events::new(&config, &mut handler);
819 events.reset();
820 events
821 .record("testzone", RecordEvent::Chat(chat(8)))
822 .unwrap();
823 events
824 .record("testzone", RecordEvent::Chat(chat(4)))
825 .unwrap();
826 events
827 .record(
828 "testzone",
829 RecordEvent::DecodeError(DecodeError {
830 kind: "decode_error",
831 opcode: 0x1004,
832 payload_hex: "00".into(),
833 error: "synthetic truncation".into(),
834 }),
835 )
836 .unwrap();
837 assert_eq!(events.messages, 2);
838 events.reset();
839 events
840 .record("testzone", RecordEvent::Chat(chat(4)))
841 .unwrap();
842
843 let records: Vec<_> = received
844 .into_iter()
845 .map(|event| match event {
846 ClientEvent::Record(record) => serde_json::to_value(record).unwrap(),
847 _ => panic!("unexpected event"),
848 })
849 .collect();
850 assert_eq!(records.len(), 3);
851 let record = &records[0];
852 assert_eq!(record["type"], "chat");
853 assert_eq!(record["channel_name"], "auction");
854 assert_eq!(record["channel"], 4);
855 assert_eq!(record["text"], "Example message");
856 assert_eq!(record["sender"], "Sender");
857 assert_eq!(record["server"], "Test Server");
858 assert_eq!(record["character"], "ExampleCharacter");
859 assert_eq!(record["zone"], "testzone");
860 assert_eq!(record["message_id"], 1);
861 assert!(record.get("event").is_none() && record.get("payload_hex").is_none());
862 assert!(
863 chrono::DateTime::parse_from_rfc3339(record["timestamp"].as_str().unwrap()).is_ok()
864 );
865 assert_eq!(records[1]["type"], "decode_error");
866 assert_eq!(records[1]["message_id"], 2);
867 assert_eq!(records[1]["payload_hex"], "00");
868 assert_eq!(records[1]["session_id"], record["session_id"]);
869 assert_eq!(records[2]["message_id"], 1);
870 assert_ne!(records[2]["session_id"], record["session_id"]);
871 let serialized = serde_json::to_string(&records).unwrap();
872 assert!(
873 !serialized.contains("EXAMPLE_ACCOUNT") && !serialized.contains("EXAMPLE_PASSWORD")
874 );
875 }
876
877 #[test]
878 fn default_channels_include_unknown_and_empty_filter_suppresses_chat() {
879 let mut config = ClientConfig::new(
880 "EXAMPLE_ACCOUNT",
881 "EXAMPLE_PASSWORD",
882 "Test Server",
883 "ExampleCharacter",
884 );
885 assert!(config.logs(&chat(999)));
886 config.channels = Some(HashSet::new());
887 assert!(!config.logs(&chat(999)) && !config.logs(&chat(4)));
888 }
889}