/
mod.rs
432 lines (367 loc) · 15.4 KB
/
mod.rs
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::{
io::{self, ErrorKind},
mem,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream as StdTcpStream},
ops::{Deref, DerefMut},
os::unix::io::{AsRawFd, FromRawFd, IntoRawFd},
pin::Pin,
sync::atomic::{AtomicBool, Ordering},
task::{self, Poll},
};
use cfg_if::cfg_if;
use futures::ready;
use log::error;
use pin_project::pin_project;
use socket2::SockAddr;
use tokio::{
io::{AsyncRead, AsyncWrite, ReadBuf},
net::{TcpSocket, TcpStream as TokioTcpStream, UdpSocket},
};
use crate::net::{
sys::{set_common_sockopt_after_connect, set_common_sockopt_for_connect},
AddrFamily,
ConnectOpts,
};
enum TcpStreamState {
Connected,
FastOpenConnect(SocketAddr),
FastOpenWrite,
FastOpenConnecting,
}
/// A `TcpStream` that supports TFO (TCP Fast Open)
#[pin_project(project = TcpStreamProj)]
pub struct TcpStream {
#[pin]
inner: TokioTcpStream,
state: TcpStreamState,
}
impl TcpStream {
pub async fn connect(addr: SocketAddr, opts: &ConnectOpts) -> io::Result<TcpStream> {
let socket = match addr {
SocketAddr::V4(..) => TcpSocket::new_v4()?,
SocketAddr::V6(..) => TcpSocket::new_v6()?,
};
// Any traffic to localhost should not be protected
// This is a workaround for VPNService
#[cfg(target_os = "android")]
if !addr.ip().is_loopback() {
use std::time::Duration;
use tokio::time;
if let Some(ref path) = opts.vpn_protect_path {
// RPC calls to `VpnService.protect()`
// Timeout in 3 seconds like shadowsocks-libev
match time::timeout(Duration::from_secs(3), vpn_protect(path, socket.as_raw_fd())).await {
Ok(Ok(..)) => {}
Ok(Err(err)) => return Err(err),
Err(..) => return Err(io::Error::new(ErrorKind::TimedOut, "protect() timeout")),
}
}
}
// Set SO_MARK for mark-based routing on Linux (since 2.6.25)
// NOTE: This will require CAP_NET_ADMIN capability (root in most cases)
if let Some(mark) = opts.fwmark {
let ret = unsafe {
libc::setsockopt(
socket.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_MARK,
&mark as *const _ as *const _,
mem::size_of_val(&mark) as libc::socklen_t,
)
};
if ret != 0 {
let err = io::Error::last_os_error();
error!("set SO_MARK error: {}", err);
return Err(err);
}
}
// Set SO_BINDTODEVICE for binding to a specific interface
if let Some(ref iface) = opts.bind_interface {
set_bindtodevice(&socket, iface)?;
}
set_common_sockopt_for_connect(addr, &socket, opts)?;
if !opts.tcp.fastopen {
// If TFO is not enabled, it just works like a normal TcpStream
let stream = socket.connect(addr).await?;
set_common_sockopt_after_connect(&stream, opts)?;
return Ok(TcpStream {
inner: stream,
state: TcpStreamState::Connected,
});
}
let mut connected = false;
// TFO in Linux was supported since 3.7
//
// But TCP_FASTOPEN_CONNECT was supported since 4.1, so we have to be compatible with it
static SUPPORT_TCP_FASTOPEN_CONNECT: AtomicBool = AtomicBool::new(true);
if SUPPORT_TCP_FASTOPEN_CONNECT.load(Ordering::Relaxed) {
unsafe {
let enable: libc::c_int = 1;
let ret = libc::setsockopt(
socket.as_raw_fd(),
libc::IPPROTO_TCP,
libc::TCP_FASTOPEN_CONNECT,
&enable as *const _ as *const libc::c_void,
mem::size_of_val(&enable) as libc::socklen_t,
);
if ret != 0 {
let err = io::Error::last_os_error();
if let Some(libc::ENOPROTOOPT) = err.raw_os_error() {
// `TCP_FASTOPEN_CONNECT` is not supported, maybe kernel version < 4.11
// Fallback to `sendto` with `MSG_FASTOPEN` (Supported after 3.7)
SUPPORT_TCP_FASTOPEN_CONNECT.store(false, Ordering::Relaxed);
} else {
error!("set TCP_FASTOPEN_CONNECT error: {}", err);
return Err(err);
}
} else {
connected = true;
}
}
}
let stream = if connected {
// call connect() if TCP_FASTOPEN_CONNECT is set
socket.connect(addr).await?
} else {
// call sendto() with MSG_FASTOPEN in poll_read
TokioTcpStream::from_std(unsafe { StdTcpStream::from_raw_fd(socket.into_raw_fd()) })?
};
set_common_sockopt_after_connect(&stream, opts)?;
Ok(TcpStream {
inner: stream,
state: if connected {
TcpStreamState::FastOpenWrite
} else {
TcpStreamState::FastOpenConnect(addr)
},
})
}
}
impl Deref for TcpStream {
type Target = TokioTcpStream;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for TcpStream {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl AsyncRead for TcpStream {
fn poll_read(self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
self.project().inner.poll_read(cx, buf)
}
}
impl AsyncWrite for TcpStream {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
loop {
let this = self.as_mut().project();
match this.state {
TcpStreamState::FastOpenConnect(addr) => {
// Fallback mode. Must be kernal < 4.11
//
// Uses sendto as BSD-like systems
let TcpStreamProj { inner, state } = this;
let stream = inner.get_mut();
let n = ready!(stream.poll_write_io(cx, || {
unsafe {
let saddr = SockAddr::from(*addr);
let ret = libc::sendto(
stream.as_raw_fd(),
buf.as_ptr() as *const libc::c_void,
buf.len(),
libc::MSG_FASTOPEN,
saddr.as_ptr(),
saddr.len(),
);
if ret >= 0 {
Ok(ret as usize)
} else {
// Error occurs
let err = io::Error::last_os_error();
// EINPROGRESS
if let Some(libc::EINPROGRESS) = err.raw_os_error() {
// For non-blocking socket, it returns the number of bytes queued (and transmitted in the SYN-data packet) if cookie is available.
// If cookie is not available, it transmits a data-less SYN packet with Fast Open cookie request option and returns -EINPROGRESS like connect().
//
// So in this state. We have to loop again to call `poll_write` for sending the first packet.
*state = TcpStreamState::FastOpenConnecting;
// Let `try_write_io` clears the write readiness.
Err(ErrorKind::WouldBlock.into())
} else {
// Other errors, including EAGAIN, EWOULDBLOCK
Err(err)
}
}
}
}))?;
// Connect successfully with fast open
*state = TcpStreamState::Connected;
return Ok(n).into();
}
TcpStreamState::FastOpenWrite => {
// First `write` after `TCP_FASTOPEN_CONNECT`
// Kernel >= 4.11
let n = ready!(this.inner.get_mut().poll_write_io(cx, || {
unsafe {
let ret = libc::send(
this.inner.as_raw_fd(),
buf.as_ptr() as *const libc::c_void,
buf.len(),
0,
);
if ret >= 0 {
Ok(ret as usize)
} else {
let err = io::Error::last_os_error();
// EINPROGRESS
if let Some(libc::EINPROGRESS) = err.raw_os_error() {
// For non-blocking socket, it returns the number of bytes queued (and transmitted in the SYN-data packet) if cookie is available.
// If cookie is not available, it transmits a data-less SYN packet with Fast Open cookie request option and returns -EINPROGRESS like connect().
//
// So in this state. We have to loop again to call `poll_write` for sending the first packet.
*(this.state) = TcpStreamState::FastOpenConnecting;
// Let `poll_write_io` clears the write readiness.
Err(ErrorKind::WouldBlock.into())
} else {
// Other errors, including EAGAIN, EWOULDBLOCK
Err(err)
}
}
}
}))?;
// Connect successfully with fast open
*(this.state) = TcpStreamState::Connected;
return Ok(n).into();
}
TcpStreamState::FastOpenConnecting => {
ready!(this.inner.poll_write_ready(cx))?;
*(this.state) = TcpStreamState::Connected;
}
TcpStreamState::Connected => return this.inner.poll_write(cx, buf),
}
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
self.project().inner.poll_shutdown(cx)
}
}
/// Enable `TCP_FASTOPEN`
///
/// `TCP_FASTOPEN` was supported since Linux 3.7
pub fn set_tcp_fastopen<S: AsRawFd>(socket: &S) -> io::Result<()> {
let queue: libc::c_int = 5;
unsafe {
let ret = libc::setsockopt(
socket.as_raw_fd(),
libc::IPPROTO_TCP,
libc::TCP_FASTOPEN,
&queue as *const _ as *const libc::c_void,
mem::size_of_val(&queue) as libc::socklen_t,
);
if ret != 0 {
let err = io::Error::last_os_error();
error!("set TCP_FASTOPEN error: {}", err);
return Err(err);
}
}
Ok(())
}
/// Create a `UdpSocket` for connecting to `addr`
pub async fn create_outbound_udp_socket(af: AddrFamily, config: &ConnectOpts) -> io::Result<UdpSocket> {
let bind_addr = match (af, config.bind_local_addr) {
(AddrFamily::Ipv4, Some(IpAddr::V4(ip))) => SocketAddr::new(ip.into(), 0),
(AddrFamily::Ipv6, Some(IpAddr::V6(ip))) => SocketAddr::new(ip.into(), 0),
(AddrFamily::Ipv4, ..) => SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0),
(AddrFamily::Ipv6, ..) => SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0),
};
let socket = UdpSocket::bind(bind_addr).await?;
// Any traffic except localhost should be protected
// This is a workaround for VPNService
#[cfg(target_os = "android")]
{
use std::time::Duration;
use tokio::time;
if let Some(ref path) = config.vpn_protect_path {
// RPC calls to `VpnService.protect()`
// Timeout in 3 seconds like shadowsocks-libev
match time::timeout(Duration::from_secs(3), vpn_protect(path, socket.as_raw_fd())).await {
Ok(Ok(..)) => {}
Ok(Err(err)) => return Err(err),
Err(..) => return Err(io::Error::new(ErrorKind::TimedOut, "protect() timeout")),
}
}
}
// Set SO_MARK for mark-based routing on Linux (since 2.6.25)
// NOTE: This will require CAP_NET_ADMIN capability (root in most cases)
if let Some(mark) = config.fwmark {
let ret = unsafe {
libc::setsockopt(
socket.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_MARK,
&mark as *const _ as *const _,
mem::size_of_val(&mark) as libc::socklen_t,
)
};
if ret != 0 {
let err = io::Error::last_os_error();
error!("set SO_MARK error: {}", err);
return Err(err);
}
}
// Set SO_BINDTODEVICE for binding to a specific interface
if let Some(ref iface) = config.bind_interface {
set_bindtodevice(&socket, iface)?;
}
Ok(socket)
}
fn set_bindtodevice<S: AsRawFd>(socket: &S, iface: &str) -> io::Result<()> {
let iface_bytes = iface.as_bytes();
unsafe {
let ret = libc::setsockopt(
socket.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_BINDTODEVICE,
iface_bytes.as_ptr() as *const _ as *const libc::c_void,
iface_bytes.len() as libc::socklen_t,
);
if ret != 0 {
let err = io::Error::last_os_error();
error!("set SO_BINDTODEVICE error: {}", err);
return Err(err);
}
}
Ok(())
}
cfg_if! {
if #[cfg(target_os = "android")] {
use std::path::Path;
use std::os::unix::io::RawFd;
mod uds;
/// This is a RPC for Android to `protect()` socket for connecting to remote servers
///
/// https://developer.android.com/reference/android/net/VpnService#protect(java.net.Socket)
///
/// More detail could be found in [shadowsocks-android](https://github.com/shadowsocks/shadowsocks-android) project.
async fn vpn_protect<P: AsRef<Path>>(protect_path: P, fd: RawFd) -> io::Result<()> {
use tokio::io::AsyncReadExt;
let mut stream = self::uds::UnixStream::connect(protect_path).await?;
// send fds
let dummy: [u8; 1] = [1];
let fds: [RawFd; 1] = [fd];
stream.send_with_fd(&dummy, &fds).await?;
// receive the return value
let mut response = [0; 1];
stream.read_exact(&mut response).await?;
if response[0] == 0xFF {
return Err(io::Error::new(ErrorKind::Other, "protect() failed"));
}
Ok(())
}
}
}