conn

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultTransferTimeout = 300 * time.Second

DefaultTransferTimeout 是 Upload/Download 未指定 timeoutMs 时的默认超时。

View Source
const SftpDialTimeout = 5 * time.Second

SftpDialTimeout 是 login 时建立 sftp 通道的超时。sftp 不可用不影响 login 成功, 仅决定 upload/download 可用性。

View Source
const SftpMaxPacket = 64 * 1024

SftpMaxPacket 是 sftp 单个 SSH_FXP_WRITE/READ 包的最大 payload 字节数。 默认 32KB 偏小(跨地域 RTT 高时 ack 次数多),调到 64KB 减半 ack 次数。 再大(128KB+)会撞 SSH channel window 默认 2MB 的边界,且边际收益递减。

注意:必须用 sftp.MaxPacketUnchecked 而非 sftp.MaxPacket 设置。pkg/sftp v1.13.11 的 MaxPacket(=MaxPacketChecked)会拒绝 > 32KB 的 size 并返回 error "sizes larger than 32KB might not work with all servers",导致 NewSftpClient 失败、sftp 通道恒不可用。sshmng 只连自己控制的 server(OpenSSH 默认支持 256KB 包),用 Unchecked 变体绕过库的保守校验。

UseConcurrentWrites(true) 启用 *sftp.File.ReadFrom 的并发 pipelining—— 多个 SSH_FXP_WRITE 包同时在飞。否则 ReadFrom 退化为串行 writeChunkAt 循环, 每包阻塞等 ack(与手写 read-then-write 循环等价)。对 Create-then-write 场景 安全(不同 offset 的乱序写不影响最终文件)。

UseConcurrentReads(true) 显式声明启用 *sftp.File.WriteTo 的并发 pipelining—— 多个 SSH_FXP_READ 包同时在飞,ack 异步回收,把跨地域 RTT 摊薄。Download 路径 依赖它。注意:pkg/sftp v1.13.11 的 Read 默认就是并发的(disableConcurrentReads 默认 false),此处显式 opt-in 是防御性写法,避免未来库默认变更时性能悄悄退化。 对 Open-then-read 场景安全(不同 offset 的乱序读由 WriteTo 内部按 offset 重组)。

Variables

View Source
var ErrConnLost = errors.New("connection lost")

ErrConnLost 表示 PTY 输出通道已关闭(SSH channel EOF / 连接断开)。 Session 层收到后应 Close session。放 conn 包供 pty 与 session 两层共同引用。

View Source
var ErrSftpUnavailable = fmt.Errorf("sftp not available for this session")

ErrSftpUnavailable 是 sftp 通道未建立时 Upload/Download 返回的错误。

Functions

func AtomicRemotePath added in v0.1.12

func AtomicRemotePath(remotePath string) string

AtomicRemotePath returns a temp path for remotePath used during atomic upload: <remotePath>.sshmng-tmp-<6 hex>. Same directory as the target (so PosixRename is same-filesystem = atomic). The random suffix avoids collisions across concurrent transfers to the same target.

func NewSftpClient

func NewSftpClient(client *ssh.Client) (*sftp.Client, error)

NewSftpClient 在已有 SSH 连接上建立 sftp 通道,5s 超时。 失败返回 error(调用方应把 sftpClient 留空,不影响 login 成功)。

sftp.NewClient 内部 open session + RequestSubsystem 都是同步的,但 ssh.Client 没有per-operation timeout;用 goroutine + select 实现总超时。超时后 goroutine 仍会泄漏直到 server 响应或连接断开,但 login 流程不被阻塞。

client == nil 时显式返回 error:sftp.NewClient(nil) 在 pkg/sftp v1.13.11 会 panic(ssh.Client.NewSession 解引用 nil),而 NewSftpClient 的语义是"失败返回 error 不 panic"。生产调用方 TryEnableSftp 总是传非 nil,此处为防御性边界守护。

func RandomSID

func RandomSID() (string, error)

RandomSID 生成 8 字节十六进制 session ID。 供 session.go 和 pty.go 使用;放在这里是为了避免循环依赖。

Types

type ConflictPolicy

type ConflictPolicy int

ConflictPolicy 定义目标文件已存在时的处理策略。

const (
	// ConflictOverwrite 覆盖目标文件(sftp.Create / os.Create 语义,truncate)。
	ConflictOverwrite ConflictPolicy = iota
	// ConflictSkip 跳过已存在的目标文件,不计入失败。
	ConflictSkip
	// ConflictRename 自动重命名源文件为 name_1、name_2... 直到无冲突。
	ConflictRename
)

func ParseConflictPolicy

func ParseConflictPolicy(s string) ConflictPolicy

ParseConflictPolicy 把字符串转为 ConflictPolicy,无效值默认 ConflictOverwrite。

func (ConflictPolicy) String

func (c ConflictPolicy) String() string

