summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 9a24515ffaf9f57b7038126c4a418c6de7b7e1ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use mt_net::{CltSender, SenderExt, ToCltPkt, ToSrvPkt};
use rand::RngCore;
use sha2::Sha256;
use srp::{client::SrpClient, groups::G_2048};
use std::time::Duration;
use tokio::time::{interval, Interval};

enum AuthState {
    Init(ToSrvPkt, Interval),
    Verify(Vec<u8>, SrpClient<'static, Sha256>),
    Done(bool),
}

pub struct Auth {
    tx: CltSender,
    state: AuthState,
    username: String,
    password: String,
    lang: String,
}

impl Auth {
    pub fn new(
        tx: CltSender,
        username: impl Into<String>,
        password: impl Into<String>,
        lang: impl Into<String>,
    ) -> Self {
        let username = username.into();
        Self {
            tx,
            state: AuthState::Init(
                ToSrvPkt::Init {
                    serialize_version: 29,
                    proto_version: 40..=40,
                    player_name: username.clone(),
                    send_full_item_meta: false,
                },
                interval(Duration::from_millis(100)),
            ),
            username,
            password: password.into(),
            lang: lang.into(),
        }
    }

    pub fn username(&self) -> &str {
        &self.username
    }

    pub fn password(&self) -> &str {
        &self.password
    }

    pub fn lang(&self) -> &str {
        &self.lang
    }

    pub fn mut_init_pkt(&mut self) -> Option<&mut ToSrvPkt> {
        if let AuthState::Init(pkt, _) = &mut self.state {
            Some(pkt)
        } else {
            None
        }
    }

    pub async fn poll(&mut self) {
        match &mut self.state {
            AuthState::Init(pkt, interval) => {
                loop {
                    // cancel safety: since init pkt is unreliable, cancelation is not an issue
                    self.tx.send(pkt).await.unwrap();
                    interval.tick().await;
                }
            }
            AuthState::Verify(_, _) | AuthState::Done(false) => futures::future::pending().await,
            AuthState::Done(unconsumed) => {
                *unconsumed = false;
            }
        }
    }

    pub async fn handle_pkt(&mut self, pkt: &ToCltPkt) {
        use ToCltPkt::*;
        match pkt {
            Hello {
                auth_methods,
                username: name,
                ..
            } => {
                use mt_net::AuthMethod;

                if !matches!(self.state, AuthState::Init(_, _)) {
                    return;
                }

                let srp = SrpClient::<Sha256>::new(&G_2048);

                let mut rand_bytes = vec![0; 32];
                rand::thread_rng().fill_bytes(&mut rand_bytes);

                if &self.username != name {
                    panic!("username changed");
                }

                if auth_methods.contains(AuthMethod::FirstSrp) {
                    let verifier = srp.compute_verifier(
                        self.username.to_lowercase().as_bytes(),
                        self.password.as_bytes(),
                        &rand_bytes,
                    );

                    self.tx
                        .send(&ToSrvPkt::FirstSrp {
                            salt: rand_bytes,
                            verifier,
                            empty_passwd: self.password.is_empty(),
                        })
                        .await
                        .unwrap();

                    self.state = AuthState::Done(false);
                } else if auth_methods.contains(AuthMethod::Srp) {
                    let a = srp.compute_public_ephemeral(&rand_bytes);

                    self.tx
                        .send(&ToSrvPkt::SrpBytesA { a, no_sha1: true })
                        .await
                        .unwrap();

                    self.state = AuthState::Verify(rand_bytes, srp);
                } else {
                    panic!("unsupported auth methods: {auth_methods:?}");
                }
            }
            SrpBytesSaltB { salt, b } => {
                if let AuthState::Verify(a, srp) = &self.state {
                    let m = srp
                        .process_reply(
                            a,
                            self.username.to_lowercase().as_bytes(),
                            self.password.as_bytes(),
                            salt,
                            b,
                        )
                        .unwrap()
                        .proof()
                        .into();

                    self.tx.send(&ToSrvPkt::SrpBytesM { m }).await.unwrap();

                    self.state = AuthState::Done(false);
                }
            }
            AcceptAuth { .. } => {
                self.tx
                    .send(&ToSrvPkt::Init2 {
                        lang: self.lang.clone(),
                    })
                    .await
                    .unwrap();

                self.state = AuthState::Done(true);
            }
            _ => {}
        }
    }
}