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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use std::cmp::min;
use std::convert::TryInto;
use std::fs::File;
use std::io::prelude::*;
use std::io::{Error, ErrorKind, Result};
use std::net::{Shutdown, TcpStream};
use std::time::{SystemTime, UNIX_EPOCH};
use sha2::Digest;
type Hash = [u8; 32];
pub struct Talker {
s: TcpStream,
queue: Option<u8>,
closed: bool,
pub chat_close: Option<Box<dyn Fn() + Send>>,
pub msg_new: Option<Box<dyn Fn(String) + Send>>,
pub file_incoming: Box<dyn Fn(usize) -> bool + Send>,
pub file_failed: Option<Box<dyn Fn(String, Error) + Send>>,
pub file_complete: Option<Box<dyn Fn(String) + Send>>,
pub file_hash_by_peer: Option<Box<dyn Fn(String, Hash) + Send>>,
pub file_our_hash: Option<Box<dyn Fn(String, Hash) + Send>>,
pub hash_of_sent: Option<Box<dyn Fn(Hash) + Send>>,
pub hash_rcvd: Option<Box<dyn Fn(Hash) + Send>>,
pub payload_too_large: Option<Box<dyn Fn(usize) + Send>>,
pub invalid_instr: Option<Box<dyn Fn(u8) + Send>>,
}
impl Talker {
pub fn new(s: TcpStream) -> Self {
Talker {
s,
queue: None,
closed: false,
chat_close: None,
msg_new: None,
file_incoming: Box::new(|_| false),
file_failed: None,
file_complete: None,
file_hash_by_peer: None,
file_our_hash: None,
hash_of_sent: None,
hash_rcvd: None,
invalid_instr: None,
payload_too_large: None,
}
}
pub fn close(&mut self) -> Result<()> {
if self.closed {
return Ok(());
} else if let Some(ref f) = self.chat_close {
f();
self.closed = true;
}
self.s.shutdown(Shutdown::Both)
}
pub fn expect_handshake(&mut self) -> Result<()> {
let mut buf = [0; 8];
self.s.read_exact(&mut buf)?;
if &buf == b"/talkers" {
Ok(())
} else {
Err(Error::new(ErrorKind::InvalidData, "Invalid handshake"))
}
}
pub fn perform_handshake(&mut self) -> Result<()> {
self.s.write_all(b"/talkers")
}
pub fn read_once(&mut self) -> Result<bool> {
let mut instr = [0; 1];
if let Some(ch) = self.queue {
instr[0] = ch;
} else {
let n = match self.s.read(&mut instr[0..1]) {
Ok(m) => m,
Err(e) => match e.kind() {
ErrorKind::WouldBlock => return Ok(false),
_ => return Err(e),
},
};
if n == 0 {
return Err(Error::new(
ErrorKind::NotConnected,
"Lost connection with peer",
));
}
}
let instr = instr[0];
let mut msg = Vec::new();
let mut is_file = false;
let mut skip = true;
let mut hasher = sha2::Sha256::new();
let mut fp;
fp = None;
if instr == 33 || instr == 35 {
if instr == 35 {
is_file = true;
}
let mut n_bytes = 0;
let mut j = 1;
self.s
.set_nonblocking(false)
.expect("Could not set TcpStream to blocking");
let mut ch = self.s.try_clone()?.bytes();
let mut filen = String::new();
loop {
if let Some(Ok(ch)) = ch.next() {
if (ch >= 48 && ch <= 57) || ch == 10 || ch == 32 {
if ch == 10 || ch == 32 {
skip = false;
break;
} else {
n_bytes *= 10;
n_bytes += usize::from(ch - 48);
}
} else {
break;
}
}
j += 1;
if j >= 16 {
break;
}
}
if !skip && is_file {
skip = !(self.file_incoming)(n_bytes);
}
if !skip && is_file {
filen = format!(
"transfer_{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
);
if let Ok(f) = File::create(&filen) {
fp = Some(f);
} else if let Some(ref f) = self.file_failed {
f(
filen.clone(),
Error::new(ErrorKind::PermissionDenied, "Could not open transfer file"),
);
}
let mut buf = [0; 1024];
while let Ok(()) = self.s.read_exact(&mut buf[..min(n_bytes, 1024)]) {
let n = min(n_bytes, 1024);
n_bytes -= n;
if is_file {
if let Some(ref mut fp) = fp {
if fp.write_all(&buf[..n]).is_err() {
if let Some(ref f) = self.file_failed {
f(
filen.clone(),
Error::new(
ErrorKind::PermissionDenied,
"Could not write to transfer file",
),
);
}
}
}
hasher.update(&buf[..n]);
}
if n_bytes == 0 {
break;
}
}
if let Some(ref f) = self.file_complete {
f(filen.clone());
}
if let Ok(()) = self.s.read_exact(&mut buf[..33]) {
if let Some(ref f) = self.file_hash_by_peer {
f(filen.clone(), buf[1..33].try_into().unwrap());
}
}
} else if !skip && !is_file {
if n_bytes <= 1024 * 1024 {
msg.resize(n_bytes, 0);
if let Ok(()) = self.s.read_exact(&mut msg[..n_bytes]) {
hasher.update(&msg);
if let Some(ref f) = &self.msg_new {
f(String::from_utf8_lossy(&msg).into_owned());
}
msg.clear();
}
} else {
if let Some(ref f) = &self.payload_too_large {
f(n_bytes);
}
}
}
let mut entire_hash = vec![61];
entire_hash.extend_from_slice(&hasher.finalize());
self.s
.write_all(&entire_hash)
.expect("Could not send hash to peer");
if is_file {
if let Some(ref f) = &self.file_our_hash {
f(filen, entire_hash[1..].try_into().unwrap());
}
}
return Ok(true);
} else if let Some(ref f) = &self.invalid_instr {
f(instr);
}
Ok(false)
}
pub fn read_maybe(&mut self) -> Result<bool> {
self.s.set_nonblocking(true)?;
let ret = self.read_once();
self.s.set_nonblocking(false)?;
ret
}
pub fn send(&mut self, msg: &str) -> Result<()> {
let mut hasher = sha2::Sha256::new();
self.s.write_all(format!("!{}\n", msg.len()).as_bytes())?;
self.s.write_all(msg.as_bytes())?;
hasher.update(msg.as_bytes());
if let Some(ref f) = self.hash_of_sent {
f(hasher.finalize().try_into().unwrap());
}
Ok(())
}
pub fn send_stream<T, U>(&mut self, stream: &mut T, len: U) -> Result<()>
where
T: Read,
U: std::fmt::Display,
{
let mut hasher = sha2::Sha256::new();
let mut buf = [0; 1024];
self.s.write_all(format!("#{}\n", len).as_bytes())?;
while let Ok(n) = stream.read(&mut buf) {
if n == 0 {
break;
}
self.s.write_all(&buf[..n])?;
hasher.update(&buf[..n]);
}
let mut entire_hash = vec![61];
entire_hash.extend_from_slice(&hasher.finalize());
self.s.write_all(&entire_hash)?;
if let Some(ref f) = self.hash_of_sent {
f(entire_hash[1..].try_into().unwrap());
}
Ok(())
}
pub fn expect_hash(&mut self) -> Result<()> {
self.s.set_nonblocking(false)?;
let mut buf = [0; 33];
if let Ok(()) = self.s.read_exact(&mut buf[..1]) {
if buf[0] == b'=' {
self.s.read_exact(&mut buf[1..])?;
if let Some(ref f) = self.hash_rcvd {
f(buf[1..33].try_into().unwrap());
}
return Ok(());
} else {
self.queue = Some(buf[0] as u8);
}
}
Err(Error::new(ErrorKind::Other, "No hash transmitted"))
}
}