String 把 ConflictPolicy 转为字符串,用于 MCP 工具 args 解析与日志。

type DialOptions

type DialOptions struct {
	Addr          string         // host:port
	User          string         // SSH 用户名
	Auth          config.SSHAuth // 认证信息(Password / PrivateKey + Passphrase)
	Proxy         *config.Proxy  // 可选:传输层代理(SOCKS5 / HTTP CONNECT)
	ServerName    string         // 可选:仅用于日志关联(dialing / host key verified 等)
	HostKeyVerify bool           // false 时完全跳过 host key 校验(不读不写 known_hosts)
}

DialOptions 是 Dial 的入参。

type Dialer

type Dialer struct {
	// contains filtered or unexported fields
}

Dialer 封装 SSH 拨号逻辑:私钥加载 + auth method 装配 + TOFU host key 校验 + 代理。

func NewDialer

func NewDialer(knownHosts *KnownHostsStore, logger *slog.Logger) *Dialer

NewDialer 创建一个绑定到 knownHosts store 的 Dialer。 logger 用于 DEBUG 级别的拨号过程日志(dialing / host key verified / auth method / proxy); nil 退化为 discard handler。

func (*Dialer) Dial

func (d *Dialer) Dial(opts DialOptions) (*ssh.Client, error)

Dial 建立 SSH 连接。

  • 加载私钥(校验文件权限 0600 或更严)
  • 装配 auth methods(同时配置 Password + PrivateKey 时仅用 PrivateKey)
  • TOFU host key 校验(首次记录,变更拒绝)
  • 走代理(如有)

失败返回 error,错误信息自解释(含 "permission denied" / "host key changed" / "connection refused" 等)。

func (*Dialer) DialThrough

func (d *Dialer) DialThrough(jumpClient *ssh.Client, opts DialOptions) (*ssh.Client, error)

DialThrough 经由 jumphost 的 SSH client 拨号到 target(ssh -J 语义)。 用 jumpClient.Dial("tcp", opts.Addr) 开 direct-tcpip 通道, 再 ssh.NewClientConn 在其上建立第二层 SSH 连接。

jumpClient 必须由调用方保持存活——target 的底层 conn 是 jumpClient 上的 channel, jumpClient 关闭会导致 target 不可用。调用方负责在 target 关闭后再关 jumpClient (PtyConn.Close 通过 SetJumpClient 绑定的引用处理此顺序)。

失败时关闭已开的 direct-tcpip conn,调用方只需关闭 jumpClient。

type DirTransferOptions

type DirTransferOptions struct {
	Conflict    ConflictPolicy // 0 = ConflictOverwrite
	Concurrency int            // 0 = 默认 4
	TimeoutMs   int            // 0 = 默认 300000(300s),per file
	// OnProgress, if non-nil, is invoked after each successfully transferred
	// file with the cumulative successful byte count and file count. Called
	// under the worker pool's mutex (serialized) so the callback need not be
	// goroutine-safe. nil = no progress reporting (MCP path).
	OnProgress func(bytes int64, files int)
}

DirTransferOptions 是文件夹传输的选项。

type DirTransferResult

type DirTransferResult struct {
	Bytes    int64 // 成功传输的字节总数
	Files    int   // 成功传输的文件数
	Skipped  int   // 因 ConflictSkip 跳过的文件数
	Renamed  int   // 因 ConflictRename 重命名的文件数
	TimedOut int   // per-file 超时的文件数
}

DirTransferResult 是文件夹传输的汇总结果。

type HostKeyStatus

type HostKeyStatus int

HostKeyStatus 表示 Check 的返回状态。

const (
	HostKeyNew     HostKeyStatus = iota // 首次见到该 host,已记录新 key
	HostKeyMatch                        // host 已知,key 匹配
	HostKeyChanged                      // host 已知,key 变更(拒绝连接)
)

type KnownHostsStore

type KnownHostsStore struct {
	// contains filtered or unexported fields
}

KnownHostsStore 管理 known_hosts 文件:TOFU(首次记录)+ 后续校验。 文件格式:每行 `host:port base64-pubkey`,权限 0600,原子写。

func NewKnownHostsStore

func NewKnownHostsStore(path string) *KnownHostsStore

NewKnownHostsStore 创建一个指向 path 的 store。文件不必存在。

func (*KnownHostsStore) Check

func (s *KnownHostsStore) Check(addr string, key ssh.PublicKey) (HostKeyStatus, error)

Check 校验 host 的公钥。

  • host 首次出现:记录 key 到文件,返回 HostKeyNew
  • host 已知,key 匹配:返回 HostKeyMatch
  • host 已知,key 变更:返回 HostKeyChanged + error(含 MITM 警告)

文件权限过宽(group/other 有任何权限)时拒绝加载。

func (*KnownHostsStore) Path

func (s *KnownHostsStore) Path() string

Path 返回 known_hosts 文件路径。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址