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
#![allow(clippy::block_in_if_condition_stmt)]
use file_protocol::{FileProtocol, FileProtocolConfig, ProtocolError, State};
use kubos_system::Config as ServiceConfig;
use log::{error, info, warn};
use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
pub fn recv_loop(config: &ServiceConfig) -> Result<(), failure::Error> {
let host = config
.hosturl()
.ok_or_else(|| failure::format_err!("Unable to fetch addr for service"))?;
let mut host_parts = host.split(':').map(|val| val.to_owned());
let host_ip = host_parts
.next()
.ok_or_else(|| failure::format_err!("Failed to parse service IP address"))?;
let prefix = match config.get("storage_dir") {
Some(val) => val.as_str().map(|str| str.to_owned()),
None => None,
};
let transfer_chunk_size = match config.get("transfer_chunk_size") {
Some(val) => val.as_integer().unwrap_or(1024),
None => 1024,
};
let hash_chunk_size = match config.get("hash_chunk_size") {
Some(val) => val.as_integer().unwrap_or(transfer_chunk_size * 2),
None => transfer_chunk_size * 2,
} as usize;
let transfer_chunk_size = transfer_chunk_size as usize;
let hold_count = match config.get("hold_count") {
Some(val) => val.as_integer().unwrap_or(5),
None => 5,
} as u16;
let downlink_port = config
.get("downlink_port")
.and_then(|i| i.as_integer())
.unwrap_or(8080) as u16;
let downlink_ip = match config.get("downlink_ip") {
Some(ip) => match ip.as_str().map(|ip| ip.to_owned()) {
Some(ip) => ip,
None => "127.0.0.1".to_owned(),
},
None => "127.0.0.1".to_owned(),
};
let inter_chunk_delay = config
.get("inter_chunk_delay")
.and_then(|i| i.as_integer())
.unwrap_or(1) as u64;
let max_chunks_transmit = config
.get("max_chunks_transmit")
.and_then(|chunks| chunks.as_integer())
.map(|chunks| chunks as u32);
info!("Starting file transfer service");
info!("Listening on {}", host);
info!("Downlinking to {}:{}", downlink_ip, downlink_port);
info!("Transfer Chunk {}", transfer_chunk_size);
info!("Hash Chunk Size {}", hash_chunk_size);
let f_config = FileProtocolConfig::new(
prefix,
transfer_chunk_size,
hold_count,
inter_chunk_delay,
max_chunks_transmit,
hash_chunk_size,
);
let c_protocol = cbor_protocol::Protocol::new(&host.clone(), transfer_chunk_size);
let timeout = config
.get("timeout")
.and_then(|val| val.as_integer().map(|num| Duration::from_secs(num as u64)))
.unwrap_or(Duration::from_secs(2));
let raw_threads: HashMap<u32, Sender<serde_cbor::Value>> = HashMap::new();
let threads = Arc::new(Mutex::new(raw_threads));
loop {
let (_source, first_message) = match c_protocol.recv_message_peer() {
Ok((source, first_message)) => (source, first_message),
Err(e) => {
warn!("Error receiving message: {:?}", e);
continue;
}
};
let config_ref = f_config.clone();
let host_ref = host_ip.clone();
let timeout_ref = timeout;
let channel_id = match file_protocol::parse_channel_id(&first_message) {
Ok(channel_id) => channel_id,
Err(e) => {
warn!("Error parsing channel ID: {:?}", e);
continue;
}
};
if !threads
.lock()
.map_err(|err| {
error!("Failed to get threads mutex: {:?}", err);
err
})
.unwrap()
.contains_key(&channel_id)
{
let (sender, receiver): (Sender<serde_cbor::Value>, Receiver<serde_cbor::Value>) =
mpsc::channel();
threads
.lock()
.map_err(|err| {
error!("Failed to get threads mutex: {:?}", err);
err
})
.unwrap()
.insert(channel_id, sender.clone());
let shared_threads = threads.clone();
let downlink_ip_ref = downlink_ip.to_owned();
thread::spawn(move || {
let state = State::Holding {
count: 0,
prev_state: Box::new(State::Done),
};
let f_protocol = FileProtocol::new(
&format!("{}:{}", host_ref, 0),
&format!("{}:{}", downlink_ip_ref, downlink_port),
config_ref,
);
if let Err(e) = f_protocol.message_engine(
|d| match receiver.recv_timeout(d) {
Ok(v) => Ok(v),
Err(RecvTimeoutError::Timeout) => Err(ProtocolError::ReceiveTimeout),
Err(e) => Err(ProtocolError::ReceiveError {
err: format!("Error {:?}", e),
}),
},
timeout_ref,
&state,
) {
warn!("Encountered errors while processing transaction: {}", e);
}
shared_threads
.lock()
.map_err(|err| {
error!("Failed to get threads mutex: {:?}", err);
err
})
.unwrap()
.remove(&channel_id);
});
}
if let Some(sender) = threads
.lock()
.map_err(|err| {
error!("Failed to get threads mutex: {:?}", err);
err
})
.unwrap()
.get(&channel_id)
{
if let Err(e) = sender.send(first_message) {
warn!("Error when sending to channel {}: {:?}", channel_id, e);
}
}
if !threads
.lock()
.map_err(|err| {
error!("Failed to get threads mutex: {:?}", err);
err
})
.unwrap()
.contains_key(&channel_id)
{
warn!("No sender found for {}", channel_id);
threads
.lock()
.map_err(|err| {
error!("Failed to get threads mutex: {:?}", err);
err
})
.unwrap()
.remove(&channel_id);
}
}
}