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
extern crate context;
extern crate mio;
extern crate slab;
extern crate native_tls;
extern crate rand;
extern crate byteorder;
extern crate libc;
#[macro_use(quick_error)]
extern crate quick_error;
#[cfg(test)]
#[macro_use]
extern crate matches;
#[cfg(target_os = "macos")]
extern crate core_foundation;
#[cfg(target_os = "macos")]
extern crate core_foundation_sys;
mod fiber;
mod runner;
#[allow(dead_code)]
mod wheel;
#[allow(dead_code)]
mod builder;
#[allow(dead_code)]
mod dns_parser;
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
#[allow(unused_variables)]
#[allow(non_snake_case)]
mod dns;
mod poller;
pub use runner::Runner;
pub use poller::Poller;
pub use fiber::{Fiber, FiberFn, FiberRef, SocketType};
#[cfg(test)]
mod tests {
extern crate rand;
use super::*;
use mio::net::{TcpStream,TcpListener};
use std::io::{Write,Read};
use std::time::{Duration};
use std::net::{SocketAddr,Ipv4Addr,IpAddr};
use std::str;
use native_tls::{TlsConnector};
use std::io;
#[derive(Clone)]
struct Param {
chosen: Option<String>,
is_https: bool,
proxy_client: bool,
http_hosts: Vec<String>,
https_hosts: Vec<String>,
}
#[derive(PartialEq)]
enum Resp<'a> {
Done,
Bytes(&'a[u8])
}
fn get_http(mut fiber: Fiber<Param,Resp>, p: Param) -> Option<Resp> {
let mut v = [0u8;2000];
let host = p.chosen.unwrap();
if p.is_https {
let connector = TlsConnector::builder().unwrap().build().unwrap();
fiber.tcp_tls_connect(connector, host.as_str()).unwrap();
fiber.socket_timeout(Some(Duration::from_millis(2000)));
} else {
fiber.socket_timeout(Some(Duration::from_millis(1000)));
};
let req = format!("GET / HTTP/1.1\r\nHost: {}\r\nConnection: keep-alive\r\nUser-Agent: test\r\n\r\n",host);
fiber.write(req.as_bytes()).expect("Can not write to socket");
loop {
match fiber.read(&mut v[..]) {
Ok(sz) => {
fiber.resp_chunk(Resp::Bytes(&v[0..sz]));
}
Err(e) => {
assert_eq!(e.kind(), io::ErrorKind::TimedOut);
break;
}
}
}
println!("Client fiber closing {}", p.proxy_client);
Some(Resp::Done)
}
fn rand_http_proxy(mut fiber: Fiber<Param,Resp>, p: Param) -> Option<Resp> {
fiber.socket_timeout(Some(Duration::from_millis(500)));
let chosen = rand::random::<usize>() % p.http_hosts.len();
let port = if rand::random::<u8>() % 2 == 0 { 80 } else { 443 };
let p1 = if port == 443 {
Param {
chosen: Some(p.https_hosts[chosen].clone()),
is_https: port == 443,
http_hosts: Vec::new(),
https_hosts: Vec::new(),
proxy_client: true,
}
} else {
Param {
chosen: Some(p.http_hosts[chosen].clone()),
is_https: port == 443,
http_hosts: Vec::new(),
https_hosts: Vec::new(),
proxy_client: true,
}
};
let addr = if let &Some(ref ch) = &p1.chosen {
ch.clone()
} else {
panic!("")
};
fiber.join_resolve_connect(addr.as_str(), SocketType::Tcp, port, Duration::from_millis(3000), get_http, p1).unwrap();
println!("Returning: {}{}", if port == 443 { "https://" } else { "http://" }, addr);
while let Some(resp) = fiber.get_child() {
if let Resp::Bytes(slice) = resp {
println!("Server got {}", slice.len());
fiber.write(slice);
}
}
println!("Server socket fiber closing");
None
}
fn sock_acceptor(fiber: Fiber<Param,Resp>, p: Param) -> Option<Resp> {
loop {
match fiber.accept_tcp() {
Ok((sock,_)) => {
fiber.new_tcp(sock,rand_http_proxy, p.clone()).unwrap();
}
_ => {
println!("Listen socket error");
break;
}
}
}
None
}
#[test]
fn http_proxy() {
rand::random::<u8>();
let p = Param {
chosen: None,
is_https: false,
proxy_client: false,
http_hosts: vec!["www.liquiddota.com".to_string(),"www.google.com".to_string(),
"www.sqlite.org".to_string(),"edition.cnn.com".to_string()],
https_hosts: vec!["www.reddit.com".to_string(), "www.google.com".to_string(),
"arstechnica.com".to_string(), "news.ycombinator.com".to_string()],
};
let poller:Poller = Poller::new(Some(4096*10)).unwrap();
let runner:Runner<Param,Resp> = Runner::new().unwrap();
let listener = TcpListener::bind(&"127.0.0.1:10000".parse().unwrap()).unwrap();
runner.new_listener(listener, sock_acceptor, p).unwrap();
let mut reqs_remain = 20;
for _ in 0..reqs_remain {
let p = Param {
chosen: Some("127.0.0.1:10000".to_string()),
is_https: false,
proxy_client: false,
http_hosts: Vec::new(),
https_hosts: Vec::new(),
};
let addr = IpAddr::V4(Ipv4Addr::new(127,0,0,1));
let client_sock = TcpStream::connect(&SocketAddr::new(addr, 10000)).unwrap();
runner.new_tcp(client_sock, get_http, p).unwrap();
}
while reqs_remain > 0 {
if !poller.poll(Duration::from_millis(10)) {
continue;
}
if !runner.run() {
continue;
}
while let Some(r) = runner.get_response() {
if Resp::Done == r {
reqs_remain -= 1;
println!("Finished executing, req_remain: {}", reqs_remain);
} else if let Resp::Bytes(slice) = r {
println!("Main stack got {} bytes", slice.len());
}
}
while let Some(_) = runner.get_fiber() {
}
}
println!("poll out");
}
}