### Rust SOCKS5 Protocol Handshake Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/index Demonstrates a basic SOCKS5 protocol handshake using the socks5-impl crate. It handles initial authentication and command requests, including error handling for failed handshakes or requests. This example is synchronous and intended for illustrative purposes, showcasing the core protocol interactions. ```rust use socks5_impl::protocol::{handshake, Address, AuthMethod, Reply, Request, Response, StreamOperation}; fn main() -> socks5_impl::Result<()> { let listener = std::net::TcpListener::bind("127.0.0.1:5000")?; let (mut stream, _) = listener.accept()?; let request = handshake::Request::retrieve_from_stream(&mut stream)?; if request.evaluate_method(AuthMethod::NoAuth) { let response = handshake::Response::new(AuthMethod::NoAuth); response.write_to_stream(&mut stream)?; } else { let response = handshake::Response::new(AuthMethod::NoAcceptableMethods); response.write_to_stream(&mut stream)?; let _ = stream.shutdown(std::net::Shutdown::Both); let err = "No available handshake method provided by client"; return Err(std::io::Error::new(std::io::ErrorKind::Unsupported, err).into()); } let req = match Request::retrieve_from_stream(&mut stream) { Ok(req) => req, Err(err) => { let resp = Response::new(Reply::GeneralFailure, Address::unspecified()); resp.write_to_stream(&mut stream)?; let _ = stream.shutdown(std::net::Shutdown::Both); return Err(err.into()); } }; match req.command { _ => {} // process request } Ok(()) } ``` -------------------------------- ### TcpStream Peer Address Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct An example showing how to connect to a TCP stream and retrieve its peer socket address using the `peer_addr` method, applicable to UdpAssociate as well. ```rust use tokio::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080").await?; println!("{:?}", stream.peer_addr()?); ``` -------------------------------- ### Rust Arc Less-Than Comparison Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Provides an example of using the less-than operator (`<`) to compare two `Arc` instances. The comparison is delegated to the inner values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five < Arc::new(6)); ``` -------------------------------- ### Rust Arc Greater-Than-or-Equal-To Comparison Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Shows an example of the greater-than-or-equal-to operator (`>=`) for comparing `Arc` instances. The comparison is based on the values held within the `Arc`s. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five >= Arc::new(5)); ``` -------------------------------- ### TcpStream Local Address Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct An example demonstrating how to connect to a TCP stream and retrieve its local socket address using the `local_addr` method, which is also available for UdpAssociate. ```rust use tokio::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080").await?; println!("{:?}", stream.local_addr()?); ``` -------------------------------- ### TCP Stream Peek and Read Example in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Demonstrates connecting to a TCP stream, peeking at incoming data into a buffer, and then reading the same data into another buffer for comparison. This showcases asynchronous I/O operations using tokio. ```rust use tokio::net::TcpStream; use tokio::io::AsyncReadExt; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to a peer let mut stream = TcpStream::connect("127.0.0.1:8080").await?; let mut b1 = [0; 10]; let mut b2 = [0; 10]; // Peek at the data let n = stream.peek(&mut b1).await?; // Read the data assert_eq!(n, stream.read(&mut b2[..n]).await?); assert_eq!(&b1[..n], &b2[..n]); Ok(()) } ``` -------------------------------- ### BufMut::remaining_mut Example in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/protocol/trait This example demonstrates the `remaining_mut` method of the `BufMut` trait. It shows how to check the number of bytes that can be written to a buffer before and after writing some data, illustrating the buffer's capacity management. ```rust use bytes::BufMut; let mut dst = [0; 10]; let mut buf = &mut dst[..]; let original_remaining = buf.remaining_mut(); buf.put(&b"hello"[..]); assert_eq!(original_remaining - 5, buf.remaining_mut()); ``` -------------------------------- ### Rust Arc Partial Comparison Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Shows how to perform a partial comparison between two `Arc` instances using `partial_cmp`. This returns an `Option` based on the comparison of their inner values. ```rust use std::sync::Arc; use std::cmp::Ordering; let five = Arc::new(5); assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); ``` -------------------------------- ### Client UDP Association via SOCKS5 Proxy Source: https://context7.com/context7/rs_socks5-impl_0_7_2_socks5_impl/llms.txt Creates a UDP client that sends packets through a SOCKS5 proxy using the ASSOCIATE command. It first sets up a general UDP client and then a specific `UdpClientImpl` for a target address. The example demonstrates sending a DNS query and receiving a response. ```rust use socks5_impl::client::{create_udp_client, UdpClientImpl}; use socks5_impl::protocol::{UserKey, Address}; use std::time::Duration; #[tokio::main] async fn main() -> socks5_impl::Result<()> { // Create UDP client through proxy let udp_client = create_udp_client( "127.0.0.1:1080", // Proxy address None // No authentication ).await?; // Create implementation for specific destination let client_impl = UdpClientImpl::datagram( "127.0.0.1:1080", Address::DomainAddress("dns.example.com".to_string(), 53), None ).await?; // Send DNS query and receive response let dns_query = b"\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00"; let response = client_impl.transfer_data( dns_query, Duration::from_secs(5) ).await?; println!("Received UDP response: {} bytes", response.len()); Ok(()) } ``` -------------------------------- ### Rust Arc Less-Than-or-Equal-To Comparison Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Demonstrates the less-than-or-equal-to operator (`<=`) for comparing `Arc` instances. The comparison is performed on the contained values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five <= Arc::new(5)); ``` -------------------------------- ### Example Implementation of AuthExecutor Trait - Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/trait This example demonstrates how to implement the `AuthExecutor` trait to create a custom authentication method. It defines a `MyAuth` struct, implements the `auth_method` to return a custom method (0x80), and provides an asynchronous `execute` method that simulates authentication logic and returns a result. It requires the `async_trait` crate for async trait implementation. ```Rust use socks5_impl::protocol::AuthMethod; use socks5_impl::server::AuthExecutor; use tokio::net::TcpStream; pub struct MyAuth; #[async_trait::async_trait] impl AuthExecutor for MyAuth { type Output = std::io::Result; fn auth_method(&self) -> AuthMethod { AuthMethod::from(0x80) } async fn execute(&self, stream: &mut TcpStream) -> Self::Output { // do something Ok(1145141919810) } } ``` -------------------------------- ### Connect and Peek TCP Stream Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Connects to a TCP stream and peeks at the initial data without consuming it. This example uses `TcpStream::connect` to establish a connection and `poll_fn` with `stream.poll_peek` to inspect data in the buffer. ```rust use tokio::io::{self, ReadBuf}; use tokio::net::TcpStream; use std::future::poll_fn; #[tokio::main] async fn main() -> io::Result<()> { let stream = TcpStream::connect("127.0.0.1:8000").await?; let mut buf = [0; 10]; let mut buf = ReadBuf::new(&mut buf); poll_fn(|cx| { stream.poll_peek(cx, &mut buf) }).await?; Ok(()) } ``` -------------------------------- ### Handling File Metadata Errors with Result Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/type Illustrates using `Result::and_then` with file system operations, specifically getting metadata and modification times. It shows how to handle successful retrieval of metadata for an existing path and how an error (e.g., `NotFound`) is propagated for a non-existent path. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Rust Arc Greater-Than Comparison Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Illustrates using the greater-than operator (`>`) to compare two `Arc` instances. The comparison logic is applied to the inner values. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five > Arc::new(4)); ``` -------------------------------- ### Client TCP Connection via SOCKS5 Proxy Source: https://context7.com/context7/rs_socks5-impl_0_7_2_socks5_impl/llms.txt Establishes a TCP connection through a SOCKS5 proxy using the CONNECT command without authentication. It sends an HTTP GET request and reads the response. Dependencies include `socks5_impl` and `tokio` for async operations. ```rust use socks5_impl::client; use socks5_impl::protocol::{UserKey, Address}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main] async fn main() -> socks5_impl::Result<()> { // Connect through proxy without authentication let mut stream = client::connect( "127.0.0.1:1080", // Proxy server address Address::DomainAddress("example.com".to_string(), 80), None // No authentication ).await?; // Send HTTP request stream.write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n").await?; // Read response let mut buffer = vec![0u8; 4096]; let n = stream.read(&mut buffer).await?; println!("Received {} bytes", n); Ok(()) } ``` -------------------------------- ### Rust Arc Inequality Comparison Example Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Illustrates comparing two `Arc` instances for inequality using the `!=` operator. Two `Arc`s are not equal if their inner values differ. ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five != Arc::new(6)); ``` -------------------------------- ### SOCKS5 UDP Header Parsing and Construction in Rust Source: https://context7.com/context7/rs_socks5-impl_0_7_2_socks5_impl/llms.txt This Rust example demonstrates how to parse and construct SOCKS5 UDP packet headers using the socks5-impl library. It covers creating UDP headers with specified addresses and ports, serializing them into a buffer, and deserializing them back. This is useful for custom UDP relay implementations. Dependencies include std::io::Cursor and socks5_impl::protocol. ```rust use socks5_impl::protocol::{UdpHeader, Address, StreamOperation}; use std::io::Cursor; fn main() -> socks5_impl::Result<()> { // Construct UDP header let header = UdpHeader::new( 0, // Fragment number (0 for unfragmented) Address::DomainAddress("target.example.com".to_string(), 8080) ); // Serialize to buffer let mut buffer = Vec::new(); header.write_to_stream(&mut buffer)?; println!("Serialized header: {} bytes", buffer.len()); println!("Max header size: {} bytes", UdpHeader::max_serialized_len()); // Parse from buffer let mut cursor = Cursor::new(buffer); let parsed_header = UdpHeader::retrieve_from_stream(&mut cursor)?; println!("Fragment: {}", parsed_header.frag); println!("Address: {:?}", parsed_header.address); // Construct complete UDP packet (header + data) let mut packet = Vec::new(); header.write_to_stream(&mut packet)?; packet.extend_from_slice(b"UDP payload data"); println!("Complete UDP packet: {} bytes", packet.len()); Ok(()) } ``` -------------------------------- ### UdpAssociate NoDelay Option Management Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Manages the TCP_NODELAY option for the socket. `nodelay` gets the current value, and `set_nodelay` configures it. Setting this option disables the Nagle algorithm for immediate data transmission. ```rust pub fn nodelay(&self) -> Result ``` ```rust pub fn set_nodelay(&self, nodelay: bool) -> Result<()> ``` -------------------------------- ### Wait for TCP Stream Readability Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Waits for a TCP stream to become readable using `stream.readable().await?`. This is typically paired with `try_read()` to attempt reading data. The example shows how to loop, wait for readiness, and then attempt to read, handling `WouldBlock` errors. ```rust use tokio::net::TcpStream; use std::error::Error; use std::io; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to a peer let stream = TcpStream::connect("127.0.0.1:8080").await?; let mut msg = vec![0; 1024]; loop { // Wait for the socket to be readable stream.readable().await?; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match stream.try_read(&mut msg) { Ok(n) => { msg.truncate(n); break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } println!("GOT = {:?}", msg); Ok(()) } ``` -------------------------------- ### Server Construction and Binding Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/struct This section details how to create and bind a new Socks5 server instance. ```APIDOC ## POST /server/new ### Description Creates a new socks5 server with the given TCP listener and authentication method. ### Method POST ### Endpoint `/server/new` ### Parameters #### Request Body - **listener** (TcpListener) - Required - The TCP listener to bind the server to. - **auth** (AuthAdaptor) - Required - The authentication method for the server. ### Request Example ```json { "listener": "", "auth": "" } ``` ### Response #### Success Response (200) - **server** (Server) - The newly created server instance. #### Response Example ```json { "server": "" } ``` --- ## POST /server/bind ### Description Creates a new socks5 server on the given socket address and authentication method. ### Method POST ### Endpoint `/server/bind` ### Parameters #### Request Body - **addr** (SocketAddr) - Required - The socket address to bind the server to. - **auth** (AuthAdaptor) - Required - The authentication method for the server. ### Request Example ```json { "addr": "127.0.0.1:8080", "auth": "" } ``` ### Response #### Success Response (200) - **server** (Server) - The newly created and bound server instance. #### Response Example ```json { "server": "" } ``` ``` -------------------------------- ### Server Creation and Binding (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/struct Provides methods to create a new SOCKS5 server instance. `new` takes an existing TcpListener and an AuthAdaptor, while `bind` creates a server bound to a specific address and an AuthAdaptor. Both return a Result. ```rust pub fn new(listener: TcpListener, auth: AuthAdaptor) -> Self ``` ```rust pub async fn bind(addr: SocketAddr, auth: AuthAdaptor) -> Result ``` -------------------------------- ### Incoming Connection Handling Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/struct APIs for accepting and polling incoming connections. ```APIDOC ## POST /server/accept ### Description Accepts an `IncomingConnection`. The connection may not be a valid socks5 connection. You need to call `IncomingConnection::authenticate` to hand-shake it into a proper socks5 connection. ### Method POST ### Endpoint `/server/accept` ### Parameters #### Request Body - **server** (Server) - Required - The server instance to accept connections from. ### Request Example ```json { "server": "" } ``` ### Response #### Success Response (200) - **connection** (IncomingConnection) - The accepted incoming connection. - **address** (SocketAddr) - The socket address of the incoming connection. #### Response Example ```json { "connection": "", "address": "192.168.1.100:12345" } ``` --- ## POST /server/poll_accept ### Description Polls to accept an `IncomingConnection`. The connection is only a freshly created TCP connection and may not be a valid SOCKS5 connection. You should call `IncomingConnection::authenticate` to perform a SOCKS5 authentication handshake. ### Method POST ### Endpoint `/server/poll_accept` ### Parameters #### Request Body - **server** (Server) - Required - The server instance to poll for connections. - **cx** (Context<'_>) - Required - The context for polling. ### Request Example ```json { "server": "", "cx": "" } ``` ### Response #### Success Response (200) - **poll_result** (Poll, SocketAddr)>>) - The result of the poll operation. #### Response Example ```json { "poll_result": "Poll::Ready(Ok((, "192.168.1.100:12345")))" } ``` ``` -------------------------------- ### Get Strong Reference Count of Arc (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Demonstrates how to get the number of active strong (`Arc`) references to a given allocation. Similar to `weak_count`, this method is safe but the returned value might be stale in concurrent environments due to potential modifications by other threads. ```rust use std::sync::Arc; let five = Arc::new(5); let _also_five = Arc::clone(&five); // This assertion is deterministic because we haven't shared // the `Arc` between threads. assert_eq!(2, Arc::strong_count(&five)); ``` -------------------------------- ### Result Implementations Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/type Documentation for various implementations of the Result type. ```APIDOC ## impl Result<&T, E> ### Description Implementations for `Result` containing a reference. #### Methods ##### `copied(self) -> Result` - **Description**: Maps a `Result<&T, E>` to a `Result` by copying the contents of the `Ok` part. - **Constraints**: `T: Copy` - **Examples**: ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ##### `cloned(self) -> Result` - **Description**: Maps a `Result<&T, E>` to a `Result` by cloning the contents of the `Ok` part. - **Constraints**: `T: Clone` - **Examples**: ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ## impl Result<&mut T, E> ### Description Implementations for mutable references within `Result`. #### Methods ##### `copied(self) -> Result` - **Description**: Maps a `Result<&mut T, E>` to a `Result` by copying the contents of the `Ok` part. - **Constraints**: `T: Copy` - **Examples**: ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ##### `cloned(self) -> Result` - **Description**: Maps a `Result<&mut T, E>` to a `Result` by cloning the contents of the `Ok` part. - **Constraints**: `T: Clone` - **Examples**: ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ## impl Result, E> ### Description Implementations for `Result` containing an `Option`. #### Methods ##### `transpose(self) -> Option>` - **Description**: Transposes a `Result` of an `Option` into an `Option` of a `Result`. `Ok(None)` will be mapped to `None`. `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))` respectively. - **Examples**: ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` ## impl Result, E> ### Description Implementations for nested `Result` types. #### Methods ##### `flatten(self) -> Result` - **Description**: Converts from `Result, E>` to `Result`. - **Examples**: ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` - **Note**: Flattening only removes one level of nesting at a time: ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` ## impl Result ### Description Core implementations for the `Result` type. #### Methods ##### `is_ok(&self) -> bool` - **Description**: Returns `true` if the result is `Ok`. - **Examples**: ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ##### `is_ok_and(self, f: F) -> bool` - **Description**: Returns `true` if the result is `Ok` and the value inside of it matches a predicate. - **Constraints**: `F: FnOnce(T) -> bool` - **Examples**: ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` ##### `is_err(&self) -> bool` - **Description**: Returns `true` if the result is `Err`. - **Examples**: ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` ##### `is_err_and(self, f: F) -> bool` - **Description**: Returns `true` if the result is `Err` and the value inside of it matches a predicate. - **Constraints**: `F: FnOnce(E) -> bool` ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Implementations for converting between types using `TryFrom` and `TryInto` traits. ```APIDOC ## TryFrom for T ### Description This implementation allows attempting to convert a type `U` into a type `T` where `U` can be converted into `T`. ### Method `try_from(value: U) -> Result>::Error>` ### Parameters * **value** (U) - Required - The value to convert. ### Error Type * `Error`: `Infallible` - Indicates that this conversion is infallible if `U: Into`. ## TryInto for T ### Description This implementation allows attempting to convert a type `T` into a type `U` where `U` implements `TryFrom`. ### Method `try_into(self) -> Result>::Error>` ### Error Type * `Error`: `>::Error` - The error type defined by the `TryFrom` implementation for `U`. ``` -------------------------------- ### IncomingConnection Blanket Implementations (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/struct Showcases various blanket implementations for `IncomingConnection`, including `Any`, `Borrow`, `BorrowMut`, `From`, `Into`, `TryFrom`, and `TryInto`, demonstrating its integration with Rust's standard traits. ```rust fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more Source ``` ```rust fn borrow(&self) -> &T Immutably borrows from an owned value. Read more Source ``` ```rust fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. Read more Source ``` ```rust fn from(t: T) -> T Returns the argument unchanged. Source ``` ```rust fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. Source ``` ```rust type Error = Infallible The type returned in the event of a conversion error. Source ``` ```rust fn try_from(value: U) -> Result>::Error> Performs the conversion. Source ``` ```rust type Error = >::Error The type returned in the event of a conversion error. Source ``` ```rust fn try_into(self) -> Result>::Error> Performs the conversion. Source ``` -------------------------------- ### Unwrap Error - Get Error Value Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/type Shows `unwrap_err()` to extract the `Err` value. It panics if the Result is `Ok`. ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### IP Time-To-Live (TTL) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Get and set the time-to-live (TTL) value for IP packets sent from this socket. ```APIDOC ## GET /tcp/ttl ### Description Gets the value of the `IP_TTL` option for this socket. ### Method GET ### Endpoint `/tcp/ttl` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **ttl** (integer) - The current time-to-live value. #### Response Example ```json { "ttl": 64 } ``` ## POST /tcp/ttl ### Description Sets the value for the `IP_TTL` option on this socket. This value sets the time-to-live field that is used in every packet sent from this socket. ### Method POST ### Endpoint `/tcp/ttl` ### Parameters #### Request Body - **ttl** (integer) - Required - The new time-to-live value. ### Request Example ```json { "ttl": 123 } ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the option was set. #### Response Example ```json { "message": "IP_TTL option set successfully." } ``` ``` -------------------------------- ### Implement Debug for Ready in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/bind/struct Provides a `Debug` implementation for the `Ready` struct, allowing instances of `Ready` to be formatted for debugging purposes. This enables developers to inspect the state of connections when debugging. ```rust impl Debug for Ready { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // Formats the value using the given formatter. // Implementation details for formatting would go here. unimplemented!("Debug formatting for Ready is not yet implemented"); } } ``` -------------------------------- ### Accepting Incoming Connections (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/struct Methods for handling incoming client connections. `accept` returns a future that resolves to an IncomingConnection and its address, requiring a subsequent call to `authenticate` for handshake. `poll_accept` provides a non-blocking way to check for new connections. ```rust pub async fn accept(&self) -> Result<(IncomingConnection, SocketAddr)> ``` ```rust pub fn poll_accept( &self, cx: &mut Context<'_>, ) -> Poll, SocketAddr)>> ``` -------------------------------- ### Arc::weak_count Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Gets the number of Weak pointers to the allocation. This method is safe but requires care to use correctly in concurrent scenarios. ```APIDOC ## Arc::weak_count ### Description Gets the number of `Weak` pointers to this allocation. ### Method `pub fn weak_count(this: &Arc) -> usize` ### Endpoint N/A (Associated function, not an endpoint) ### Parameters N/A ### Request Example N/A ### Response N/A ### Safety Requires extra care due to potential changes from other threads. ``` -------------------------------- ### UdpClientImpl Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/client/struct Documentation for the UdpClientImpl struct and its associated methods for UDP client operations. ```APIDOC ## Struct UdpClientImpl Represents a UDP client implementation for the SOCKS5 protocol. ### Source `socks5_impl::client::UdpClientImpl` ### Implementations #### `impl UdpClientImpl` ##### `pub async fn transfer_data(&self, data: &[u8], timeout: Duration) -> Result>` **Description**: Transfers UDP data through the SOCKS5 proxy. **Method**: `async fn` **Parameters**: * `data` (slice of u8) - The data to transfer. * `timeout` (Duration) - The timeout for the transfer operation. **Response**: * **Success Response (Result>)**: Returns the received data as a vector of bytes upon successful transfer. ##### `pub async fn datagram(proxy_addr: A1, udp_server_addr: A2, auth: Option) -> Result` **Description**: Establishes a UDP client connection for sending datagrams. **Method**: `async fn` **Generic Parameters**: * `A1`: Type that can be converted into `SocketAddr`. * `A2`: Type that can be converted into `Address`. **Parameters**: * `proxy_addr` (A1) - The address of the SOCKS5 proxy. * `udp_server_addr` (A2) - The address of the UDP server to connect to. * `auth` (Option) - Optional authentication credentials. **Response**: * **Success Response (Result)**: Returns a new `UdpClientImpl` instance upon successful connection. ``` -------------------------------- ### Create UserKeyAuth Instance in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/struct Provides a constructor function `new` for creating an instance of UserKeyAuth. It takes a username and password as string slices and returns a UserKeyAuth instance. ```rust pub fn new(username: &str, password: &str) -> Self ``` -------------------------------- ### Arc::strong_count Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Gets the number of strong (Arc) pointers to this allocation. This method is safe but requires care to use correctly in concurrent scenarios. ```APIDOC ## Arc::strong_count ### Description Gets the number of strong (`Arc`) pointers to this allocation. ### Method `pub fn strong_count(this: &Arc) -> usize` ### Endpoint N/A (Associated function, not an endpoint) ### Parameters N/A ### Request Example N/A ### Response N/A ### Safety Requires extra care due to potential changes from other threads. ``` -------------------------------- ### Get IP_TTL Socket Option in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Demonstrates retrieving the IP_TTL (Time-To-Live) value for a TcpStream. This value determines the maximum number of hops a packet can take before being discarded. ```rust use tokio::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080").await?; println!("{:?}", stream.ttl()?); ``` -------------------------------- ### Implement UdpClientImpl for SocksUdpClient - Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/client/struct This section details the implementation of UdpClientImpl specifically for the SocksUdpClient type. It includes methods for transferring data over UDP and establishing new UDP datagram connections through a proxy. ```rust impl UdpClientImpl pub async fn transfer_data(&self, data: &[u8], timeout: Duration) -> Result> pub async fn datagram(proxy_addr: A1, udp_server_addr: A2, auth: Option) -> Result where A1: Into, A2: Into
, ``` -------------------------------- ### Get Request Length (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/protocol/handshake/struct Returns the size of the Request object in bytes. This function is part of the StreamOperation trait and can be used to determine the amount of buffer space needed for the request. ```rust fn len(&self) -> usize ``` -------------------------------- ### Server Conversion Into Tuple (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/struct Implements the `From` trait for `Server` to convert it back into a tuple containing a `TcpListener` and an `AuthAdaptor`, effectively deconstructing the server. ```rust impl From> for (TcpListener, AuthAdaptor) fn from(server: Server) -> Self ``` -------------------------------- ### Get Maximum Serialized Length of UdpHeader (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/protocol/struct A constant function `max_serialized_len` that returns the maximum possible byte length when the UdpHeader is serialized. This is useful for buffer allocation. ```rust pub const fn max_serialized_len() -> usize ``` -------------------------------- ### Rust Function to Get Username as Byte Array Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/protocol/handshake/password_method/struct A method on the UserKey struct that returns the username as a byte vector (Vec). This can be useful for network transmissions or other byte-oriented operations. ```rust pub fn username_arr(&self) -> Vec ``` -------------------------------- ### Rust SOCKS5 Server with Username/Password Authentication Source: https://context7.com/context7/rs_socks5-impl_0_7_2_socks5_impl/llms.txt This snippet demonstrates setting up a SOCKS5 server in Rust that enforces username and password authentication. It utilizes the 'UserKeyAuth' feature from the 'socks5-impl' crate. A hash map is used to store valid user credentials. The server listens for connections, and each connection attempt is authenticated before further processing. ```rust use socks5_impl::server::{Server, IncomingConnection, ClientConnection}; use socks5_impl::server::auth::UserKeyAuth; use socks5_impl::protocol::UserKey; use std::sync::Arc; use std::collections::HashMap; #[tokio::main] async fn main() -> socks5_impl::Result<()> { // Create user database let mut users = HashMap::new(); users.insert( UserKey::new("alice", "secret123"), () // User metadata (can be any type) ); users.insert( UserKey::new("bob", "password456"), () ); // Create server with username/password authentication let auth = UserKeyAuth::new(users); let server = Server::bind( "127.0.0.1:1080", Arc::new(auth) ).await?; println!("Authenticated SOCKS5 server running on {}", server.local_addr()?); loop { let (incoming, client_addr) = server.accept().await?; tokio::spawn(async move { match incoming.authenticate().await { Ok((connection, _user_metadata)) => { println!("Client {} authenticated successfully", client_addr); // Handle the authenticated connection } Err(e) => { eprintln!("Authentication failed for {}: {}", client_addr, e); } } }); } } ``` -------------------------------- ### Create Arc with Default Value in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Shows how to create an Arc with the default value for type T. This is useful when you need a shared, mutable value that starts with a default. ```rust use std::sync::Arc; let x: Arc = Default::default(); assert_eq!(*x, 0); ``` -------------------------------- ### Rust SOCKS5 CONNECT Command Handler with Bidirectional Data Relay Source: https://context7.com/context7/rs_socks5-impl_0_7_2_socks5_impl/llms.txt This Rust code implements a SOCKS5 server that handles the CONNECT command. It establishes a connection to the target address specified by the client and then relays data bidirectionally between the client and the target server. It uses tokio for asynchronous operations and the socks5-impl crate for SOCKS5 protocol handling. Dependencies include `socks5_impl` and `tokio`. ```rust use socks5_impl::server::{Server, IncomingConnection, ClientConnection}; use socks5_impl::server::auth::NoAuth; use socks5_impl::protocol::Address; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; use std::sync::Arc; #[tokio::main] async fn main() -> socks5_impl::Result<()> { let server = Server::bind("127.0.0.1:1080", Arc::new(NoAuth)).await?; loop { let (incoming, _) = server.accept().await?; tokio::spawn(handle_connect(incoming)); } } async fn handle_connect(incoming: IncomingConnection<()>) -> socks5_impl::Result<()> { let (connection, _) = incoming.authenticate().await?; if let ClientConnection::Connect(connect, target_addr) = connection { // Resolve target address let target = match &target_addr { Address::SocketAddress(addr) => TcpStream::connect(addr).await?, Address::DomainAddress(domain, port) => { TcpStream::connect(format!("{}:{}", domain, port)).await? } }; // Send success reply and get client stream let mut client = connect.reply_ok().await?; // Split streams for bidirectional relay let (mut client_read, mut client_write) = tokio::io::split(client); let (mut target_read, mut target_write) = tokio::io::split(target); // Relay data bidirectionally let client_to_target = async { let mut buf = vec![0u8; 8192]; loop { let n = client_read.read(&mut buf).await?; if n == 0 { break; } target_write.write_all(&buf[..n]).await?; } Ok::<_, std::io::Error>(()) }; let target_to_client = async { let mut buf = vec![0u8; 8192]; loop { let n = target_read.read(&mut buf).await?; if n == 0 { break; } client_write.write_all(&buf[..n]).await?; } Ok::<_, std::io::Error>(()) }; // Run both directions concurrently tokio::try_join!(client_to_target, target_to_client)?; } Ok(()) } ``` -------------------------------- ### Get TCP_NODELAY Socket Option in Rust Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/connection/associate/struct Shows how to retrieve the current status of the TCP_NODELAY option for a TcpStream. This option, when enabled, disables the Nagle algorithm, ensuring data is sent immediately. ```rust use tokio::net::TcpStream; let stream = TcpStream::connect("127.0.0.1:8080").await?; println!("{:?}", stream.nodelay()?); ``` -------------------------------- ### Rust Function to Get Password as Byte Array Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/protocol/handshake/password_method/struct A method on the UserKey struct that returns the password as a byte vector (Vec). This is useful for securely handling or transmitting password data. ```rust pub fn password_arr(&self) -> Vec ``` -------------------------------- ### Into Ok - Never Panics Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/type Demonstrates `into_ok()`, an experimental API that returns the `Ok` value without panicking. It's a compile-time safeguard against future panics if the error type can never occur. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Server Conversion From Tuple (Rust) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/struct Implements the `From` trait to allow conversion of a tuple containing a `TcpListener` and an `AuthAdaptor` directly into a `Server` instance. ```rust impl From<(TcpListener, Arc + Send + Sync>)> for Server fn from((listener, auth): (TcpListener, AuthAdaptor)) -> Self ``` -------------------------------- ### Try Construct Uninitialized Arc with Allocator API (Rust - Experimental) Source: https://docs.rs/socks5-impl/0.7.2/socks5_impl/server/auth/type Tries to construct an `Arc` with uninitialized contents using the allocator API. Returns `Ok(Arc>)` on success or `Err(AllocError)` if allocation fails. This API is experimental. ```rust #![feature(allocator_api)] use std::sync::Arc; // let mut five = Arc::::try_new_uninit()?; // // // Deferred initialization: // Arc::get_mut(&mut five).unwrap().write(5); // // let five = unsafe { five.assume_init() }; // // assert_eq!(*five, 5); ```