SshTunnel Zig Reference Documentation
SshTunnel
Current Version: 11.6.1
Chilkat.SshTunnel
Listen on a local port and forward accepted client connections through an
SSH server to a configured destination host and port.
Enable SOCKS-style dynamic port forwarding when each client connection
should choose its own destination through the tunnel.
Authenticate to the SSH server using passwords, public keys,
password-plus-key, secure password lookup, or keyboard-interactive
authentication.
Reach the SSH server through HTTP or SOCKS proxies, or build tunnels
through an existing SSH connection for multi-hop scenarios.
Start accepting client connections in the background, inspect current
state, stop accepting new clients, and disconnect active tunnel clients.
Use accept logs, tunnel logs, current-state XML, and
Learn how static forwarding, dynamic SOCKS forwarding, multi-hop tunneling,
proxies, background threads, lifecycle management, and troubleshooting fit
together.
A shorter API-focused introduction is also available in the
SshTunnel Class Overview.
Create SSH tunnels for secure local, fixed-destination, dynamic, and multi-hop forwarding.
Chilkat.SshTunnel creates SSH tunnels for forwarding local
client connections through an SSH server to a destination service, such as a
database server or other TCP service. It supports fixed destination
forwarding, dynamic SOCKS-style port forwarding, password and public-key
authentication, keyboard-interactive authentication, proxy connections to the
SSH server, multi-hop SSH connections, background accept threads,
tunnel/client logging, secure secret lookup, and connection diagnostics.
Local port forwarding
Dynamic forwarding
SSH authentication
Proxy and multi-hop access
Accept and manage clients
Logging and diagnostics
LastErrorText to troubleshoot SSH connection, forwarding,
authentication, or client-connection problems.
BeginAccepting to
start the tunnel. Local client applications connect to the tunnel's listen
port, and SshTunnel forwards the traffic through SSH. Use
Chilkat.SshTunnel for port forwarding; use
Chilkat.Ssh for direct SSH sessions, commands, channels, and
shell access.
Object Creation
// Add the package once:
// zig fetch --save https://chilkatdownload.com/11.6.1/chilkat-zig-11.6.1.tar.gz
// and in build.zig:
// const chilkat = b.dependency("chilkat", .{ .target = target, .optimize = optimize });
// exe.root_module.addImport("chilkat", chilkat.module("chilkat"));
const chilkat = @import("chilkat");
// Once per process, before any other Chilkat call:
try chilkat.unlockBundle("Anything for 30-day trial");
const ssh_tunnel = try chilkat.SshTunnel.init();
defer ssh_tunnel.deinit();Creates the underlying native Chilkat object. SshTunnel is a one-pointer struct passed by value; copying it copies the handle (two names for one object). Returns error.OutOfMemory if the library could not allocate the object. Use an object from one thread at a time; it may be handed from one thread to another.
Releases the native object. Call it exactly once per object (usually with defer); the handle is invalid afterwards. Objects returned by methods are owned by the caller too and are released the same way.
Wraps a handle obtained from the C API (chilkat.c.CkSshTunnel), taking ownership of it. The struct's handle field goes the other way, for anything the Zig API does not cover.
Errors and memory
Methods that can fail return an error union: a method whose only outcome is success or failure returns Error!void; a method producing a string returns (Error || Allocator.Error)![:0]u8; a method producing an object returns Error!T. chilkat.Error is error{ChilkatFailed}; the reason for a failure is in getLastErrorText, and the object remains usable. Properties never fail, and methods that answer a question (hasMember, isUnlocked, ...) return a plain bool.
String arguments are [:0]const u8 (UTF-8; string literals can be passed as is). String results are copies allocated with the allocator argument and owned by the caller, so they stay valid across later calls on the same object.
const text = ssh_tunnel.someMethod(allocator, ...) catch |err| {
const why = try ssh_tunnel.getLastErrorText(allocator);
defer allocator.free(why);
std.debug.print("{s}\n", .{why});
return err;
};
defer allocator.free(text);
Properties
AbortCurrent
pub fn getAbortCurrent(self: SshTunnel) bool
pub fn setAbortCurrent(self: SshTunnel, value: bool) void
Set this property to from another thread to request that
the currently running foreground operation be aborted. For example, it can
interrupt a synchronous
trueConnect that is waiting for an SSH
server response.
This property does not stop the background listener or terminate established background tunnel clients.
true; set it back to
false before starting another operation.
AcceptLog
pub fn getAcceptLog(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setAcceptLog(self: SshTunnel, value: [:0]const u8) void
Contains the in-memory activity log for the background listener thread started by
BeginAccepting.
The log is populated only when
KeepAcceptLog is
.
true
AcceptLogPath
pub fn getAcceptLogPath(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setAcceptLogPath(self: SshTunnel, value: [:0]const u8) void
Specifies the local file path where activity from the background listener thread is written.
This file-based log is separate from the in-memory
AcceptLog.
ClientIdentifier
pub fn getClientIdentifier(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setClientIdentifier(self: SshTunnel, value: [:0]const u8) void
Specifies the SSH client-identification string sent when connecting to the SSH server.
Starting in Chilkat v9.5.0.99, the default is
SSH-2.0-Chilkat_ followed by the Chilkat version number, such
as SSH-2.0-Chilkat_9.5.0.99.
SSH-2.0-. Some SSH servers
disconnect clients that send an invalid identification string.
ClientLogDir
pub fn getClientLogDir(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setClientLogDir(self: SshTunnel, value: [:0]const u8) void
Specifies the local directory where a separate log file is created for each tunnel client.
When this property is not empty, files are named using the pattern
tunnel_client_log_{random_id}.txt.
ConnectTimeoutMs
pub fn getConnectTimeoutMs(self: SshTunnel) i32
pub fn setConnectTimeoutMs(self: SshTunnel, value: i32) void
Specifies the maximum number of milliseconds allowed for establishing the SSH connection.
- The default value is
30000milliseconds (30 seconds). - A value of
0disables the connection timeout and allows an unlimited wait.
The timeout applies to more than the initial TCP connection. It also covers connection setup performed through an HTTP or SOCKS proxy and waiting for the SSH server identification string after the TCP connection has been established.
DebugLogFilePath
pub fn getDebugLogFilePath(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setDebugLogFilePath(self: SshTunnel, value: [:0]const u8) void
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
DestHostname
pub fn getDestHostname(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setDestHostname(self: SshTunnel, value: [:0]const u8) void
Specifies the destination hostname or IP address for fixed-destination port forwarding. This is typically the host running the database server or other TCP service that local clients need to reach.
The destination is interpreted from the SSH server's network environment. For
example, localhost and 127.0.0.1 refer to the SSH
server itself, not the computer running the application. Hostname resolution is
therefore performed as part of the forwarding request on the SSH-server side.
Traffic accepted by the local listener is carried through SSH, forwarded by the SSH server to this destination, and returned through the same tunnel.
DynamicPortForwarding
is true. Changing the destination while the listener is
running affects new clients only; existing clients remain connected to the
destination selected when they were accepted.
DestPort
pub fn getDestPort(self: SshTunnel) i32
pub fn setDestPort(self: SshTunnel, value: i32) void
Specifies the TCP port of the destination service used for fixed-destination forwarding, such as the port of a database server.
It is used together with
DestHostname and is ignored
when
DynamicPortForwarding
is .
true
DynamicPortForwarding
pub fn getDynamicPortForwarding(self: SshTunnel) bool
pub fn setDynamicPortForwarding(self: SshTunnel, value: bool) void
Controls whether the listener performs fixed-destination or dynamic port forwarding.
-
When
(the default), every accepted connection is forwarded tofalseDestHostnameandDestPort. -
When
, the listener acts as a SOCKS proxy and each inbound client supplies its own destination.true
The SOCKS version is detected independently from each inbound client handshake;
there is no separate inbound SOCKS-version property. SOCKS4 and SOCKS5
CONNECT requests are supported. SOCKS5 BIND and
UDP association are not supported.
Leave
InboundSocksUsername
empty to allow SOCKS5 clients to use the no-authentication method. Set the
inbound username and password to require SOCKS5 username/password
authentication. For SOCKS4, only the user ID can be checked because SOCKS4 has
no password field.
EnableSecrets
pub fn getEnableSecrets(self: SshTunnel) bool
pub fn setEnableSecrets(self: SshTunnel, value: bool) void
Enables automatic resolution of credentials from secure storage provided by the operating system.
When set to , supported password properties and methods
may receive a secret specification string beginning with
true!! instead of a literal password. Chilkat resolves the secret
from:
- Windows Credential Manager on Windows.
- Apple Keychain on macOS.
The specification format is:
!![appName|]service[|domain]|username
This applies to
HttpProxyPassword,
SocksPassword,
AuthenticatePw, and
AuthenticatePwPk.
The default value is .
false
HostKeyFingerprint
pub fn getHostKeyFingerprint(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
Contains the SSH server host-key fingerprint after
Connect or
ConnectThroughSsh
establishes the SSH connection. The value is available before user
authentication.
Example:
ssh-ed25519 256 e0:33:b1:81:a5:c6:9a:d2:2e:c9:d3:15:60:ea:cf:4c
Compare this value with a trusted expected fingerprint to verify the identity
of the SSH server. For
ConnectThroughSsh, the
fingerprint is for the final SSH server, not the first-hop server.
CloseTunnel or after the
connection is lost. Use
IsSshConnected to determine
current connection state.
HttpProxyAuthMethod
pub fn getHttpProxyAuthMethod(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setHttpProxyAuthMethod(self: SshTunnel, value: [:0]const u8) void
Specifies the authentication method to use when the outbound connection to the SSH server passes through an HTTP proxy that requires authentication.
Valid values are Basic and NTLM.
If SocksVersion is set to 4 or 5, the SOCKS proxy takes precedence and these HTTP proxy settings are ignored. The proxies are not chained.
HttpProxyDomain
pub fn getHttpProxyDomain(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setHttpProxyDomain(self: SshTunnel, value: [:0]const u8) void
Specifies the optional Windows domain used for NTLM authentication with the HTTP proxy.
This applies only to the outbound proxy connection used to reach the SSH server,
and only when
HttpProxyAuthMethod
is NTLM.
If SocksVersion is set to 4 or 5, the SOCKS proxy takes precedence and these HTTP proxy settings are ignored. The proxies are not chained.
HttpProxyHostname
pub fn getHttpProxyHostname(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setHttpProxyHostname(self: SshTunnel, value: [:0]const u8) void
Specifies the hostname or IPv4 address of the HTTP proxy through which the outbound connection to the SSH server is made.
Leave this property empty when no HTTP proxy is required.
If SocksVersion is set to 4 or 5, the SOCKS proxy takes precedence and these HTTP proxy settings are ignored. The proxies are not chained.
HttpProxyPassword
pub fn getHttpProxyPassword(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setHttpProxyPassword(self: SshTunnel, value: [:0]const u8) void
Specifies the password used to authenticate with the HTTP proxy for the outbound connection to the SSH server.
If SocksVersion is set to 4 or 5, the SOCKS proxy takes precedence and these HTTP proxy settings are ignored. The proxies are not chained.
HttpProxyPort
pub fn getHttpProxyPort(self: SshTunnel) i32
pub fn setHttpProxyPort(self: SshTunnel, value: i32) void
Specifies the TCP port of the HTTP proxy used for the outbound connection to the SSH server.
Common HTTP proxy ports include 8080 and
3128.
If SocksVersion is set to 4 or 5, the SOCKS proxy takes precedence and these HTTP proxy settings are ignored. The proxies are not chained.
HttpProxyUsername
pub fn getHttpProxyUsername(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setHttpProxyUsername(self: SshTunnel, value: [:0]const u8) void
Specifies the username used to authenticate with the HTTP proxy for the outbound connection to the SSH server.
If SocksVersion is set to 4 or 5, the SOCKS proxy takes precedence and these HTTP proxy settings are ignored. The proxies are not chained.
IdleTimeoutMs
pub fn getIdleTimeoutMs(self: SshTunnel) i32
pub fn setIdleTimeoutMs(self: SshTunnel, value: i32) void
Specifies a stall timeout, in milliseconds, for tunnel data-transfer operations.
The default value is 30000 milliseconds (30 seconds). A value of
0 disables the timeout.
InboundSocksPassword
pub fn getInboundSocksPassword(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setInboundSocksPassword(self: SshTunnel, value: [:0]const u8) void
Specifies the password required from inbound SOCKS5 clients when
DynamicPortForwarding
is .
true
This property is used together with
InboundSocksUsername.
It does not apply to SOCKS4 because the SOCKS4 protocol has no password field.
InboundSocksUsername
pub fn getInboundSocksUsername(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setInboundSocksUsername(self: SshTunnel, value: [:0]const u8) void
Specifies the username required from inbound SOCKS clients when
DynamicPortForwarding
is .
true
- For SOCKS5, setting this property enables username/password authentication.
- For SOCKS4, the value is compared with the client-supplied user ID.
- Leave it empty to require no inbound SOCKS username.
IsAccepting
pub fn getIsAccepting(self: SshTunnel) bool
when the local listener thread is running and accepting
inbound TCP connections; otherwise true.
false
This property describes only the local listener. It can remain
after the SSH connection is lost or after
trueCloseTunnel is called. In those
states a client may connect to the local port even though its traffic cannot be
forwarded.
Use IsSshConnected separately
when the application also needs to know whether the SSH transport is available.
KeepAcceptLog
pub fn getKeepAcceptLog(self: SshTunnel) bool
pub fn setKeepAcceptLog(self: SshTunnel, value: bool) void
Controls whether activity from the background listener thread is retained in memory.
The default value is . When enabled, retrieve the log
from falseAcceptLog.
KeepTunnelLog
pub fn getKeepTunnelLog(self: SshTunnel) bool
pub fn setKeepTunnelLog(self: SshTunnel, value: bool) void
Controls whether SSH tunnel-thread activity is retained in memory.
The default value is . When enabled, retrieve the log
from falseTunnelLog.
LastErrorHtml
pub fn getLastErrorHtml(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
pub fn getLastErrorText(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
pub fn getLastErrorXml(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
pub fn getLastMethodSuccess(self: SshTunnel) bool
pub fn setLastMethodSuccess(self: SshTunnel, value: bool) void
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
ListenBindIpAddress
pub fn getListenBindIpAddress(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setListenBindIpAddress(self: SshTunnel, value: [:0]const u8) void
Specifies the local IPv4 address to which the tunnel's listening socket is bound.
| Value | Listener exposure |
|---|---|
| Empty string | Binds to 0.0.0.0 and accepts connections on all local IPv4 interfaces, subject to firewall rules. |
127.0.0.1 |
Accepts connections only from the local computer through loopback. |
| A specific local LAN address | Accepts connections through that interface only; loopback is not included automatically. |
127.0.0.1. Leaving it empty may expose the listening port to
other computers on the network.
If the value is malformed or is not assigned to a local interface,
BeginAccepting returns
and the bind failure is available in
falseLastErrorText and the accept log.
ListenPort
pub fn getListenPort(self: SshTunnel) i32
Contains the local TCP port used by the listener started by
BeginAccepting.
-
If
BeginAcceptingsucceeds with a nonzero requested port, this property contains that port. -
If
BeginAcceptingsucceeds with0, the operating system chooses an available port and this property contains the allocated port when the method returns. -
After a bind failure for an explicitly requested port, this property may still
contain the requested port even though
IsAcceptingis.false - The value is initially
0.
OutboundBindIpAddress
pub fn getOutboundBindIpAddress(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setOutboundBindIpAddress(self: SshTunnel, value: [:0]const u8) void
Specifies the local IP address to which the outbound socket is bound before connecting to the SSH server.
Most applications should leave this property empty. Set it only on a multihomed computer when the SSH connection must originate from a specific local network interface or IP address.
OutboundBindPort
pub fn getOutboundBindPort(self: SshTunnel) i32
pub fn setOutboundBindPort(self: SshTunnel, value: i32) void
Specifies the local TCP port to bind before making the outbound connection to the SSH server.
The default value is 0, which allows the operating system to
choose an available ephemeral port. Nearly all applications should leave this
property unchanged.
PreferIpv6
pub fn getPreferIpv6(self: SshTunnel) bool
pub fn setPreferIpv6(self: SshTunnel, value: bool) void
Controls which IP version is preferred when a hostname resolves to both IPv4 and IPv6 addresses.
(the default) prefers IPv4.falseprefers IPv6.true
SocksHostname
pub fn getSocksHostname(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setSocksHostname(self: SshTunnel, value: [:0]const u8) void
Specifies the hostname or IPv4 address of the outbound SOCKS4 or SOCKS5 proxy used to reach the SSH server.
This property is used only when
SocksVersion is
4 or 5.
SocksPassword
pub fn getSocksPassword(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setSocksPassword(self: SshTunnel, value: [:0]const u8) void
Specifies the password for authenticating with an outbound SOCKS5 proxy used to reach the SSH server.
SOCKS4 does not support password authentication, so this property does not apply
when SocksVersion is
4.
SocksPort
pub fn getSocksPort(self: SshTunnel) i32
pub fn setSocksPort(self: SshTunnel, value: i32) void
Specifies the TCP port of the outbound SOCKS4 or SOCKS5 proxy used to reach the SSH server.
The default value is 1080. This property is used only when
SocksVersion is
4 or 5.
SocksUsername
pub fn getSocksUsername(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setSocksUsername(self: SshTunnel, value: [:0]const u8) void
Specifies the username for the outbound SOCKS4 or SOCKS5 proxy used to reach the SSH server.
This property is used only when
SocksVersion is
4 or 5.
SocksVersion
pub fn getSocksVersion(self: SshTunnel) i32
pub fn setSocksVersion(self: SshTunnel, value: i32) void
Selects whether the outbound connection to the SSH server is made through a SOCKS proxy.
| Value | Behavior |
|---|---|
0 |
Do not use a SOCKS proxy. This is the default. |
4 |
Connect through a SOCKS4 proxy. |
5 |
Connect through a SOCKS5 proxy. |
When this property is 4 or 5, the SOCKS proxy
settings take precedence over the HTTP proxy settings. The SOCKS and HTTP
proxies are not chained.
SoRcvBuf
pub fn getSoRcvBuf(self: SshTunnel) i32
pub fn setSoRcvBuf(self: SshTunnel, value: i32) void
Sets the receive-buffer size for the underlying TCP socket.
The default value is 4194304 bytes. Normally this property
should remain unchanged. If receive performance is unusually slow, testing a
larger value that is a multiple of 4096 may help.
SoSndBuf
pub fn getSoSndBuf(self: SshTunnel) i32
pub fn setSoSndBuf(self: SshTunnel, value: i32) void
Sets the send-buffer size for the underlying TCP socket.
The default value is 262144 bytes. Normally this property
should remain unchanged. If send performance is unusually slow, testing values
such as 524288 or 1048576 may help. A
multiple of 4096 is recommended.
TcpNoDelay
pub fn getTcpNoDelay(self: SshTunnel) bool
pub fn setTcpNoDelay(self: SshTunnel, value: bool) void
Controls the TCP_NODELAY socket option for the underlying TCP
connection.
The default value is . Setting it to
false disables the Nagle algorithm, which can reduce latency
when many small amounts of data are sent.
true
TunnelLog
pub fn getTunnelLog(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setTunnelLog(self: SshTunnel, value: [:0]const u8) void
Contains the in-memory activity log for the SSH tunnel and client-manager
threads. The log is populated only when
KeepTunnelLog is
.
true
TunnelLogPath
pub fn getTunnelLogPath(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setTunnelLogPath(self: SshTunnel, value: [:0]const u8) void
Specifies the local file path where SSH tunnel-thread activity is written.
This file-based log is separate from the in-memory
TunnelLog.
UncommonOptions
pub fn getUncommonOptions(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
pub fn setUncommonOptions(self: SshTunnel, value: [:0]const u8) void
Provides optional behavior for uncommon requirements. The default value is an empty string, which is appropriate for most applications.
To enable more than one option, provide a comma-separated list of keywords.
| Keyword | Effect |
|---|---|
ForceUserAuthRsaSha1 |
Forces rsa-sha1 for public-key user authentication. Set this before connecting. Added in v9.5.0.98. |
NoKeepAliveIgnoreMsg |
Disables the default SSH ignore message sent every 20 seconds to keep an idle connection alive. Added in v9.5.0.76. |
no-weak-mac-algs |
Removes hmac-sha1-96, hmac-sha1, hmac-md5, and hmac-ripemd160 from the offered MAC algorithms. Added in v9.5.0.98. |
ProtectFromVpn |
On Android, bypasses an installed or active VPN. Added in v9.5.0.80. |
+ssh-hmac-etm |
Re-enables SSH encrypt-then-MAC algorithms that were disabled by default in v9.5.0.97 as part of the Terrapin mitigation. |
+chacha20-poly1305@openssh.com |
Re-enables chacha20-poly1305@openssh.com, which was removed from the default offer in v9.5.0.97 as part of the Terrapin mitigation. |
VerboseLogging
pub fn getVerboseLogging(self: SshTunnel) bool
pub fn setVerboseLogging(self: SshTunnel, value: bool) void
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
pub fn getVersion(self: SshTunnel, allocator: Allocator) Allocator.Error![:0]u8
Methods
AuthenticatePk
Authenticates with the SSH server using public-key authentication.
The public key corresponding to privateKey must already be
installed for username on the SSH server.
Call Connect or
ConnectThroughSsh
before calling this method.
LastErrorText.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
AuthenticatePw
Authenticates with the SSH server using login and
password.
Establish the SSH connection first by calling
Connect or
ConnectThroughSsh.
After authentication succeeds, call
BeginAccepting to begin
accepting tunnel clients.
- A rejected username or password does not close the SSH connection; the application may correct the credentials and call this method again.
- Calling this method again after authentication has already succeeded returns
with an “Already authenticated” error.false
LastErrorText captured immediately after the failed call.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
AuthenticatePwPk
Authenticates with an SSH server that requires both a password and a private key.
The public key corresponding to privateKey must already be
installed for username on the SSH server. Most SSH servers
require either password authentication or public-key authentication rather than
both.
LastErrorText.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
AuthenticateSecPw
Performs the same password authentication as
AuthenticatePw, but receives
the login and password in SecureString objects.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
AuthenticateSecPwPk
Performs the same combined password-and-private-key authentication as
AuthenticatePwPk, but
receives the username and password in SecureString objects.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
BeginAccepting
Creates and starts the local listener on listenPort.
The SSH connection must already have been established. Although the listener can be started before user authentication, clients accepted in that state cannot be forwarded. The recommended sequence is to connect, authenticate, and then call this method.
- The requested port must not already be in use on the selected local interface.
- Pass
0to let the operating system choose an available port, then readListenPort. - Calling this method while the listener is already running returns
.false
The method waits for the initial bind-and-listen result. It returns
for errors such as an occupied port, a malformed bind
address, or an address that is not assigned to the local computer. Details are
available immediately in falseLastErrorText and, when enabled, the
accept log.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
CloseTunnel
Disconnects active tunnel clients and stops the tunnel-manager thread.
When waitForThreads is , the method waits
for the client and tunnel-manager threads to exit. It returns
true if a worker thread does not stop; capture
falseLastErrorText immediately for details.
StopAccepting separately to
stop accepting local TCP connections. After this method returns, the listener
may still accept a local connection even though the connection cannot be
forwarded.
Calling this method more than once is allowed. However, it does not reset the
object for a new call to
Connect. Use a new
SshTunnel object when connecting to a different SSH server.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
Connect
Establishes the SSH connection that will carry tunneled traffic. This method performs the TCP or proxy connection, the SSH protocol handshake, and host-key negotiation, but it does not authenticate the SSH user.
After connecting, verify
HostKeyFingerprint, then
authenticate by calling one of the Authenticate* methods. Finally,
call BeginAccepting to start
the local listener.
The host-key fingerprint is available immediately after this method succeeds,
before user authentication. Calling Connect again while an SSH
tunnel already exists returns .
false
Chilkat sends an SSH ignore message every 20 seconds to help
keep an unused SSH connection alive. To disable this behavior, add
NoKeepAliveIgnoreMsg to
UncommonOptions before
connecting.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
ConnectThroughSsh
Connects to a second SSH server through the existing connected and authenticated
Ssh object supplied in ssh.
application -> first SSH server -> second SSH server
hostname and port identify the second SSH server.
After this method succeeds, call an authentication method on this
SshTunnel object to authenticate with the second server.
The supplied Ssh object is borrowed, not copied. It must remain
alive, connected, and authenticated for as long as this tunnel is used. If the
first-hop object is disconnected, existing forwarded clients stop working and
new local connections cannot be forwarded. The local listener may nevertheless
remain active until explicitly stopped.
HostKeyFingerprint reports
the fingerprint of the second SSH server. After the connection is established,
fixed forwarding destinations such as 127.0.0.1 are interpreted
from the second server's network environment.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
ContinueKeyboardAuth
Continues a keyboard-interactive authentication exchange started by
StartKeyboardAuth.
If the server requested one response, pass that value directly in
response. If it requested multiple responses, pass XML in the
following form:
<response> <response1>response to first prompt</response1> <response2>response to second prompt</response2> ... <responseN>response to Nth prompt</responseN> </response>
When authentication completes, the returned XML indicates success or failure:
<success>success message</success> <error>error message</error>
If another challenge is required, the method returns another
infoRequest XML document containing the next set of prompts.
Returns error.ChilkatFailed on failure; getLastErrorText explains why. The string is allocated with allocator and owned by the caller (defer allocator.free(s)).
DisconnectAllClients
Disconnects all active tunnel clients while leaving the local listener and SSH connection available.
When waitForThreads is , the method waits
for the current client threads to exit before returning. The listener continues
accepting new clients, and newly accepted clients can be forwarded normally.
true
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
GetCurrentState
Returns an XML snapshot describing the tunnel manager, SSH channels, and current tunnel clients. The returned data is intended for diagnostics and monitoring.
A typical result has the following structure:
<CurrentState>
<tunnelManager rcvByteCount="433" sndByteCount="34"
threadRunning="1" dynamicPortForwarding="0"
staticDestHost="localhost" staticDestPort="18080">
<openChannels count="1">
<channel num="101" channelType="direct-tcpip"
clientWinSize="2096927" serverWinSize="2097127" />
</openChannels>
<closedChannels count="0" />
</tunnelManager>
<clients count="1">
<client destIp="localhost" destPort="18080"
sshChannelNum="101" threadRunning="1"
rcvByteCount="25" sndByteCount="225" />
</clients>
</CurrentState>
The exact child elements can vary with state. For example, channel collections may be empty, and some transport details may be omitted before the tunnel is started or after it stops.
| Section | Information |
|---|---|
tunnelManager |
Aggregate byte counts, worker-thread state, forwarding mode, and configured fixed destination. |
openChannels and closedChannels |
SSH channel numbers, close/EOF flags, packet sizes, and flow-control window sizes. |
clients |
Per-client destination, SSH channel number, worker state, age/activity counters, pending-data flags, and byte counts. |
Returns error.ChilkatFailed on failure; getLastErrorText explains why. The string is allocated with allocator and owned by the caller (defer allocator.free(s)).
IsSshConnected
Returns when the SSH transport used by this tunnel is
connected; otherwise returns true.
false
This is independent of the local listener state. The listener may still be
accepting local TCP connections when this method returns ,
but those connections cannot be forwarded until a usable SSH transport exists.
false
For a tunnel created with
ConnectThroughSsh, this
method becomes when the borrowed first-hop
falseSsh connection is disconnected.
SetAllowedAlgorithms
Restricts the SSH connection to the algorithms specified in
json.
This allows an application to define the exact algorithm set that may be used during SSH negotiation.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
StartKeyboardAuth
Begins keyboard-interactive authentication for login.
When the server requests one or more responses, the returned XML contains the request name, instructions, and prompts:
<infoRequest numPrompts="N"> <name>name text</name> <instruction>instruction text</instruction> <prompt1 echo="1_or_0">prompt text</prompt1> ... <promptN echo="1_or_0">prompt text</promptN> </infoRequest>
The echo attribute indicates whether the response should be
displayed while entered.
If authentication immediately succeeds or fails without requiring a response, the returned XML has one of these forms:
<success>success message</success> <error>error message</error>
Pass the requested response or responses to
ContinueKeyboardAuth.
Returns error.ChilkatFailed on failure; getLastErrorText explains why. The string is allocated with allocator and owned by the caller (defer allocator.free(s)).
StopAccepting
Stops the local listener so that no new client connections are accepted. Existing forwarded clients remain connected and continue exchanging data.
- When
waitForThreadis, the method waits for the listener thread to exit before returning.true - When it is
, shutdown is asynchronous andfalseIsAcceptingmay remainbriefly after the method returns.true
Call BeginAccepting again to
resume accepting connections. The listener can be restarted on the same port
after the previous listener has stopped.
Returns error.ChilkatFailed on failure; getLastErrorText explains why.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a call, SshTunnel raises three events so your program can show progress and offer a way out. Declare any subset of abortCheck, percentDone and progressInfo in a struct of your own and install a pointer to it with setEventHandler:
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
std.debug.print("{d}%\n", .{pct});
return false; // return true to abort the method in progress
}
pub fn progressInfo(_: *Progress, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var progress = Progress{};
ssh_tunnel.setEventHandler(&progress); // progress must outlive the installation
defer ssh_tunnel.clearEventHandler();
ssh_tunnel.setHeartbeatMs(250); // abortCheck 4 times per second during Chilkat callsInstalls handler, a pointer to any struct, as the receiver of this object's events, replacing any handler installed earlier. The dispatch is resolved at compile time: only the methods the struct declares are called, and a struct declaring none of the three is a compile error. The struct must stay alive, at the same address, until clearEventHandler or deinit.
Removes the handler; events are no longer delivered.
AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from abortCheck or percentDone aborts the running method, which then returns error.ChilkatFailed.
Events fire on the thread that called the method, before that method returns. To abort a long operation from another thread, have abortCheck read a std.atomic.Value(bool), or set the object's AbortCurrent property.
AbortCheck
pub fn abortCheck(self: *T) bool
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
const Abort = struct {
stop: std.atomic.Value(bool) = .init(false),
pub fn abortCheck(self: *Abort) bool {
return self.stop.load(.acquire); // another thread may call abort.stop.store(true, .release)
}
};
var abort = Abort{};
ssh_tunnel.setHeartbeatMs(250); // call abortCheck 4 times per second
ssh_tunnel.setEventHandler(&abort);
defer ssh_tunnel.clearEventHandler();PercentDone
pub fn percentDone(self: *T, pct: i32) bool
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
const Progress = struct {
pub fn percentDone(_: *Progress, pct: i32) bool {
// pct ranges from 1 to 100.
std.debug.print("Percent done: {d}\n", .{pct});
return false; // return true to abort the method in progress
}
};
var progress = Progress{};
ssh_tunnel.setEventHandler(&progress);
defer ssh_tunnel.clearEventHandler();ProgressInfo
pub fn progressInfo(self: *T, name: [:0]const u8, value: [:0]const u8) void
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
const Info = struct {
pub fn progressInfo(_: *Info, name: [:0]const u8, value: [:0]const u8) void {
std.debug.print("{s}: {s}\n", .{ name, value });
}
};
var info = Info{};
ssh_tunnel.setEventHandler(&info);
defer ssh_tunnel.clearEventHandler();