Debian Codegraph @

src/v4.rs

raw symbols SCIP
1 use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
2 use std::io::{self, Read, Write};
3 use std::net::{SocketAddr, ToSocketAddrs, SocketAddrV4, SocketAddrV6, TcpStream, Ipv4Addr};
4
5 use {ToTargetAddr, TargetAddr};
6
7 fn read_response(socket: &mut TcpStream) -> io::Result<SocketAddrV4> {
8 let mut response = [0u8; 8];
9 socket.read_exact(&mut response)?;
10 let mut response = &response[..];
11
12 if response.read_u8()? != 0 {
13 return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid response version"));
14 }
15
16 match response.read_u8()? {
17 90 => {}
18 91 => return Err(io::Error::new(io::ErrorKind::Other, "request rejected or failed")),
19 92 => {
20 return Err(io::Error::new(io::ErrorKind::PermissionDenied,
21 "request rejected because SOCKS server cannot connect to \
22 idnetd on the client"))
23 }
24 93 => {
25 return Err(io::Error::new(io::ErrorKind::PermissionDenied,
26 "request rejected because the client program and identd \
27 report different user-ids"))
28 }
29 _ => return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid response code")),
30 }
31
32 let port = response.read_u16::<BigEndian>()?;
33 let ip = Ipv4Addr::from(response.read_u32::<BigEndian>()?);
34
35 Ok(SocketAddrV4::new(ip, port))
36 }
37
38 /// A SOCKS4 client.
39 #[derive(Debug)]
40 pub struct Socks4Stream {
41 socket: TcpStream,
42 proxy_addr: SocketAddrV4,
43 }
44
45 impl Socks4Stream {
46 /// Connects to a target server through a SOCKS4 proxy.
47 ///
48 /// # Note
49 ///
50 /// If `target` is a `TargetAddr::Domain`, the domain name will be forwarded
51 /// to the proxy server using the SOCKS4A protocol extension. If the proxy
52 /// server does not support SOCKS4A, consider performing the DNS lookup
53 /// locally and passing a `TargetAddr::Ip`.
54 pub fn connect<T, U>(proxy: T, target: U, userid: &str) -> io::Result<Socks4Stream>
55 where T: ToSocketAddrs,
56 U: ToTargetAddr
57 {
58 Self::connect_raw(1, proxy, target, userid)
59 }
60
61 fn connect_raw<T, U>(command: u8, proxy: T, target: U, userid: &str) -> io::Result<Socks4Stream>
62 where T: ToSocketAddrs,
63 U: ToTargetAddr
64 {
65 let mut socket = TcpStream::connect(proxy)?;
66
67 let target = target.to_target_addr()?;
68
69 let mut packet = vec![];
70 let _ = packet.write_u8(4); // version
71 let _ = packet.write_u8(command); // command code
72 match target.to_target_addr()? {
73 TargetAddr::Ip(addr) => {
74 let addr = match addr {
75 SocketAddr::V4(addr) => addr,
76 SocketAddr::V6(_) => {
77 return Err(io::Error::new(io::ErrorKind::InvalidInput,
78 "SOCKS4 does not support IPv6"));
79 }
80 };
81 let _ = packet.write_u16::<BigEndian>(addr.port());
82 let _ = packet.write_u32::<BigEndian>((*addr.ip()).into());
83 let _ = packet.write_all(userid.as_bytes());
84 let _ = packet.write_u8(0);
85 }
86 TargetAddr::Domain(ref host, port) => {
87 let _ = packet.write_u16::<BigEndian>(port);
88 let _ = packet.write_u32::<BigEndian>(Ipv4Addr::new(0, 0, 0, 1).into());
89 let _ = packet.write_all(userid.as_bytes());
90 let _ = packet.write_u8(0);
91 let _ = packet.extend(host.as_bytes());
92 let _ = packet.write_u8(0);
93 }
94 }
95
96 socket.write_all(&packet)?;
97 let proxy_addr = read_response(&mut socket)?;
98
99 Ok(Socks4Stream {
100 socket: socket,
101 proxy_addr: proxy_addr,
102 })
103 }
104
105 /// Returns the proxy-side address of the connection between the proxy and
106 /// target server.
107 pub fn proxy_addr(&self) -> SocketAddrV4 {
108 self.proxy_addr
109 }
110
111 /// Returns a shared reference to the inner `TcpStream`.
112 pub fn get_ref(&self) -> &TcpStream {
113 &self.socket
114 }
115
116 /// Returns a mutable reference to the inner `TcpStream`.
117 pub fn get_mut(&mut self) -> &mut TcpStream {
118 &mut self.socket
119 }
120
121 /// Consumes the `Socks4Stream`, returning the inner `TcpStream`.
122 pub fn into_inner(self) -> TcpStream {
123 self.socket
124 }
125 }
126
127 impl Read for Socks4Stream {
128 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
129 self.socket.read(buf)
130 }
131 }
132
133 impl<'a> Read for &'a Socks4Stream {
134 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
135 (&self.socket).read(buf)
136 }
137 }
138
139 impl Write for Socks4Stream {
140 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
141 self.socket.write(buf)
142 }
143
144 fn flush(&mut self) -> io::Result<()> {
145 self.socket.flush()
146 }
147 }
148
149 impl<'a> Write for &'a Socks4Stream {
150 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
151 (&self.socket).write(buf)
152 }
153
154 fn flush(&mut self) -> io::Result<()> {
155 (&self.socket).flush()
156 }
157 }
158
159 /// A SOCKS4 BIND client.
160 #[derive(Debug)]
161 pub struct Socks4Listener(Socks4Stream);
162
163 impl Socks4Listener {
164 /// Initiates a BIND request to the specified proxy.
165 ///
166 /// The proxy will filter incoming connections based on the value of
167 /// `target`.
168 pub fn bind<T, U>(proxy: T, target: U, userid: &str) -> io::Result<Socks4Listener>
169 where T: ToSocketAddrs,
170 U: ToTargetAddr
171 {
172 Socks4Stream::connect_raw(2, proxy, target, userid).map(Socks4Listener)
173 }
174
175 /// The address of the proxy-side TCP listener.
176 ///
177 /// This should be forwarded to the remote process, which should open a
178 /// connection to it.
179 pub fn proxy_addr(&self) -> io::Result<SocketAddr> {
180 if self.0.proxy_addr.ip().octets() != [0, 0, 0, 0] {
181 Ok(SocketAddr::V4(self.0.proxy_addr()))
182 } else {
183 let port = self.0.proxy_addr.port();
184 let peer = match self.0.socket.peer_addr()? {
185 SocketAddr::V4(addr) => SocketAddr::V4(SocketAddrV4::new(*addr.ip(), port)),
186 SocketAddr::V6(addr) => SocketAddr::V6(SocketAddrV6::new(*addr.ip(), port, 0, 0)),
187 };
188 Ok(peer)
189 }
190 }
191
192 /// Waits for the remote process to connect to the proxy server.
193 ///
194 /// The value of `proxy_addr` should be forwarded to the remote process
195 /// before this method is called.
196 pub fn accept(mut self) -> io::Result<Socks4Stream> {
197 self.0.proxy_addr = read_response(&mut self.0.socket)?;
198 Ok(self.0)
199 }
200 }
201
202 #[cfg(test)]
203 mod test {
204 use std::io::{Read, Write};
205 use std::net::{SocketAddr, SocketAddrV4, ToSocketAddrs, TcpStream};
206
207 use super::*;
208
209 fn google_ip() -> SocketAddrV4 {
210 "google.com:80"
211 .to_socket_addrs()
212 .unwrap()
213 .filter_map(|a| {
214 match a {
215 SocketAddr::V4(a) => Some(a),
216 SocketAddr::V6(_) => None,
217 }
218 })
219 .next()
220 .unwrap()
221 }
222
223 #[test]
224 fn google() {
225 let mut socket = Socks4Stream::connect("127.0.0.1:1080", google_ip(), "").unwrap();
226
227 socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
228 let mut result = vec![];
229 socket.read_to_end(&mut result).unwrap();
230
231 println!("{}", String::from_utf8_lossy(&result));
232 assert!(result.starts_with(b"HTTP/1.0"));
233 assert!(result.ends_with(b"</HTML>\r\n") || result.ends_with(b"</html>"));
234 }
235
236 #[test]
237 #[ignore] // dante doesn't support SOCKS4A
238 fn google_dns() {
239 let mut socket = Socks4Stream::connect("127.0.0.1:8080", "google.com:80", "").unwrap();
240
241 socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
242 let mut result = vec![];
243 socket.read_to_end(&mut result).unwrap();
244
245 println!("{}", String::from_utf8_lossy(&result));
246 assert!(result.starts_with(b"HTTP/1.0"));
247 assert!(result.ends_with(b"</HTML>\r\n") || result.ends_with(b"</html>"));
248 }
249
250 #[test]
251 fn bind() {
252 // First figure out our local address that we'll be connecting from
253 let socket = Socks4Stream::connect("127.0.0.1:1080", google_ip(), "").unwrap();
254 let addr = socket.proxy_addr();
255
256 let listener = Socks4Listener::bind("127.0.0.1:1080", addr, "").unwrap();
257 let addr = listener.proxy_addr().unwrap();
258 let mut end = TcpStream::connect(addr).unwrap();
259 let mut conn = listener.accept().unwrap();
260 conn.write_all(b"hello world").unwrap();
261 drop(conn);
262 let mut result = vec![];
263 end.read_to_end(&mut result).unwrap();
264 assert_eq!(result, b"hello world");
265 }
266 }