### Example: bind_v4 using Socks4Listener Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Example usage of Socks4Listener::bind, bind_addr, and accept. The pattern mirrors test_bind_socks4 in tests/common/tokio_utils.rs. ```rust use tokio_socks::{tcp::Socks4Listener, Error}; async fn bind_v4() -> Result<(), Error> { let listener = Socks4Listener::bind("127.0.0.1:41081", ("192.168.1.10", 0)).await?; let addr = listener.bind_addr().to_owned(); // send to remote peer let accepted = listener.accept().await?; // completes when peer connects to addr Ok(()) } ``` -------------------------------- ### Example manifests with required features Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/configuration.md Example manifests from Cargo.toml. Each example requires specific feature combinations: chainproxy needs tokio, while socket and tor need both tokio and tor. ```toml [[example]] name = "chainproxy" required-features = ["tokio"] [[example]] name = "socket" required-features = ["tokio", "tor"] [[example]] name = "tor" required-features = ["tokio", "tor"] ``` -------------------------------- ### Socks5Listener bind example Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Example usage of Socks5Listener::bind, bind_addr, and accept. Note that listener.accept() must be awaited before/while the peer connects to bind_addr. The pattern mirrors test_bind in tests/common/tokio_utils.rs. ```rust use std::net::TcpStream as StdTcpStream; use std::io::{Write, Read}; use tokio_socks::{tcp::Socks5Listener, Error}; async fn bind_example() -> Result<(), Error> { let listener = Socks5Listener::bind("127.0.0.1:1080", ("peer.example.com", 0)).await?; let bind_addr = listener.bind_addr().to_owned(); // give this to the remote peer let peer_conn = listener.accept().await?; // resolves once the peer connects // peer_conn: Socks5Stream — use with tokio AsyncRead/AsyncWrite Ok(()) } ``` -------------------------------- ### Connect to SOCKS4 proxy example Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Example usage of Socks4Stream::connect to establish a SOCKS4 connection to a target through a proxy. The connection is used to write data. ```rust use tokio_socks::{tcp::Socks4Stream, Error}; async fn connect_v4() -> Result<(), Error> { let mut conn = Socks4Stream::connect("127.0.0.1:41081", "192.168.1.10:22").await?; conn.write_all(b"...").await?; Ok(()) } ``` -------------------------------- ### Connect to proxy and send request Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Example of using Socks5Stream::connect to establish a connection to a proxy and write data. The stream implements tokio AsyncWrite, allowing write_all to be used. ```rust use tokio_socks::{tcp::Socks5Stream, Error}; async fn fetch() -> Result<(), Error> { let mut conn = Socks5Stream::connect("127.0.0.1:9050", "example.onion:80").await?; conn.write_all(b"GET /\r\n\r\n").await?; // Socks5Stream is tokio AsyncWrite // read ... Ok(()) } ``` -------------------------------- ### connect_with_password_and_socket usage with UnixStream Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Example using connect_with_password_and_socket with a non-tokio UnixStream wrapped in Compat. Connects to a SOCKS5 proxy at /tmp/proxy.s and targets example.com:80. ```rust use tokio_socks::{io::Compat, tcp::Socks5Stream, Error}; use smol::net::unix::UnixStream; // non-tokio socket via Compat async fn auth_over_unix() -> Result<(), Error> { let socket = Compat::new(UnixStream::connect("/tmp/proxy.s").await.map_err(Error::Io)?); let conn = Socks5Stream::connect_with_password_and_socket(socket, ("example.com", 80), "u", "p").await?; Ok(()) } ``` -------------------------------- ### Catching errors in consumer code with explicit handling Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/errors.md Shows how to use the Error type with ? and match, including Display and Debug formatting, and automatic conversion from std::io::Error via #[from]. The example connects with SOCKS5 credentials and handles specific error variants. ```rust use tokio_socks::{tcp::Socks5Stream, Error}; async fn connect_with_explicit_handling() -> Result<(), Error> { let conn = match Socks5Stream::connect_with_password("127.0.0.1:1080", "example.com:80", "u", "p").await { Ok(c) => c, Err(e) => { eprintln!("{}", e); // Display message match e { Error::InvalidAuthValues(msg) => println!("bad credentials: {}", msg), Error::PasswordAuthFailure(c) => println!("server rejected auth (code {})", c), Error::ProxyServerUnreachable => println!("proxy down (all addrs tried)"), Error::InvalidTargetAddress(m) => println!("bad target: {}", m), other => println!("other: {:?}", other), } return Ok(()); } }; // use conn ... Ok(()) } // The `#[from]` attribute also enables automatic conversions: fn io_to_error(e: std::io::Error) -> Error { e.into() // Error::Io } ``` -------------------------------- ### connect_with_password: Authenticated SOCKS5 connection Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Connects to a SOCKS5 proxy with username/password authentication (RFC 1929). The method signature shows the parameters and constraints; the example demonstrates usage with a proxy address, target, and credentials. Username and password must have UTF-8 byte lengths between 1 and 255, otherwise `Error::InvalidAuthValues` is returned. ```rust pub async fn connect_with_password<'a, 't, P, T>( proxy: P, target: T, username: &'a str, password: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, ``` ```rust use tokio_socks::{tcp::Socks5Stream, Error}; async fn connect_authed() -> Result<(), Error> { let conn = Socks5Stream::connect_with_password("127.0.0.1:1080", "db.internal:5432", "app", "hunter2").await?; Ok(()) } ``` -------------------------------- ### connect_with_socket: Connect over a provided socket (chaining) Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Runs the no-auth `CONNECT` handshake over a caller-provided socket that is already connected to the proxy. Skips proxy address resolution, so there is no fallback list and the caller must handle unreachable proxy errors. The example chains two SOCKS5 connections by passing a `Socks5Stream` as the socket for the next hop. ```rust pub async fn connect_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t>, ``` ```rust use tokio::net::TcpStream; use tokio_socks::{tcp::Socks5Stream, Error}; async fn chain() -> Result<(), Error> { let first = TcpStream::connect("184.176.166.20:4145").await?; let second = Socks5Stream::connect_with_socket(first, "90.89.205.248:1080").await?; // chain hop 2 let mut conn = Socks5Stream::connect_with_socket(second, "duckduckgo.com:80").await?; Ok(()) } ``` -------------------------------- ### Error Handling Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/errors.md Documentation for handling errors in the tokio-socks library, including the Error type, its variants, and usage examples. ```APIDOC ## Error Handling in tokio-socks ### Description This section describes how to catch and handle errors returned by the tokio-socks library. The `Error` type implements `std::error::Error`, `Display`, and `Debug`, and can be used with `?`, `{}`, `{:?}`, and `Box`. ### Error Type - **`Error`** - The main error type for the library. It implements `std::error::Error`, `Display`, and `Debug`. ### Error Variants - **`Error::InvalidAuthValues(String)`** - Invalid authentication values provided. - **`Error::PasswordAuthFailure(u8)`** - Password authentication failed with the given code. - **`Error::ProxyServerUnreachable`** - The proxy server is unreachable (all addresses tried). - **`Error::InvalidTargetAddress(String)`** - The target address is invalid. - **`Error::Io(std::io::Error)`** - An I/O error occurred. Can be unwrapped with a `match` or `if let`. - **`Error::IdentdAuthFailure`** - SOCKS4-only failure: Identd authentication failed. - **`Error::InvalidUserIdAuthFailure`** - SOCKS4-only failure: Invalid user ID authentication. - **`Error::AuthorizationRequired`** - SOCKS5-only: Authorization required. - **`Error::NoAcceptableAuthMethods`** - SOCKS5-only: No acceptable authentication methods. - **`Error::UnknownAuthMethod`** - SOCKS5-only: Unknown authentication method. Note: This is also returned for any reply code outside `0x00..=0x08` in `receive_reply`. ### Usage Example ```rust use tokio_socks::{tcp::Socks5Stream, Error}; async fn connect_with_explicit_handling() -> Result<(), Error> { let conn = match Socks5Stream::connect_with_password("127.0.0.1:1080", "example.com:80", "u", "p").await { Ok(c) => c, Err(e) => { eprintln!("{}", e); // Display message match e { Error::InvalidAuthValues(msg) => println!("bad credentials: {}", msg), Error::PasswordAuthFailure(c) => println!("server rejected auth (code {})", c), Error::ProxyServerUnreachable => println!("proxy down (all addrs tried)"), Error::InvalidTargetAddress(m) => println!("bad target: {}", m), other => println!("other: {:?}", other), } return Ok(()); } }; // use conn ... Ok(()) } // The `#[from]` attribute also enables automatic conversions: fn io_to_error(e: std::io::Error) -> Error { e.into() // Error::Io } ``` ### Notes - `Error::Io` carries the underlying `std::io::Error`. - SOCKS4-only failures (`IdentdAuthFailure`, `InvalidUserIdAuthFailure`) only appear from the `tcp::socks4` module. - SOCKS5-only failures (`AuthorizationRequired`, `NoAcceptableAuthMethods`, `UnknownAuthMethod`, `PasswordAuthFailure`, `InvalidAuthValues`) only appear from the SOCKS5 handshake. ``` -------------------------------- ### Handle IntoTargetAddr conversion error for overlong domain Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/lib.md Demonstrates the conversion error when a target address domain exceeds 255 bytes. Calling into_target_addr() on such a string returns Error::InvalidTargetAddress with a message indicating an overlong domain. The example prints the rejection message and uses unreachable!() for the success case. ```rust use tokio_socks::{Error, IntoTargetAddr}; fn main() { // A domain longer than 255 bytes fails conversion: let long: String = format!("www.{}.com", "a".repeat(300)); match long.as_str().into_target_addr() { Err(Error::InvalidTargetAddress(msg)) => println!("rejected: {}", msg), // "overlong domain" _ => unreachable!(), } } ``` -------------------------------- ### accept method Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Consumes the listener, waits for the proxy's second BIND reply (after the peer connected), and returns the Socks5Stream carrying the accepted connection. Throws the same reply-parsing errors as connect, including Error::ConnectionRefused if the peer never connects within the server's timeout. ```rust pub async fn accept(mut self) -> Result> { // reads the second BIND reply (the rendezvous address) over the stored socket let target = connector.receive_reply(&mut self.inner.socket).await?; Ok(Socks5Stream { socket: self.inner.socket, target }) } ``` -------------------------------- ### Compat::new Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/io.md Documentation for the `Compat` wrapper type used to adapt `futures-io` sockets for use with `tokio_socks`. ```APIDOC ## Compat::new ### Description Wraps a `futures-io` socket (e.g., `smol::net::unix::UnixStream`) to make it compatible with `tokio_socks`'s `AsyncSocket` trait. This is needed when using sockets that implement `futures_io::AsyncRead` and `AsyncWrite` but not `tokio::io::AsyncRead` and `AsyncWrite`. ### Method `Compat::new` ### Parameters - **inner** (socket type) - Required - The `futures-io` socket to wrap. ### Return Value Returns a `Compat` wrapper that implements `futures_io::AsyncRead` and `AsyncWrite`. ### Example ```rust use smol::net::unix::UnixStream; use tokio_socks::{io::Compat, tcp::Socks5Stream, Error}; async fn connect_via_unix_socket() -> Result<(), Error> { let socket = Compat::new(UnixStream::connect("/tmp/proxy.s").await.map_err(Error::Io)?); let conn = Socks5Stream::connect_with_socket(socket, ("example.com", 80)).await?; // conn implements futures_io::AsyncRead + AsyncWrite Ok(()) } ``` ``` -------------------------------- ### accept method implementation Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Consumes the listener, waits for the second BIND reply, and returns the accepted Socks4Stream. Throws reply-parsing errors as connect, including InvalidResponseVersion if VN != 0, CD codes, and Io. ```rust pub async fn accept(mut self) -> Result> { // reads the second SOCKS4 reply (8 bytes: VN, CD, PORT, IP) over the stored socket let target = connector.receive_reply(&mut self.inner.socket).await?; Ok(Socks4Stream { socket: self.inner.socket, target }) } ``` -------------------------------- ### bind_with_password_and_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Sends a SOCKS5 BIND request with authentication using an existing socket. Returns a Socks5Listener. ```APIDOC ## bind_with_password_and_socket ### Description Sends a SOCKS5 BIND request with authentication using an existing socket. Returns a Socks5Listener. ### Method bind_with_password_and_socket ### Endpoint Socks5Listener::bind_with_password_and_socket ### Parameters #### Path Parameters - **socket** (S: AsyncSocket + Unpin) - Required - The socket to use for the BIND request. - **target** (T: IntoTargetAddr<'t>) - Required - The remote peer address expected to connect; the proxy only accepts connections matching it. - **username** (&'a str) - Required - Username for authentication. - **password** (&'a str) - Required - Password for authentication. ### Response #### Success Response (200) - **Result>** - The listener for the BIND operation. ### Error Handling Throws: as `connect` (same reply-code error mapping), e.g. `Error::ConnectionRefused`/`Error::CommandNotSupported` if the proxy refuses `BIND`. ``` -------------------------------- ### Compat Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/io.md Documentation for the Compat struct, including its constructor, accessor methods, and trait implementations. ```APIDOC ## Compat ### Description A compatibility wrapper that makes non-tokio async types usable with this crate. It implements `AsyncSocket`, `futures_io::AsyncRead`, and `futures_io::AsyncWrite` when the inner type `S` implements the corresponding `futures-io` traits. ### Type `pub struct Compat(S);` ### Availability Available only with the `futures-io` feature. ### Methods #### `new` - **Signature**: `pub fn new(inner: S) -> Self` - **Description**: Wraps an inner value. #### `into_inner` - **Signature**: `pub fn into_inner(self) -> S` - **Description**: Consumes the wrapper, returning the inner value. ### Trait Implementations #### `AsRef` - **Method**: `fn as_ref(&self) -> &S` - **Description**: Borrows the inner value. #### `AsMut` - **Method**: `fn as_mut(&mut self) -> &mut S` - **Description**: Mutably borrows the inner value. ### Notes - No `Default`, `Clone`, or `Debug` derive is provided. - Defined at `src/io/compat.rs:17-41` and re-exported at `src/io/mod.rs:19`. ``` -------------------------------- ### Connect via Unix socket with Compat Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/io.md Wraps a `futures-io` socket (e.g., `smol::net::unix::UnixStream`) with `tokio_socks::io::Compat` to use it with `Socks5Stream::connect_with_socket`. The `Compat` type adapts the socket to implement `futures_io::AsyncRead` and `AsyncWrite`. ```rust use smol::net::unix::UnixStream; use tokio_socks::{io::Compat, tcp::Socks5Stream, Error}; async fn connect_via_unix_socket() -> Result<(), Error> { let socket = Compat::new(UnixStream::connect("/tmp/proxy.s").await.map_err(Error::Io)?); let conn = Socks5Stream::connect_with_socket(socket, ("example.com", 80)).await?; // conn implements futures_io::AsyncRead + AsyncWrite Ok(()) } ``` -------------------------------- ### SocksConnector::execute_with_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Runs method selection, optional password auth, `CONNECT`/`BIND`/Tor command, and reply parsing over an existing socket, returning the `Socks5Stream`. ```rust pub async fn execute_with_socket(&mut self, mut socket: T) -> Result> { self.authenticate(&mut socket).await?; self.prepare_send_request(); socket.write_all(&self.buf[self.ptr..self.len]).await?; let target = self.receive_reply(&mut socket).await?; Ok(Socks5Stream { socket, target }) } ``` -------------------------------- ### accept Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Consumes the listener, waits for the proxy's second BIND reply (after the peer connects), and returns the Socks5Stream carrying the accepted connection. ```APIDOC ## accept ### Description Consumes the listener, waits for the proxy's second BIND reply (after the peer connects), and returns the Socks5Stream carrying the accepted connection. ### Method accept ### Endpoint Socks5Listener::accept ### Parameters None ### Response #### Success Response (200) - **Result>** - The accepted connection stream. #### Response Example ```rust let peer_conn = listener.accept().await?; ``` ### Error Handling Throws: the same reply-parsing errors as `connect` (`InvalidResponseVersion`, `InvalidReservedByte`, reply codes, `UnknownAddressType`, `Io`); in particular `Error::ConnectionRefused` if the peer never connects within the server's timeout. ``` -------------------------------- ### bind_addr method Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Returns the proxy-side listening address from the BIND reply as TargetAddr<'_>. Forward this to the remote process; the remote then connects to it. ```rust pub fn bind_addr(&self) -> TargetAddr<'_> { self.inner.target_addr() } ``` -------------------------------- ### Socks5Stream::connect_with_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/io.md Documentation for the `Socks5Stream::connect_with_socket` method, which connects to a SOCKS5 proxy using an existing socket. ```APIDOC ## Socks5Stream::connect_with_socket ### Description Establishes a SOCKS5 connection using an existing socket that implements `AsyncSocket` (e.g., `tokio::net::TcpStream` or a `Compat` wrapper). This method is used when you already have a connected socket to the SOCKS proxy. ### Method `Socks5Stream::connect_with_socket` ### Parameters - **socket** (AsyncSocket) - Required - The socket connected to the SOCKS proxy. - **target** (TargetAddr) - Required - The target address to connect to, either as a tuple `(host, port)` or a string like `"example.com:80"`. ### Return Value Returns a `Result` containing a `Socks5Stream` that implements `AsyncRead` and `AsyncWrite`. ### Example ```rust use tokio::net::TcpStream; use tokio_socks::{tcp::Socks5Stream, Error}; async fn connect_with_existing_socket() -> Result<(), Error> { let socket = TcpStream::connect("127.0.0.1:1080").await?; // tokio's TcpStream implements AsyncRead + AsyncWrite, so it is an AsyncSocket let conn = Socks5Stream::connect_with_socket(socket, "example.com:80").await?; Ok(()) } ``` ``` -------------------------------- ### bind_with_password Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Sends a SOCKS5 BIND request with RFC 1929 username/password authentication. Returns a Socks5Listener. ```APIDOC ## bind_with_password ### Description Sends a SOCKS5 BIND request with RFC 1929 username/password authentication. Returns a Socks5Listener. ### Method bind_with_password ### Endpoint Socks5Listener::bind_with_password ### Parameters #### Path Parameters - **proxy** (P: ToProxyAddrs) - Required - Proxy address spec. - **target** (T: IntoTargetAddr<'t>) - Required - The remote peer address expected to connect; the proxy only accepts connections matching it. - **username** (&'a str) - Required - Username for authentication. - **password** (&'a str) - Required - Password for authentication. ### Response #### Success Response (200) - **Result>** - The listener for the BIND operation. ### Error Handling Throws: as `connect` (same reply-code error mapping), e.g. `Error::ConnectionRefused`/`Error::CommandNotSupported` if the proxy refuses `BIND`. ``` -------------------------------- ### Connect with existing tokio TcpStream Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/io.md Uses a `tokio::net::TcpStream` directly with `Socks5Stream::connect_with_socket` without needing `Compat`, because tokio's `TcpStream` already implements `AsyncRead` and `AsyncWrite`. ```rust use tokio::net::TcpStream; use tokio_socks::{tcp::Socks5Stream, Error}; async fn connect_with_existing_socket() -> Result<(), Error> { let socket = TcpStream::connect("127.0.0.1:1080").await?; // tokio's TcpStream implements AsyncRead + AsyncWrite, so it is an AsyncSocket let conn = Socks5Stream::connect_with_socket(socket, "example.com:80").await?; Ok(()) } ``` -------------------------------- ### IntoTargetAddr::into_target_addr Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/lib.md Converts a string into a target address for SOCKS5 usage. Returns an error if the domain is longer than 255 bytes. ```APIDOC ## [CONVERT] IntoTargetAddr::into_target_addr ### Description Converts a string into a target address for SOCKS5 usage. Returns an error if the domain is longer than 255 bytes. ### Method CONVERT ### Endpoint IntoTargetAddr::into_target_addr ### Parameters #### Parameters - **value** (string) - Required - The target address string to convert. ### Request Example ```rust let long: String = format!("www.{}.com", "a".repeat(300)); let result = long.as_str().into_target_addr(); ``` ### Response #### Success Response - **target_addr** (IntoTargetAddr) - The converted target address. #### Error Response - **Error::InvalidTargetAddress** (Error) - Returned when the domain is overlong. #### Response Example ```rust match long.as_str().into_target_addr() { Err(Error::InvalidTargetAddress(msg)) => println!("rejected: {}", msg), _ => unreachable!(), } ``` ``` -------------------------------- ### Compat::new Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/types.md Wraps an inner value with the Compat struct. ```APIDOC ## Compat::new ### Description Creates a new Compat wrapper around the provided inner value. ### Method new ### Signature pub fn new(inner: S) -> Self ### Parameters - **inner** (S) - Required - The inner value to wrap. ### Returns - **Self** - The newly created Compat instance. ``` -------------------------------- ### connect_with_password_and_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Establishes a SOCKS5 connection over a provided socket with RFC 1929 username/password authentication. ```APIDOC ## connect_with_password_and_socket ### Description Establishes a SOCKS5 connection over a provided socket with RFC 1929 username/password authentication. This method combines `connect_with_socket` with authentication, allowing the use of non-Tokio sockets via the `Compat` wrapper. ### Method connect_with_password_and_socket ### Signature ```rust pub async fn connect_with_password_and_socket<'a, 't, T>( socket: S, target: T, username: &'a str, password: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, ``` ### Parameters - **socket** (S) - Required - The underlying socket to use for the connection. - **target** (T) - Required - The target address to connect to through the proxy. - **username** (&'a str) - Required - The username for authentication. Must be 1..=255 UTF-8 bytes. - **password** (&'a str) - Required - The password for authentication. Must be 1..=255 UTF-8 bytes. ### Return `Result>` ### Errors Throws as `connect_with_password`, minus proxy-address errors. Returns `Error::InvalidAuthValues` if username or password constraints are violated. ### Example ```rust use tokio_socks::{io::Compat, tcp::Socks5Stream, Error}; use smol::net::unix::UnixStream; // non-tokio socket via Compat async fn auth_over_unix() -> Result<(), Error> { let socket = Compat::new(UnixStream::connect("/tmp/proxy.s").await.map_err(Error::Io)?); let conn = Socks5Stream::connect_with_password_and_socket(socket, ("example.com", 80), "u", "p").await?; Ok(()) } ``` ``` -------------------------------- ### connect_with_password Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Establishes a SOCKS5 connection to a target through a proxy using username/password authentication (RFC 1929). ```APIDOC ## connect_with_password ### Description Establishes a SOCKS5 connection to a target through a proxy using username/password authentication (RFC 1929). ### Method async function ### Signature ```rust pub async fn connect_with_password<'a, 't, P, T>( proxy: P, target: T, username: &'a str, password: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, ``` ### Parameters - **proxy** (`P: ToProxyAddrs`) - Required - Proxy address spec. - **target** (`T: IntoTargetAddr<'t>`) - Required - Destination. - **username** (`&'a str`) - Required - Username; UTF-8 byte length must be 1..=255 (`Error::InvalidAuthValues` otherwise). - **password** (`&'a str`) - Required - Password; UTF-8 byte length must be 1..=255. ### Return `Result>` ### Errors Throws all `connect` errors plus: - `Error::InvalidAuthValues` (username/password length outside 1..=255) - `Error::PasswordAuthFailure(u8)` (server rejected credentials) - `Error::UnknownAuthMethod` (server selected an unannounced method) - `Error::AuthorizationRequired` ### Example ```rust use tokio_socks::{tcp::Socks5Stream, Error}; async fn connect_authed() -> Result<(), Error> { let conn = Socks5Stream::connect_with_password("127.0.0.1:1080", "db.internal:5432", "app", "hunter2").await?; Ok(()) } ``` ``` -------------------------------- ### into_inner Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Consumes the Socks5Stream and returns the underlying socket. ```APIDOC ## into_inner ### Description Consumes the `Socks5Stream`, returning the inner socket. This allows access to the underlying socket after the SOCKS5 connection is established. ### Method into_inner ### Signature ```rust pub fn into_inner(self) -> S { self.socket } ``` ### Parameters - **self** (Socks5Stream) - Required - The stream to consume. ### Return `S` - The underlying socket. ``` -------------------------------- ### Socks5Stream::connect Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/lib.md Establishes a SOCKS5 connection to a target address through a proxy. The proxy address is accepted as a string via ToProxyAddrs, and the target as a string via IntoTargetAddr. ```APIDOC ## [CONNECT] Socks5Stream::connect ### Description Establishes a SOCKS5 connection to a target address through a proxy. The proxy address is accepted as a string via ToProxyAddrs, and the target as a string via IntoTargetAddr. ### Method CONNECT ### Endpoint Socks5Stream::connect ### Parameters #### Parameters - **proxy** (string) - Required - The proxy address in the format "host:port". - **target** (string) - Required - The target address in the format "host:port". ### Request Example ```rust let mut conn = Socks5Stream::connect("127.0.0.1:1080", "example.com:80").await?; ``` ### Response #### Success Response - **conn** (Socks5Stream) - The established SOCKS5 stream. #### Response Example ```rust let mut conn = Socks5Stream::connect("127.0.0.1:1080", "example.com:80").await?; ``` ``` -------------------------------- ### Connect to SOCKS5 proxy with Socks5Stream::connect Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/lib.md Shows how to connect to a SOCKS5 proxy and send a request using Socks5Stream::connect. The proxy address and target address are accepted as &str via the ToProxyAddrs and IntoTargetAddr traits. The same pattern works against a Tor proxy as shown in examples/tor.rs; a bad target string is caught as Error::InvalidTargetAddress. ```rust use tokio::runtime::Runtime; use tokio_socks::{tcp::Socks5Stream, Error}; fn main() -> Result<(), Error> { let rt = Runtime::new().unwrap(); rt.block_on(async { // proxy accepted as &str via ToProxyAddrs; target as &str via IntoTargetAddr let mut conn = Socks5Stream::connect("127.0.0.1:1080", "example.com:80").await?; conn.write_all(b"GET / HTTP/1.0\r\n\r\n").await?; // ... Ok(()) }) } ``` -------------------------------- ### bind_with_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Sends a SOCKS5 BIND request using an existing socket, without address resolution. Returns a Socks5Listener. ```APIDOC ## bind_with_socket ### Description Sends a SOCKS5 BIND request using an existing socket, without address resolution. Returns a Socks5Listener. ### Method bind_with_socket ### Endpoint Socks5Listener::bind_with_socket ### Parameters #### Path Parameters - **socket** (S: AsyncSocket + Unpin) - Required - The socket to use for the BIND request. - **target** (T: IntoTargetAddr<'t>) - Required - The remote peer address expected to connect; the proxy only accepts connections matching it. ### Response #### Success Response (200) - **Result>** - The listener for the BIND operation. ### Error Handling Throws: as `connect` (same reply-code error mapping), e.g. `Error::ConnectionRefused`/`Error::CommandNotSupported` if the proxy refuses `BIND`. ``` -------------------------------- ### Socks4Connector::execute (tokio feature) Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Connects to each candidate proxy address in order, falling back to the next resolved address on connection failure. Returns `Error::ProxyServerUnreachable` when all candidates fail. Requires the `tokio` feature. ```rust pub async fn execute(&mut self) -> Result> { while let Some(next_addr) = self.proxy.next().await { let tcp = match TcpStream::connect(next_addr?).await { Ok(tcp) => tcp, Err(_) => continue, // fall back to next resolved proxy address }; return self.execute_with_socket(tcp).await; } Err(Error::ProxyServerUnreachable) } ``` -------------------------------- ### connect_with_password_and_socket signature Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Signature for Socks5Stream::connect_with_password_and_socket. Adds RFC 1929 username/password authentication to connect_with_socket. Username and password must be 1..=255 UTF-8 bytes each, otherwise Error::InvalidAuthValues is returned. ```rust pub async fn connect_with_password_and_socket<'a, 't, T>( socket: S, target: T, username: &'a str, password: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, ``` -------------------------------- ### bind_with_password method signature Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Signature for bind_with_password on Socks5Listener (tokio feature). Same as bind but with RFC 1929 authentication; username/password length constraints apply as in connect_with_password. ```rust pub async fn bind_with_password<'a, 't, P, T>( proxy: P, target: T, username: &'a str, password: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, ``` -------------------------------- ### Socks4Listener::bind_with_user_and_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Issues a SOCKS4 BIND command using a provided socket and user ID. This is a socket-based variant of `bind_with_userid`. ```APIDOC ## [BIND] Socks4Listener::bind_with_user_and_socket ### Description Issues a SOCKS4 BIND command using a provided socket and user ID. This is a socket-based variant of `bind_with_userid`. ### Method BIND (SOCKS4 command) ### Endpoint Socks4Listener::bind_with_user_and_socket ### Parameters #### Path Parameters - **socket** (`S: AsyncSocket + Unpin`) - Required - The socket to use for the connection. - **target** (`T: IntoTargetAddr<'t>`) - Required - Expected peer address; must not be IPv6. - **user_id** (`&'a str`) - Required - User ID to send, 1..=255 bytes. ### Request Example ```rust let listener = Socks4Listener::bind_with_user_and_socket(socket, ("192.168.1.10", 0), "user").await?; ``` ### Response #### Success Response - **Result>** - A new Socks4Listener instance. #### Response Example ```rust let listener = Socks4Listener::bind_with_user_and_socket(socket, ("192.168.1.10", 0), "user").await?; ``` ### Error Handling Throws errors as `connect` (reply code mapping in `receive_reply`). ``` -------------------------------- ### bind_with_socket and bind_with_user_and_socket signatures Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Signatures for the socket-based BIND variants. Note the method name asymmetry: bind_with_user_and_socket, not bind_with_userid_and_socket. ```rust pub async fn bind_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t>, pub async fn bind_with_user_and_socket<'a, 't, T>( socket: S, target: T, user_id: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, ``` -------------------------------- ### connect_with_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Runs the no-auth CONNECT handshake over a caller-provided socket that is already connected to the proxy, skipping proxy address resolution. ```APIDOC ## connect_with_socket ### Description Runs the no-auth `CONNECT` handshake over a caller-provided socket that is already connected to the proxy. Skips proxy address resolution; the caller must handle errors if the proxy is unreachable. ### Method async function ### Signature ```rust pub async fn connect_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t>, ``` ### Parameters - **socket** (`S: AsyncSocket + Unpin`) - Required - Connected socket to the proxy (tokio `TcpStream`, `Compat<..>`, or another `Socks5Stream` for chaining). - **target** (`T: IntoTargetAddr<'t>`) - Required - Destination. ### Return `Result>` ### Errors Throws handshake errors as `connect`, plus `Error::Io` for socket I/O; no `ProxyServerUnreachable` (no address list). ### Example ```rust use tokio::net::TcpStream; use tokio_socks::{tcp::Socks5Stream, Error}; async fn chain() -> Result<(), Error> { let first = TcpStream::connect("184.176.166.20:4145").await?; let second = Socks5Stream::connect_with_socket(first, "90.89.205.248:1080").await?; // chain hop 2 let mut conn = Socks5Stream::connect_with_socket(second, "duckduckgo.com:80").await?; Ok(()) } ``` ``` -------------------------------- ### bind_with_userid method signature Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Signature for bind_with_userid, which is bind with a 1..=255-byte user_id. ```rust pub async fn bind_with_userid<'a, 't, P, T>( proxy: P, target: T, user_id: &'a str, ) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, ``` -------------------------------- ### bind_with_socket and bind_with_password_and_socket signatures Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Signatures for bind_with_socket and bind_with_password_and_socket on impl Socks5Listener. These are socket-based BIND variants that do not perform address resolution. ```rust pub async fn bind_with_socket<'t, T>(socket: S, target: T) -> Result> where T: IntoTargetAddr<'t>, pub async fn bind_with_password_and_socket<'a, 't, T>( socket: S, target: T, username: &'a str, password: &'a str, ) -> Result> where T: IntoTargetAddr<'t>, ``` -------------------------------- ### bind method signature Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Signature for the bind method on Socks5Listener (tokio feature). Sends BIND with the given target (the proxy filters incoming connections using this value) without auth. Returns Result> and throws the same reply-code errors as connect, e.g. Error::ConnectionRefused or Error::CommandNotSupported. ```rust pub async fn bind<'t, P, T>(proxy: P, target: T) -> Result> where P: ToProxyAddrs, T: IntoTargetAddr<'t>, ``` -------------------------------- ### bind Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Sends a SOCKS5 BIND request to the proxy without authentication. Returns a Socks5Listener that can be used to accept an incoming connection. ```APIDOC ## bind ### Description Sends a SOCKS5 BIND request to the proxy without authentication. Returns a Socks5Listener that can be used to accept an incoming connection. ### Method bind ### Endpoint Socks5Listener::bind ### Parameters #### Path Parameters - **proxy** (P: ToProxyAddrs) - Required - Proxy address spec. - **target** (T: IntoTargetAddr<'t>) - Required - The remote peer address expected to connect; the proxy only accepts connections matching it. ### Response #### Success Response (200) - **Result>** - The listener for the BIND operation. #### Response Example ```rust let listener = Socks5Listener::bind("127.0.0.1:1080", ("peer.example.com", 0)).await?; ``` ### Error Handling Throws: as `connect` (same reply-code error mapping), e.g. `Error::ConnectionRefused`/`Error::CommandNotSupported` if the proxy refuses `BIND`. ``` -------------------------------- ### bind_addr Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Returns the proxy-side listening address from the BIND reply. This address should be forwarded to the remote process. ```APIDOC ## bind_addr ### Description Returns the proxy-side listening address from the BIND reply. This address should be forwarded to the remote process. ### Method bind_addr ### Endpoint Socks5Listener::bind_addr ### Parameters None ### Response #### Success Response (200) - **TargetAddr<'_>** - The proxy-side listening address. #### Response Example ```rust let bind_addr = listener.bind_addr().to_owned(); ``` ``` -------------------------------- ### target_addr implementation Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks5.md Returns the target address that the proxy server connects to, as reported in the SOCKS5 reply. The returned TargetAddr is borrowed from the stored TargetAddr<'static>. ```rust /// Returns the target address that the proxy server connects to. pub fn target_addr(&self) -> TargetAddr<'_> { match &self.target { TargetAddr::Ip(addr) => TargetAddr::Ip(*addr), TargetAddr::Domain(domain, port) => { let domain: &str = domain.borrow(); TargetAddr::Domain(domain.into(), *port) }, } } ``` -------------------------------- ### Socks4Listener::bind_with_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Issues a SOCKS4 BIND command using a provided socket. This is a socket-based variant of `bind`. ```APIDOC ## [BIND] Socks4Listener::bind_with_socket ### Description Issues a SOCKS4 BIND command using a provided socket. This is a socket-based variant of `bind`. ### Method BIND (SOCKS4 command) ### Endpoint Socks4Listener::bind_with_socket ### Parameters #### Path Parameters - **socket** (`S: AsyncSocket + Unpin`) - Required - The socket to use for the connection. - **target** (`T: IntoTargetAddr<'t>`) - Required - Expected peer address; must not be IPv6. ### Request Example ```rust let listener = Socks4Listener::bind_with_socket(socket, ("192.168.1.10", 0)).await?; ``` ### Response #### Success Response - **Result>** - A new Socks4Listener instance. #### Response Example ```rust let listener = Socks4Listener::bind_with_socket(socket, ("192.168.1.10", 0)).await?; ``` ### Error Handling Throws errors as `connect` (reply code mapping in `receive_reply`). ``` -------------------------------- ### Socks4Connector::execute_with_socket Source: https://github.com/sticnarf/tokio-socks/blob/master/_autodocs/api-reference/socks4.md Writes the SOCKS4 request and parses the 8-byte reply `[VN, CD, DSTPORT, DSTIP]`. Returns a `Socks4Stream` wrapping the socket and target address. ```rust pub async fn execute_with_socket(&mut self, mut socket: T) -> Result> { self.prepare_send_request()?; socket.write_all(&self.buf[self.ptr..self.len]).await?; let target = self.receive_reply(&mut socket).await?; Ok(Socks4Stream { socket, target }) } ```