### Minimal SOCKS5 Tunnel Setup Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Create and run a basic SOCKS5 tunnel synchronously using a configuration string. This example demonstrates defining MTU, SOCKS5 proxy details, and log level. ```swift import Tun2SocksKit // Step 1: Define configuration let config = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 address: 127.0.0.1 misc: log-level: error """) // Step 2: Run the tunnel synchronously let exitCode = Socks5Tunnel.run(withConfig: config) // Step 3: Check result if exitCode == 0 { print("Tunnel ran successfully") } else if exitCode == -1 { print("Error: No TUN interface available") } else { print("Tunnel error code: \(exitCode)") } ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/INDEX.md Demonstrates how to set up and run the SOCKS5 tunnel with a minimal configuration string. ```swift import Tun2SocksKit let config = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 """) let code = Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### High-Capacity Configuration Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Optimized configuration for high throughput and many concurrent connections. This example sets various parameters for performance. ```swift let highCapacityConfig = """ tunnel: mtu: 9000 socks5: port: 7890 address: :: udp: 'udp' misc: task-stack-size: 32768 tcp-buffer-size: 8192 max-session-count: 2048 connect-timeout: 10000 read-write-timeout: 120000 log-file: /var/log/tun2socks.log log-level: warn limit-nofile: 131072 """ Socks5Tunnel.run(withConfig: .string(content: highCapacityConfig)) { code in print("Tunnel exited: \(code)") } ``` -------------------------------- ### Manage Tunnel Lifecycle Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md A complete example demonstrating how to start a tunnel asynchronously with a configuration, check its status, and stop it. The stop action is triggered via Socks5Tunnel.quit(). ```swift import Tun2SocksKit import Foundation class TunnelSession { private var isRunning = false func start(config: Socks5Tunnel.Config) { guard !isRunning else { return } isRunning = true print("Starting tunnel...") Socks5Tunnel.run(withConfig: config) { [weak self] exitCode in self?.isRunning = false DispatchQueue.main.async { print("Tunnel stopped with code: \(exitCode)") } } } func stop() { guard isRunning else { return } print("Stopping tunnel...") Socks5Tunnel.quit() } func status() -> String { let stats = Socks5Tunnel.stats return "Running: \(isRunning), Sent: \(stats.up.bytes) bytes" } } // Usage let session = TunnelSession() let config = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 address: 127.0.0.1 """) session.start(config: config) print(session.status()) // ... later ... session.stop() ``` -------------------------------- ### Socks5Tunnel.Config Examples Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/types.md Demonstrates how to create configuration objects for a SOCKS5 tunnel using both file-based and string-based methods. ```swift // File-based configuration let url = URL(fileURLWithPath: "/etc/config.yaml") let fileConfig = Socks5Tunnel.Config.file(path: url) // String-based configuration let yaml = """ tunnel: mtu: 9000 socks5: port: 7890 """ let stringConfig = Socks5Tunnel.Config.string(content: yaml) ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Provides a basic configuration for Tun2SocksKit with default SOCKS5 listening on localhost. Requires the Tun2SocksKit import. ```swift import Tun2SocksKit let minimalConfig = """ tunnel: mtu: 9000 socks5: port: 7890 address: ::1 """ let code = Socks5Tunnel.run(withConfig: .string(content: minimalConfig)) ``` -------------------------------- ### File-Based Configuration Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Demonstrates loading Tun2SocksKit configuration from a YAML file located at a specified URL. Requires the Tun2SocksKit import. ```swift import Tun2SocksKit let configURL = URL(fileURLWithPath: "/etc/tun2socks/config.yaml") let code = Socks5Tunnel.run(withConfig: .file(path: configURL)) ``` -------------------------------- ### Debug Configuration Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Configuration with verbose logging enabled for troubleshooting purposes. Sets log level to debug and specifies stderr for log output. ```swift let debugConfig = """ tunnel: mtu: 9000 socks5: port: 7890 address: 127.0.0.1 misc: tcp-buffer-size: 4096 max-session-count: 256 log-file: stderr log-level: debug """ let code = Socks5Tunnel.run(withConfig: .string(content: debugConfig)) ``` -------------------------------- ### Background Tunnel with Main Thread UI Updates Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md A common pattern for UI applications, this example shows starting a tunnel asynchronously and updating UI elements on the main thread upon tunnel start and stop. ```swift import Tun2SocksKit import Dispatch class TunnelViewController: UIViewController { @IBOutlet weak var statusLabel: UILabel! @IBAction func startTapped(_ sender: Any) { let config = Socks5Tunnel.Config.string(content: configYAML) Socks5Tunnel.run(withConfig: config) { [weak self] exitCode in // Called on background thread DispatchQueue.main.async { self?.statusLabel.text = "Tunnel stopped: \(exitCode)" } } // Update UI immediately on main thread DispatchQueue.main.async { self.statusLabel.text = "Starting tunnel..." } } @IBAction func stopTapped(_ sender: Any) { // Safe to call from main thread Socks5Tunnel.quit() } } ``` -------------------------------- ### Install with CocoaPods Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Integrate Tun2SocksKit into your project using CocoaPods by adding the pod to your Podfile and running 'pod install'. ```ruby pod 'Tun2SocksKit', '~> 5.14.4' ``` ```bash pod install ``` -------------------------------- ### Start Tunnel with Configuration File Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Initializes and runs the SOCKS5 tunnel using a configuration file. Called by Swift's Socks5Tunnel.run(withConfig: .file(path:)). ```c int hev_socks5_tunnel_main( const char *config_file, int tun_fd ); ``` -------------------------------- ### Socks5Tunnel.Stats Usage Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/types.md Shows how to access and print the current transmission and reception statistics for a SOCKS5 tunnel. ```swift let stats = Socks5Tunnel.stats print("Packets sent: \(stats.up.packets)") print("Bytes sent: \(stats.up.bytes)") print("Packets received: \(stats.down.packets)") print("Bytes received: \(stats.down.bytes)") ``` -------------------------------- ### Run Asynchronous Tunnel with Completion Handler Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/overview.md Shows how to start a SOCKS5 tunnel asynchronously using a configuration string and handle its completion via a closure on the main dispatch queue. ```swift let configString = """ tunnel: mtu: 9000 socks5: port: 7890 address: 127.0.0.1 """ Socks5Tunnel.run(withConfig: .string(content: configString)) { exitCode in DispatchQueue.main.async { print("Tunnel exited with code: \(exitCode)") } } ``` -------------------------------- ### Start Tunnel with Configuration String Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Initializes and runs the SOCKS5 tunnel using a configuration provided as a string. Called by Swift's Socks5Tunnel.run(withConfig: .string(content:)). ```c int hev_socks5_tunnel_main_from_str( const char *config_string, uint32_t config_len, int tun_fd ); ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Run this command in your terminal after updating your Podfile to install Tun2SocksKit and other dependencies. ```bash pod install ``` -------------------------------- ### Socks5Tunnel.Stats.Stat Usage Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/types.md Illustrates how to retrieve and display detailed upstream and downstream statistics, and calculate total transferred data in megabytes. ```swift let stats = Socks5Tunnel.stats let upStat = stats.up let downStat = stats.down print("Upload: \(upStat.packets) packets, \(upStat.bytes) bytes") print("Download: \(downStat.packets) packets, \(downStat.bytes) bytes") // Calculate bandwidth in megabytes let totalMB = Double(stats.up.bytes + stats.down.bytes) / (1024 * 1024) print("Total transferred: \(totalMB) MB") ``` -------------------------------- ### Configure Tunnel Using a String Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Provide the tunnel configuration directly as a string. This example shows how to set MTU, SOCKS5 proxy details, max session count, and log level. ```swift let config = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 address: ::1 udp: 'udp' misc: max-session-count: 768 log-level: warn """) Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### Graceful Tunnel Shutdown Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/overview.md Demonstrates starting a tunnel in the background and then initiating a graceful shutdown after a specified delay. ```swift // Start tunnel in background Socks5Tunnel.run(withConfig: config) { code in print("Tunnel stopped with code: \(code)") } // Stop after 60 seconds DispatchQueue.main.asyncAfter(deadline: .now() + 60) { Socks5Tunnel.quit() } ``` -------------------------------- ### Verify Tun2SocksKit Installation Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Confirm that Tun2SocksKit is correctly installed and accessible by referencing its main API types, such as Socks5Tunnel.Config and Socks5Tunnel.Stats. ```swift // This should compile without errors let configType: Socks5Tunnel.Config = .string(content: "") let statsType: Socks5Tunnel.Stats = Socks5Tunnel.stats ``` -------------------------------- ### IPv4-Only Configuration Example Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Configures the SOCKS5 server to bind exclusively to the IPv4 localhost address. Sets a custom port to 1080. ```swift let ipv4Config = """ tunnel: mtu: 9000 socks5: port: 1080 address: 127.0.0.1 """ Socks5Tunnel.run(withConfig: .string(content: ipv4Config)) { code in // Tunnel running on 127.0.0.1:1080 } ``` -------------------------------- ### Using Named Dispatch Queues for Debugging Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Create named dispatch queues to simplify debugging. This example shows how to initialize a queue with a specific label and retrieve that label within an asynchronous task. ```swift let tunnelQueue = DispatchQueue( label: "com.app.tunnel", qos: .userInitiated ) tunnelQueue.async { print(DispatchQueue.getLabel(DispatchQueue.currentLabel())) // Prints: "com.app.tunnel" } ``` -------------------------------- ### Asynchronous SOCKS5 Tunnel Setup Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Run a SOCKS5 tunnel in the background and handle its exit using a completion handler. This is suitable for most applications where the tunnel should not block the main thread. ```swift import Tun2SocksKit import Foundation class TunnelManager { func startTunnel() { let config = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 address: 127.0.0.1 misc: log-level: info """) // Run tunnel in background Socks5Tunnel.run(withConfig: config) { exitCode in // Called when tunnel exits DispatchQueue.main.async { self.handleTunnelExit(code: exitCode) } } } func handleTunnelExit(code: Int32) { switch code { case 0: print("Tunnel exited normally") case -1: print("TUN interface not available") default: print("Tunnel error: \(code)") } } func stopTunnel() { Socks5Tunnel.quit() } } // Usage let manager = TunnelManager() manager.startTunnel() // ... later ... manager.stopTunnel() ``` -------------------------------- ### File-Based Configuration Content Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Example content for a YAML configuration file used with Tun2SocksKit. This file specifies tunnel MTU, SOCKS5 server details, and miscellaneous runtime options. ```yaml tunnel: mtu: 9000 socks5: port: 7890 address: ::1 udp: 'udp' misc: max-session-count: 768 connect-timeout: 5000 log-level: info ``` -------------------------------- ### Install with Swift Package Manager Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Add Tun2SocksKit as a dependency in your Swift Package Manager project by specifying the repository URL and version. ```swift let package = Package( name: "MyApp", dependencies: [ .package( url: "https://github.com/EbrahimTahernejad/Tun2SocksKit.git", from: "5.14.4" ) ], targets: [ .target( name: "MyApp", dependencies: ["Tun2SocksKit"] ) ] ) ``` -------------------------------- ### Reasonable Statistics Monitoring Interval Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Avoid calling the `stats` property too frequently. This example demonstrates a reasonable approach using a `Timer` to fetch statistics once per second, contrasting with an overly frequent polling method. ```swift // ✅ Reasonable: Once per second Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { let stats = Socks5Tunnel.stats } ``` -------------------------------- ### Monitor Tunnel Statistics Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/overview.md Illustrates how to start a tunnel and periodically poll its statistics (sent and received bytes) using a background dispatch after delay. ```swift let config = Socks5Tunnel.Config.string(content: configYAML) Socks5Tunnel.run(withConfig: config) { _ in print("Tunnel stopped") } // Monitor statistics periodically DispatchQueue.main.asyncAfter(deadline: .now() + 5) { let stats = Socks5Tunnel.stats print("Sent: \(stats.up.bytes) bytes") print("Received: \(stats.down.bytes) bytes") } ``` -------------------------------- ### Monitoring Tunnel Statistics Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/INDEX.md Provides an example of how to periodically monitor and log the total transferred bytes using the `stats` property. ```swift let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in let stats = Socks5Tunnel.stats print("Transferred: \(stats.up.bytes + stats.down.bytes) bytes") } ``` -------------------------------- ### Start Tunnel Synchronously (Blocking) Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Initiates the SOCKS5 tunnel and blocks the current thread until the tunnel exits. The exit code is returned immediately upon termination. ```swift let code = Socks5Tunnel.run(withConfig: config) // Returns immediately when tunnel exits ``` -------------------------------- ### Socks5Tunnel Core API Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/INDEX.md The main entry point for interacting with the SOCKS5 tunnel. It provides methods to start, stop, and retrieve statistics. ```APIDOC ## Socks5Tunnel Core API ### Description The `Socks5Tunnel` enum serves as the primary interface for managing the SOCKS5 tunnel. It allows users to configure, run, and gracefully stop the tunnel, as well as access runtime statistics. ### Methods #### `run(withConfig:)` - **Signature**: `(Config) -> Int32` - **Purpose**: Synchronously starts and runs the SOCKS5 tunnel with the provided configuration. #### `run(withConfig:completionHandler:)` - **Signature**: `(Config, @escaping (Int32) -> ()) -> Void` - **Purpose**: Asynchronously starts and runs the SOCKS5 tunnel. The completion handler is called with the exit code when the tunnel stops. #### `quit()` - **Signature**: `() -> Void` - **Purpose**: Gracefully stops the running SOCKS5 tunnel. ### Properties #### `stats` - **Type**: `Stats` - **Purpose**: Provides access to the current tunnel statistics, including transferred data. ### Associated Types #### `Config` - **Kind**: Enum - **Purpose**: Represents the source of the tunnel configuration, which can be provided via a file path or a string content. #### `Stats` - **Kind**: Struct - **Purpose**: A container structure holding various statistics related to the tunnel's operation. #### `Stats.Stat` - **Kind**: Struct - **Purpose**: Holds directional traffic statistics (e.g., bytes transferred up or down). ``` -------------------------------- ### Monitor Tunnel Statistics Periodically Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Start a timer to periodically print upload and download statistics of the SOCKS5 tunnel. Ensure you stop the monitoring when it's no longer needed. ```swift import Tun2SocksKit import Foundation class StatisticsMonitor { private var timer: Timer? func startMonitoring() { timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in self?.printStats() } } func stopMonitoring() { timer?.invalidate() timer = nil } private func printStats() { let stats = Socks5Tunnel.stats let uploadMB = Double(stats.up.bytes) / (1024 * 1024) let downloadMB = Double(stats.down.bytes) / (1024 * 1024) print(""" Tunnel Statistics: Upload: \(uploadMB) MB (\(stats.up.packets) packets) Download: \(downloadMB) MB (\(stats.down.packets) packets) """) } } // Usage let monitor = StatisticsMonitor() monitor.startMonitoring() // ... tunnel is running ... monitor.stopMonitoring() ``` -------------------------------- ### Monitor Statistics from Main Thread Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Start a tunnel in the background and use a Timer to periodically update statistics on the main thread. Ensure the timer is invalidated when the tunnel stops. ```swift class StatisticsViewController: UIViewController { @IBOutlet weak var bytesLabel: UILabel! private var monitorTimer: Timer? func startTunnel() { let config = Socks5Tunnel.Config.string(content: configYAML) // Start tunnel in background Socks5Tunnel.run(withConfig: config) { _ in print("Tunnel stopped") } // Monitor on main thread monitorTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.updateStats() } } func updateStats() { // Safe to call from main thread while tunnel runs in background let stats = Socks5Tunnel.stats bytesLabel.text = "\(stats.up.bytes + stats.down.bytes) bytes" } func stopTunnel() { monitorTimer?.invalidate() Socks5Tunnel.quit() } } ``` -------------------------------- ### Start Tunnel Asynchronously (Non-blocking) Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Initiates the SOCKS5 tunnel without blocking the current thread. A completion handler is called on a background thread when the tunnel exits, providing the exit code. ```swift Socks5Tunnel.run(withConfig: config) { exitCode in // Called when tunnel exits; runs on background thread } // Returns immediately ``` -------------------------------- ### Asynchronous run() Does Not Block Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Using the asynchronous version of `Socks5Tunnel.run()` allows the calling thread to continue execution immediately after starting the tunnel. The provided callback is executed when the tunnel exits. ```swift // Does not block Socks5Tunnel.run(withConfig: config) { code in print("Tunnel exited: \(code)") } // This line executes immediately print("Tunnel started") ``` -------------------------------- ### Call quit() From a Different Thread Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Since `Socks5Tunnel.run()` blocks the calling thread, `Socks5Tunnel.quit()` must be called from a different thread to avoid a deadlock. This example shows starting the tunnel in the background and calling `quit()` from the main thread after a delay. ```swift // ✅ Correct: Start tunnel in background, quit from main/another thread Socks5Tunnel.run(withConfig: config) { code in print("Tunnel exited: \(code)") } DispatchQueue.main.asyncAfter(deadline: .now() + 30) { Socks5Tunnel.quit() // Safe: called from different thread } ``` -------------------------------- ### Load Tun2SocksKit Configuration Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/api-reference.md Demonstrates how to load Tun2SocksKit configurations from both a file path and a string. Ensure the file path points to a valid configuration file. ```swift import Tun2SocksKit // Load from file let fileConfig = Socks5Tunnel.Config.file(path: URL(fileURLWithPath: "/etc/tun2socks/config.yaml")) // Load from string let stringConfig = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 address: 127.0.0.1 """) ``` -------------------------------- ### Preventing Multiple Tunnel Starts Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Ensures that the tunnel can only be started once by using a boolean flag to track the running state. This prevents concurrent or multiple calls to run(). ```swift class TunnelManager { private var isRunning = false func start(config: Socks5Tunnel.Config) { guard !isRunning else { return } isRunning = true Socks5Tunnel.run(withConfig: config) { code in self.isRunning = false } } } ``` -------------------------------- ### Load Configuration from File Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Specify the path to a YAML configuration file using a URL and pass it to the Config.file() method. The file must exist at the provided path. ```swift let configPath = URL(fileURLWithPath: "/path/to/config.yaml") let config = Socks5Tunnel.Config.file(path: configPath) Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### Get Tun2SocksKit Statistics Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/README.md Retrieve statistics for the Tun2SocksKit tunnel. This includes packet counts and byte transmission data. ```swift let stats = Socks5Tunnel.stats ``` -------------------------------- ### Load Tunnel Configuration from File Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Configure the SOCKS5 tunnel by loading settings from a YAML file located at a specified URL. Ensure the file path is correct and the file exists. ```swift import Tun2SocksKit let configURL = URL(fileURLWithPath: "/Library/Preferences/tun2socks.yaml") let code = Socks5Tunnel.run(withConfig: .file(path: configURL)) ``` -------------------------------- ### Load Configuration from String Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Pass the YAML configuration content as a string directly to the Config.string() method. Ensure the YAML content is correctly formatted. ```swift let config = Socks5Tunnel.Config.string(content: """ tunnel: mtu: 9000 socks5: port: 7890 """) Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### Monitoring with .utility QoS Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md For monitoring tasks, it is recommended to use the `.utility` QoS level, which offers medium priority suitable for longer tasks. This snippet shows how to create a dedicated queue for monitoring statistics. ```swift let monitorQueue = DispatchQueue.global(qos: .utility) monitorQueue.async { let stats = Socks5Tunnel.stats // Process stats } ``` -------------------------------- ### Create xcframework Binary Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Generate an xcframework from built iOS device and simulator frameworks. This command requires pre-built framework binaries in the 'build' directory. ```bash # Create xcframework (requires built binaries) xcodebuild -create-xcframework \ -framework build/Release-iphoneos/Tun2SocksKit.framework \ -framework build/Release-iphonesimulator/Tun2SocksKit.framework \ -output Tun2SocksKit.xcframework ``` -------------------------------- ### Dynamically Generate Configuration Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md Build configuration at runtime by constructing a YAML string dynamically based on application state or parameters. This allows for flexible configuration based on current needs. ```swift func buildConfig(port: Int, loglevel: String) -> Socks5Tunnel.Config { let yaml = """ tunnel: mtu: 9000 socks5: port: \(port) address: 127.0.0.1 misc: log-level: \(loglevel) """ return Socks5Tunnel.Config.string(content: yaml) } let config = buildConfig(port: 8080, loglevel: "info") Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### Import Tun2SocksKit Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/README.md Import the Tun2SocksKit library to begin using its functionalities. ```swift import Tun2SocksKit ``` -------------------------------- ### Handle Configuration from File or String in C Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Selects the appropriate C function (hev_socks5_tunnel_main or hev_socks5_tunnel_main_from_str) based on the configuration source. Converts Swift Strings/URLs to C-compatible strings. ```c switch config { case .file(let path): // Use hev_socks5_tunnel_main with file path return hev_socks5_tunnel_main( path.path.cString(using: .utf8), fileDescriptor ) case .string(let content): // Use hev_socks5_tunnel_main_from_str with inline content return hev_socks5_tunnel_main_from_str( content.cString(using: .utf8), UInt32(content.count), fileDescriptor ) } ``` -------------------------------- ### Socks5Tunnel.run(withConfig:) Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/api-reference.md Synchronously runs the SOCKS5 tunnel with the provided configuration. This method is suitable for direct execution where blocking is acceptable. ```APIDOC ## Socks5Tunnel.run(withConfig:) ### Description Synchronously runs the SOCKS5 tunnel with the provided configuration. ### Method `public static func run(withConfig config: Config) -> Int32` ### Parameters #### Path Parameters - **config** (`Socks5Tunnel.Config`) - Required - The tunnel configuration, either from a file or string ### Return Value **Type:** `Int32` An integer status code. Returns `-1` if the tunnel file descriptor cannot be obtained. Returns `0` on successful execution. Other values indicate error conditions from the underlying hev-socks5-tunnel library. ### Throws/Errors - **Error Type:** Returns -1 - **Condition:** TUN interface is not available or not accessible - **How to Handle:** Check that the app has the necessary entitlements to create TUN interfaces ### Request Example ```swift import Tun2SocksKit // Run tunnel from a configuration file let configURL = URL(fileURLWithPath: "/path/to/config.yaml") let code = Socks5Tunnel.run(withConfig: .file(path: configURL)) if code == 0 { print("Tunnel started successfully") } else { print("Tunnel failed with code: \(code)") } ``` ``` -------------------------------- ### Share Configuration via App Groups Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Use App Groups to share configuration files between your main app and its network extension. Ensure the 'group.com.example.myapp' identifier is correctly set. ```swift let appGroupId = "group.com.example.myapp" let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupId) let configURL = containerURL?.appendingPathComponent("config.yaml") // Share config file between main app and extension let config = Socks5Tunnel.Config.file(path: configURL!) Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### File Structure Overview Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/INDEX.md Directory structure of the Tun2SocksKit project, outlining the purpose of each file. ```text output/ ├── INDEX.md # This file ├── overview.md # Architecture and design ├── getting-started.md # Installation and setup ├── api-reference.md # Complete API documentation ├── types.md # Type definitions ├── configuration.md # YAML configuration schema ├── c-interop.md # C language bridging ├── threading-concurrency.md # Threading and async patterns └── deployment-distribution.md # Distribution and integration ``` -------------------------------- ### Configure Framework Search Paths in Xcode Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Specify the directories where Xcode should look for the Tun2SocksKit framework. Adjust paths based on your project structure and integration method. ```text $(SRCROOT)/Frameworks $(SRCROOT)/.build /path/to/Tun2SocksKit ``` -------------------------------- ### Run Tun2SocksKit with File Config Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/README.md Run Tun2SocksKit using a configuration file specified by its URL. This is a blocking operation. ```swift let code = Socks5Tunnel.run(withConfig: .file(path: localConfigFileURL)) ``` -------------------------------- ### Verify Framework Loading Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md A simple test to ensure the Tun2SocksKit framework is loaded correctly by attempting to access its API. This is a basic check for integration success. ```swift import Tun2SocksKit func testFrameworkLoaded() -> Bool { // Try to access the API let config: Socks5Tunnel.Config = .string(content: "") let _: Socks5Tunnel.Stats = Socks5Tunnel.stats return true } assert(testFrameworkLoaded(), "Framework failed to load") ``` -------------------------------- ### Run Tun2SocksKit with String Config Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/README.md Run Tun2SocksKit using the content of a configuration file provided as a string. This is a blocking operation. ```swift let code = Socks5Tunnel.run(withConfig: .string(content: stringConfigContent)) ``` -------------------------------- ### Build Tun2SocksKit for macOS Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Build the Tun2SocksKit framework for macOS using xcodebuild. Specify the appropriate scheme and destination. ```bash # Build for macOS xcodebuild build \ -scheme Tun2SocksKit \ -destination generic/platform=macOS ``` -------------------------------- ### Unit Tests for Tun2SocksKit Configuration Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Write unit tests to verify the creation and validation of different configuration types (file, string) and check statistics structure. ```swift import XCTest import Tun2SocksKit class Tun2SocksKitTests: XCTestCase { func testConfigFile() { let url = URL(fileURLWithPath: "/path/to/config.yaml") let config = Socks5Tunnel.Config.file(path: url) // Verify config is created } func testConfigString() { let yaml = "tunnel:\n mtu: 9000\n" let config = Socks5Tunnel.Config.string(content: yaml) // Verify config is created } func testStatsStructure() { let stats = Socks5Tunnel.stats XCTAssertGreaterThanOrEqual(stats.up.packets, 0) XCTAssertGreaterThanOrEqual(stats.down.bytes, 0) } } ``` -------------------------------- ### Socks5Tunnel.run(withConfig:completionHandler:) Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/api-reference.md Asynchronously runs the SOCKS5 tunnel with the provided configuration. This method is ideal for non-blocking operations, dispatching the tunnel to a background queue. ```APIDOC ## Socks5Tunnel.run(withConfig:completionHandler:) ### Description Asynchronously runs the SOCKS5 tunnel with the provided configuration. This method dispatches tunnel execution to a background queue. ### Method `public static func run(withConfig config: Config, completionHandler: @escaping (Int32) -> ())` ### Parameters #### Path Parameters - **config** (`Socks5Tunnel.Config`) - Required - The tunnel configuration, either from a file or string - **completionHandler** (`@escaping (Int32) -> ()`) - Required - Callback executed on a background thread when the tunnel exits, receives the exit code ### Behavior - Dispatches tunnel execution to a background queue with `.userInitiated` quality of service - Blocks until the tunnel exits, then calls the completion handler on the background queue - The completion handler runs on a background thread; dispatch to main thread if needed for UI updates ### Request Example ```swift import Tun2SocksKit import DispatchQueue let configContent = """ tunnel: mtu: 9000 socks5: port: 7890 address: ::1 """ Socks5Tunnel.run(withConfig: .string(content: configContent)) { exitCode in DispatchQueue.main.async { if exitCode == 0 { print("Tunnel exited normally") } else { print("Tunnel exited with error code: \(exitCode)") } } } // This returns immediately; tunnel runs in background ``` ``` -------------------------------- ### Asynchronous Tunnel Execution with UI Update Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/INDEX.md Shows how to run the SOCKS5 tunnel asynchronously and update the UI on the main thread upon completion. ```swift Socks5Tunnel.run(withConfig: config) { exitCode in DispatchQueue.main.async { self.updateUI(exitCode: exitCode) } } ``` -------------------------------- ### Build Tun2SocksKit with Swift Package Manager Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Build the Tun2SocksKit project in release mode using Swift Package Manager. This command is typically run from the project's root directory. ```bash # Build with Swift Package Manager swift build -c release ``` -------------------------------- ### Run SOCKS5 Tunnel Synchronously Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/api-reference.md Use this method to synchronously run the SOCKS5 tunnel with a configuration loaded from a file. Ensure the app has necessary entitlements for TUN interfaces. ```swift import Tun2SocksKit // Run tunnel from a configuration file let configURL = URL(fileURLWithPath: "/path/to/config.yaml") let code = Socks5Tunnel.run(withConfig: .file(path: configURL)) if code == 0 { print("Tunnel started successfully") } else { print("Tunnel failed with code: \(code)") } ``` -------------------------------- ### Enabling C Library Logging via Configuration Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Enable C library logging by setting the log level to 'debug' and specifying the log file (e.g., stderr or stdout) in the configuration YAML. This is useful for diagnosing issues within the C library itself. ```yaml misc: log-level: debug log-file: stderr # or stdout ``` -------------------------------- ### UI Updates from Background Thread Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Demonstrates the correct way to update UI elements from a background thread by dispatching the UI update operation to the main thread using DispatchQueue.main.async. ```swift Socks5Tunnel.run(withConfig: config) { exitCode in // This runs on a background thread // Wrong: UI updates must happen on main thread // self.statusLabel.text = "Tunnel exited" // Correct: dispatch to main DispatchQueue.main.async { self.statusLabel.text = "Tunnel exited" } } ``` -------------------------------- ### Test Configuration Parsing Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Validates that the `Socks5Tunnel.Config.string(content:)` initializer correctly parses a given YAML configuration string. Successful execution implies valid configuration format. ```swift func testConfiguration() { let testConfig = """ tunnel: mtu: 9000 socks5: port: 7890 """ let config = Socks5Tunnel.Config.string(content: testConfig) // If we got here, config is valid print("Configuration valid") } ``` -------------------------------- ### Configuration Schema Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/INDEX.md YAML schema for configuring the SOCKS5 tunnel, including MTU, SOCKS5 port and address, UDP support, and various performance-related settings. ```yaml tunnel: mtu: 9000 # TUN interface MTU in bytes socks5: port: 7890 # SOCKS5 listen port address: ::1 # SOCKS5 listen address udp: 'udp' # Enable UDP support misc: task-stack-size: 24576 # Task stack size in bytes tcp-buffer-size: 4096 # TCP buffer size in bytes max-session-count: 768 # Maximum concurrent sessions connect-timeout: 5000 # Connection timeout (ms) read-write-timeout: 60000 # Read/write timeout (ms) log-file: stderr # Log destination log-level: error # Log level limit-nofile: 65535 # Max open file descriptors ``` -------------------------------- ### Tun2SocksKit Public API - Entry Points Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/overview.md Defines the main entry points for controlling and querying the SOCKS5 tunnel, including running, quitting, and accessing statistics. ```swift import Tun2SocksKit public enum Socks5Tunnel { // Static methods for tunnel control public static func run(withConfig: Config) -> Int32 public static func run(withConfig: Config, completionHandler: @escaping (Int32) -> Void) public static func quit() // Property for retrieving statistics public static var stats: Stats { get } // Associated types public enum Config { ... } public struct Stats { ... } } ``` -------------------------------- ### Check Platform Type Sizes in Swift Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Prints the memory size of C structs `ctl_info` and `sockaddr_ctl` to verify they match expectations on the current platform. Useful for debugging C interop issues. ```swift print(MemoryLayout.size) print(MemoryLayout.size) ``` -------------------------------- ### Build Tun2SocksKit for iOS Device Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Build the Tun2SocksKit framework for an iOS device using xcodebuild. Ensure the correct scheme and destination are specified. ```bash cd Tun2SocksKit # Build for iOS device xcodebuild build \ -scheme Tun2SocksKit \ -destination generic/platform=iOS ``` -------------------------------- ### Required macOS/iOS Entitlements Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Add the necessary entitlements to your app's Entitlements.plist file to enable TUN interface creation and VPN/Network Extension support. ```xml com.apple.networking.local-outbound com.apple.networking.vpn ``` -------------------------------- ### Socks5Tunnel - Core Methods Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/overview.md Provides static methods for controlling the SOCKS5 tunnel lifecycle and accessing statistics. ```APIDOC ## Socks5Tunnel - Core Methods ### Description Provides static methods for controlling the SOCKS5 tunnel lifecycle and accessing statistics. ### Methods - **run(withConfig:)** - **Signature:** `(Config) -> Int32` - **Purpose:** Synchronously run tunnel. - **run(withConfig:completionHandler:)** - **Signature:** `(Config, @escaping (Int32) -> ()) -> Void` - **Purpose:** Asynchronously run tunnel. - **quit()** - **Signature:** `() -> Void` - **Purpose:** Stop tunnel gracefully. - **stats** - **Signature:** `var stats: Stats { get }` - **Purpose:** Get current statistics. ``` -------------------------------- ### Zip xcframework for Distribution Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Compress the generated xcframework into a zip archive for easier distribution. This command should be run in the directory where the xcframework was created. ```bash # Zip for distribution zip -r Tun2SocksKit.xcframework.zip Tun2SocksKit.xcframework ``` -------------------------------- ### Add Custom C Feature Wrapper in Swift Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Demonstrates how to create a Swift wrapper for a new C function from HevSocks5Tunnel. Assumes the C function `hev_socks5_tunnel_custom_feature` exists and returns a C string. ```swift // In Tunnel.swift public static func customFeature() -> String { let result = hev_socks5_tunnel_custom_feature() return String(cString: result) } ``` -------------------------------- ### Module Map Configuration for Manual Integration Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/deployment-distribution.md Define the module map for Tun2SocksKit if you are integrating manually. This helps Swift understand how to import the C headers. ```text module Tun2SocksKit { header "Tun2SocksKitC.h" export * } ``` -------------------------------- ### High Priority Background Work with .userInitiated QoS Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Use `.userInitiated` QoS for background tasks that require high priority, such as interactive background operations. This is the default QoS level used by the framework for background execution. ```swift DispatchQueue.global(qos: .userInitiated).async { // High priority background work } ``` -------------------------------- ### Complete Configuration Schema Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/configuration.md This is the full schema for Tun2SocksKit configuration in YAML format. It covers tunnel, SOCKS5, and miscellaneous settings. ```yaml tunnel: mtu: 9000 socks5: port: 7890 address: ::1 udp: 'udp' misc: task-stack-size: 24576 tcp-buffer-size: 4096 max-session-count: 768 connect-timeout: 5000 read-write-timeout: 60000 log-file: stderr log-level: error limit-nofile: 65535 ``` -------------------------------- ### Conditional Compilation for Platform-Specific Code Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Illustrates using Swift's preprocessor directives (`#if`, `#elseif`) to include platform-specific code blocks for macOS and iOS. ```swift #if os(macOS) // macOS-specific implementation #elseif os(iOS) // iOS-specific implementation #endif ``` -------------------------------- ### Run Tunnel and Monitoring on Dedicated Queues Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Utilize separate GCD queues for running the tunnel and monitoring its statistics to avoid blocking the main thread and to manage concurrency effectively. Update UI elements on the main thread. ```swift class TunnelService { private let tunnelQueue = DispatchQueue(label: "com.app.tunnel", qos: .userInitiated) private let monitorQueue = DispatchQueue(label: "com.app.monitor", qos: .utility) func start(config: Socks5Tunnel.Config) { tunnelQueue.async { [weak self] in // Run synchronously on dedicated queue let code = Socks5Tunnel.run(withConfig: config) DispatchQueue.main.async { print("Tunnel exited: \(code)") } } // Start monitoring on separate queue monitorQueue.async { [weak self] in while true { Thread.sleep(forTimeInterval: 2.0) let stats = Socks5Tunnel.stats DispatchQueue.main.async { // Update UI } } } } func stop() { // Safe to call from any thread Socks5Tunnel.quit() } } ``` -------------------------------- ### Logging C Calls in Swift Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Add debug output in Swift wrappers to log calls to C functions and their return values. This helps in debugging the interaction between Swift and the C library. ```swift print("Calling hev_socks5_tunnel_main with fd: \(fileDescriptor)") let code = hev_socks5_tunnel_main(configPath, fileDescriptor) print("C function returned: \(code)") ``` -------------------------------- ### Define ctl_info Structure for macOS/BSD Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/c-interop.md Structure used to query control interface information on macOS/BSD systems. Used in TUN interface discovery. ```c struct ctl_info { u_int32_t ctl_id; char ctl_name[96]; }; ``` -------------------------------- ### Handle Tunnel Exit Codes Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Demonstrates how to interpret the integer exit code returned by `Socks5Tunnel.run()`. Specific codes like 0 for success and -1 for TUN interface issues are highlighted. ```swift let exitCode = Socks5Tunnel.run(withConfig: config) switch exitCode { case 0: print("Success") case -1: print("TUN interface not available") print("Ensure entitlements are set and OS supports TUN") default: print("Error: \(exitCode)") print("Check configuration and logs") } ``` -------------------------------- ### Run Tun2SocksKit Non-Blocking Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/README.md Execute Tun2SocksKit in a non-blocking manner using string configuration content. A completion handler is provided to process the result code. ```swift Socks5Tunnel.run(withConfig: .string(content: stringConfigContent)) { code in // Do stuff with code } ``` -------------------------------- ### Run SOCKS5 Tunnel Asynchronously Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/api-reference.md Use this method to asynchronously run the SOCKS5 tunnel with a configuration provided as a string. The completion handler is called on a background thread upon tunnel exit. ```swift import Tun2SocksKit import DispatchQueue let configContent = """ tunnel: mtu: 9000 socks5: port: 7890 address: ::1 """ Socks5Tunnel.run(withConfig: .string(content: configContent)) { exitCode in DispatchQueue.main.async { if exitCode == 0 { print("Tunnel exited normally") } else { print("Tunnel exited with error code: \(exitCode)") } } } // This returns immediately; tunnel runs in background ``` -------------------------------- ### Dynamically Generate Tunnel Configuration Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/getting-started.md Generate tunnel configuration at runtime based on dynamic parameters, such as a port number. This allows for flexible configuration based on application needs. ```swift func configureForPort(_ port: Int) -> Socks5Tunnel.Config { return .string(content: """ tunnel: mtu: 9000 socks5: port: \(port) address: 127.0.0.1 misc: log-level: error """) } // Use the configuration let config = configureForPort(8080) Socks5Tunnel.run(withConfig: config) ``` -------------------------------- ### Internal Dispatch Queue Behavior (Simplified) Source: https://github.com/ebrahimtahernejad/tun2sockskit/blob/main/_autodocs/threading-concurrency.md Illustrates the internal mechanism of asynchronous execution, where work is dispatched to a background queue and the completion handler is invoked on the same background thread. ```swift // Internal behavior (simplified) DispatchQueue.global(qos: .userInitiated).async { let code = Socks5Tunnel.run(withConfig: config) completionHandler(code) // Called on background thread } ```