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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use failure::Error;
use reqwest::{self as rq, Proxy, RequestBuilder};
use sha3::{Digest, Sha3_256};
use url::Host;

pub struct Pubkey(pub [u8; 32]);
impl AsRef<[u8; 32]> for Pubkey {
    fn as_ref(&self) -> &[u8; 32] {
        &self.0
    }
}

pub fn onion_to_pubkey(onion: &str) -> Result<Pubkey, Error> {
    let s = onion.split(".").next().unwrap();
    let b = base32::decode(base32::Alphabet::RFC4648 { padding: false }, s)
        .ok_or_else(|| failure::format_err!("invalid base32"))?;
    failure::ensure!(b.len() >= 35, "invalid base32 length");
    failure::ensure!(b[34] == 3, "invalid version");
    let pubkey = &b[..32];
    let mut hasher = Sha3_256::new();
    hasher.input(b".onion checksum");
    hasher.input(pubkey);
    hasher.input(&[3]);
    failure::ensure!(&b[32..34] == &hasher.result()[..2], "invalid checksum");
    let mut pk = [0; 32];
    pk.clone_from_slice(pubkey);
    Ok(Pubkey(pk))
}

pub fn pubkey_to_onion(pubkey: &[u8]) -> Result<String, Error> {
    if pubkey.len() != 32 {
        failure::bail!("invalid pubkey length")
    }
    let mut hasher = Sha3_256::new();
    hasher.input(b".onion checksum");
    hasher.input(pubkey);
    hasher.input(&[3]);
    let mut onion = Vec::with_capacity(35);
    onion.extend_from_slice(pubkey);
    onion.extend_from_slice(&hasher.result()[..2]);
    onion.push(3);
    Ok(format!(
        "{}.onion",
        base32::encode(base32::Alphabet::RFC4648 { padding: false }, &onion).to_lowercase()
    ))
}

#[derive(Clone, Debug)]
pub struct Creds {
    pub host: Host,
    pub proxy: Option<Proxy>,
    pub password: String,
}
impl AsRef<Creds> for Creds {
    fn as_ref(&self) -> &Creds {
        self
    }
}
impl Creds {
    pub fn get(&self, rel_url: &str) -> Result<RequestBuilder, Error> {
        Ok(if let Some(proxy) = &self.proxy {
            rq::Client::builder().proxy(proxy.clone()).build()?
        } else {
            rq::Client::new()
        }
        .get(&format!("http://{}:59001/{}", self.host, rel_url))
        .basic_auth("me", Some(&self.password)))
    }
    pub fn post<T: Into<rq::Body>>(&self, body: T) -> Result<RequestBuilder, Error> {
        Ok(if let Some(proxy) = &self.proxy {
            rq::Client::builder().proxy(proxy.clone()).build()?
        } else {
            rq::Client::new()
        }
        .post(&format!("http://{}:59001", self.host))
        .basic_auth("me", Some(&self.password))
        .body(body))
    }
}

#[derive(Clone, Debug)]
pub struct UserData {
    pub id: [u8; 32],
    pub name: Option<String>,
    pub unreads: u64,
}

pub async fn fetch_users<C: AsRef<Creds>>(creds: C) -> Result<Vec<UserData>, Error> {
    use std::io::Read;
    let mut users = Vec::new();

    let res = creds.as_ref().get("?type=users")?.send().await?;
    let status = res.status();
    if !status.is_success() {
        failure::bail!("{}", status.canonical_reason().unwrap_or("UNKNOWN STATUS"));
    }
    let mut b = std::io::Cursor::new(res.bytes().await?);
    loop {
        let mut id = [0; 32];
        match b.read_exact(&mut id) {
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
            a => a?,
        };
        let mut buf = [0; 8];
        b.read_exact(&mut buf)?;
        let unreads = u64::from_be_bytes(buf);
        let mut buf = [0];
        b.read_exact(&mut buf)?;
        let name = if buf[0] == 0 {
            None
        } else {
            let mut buf = vec![0; buf[0] as usize];
            b.read_exact(&mut buf)?;
            Some(String::from_utf8(buf)?)
        };
        users.push(UserData { id, name, unreads })
    }
    Ok(users)
}

pub async fn add_user(creds: &Creds, onion: &str, name: &str) -> Result<(), Error> {
    let mut req = Vec::new();
    req.push(1);
    req.extend_from_slice(onion_to_pubkey(onion)?.as_ref());
    req.extend_from_slice(name.as_bytes());
    let status = creds.post(req)?.send().await?.status();
    if !status.is_success() {
        failure::bail!("{}", status.canonical_reason().unwrap_or("UNKNOWN STATUS"));
    }
    Ok(())
}

#[derive(Clone, Debug)]
pub struct Message {
    pub inbound: bool,
    pub time: i64,
    pub content: String,
}

pub async fn fetch_messages<C: AsRef<Creds>, I: AsRef<[u8; 32]>>(
    creds: C,
    id: I,
    limit: Option<usize>,
) -> Result<Vec<Message>, Error> {
    use std::io::Read;

    let mut msgs = Vec::new();
    let res = creds
        .as_ref()
        .get(&if let Some(limit) = limit {
            format!(
                "?type=messages&pubkey={}&limit={}",
                base32::encode(base32::Alphabet::RFC4648 { padding: false }, id.as_ref())
                    .to_lowercase(),
                limit
            )
        } else {
            format!(
                "?type=messages&pubkey={}",
                base32::encode(base32::Alphabet::RFC4648 { padding: false }, id.as_ref())
                    .to_lowercase()
            )
        })?
        .send()
        .await?;
    let status = res.status();
    if !status.is_success() {
        failure::bail!("{}", status.canonical_reason().unwrap_or("UNKNOWN STATUS"));
    }
    let mut b = std::io::Cursor::new(res.bytes().await?);

    loop {
        let mut buf = [0];
        match b.read_exact(&mut buf) {
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
            a => a?,
        };
        let inbound = buf[0] != 0;
        let mut buf = [0; 8];
        b.read_exact(&mut buf)?;
        let time = i64::from_be_bytes(buf);
        let mut buf = [0; 8];
        b.read_exact(&mut buf)?;
        let len = u64::from_be_bytes(buf);
        let mut buf = vec![0; len as usize];
        b.read_exact(&mut buf)?;
        msgs.push(Message {
            inbound,
            time,
            content: String::from_utf8(buf)?,
        });
    }

    Ok(msgs)
}

pub async fn send_message(creds: &Creds, id: &[u8; 32], content: &str) -> Result<(), Error> {
    let mut req = Vec::new();
    req.push(0);
    req.extend_from_slice(id);
    req.extend_from_slice(content.as_bytes());
    let status = creds.post(req)?.send().await?.status();
    if !status.is_success() {
        failure::bail!(
            "{}",
            status.canonical_reason().unwrap_or("UNKNOWN STATUS CODE")
        );
    }
    Ok(())
}