goed2k

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 44 Imported by: 0

README

goed2k

CI

goed2k 是一个用 Go 编写的 ED2K/eMule 客户端库,附带一个可交互的终端下载管理器。

Demo

AI 参与开发

这个项目主要由 AI 辅助完成,使用的工具包括:

  • Codex
  • ChatGPT 5.4

实现过程中主要参考了仓库内的两个开源项目:

  • jed2k
  • amule

特性

goed2k 目前已经覆盖了一套可用的 ED2K/eMule 客户端能力,主要包括:

  • ED2K 文件下载与多任务并发
  • 多个 ED2K server 并发找源与 server.met 加载
  • KAD(Kad4)bootstrap、搜源与完成发布
  • KADV6(IPv6 DHT)搜源、发布与 TUI/CLI 开关
  • UPNP 端口映射(含混淆 TCP 与 KADV6 UDP)
  • 客户端间来源交换(Source Exchange)
  • Server / Kad Callback(低 ID 穿透)
  • 协议混淆 CryptLayer(--crypt-layer,默认关闭)
  • AICH 损坏块检测与恢复
  • Secure Ident 安全身份(--sec-ident--identity-key,默认关闭)
  • 上传 zlib 压缩与下载限速
  • 本地共享库、Server OfferFiles、KAD/KADV6 发布
  • Kad 关键字/Notes 搜索、Collection 链接
  • 任务优先级、分类路由、IP 过滤与封禁
  • 状态持久化与恢复、.part.met JSON 导出
  • 可交互终端下载管理器(TUI)

Web 控制台请使用独立仓库 goed2k/daemon + goed2k/webui。守护进程可复用本仓库公开包 github.com/goed2k/core/bootstrap 进行客户端初始化。

相关文档

开发与测试

# 默认单元测试(CI 同款,跳过外网联调)
go test -race -count=1 ./...

# 运行外网联调测试(需可访问 ED2K 网络)
GOED2K_RUN_LIVE_TESTS=1 go test -run LiveDownload -count=1 .

# 运行 KADV6 IPv6 联调(需本机 IPv6 出站)
GOED2K_RUN_KADV6_INTEGRATION=1 go test -run KADV6PublishSearchPipelineLive -count=1 .

推送至 main 或提交 Pull Request 时,GitHub Actions 会自动运行 go vet、全量单元测试(含覆盖率)与构建检查。Integration 工作流每日 UTC 03:00 定时运行单元测试。

安全与混淆开关(CLI)
goed2k --crypt-layer --crypt-layer-required --sec-ident --identity-key ./identity.pem \
  --credits-only-verified --max-download-rate-kb 1024 \
  --categories 'video:mp4,mkv:/videos;music:mp3:/music'

TUI 设置页(/setting)亦可配置上述选项。

状态持久化与常用参数
goed2k --state-path ~/.config/goed2k/state.json \
  --server 'host:port,host:port' \
  --out-dir ./downloads \
  --link 'ed2k://|file|...|/' \
  --setup   # 可选:启动前进入设置向导

默认状态文件:~/.config/goed2k/state.json(可用 --no-state 关闭)。退出时自动保存任务与积分等。

Web 控制台(daemon + webui)
组件 仓库 说明
守护进程 goed2k/daemon goed2kd,HTTP /api/v1 + WebSocket 事件
浏览器 UI goed2k/webui React 控制台,对接 daemon API

共享初始化逻辑见包 bootstrapConfigInitClientRunBackground)。

安装

可执行文件
go install github.com/goed2k/core/cmd/goed2k@latest
作为库
go get github.com/goed2k/core@v0.1.3

守护进程或自定义程序可复用 github.com/goed2k/core/bootstrap 进行客户端初始化(见 bootstrap/doc.go)。

快速开始

运行终端下载管理器
goed2k

如果你想直接从源码运行:

go run ./cmd/goed2k

库使用示例

package main

import (
	"log"

	"github.com/goed2k/core"
)

func main() {
	settings := goed2k.NewSettings()
	settings.ReconnectToServer = true
	settings.EnableUPnP = true

	client := goed2k.NewClient(settings)
	if err := client.Start(); err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	if err := client.ConnectServers("176.123.5.89:4725", "45.82.80.155:5687"); err != nil {
		log.Fatal(err)
	}

	if _, _, err := client.AddLink(
		"ed2k://|file|example-file.mp3|12345678|0123456789ABCDEF0123456789ABCDEF|/",
		"./downloads",
	); err != nil {
		log.Fatal(err)
	}

	if err := client.Wait(); err != nil && err != goed2k.ErrClientStopped {
		log.Fatal(err)
	}
}

License

本项目采用 MIT License。

你可以在保留原始版权声明和许可声明的前提下,自由使用、复制、修改、合并、发布、分发、再许可和销售本项目的副本。项目按“现状”提供,作者不对其适用性或稳定性作任何明示或暗示担保。

Documentation

Overview

Package goed2k provides a Go library for ED2K/eMule style downloads.

The public API is exposed from the module root so callers can import:

import "github.com/goed2k/core"

Lower-level protocol helpers are available from subpackages such as protocol, protocol/client, protocol/server, and protocol/kad.

Index

Constants

View Source
const (
	AICHBlockSize      = 180 * 1024
	AICHPieceSize      = int64(9728000)
	AICHBlocksPerPiece = 53
	AICHLastBlockSize  = AICHPieceSize - int64(AICHBlocksPerPiece-1)*AICHBlockSize
)
View Source
const (
	PieceSize        int64 = 9728000
	BlockSize        int64 = 190 * 1024
	BlockSizeInt           = int(BlockSize)
	BlocksPerPiece         = int(PieceSize / BlockSize)
	HighestLowIDED2K int64 = 16777216
	RequestQueueSize       = 3
	PartsInRequest         = 3
)
View Source
const (
	PeerIncoming       byte = 0x1
	PeerServer         byte = 0x2
	PeerDHT            byte = 0x4
	PeerResume         byte = 0x8
	PeerSourceExchange byte = 0x10
	PeerKADV6          byte = 0x20
	PeerWeb            byte = 0x40
)
View Source
const (
	MaxPeerListSize         = 100
	MinReconnectTimeout     = 10
	SourceExchangePeerLimit = 50
)
View Source
const (
	SecIdentWireVersion = 1

	SecIdentStateUnavailable     = 0
	SecIdentStateSignatureNeeded = 1
	SecIdentStateKeyAndSigNeeded = 2
)
View Source
const EndGameDPLimit = 4
View Source
const InvalidETA int64 = -1
View Source
const (
	InvalidSpeed int64 = -1
)
View Source
const MaxOutgoingBufferSize = 102*2 + 8

Variables

View Source
var ErrClientStopped = errors.New("client stopped")

Functions

func AICHBlockCount added in v0.1.0

func AICHBlockCount(size int64) int

AICHBlockCount returns how many 180KB AICH blocks cover size bytes.

func AICHRequestMarker added in v0.1.0

func AICHRequestMarker(pieceIndex, blockIndex int) protocol.AICHHash

func AllocEmuleTempPartSlot added in v0.1.3

func AllocEmuleTempPartSlot(tempDir string) (slot int, partPath string, err error)

AllocEmuleTempPartSlot 在 tempDir 中分配最小可用三位编号槽位。

func ApplyEmulePreferences added in v0.1.3

func ApplyEmulePreferences(settings *Settings, prefs EmulePreferences)

ApplyEmulePreferences 将解析结果合并到 Settings(仅覆盖非零/非空字段)。

func BuildAICHBlockHashes added in v0.1.0

func BuildAICHBlockHashes(data []byte) []protocol.AICHHash

BuildAICHBlockHashes splits data into 180KB blocks and hashes each with SHA-1.

func BuildAICHPieceRoot added in v0.1.0

func BuildAICHPieceRoot(pieceData []byte) protocol.AICHHash

BuildAICHPieceRoot computes the AICH tree root for one ed2k piece/chunk.

func BuildAICHRootFromData added in v0.1.0

func BuildAICHRootFromData(data []byte) protocol.AICHHash

BuildAICHRootFromData computes the AICH root hash for an in-memory blob.

func BuildAICHRootFromFile added in v0.1.0

func BuildAICHRootFromFile(path string) (protocol.AICHHash, error)

BuildAICHRootFromFile computes the AICH root hash for a local file.

func BuildAICHRootFromReader added in v0.1.0

func BuildAICHRootFromReader(r io.Reader, size int64) (protocol.AICHHash, error)

BuildAICHRootFromReader streams file data and returns the file-level AICH root hash.

func BuildAICHTreeRoot added in v0.1.0

func BuildAICHTreeRoot(leaves []protocol.AICHHash) protocol.AICHHash

BuildAICHTreeRoot builds the binary SHA-1 tree over leaf hashes (eMule AICH).

func Byte2String

func Byte2String(value []byte) string

func ComputeAICHHash added in v0.1.0

func ComputeAICHHash(data []byte) protocol.AICHHash

ComputeAICHHash returns the SHA-1 block hash for a single AICH sub-block.

func ComputeEd2kFileMeta

func ComputeEd2kFileMeta(path string) (root protocol.Hash, size int64, pieceHashes []protocol.Hash, err error)

ComputeEd2kFileMeta 从本地文件计算 ed2k 根哈希、大小与分片哈希列表(与 eMule 分片规则一致)。

func CurrentTime

func CurrentTime() int64

func CurrentTimeHiRes

func CurrentTimeHiRes() int64

func CurrentTimeMillis

func CurrentTimeMillis() int64

func CurrentTimeToDeadline

func CurrentTimeToDeadline(nsFromNow int64) time.Time

func DecodeAICHRequestMarker added in v0.1.0

func DecodeAICHRequestMarker(h protocol.AICHHash) (pieceIndex, blockIndex int, ok bool)

func DefaultIdentityKeyPath added in v0.1.2

func DefaultIdentityKeyPath() string

DefaultIdentityKeyPath 返回 SecIdent 默认密钥路径。

func DivCeil

func DivCeil(a, b int64) int64

func EmuleTempPartPath added in v0.1.3

func EmuleTempPartPath(tempDir string, slot int) string

EmuleTempPartPath 返回 eMule/aMule Temp 目录下的 NNN.part 路径(slot 为 1..999)。

func EnsureIdentityKeyForSecIdent added in v0.1.2

func EnsureIdentityKeyForSecIdent(settings *Settings) string

EnsureIdentityKeyForSecIdent 在启用 SecIdent 时确保 identity 路径非空。

func ExportPartMet added in v0.1.0

func ExportPartMet(path string, info PartMetInfo) error

ExportPartMet 导出 eMule 二进制 .part.met(主格式)及 goed2k JSON 旁注(.part.met.json)。

func FormatCategoriesConfig added in v0.1.2

func FormatCategoriesConfig(categories []Category) string

FormatCategoriesConfig 将分类列表编码为配置字符串。

func FormatLink(fileName string, fileSize int64, hash fmt.Stringer) string

func HTONL

func HTONL(ip int32) int32

func HTONLBytes

func HTONLBytes(order []byte) int32

func HiPart

func HiPart(value int64) int32

func Hours

func Hours(value int64) int64

func IP2String

func IP2String(ip int32) string

func Int2Address

func Int2Address(ip int32) net.IP

func IsBit

func IsBit(value, mask int32) bool

func IsLocalAddress

func IsLocalAddress(ip int32) bool

func IsLowID

func IsLowID(v int32) bool

func LocateCorruptAICHBlocks added in v0.1.0

func LocateCorruptAICHBlocks(pieceData []byte, blockHashes []protocol.AICHHash) []int

LocateCorruptAICHBlocks compares piece data against trusted block hashes.

func LowPart

func LowPart(value int64) int32

func MakeFullED2KVersion

func MakeFullED2KVersion(clientID, a, b, c int64) int64

func Minutes

func Minutes(value int64) int64

func NTOHL

func NTOHL(ip int32) int32

func NewOutgoingClientObfuscatedConn added in v0.1.0

func NewOutgoingClientObfuscatedConn(conn net.Conn, peerUserHash protocol.Hash) (net.Conn, error)

NewOutgoingClientObfuscatedConn wraps a TCP connection for client-client obfuscation. The handshake is completed lazily on the first Read/Write via PumpIO (non-blocking).

func NewOutgoingServerObfuscatedConn added in v0.1.0

func NewOutgoingServerObfuscatedConn(conn net.Conn) (net.Conn, error)

NewOutgoingServerObfuscatedConn performs simplified server obfuscation (DH key exchange).

func PackToNetworkByteOrder

func PackToNetworkByteOrder(order []byte) int32

func PeerSourceLabels

func PeerSourceLabels(sourceFlag int) []string

func PublicKeyFingerprint added in v0.1.0

func PublicKeyFingerprint(pubDER []byte) uint32

PublicKeyFingerprint returns the first four bytes of SHA-1(pubDER) as little-endian uint32.

func ResolveCategoryOutputDir added in v0.1.0

func ResolveCategoryOutputDir(categories []Category, filename, defaultDir string) string

ResolveCategoryOutputDir 按扩展名选择输出目录,无匹配时返回 defaultDir。

func ResolveEmuleDownloadPath added in v0.1.3

func ResolveEmuleDownloadPath(settings Settings, outDir, filename string) (path string, cleanup func(), err error)

ResolveEmuleDownloadPath 根据设置决定下载数据文件路径。 UseEmuleTempLayout 为 true 时使用 NNN.part;否则为 outDir/filename。

func SHA1Sum added in v0.1.0

func SHA1Sum(data []byte) [sha1.Size]byte

SHA1Sum exposes raw SHA-1 for tests.

func Seconds

func Seconds(value int64) int64

func String2IP

func String2IP(s string) (int32, error)

func UpdateCachedTime

func UpdateCachedTime()

func UserHashFromPublicKey added in v0.1.0

func UserHashFromPublicKey(pubDER []byte) (protocol.Hash, error)

UserHashFromPublicKey derives a 16-byte user hash from the public key (MD4 + eMule markers).

func VerifyAICHBlock added in v0.1.0

func VerifyAICHBlock(pieceData []byte, expected protocol.AICHHash) bool

VerifyAICHBlock checks whether pieceData matches the expected AICH block hash.

func VerifySecIdentSignature added in v0.1.0

func VerifySecIdentSignature(senderPubKey []byte, localPubKey []byte, challenge uint32, signature []byte) error

VerifySecIdentSignature verifies sender's signature over localPubKey||challenge.

func WrapIncomingObfuscatedConn added in v0.1.0

func WrapIncomingObfuscatedConn(conn net.Conn, localUserHash protocol.Hash, forceObfuscated, required bool) net.Conn

WrapIncomingObfuscatedConn accepts an inbound connection that may use obfuscation.

Types

type AICHHasher added in v0.1.0

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

AICHHasher incrementally hashes a file for AICH root computation.

func NewAICHHasher added in v0.1.0

func NewAICHHasher() *AICHHasher

func (*AICHHasher) Sum added in v0.1.0

func (h *AICHHasher) Sum() protocol.AICHHash

func (*AICHHasher) Write added in v0.1.0

func (h *AICHHasher) Write(p []byte) (int, error)

type AddTransferParams

type AddTransferParams struct {
	Hash         protocol.Hash
	AICHRootHash protocol.AICHHash
	CreateTime   int64
	Size         int64
	FilePath     string
	FileComment  string
	Paused       bool
	ResumeData   *protocol.TransferResumeData
	Handler      disk.FileHandler
	PieceHashes  []protocol.Hash
	HttpSources  []string
}

func NewAddTransferParamsFromFile

func NewAddTransferParamsFromFile(h protocol.Hash, createTime int64, size int64, file *os.File, paused bool) AddTransferParams

func NewAddTransferParamsFromHandler

func NewAddTransferParamsFromHandler(h protocol.Hash, createTime int64, size int64, handler disk.FileHandler, paused bool) AddTransferParams

func (*AddTransferParams) SetExternalFileHandler

func (a *AddTransferParams) SetExternalFileHandler(handler disk.FileHandler)

type AsyncHash

type AsyncHash struct {
	PieceIndex int
	// contains filtered or unexported fields
}

func NewAsyncHash

func NewAsyncHash(transfer *Transfer, pieceIndex int) *AsyncHash

func (*AsyncHash) Call

func (a *AsyncHash) Call() AsyncOperationResult

func (AsyncHash) Transfer

func (t AsyncHash) Transfer() *Transfer

type AsyncHashResult

type AsyncHashResult struct {
	Hash       protocol.Hash
	Transfer   *Transfer
	PieceIndex int
}

func (*AsyncHashResult) Code

func (a *AsyncHashResult) Code() BaseErrorCode

func (*AsyncHashResult) OnCompleted

func (a *AsyncHashResult) OnCompleted()

type AsyncOperationResult

type AsyncOperationResult interface {
	OnCompleted()
	Code() BaseErrorCode
}

type AsyncRelease

type AsyncRelease struct {
	DeleteFile bool
	// contains filtered or unexported fields
}

func NewAsyncRelease

func NewAsyncRelease(transfer *Transfer, deleteFile bool) *AsyncRelease

func (*AsyncRelease) Call

func (AsyncRelease) Transfer

func (t AsyncRelease) Transfer() *Transfer

type AsyncReleaseResult

type AsyncReleaseResult struct {
	Transfer   *Transfer
	Buffers    [][]byte
	DeleteFile bool
	EC         BaseErrorCode
}

func (*AsyncReleaseResult) Code

func (*AsyncReleaseResult) OnCompleted

func (a *AsyncReleaseResult) OnCompleted()

type AsyncRestore

type AsyncRestore struct {
	Block    data.PieceBlock
	FileSize int64
	// contains filtered or unexported fields
}

func NewAsyncRestore

func NewAsyncRestore(transfer *Transfer, block data.PieceBlock, fileSize int64) *AsyncRestore

func (*AsyncRestore) Call

func (AsyncRestore) Transfer

func (t AsyncRestore) Transfer() *Transfer

type AsyncRestoreResult

type AsyncRestoreResult struct {
	Block    data.PieceBlock
	Buffers  [][]byte
	Transfer *Transfer
	EC       BaseErrorCode
}

func (*AsyncRestoreResult) Code

func (*AsyncRestoreResult) OnCompleted

func (a *AsyncRestoreResult) OnCompleted()

type AsyncWrite

type AsyncWrite struct {
	Block  data.PieceBlock
	Buffer []byte
	// contains filtered or unexported fields
}

func NewAsyncWrite

func NewAsyncWrite(block data.PieceBlock, buffer []byte, transfer *Transfer) *AsyncWrite

func (*AsyncWrite) Call

func (a *AsyncWrite) Call() AsyncOperationResult

func (AsyncWrite) Transfer

func (t AsyncWrite) Transfer() *Transfer

type AsyncWriteResult

type AsyncWriteResult struct {
	Block    data.PieceBlock
	Buffers  [][]byte
	Transfer *Transfer
	EC       BaseErrorCode
}

func (*AsyncWriteResult) Code

func (a *AsyncWriteResult) Code() BaseErrorCode

func (*AsyncWriteResult) OnCompleted

func (a *AsyncWriteResult) OnCompleted()

type BaseErrorCode

type BaseErrorCode interface {
	Code() int
	Description() string
}

type BlockManager

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

func NewBlockManager

func NewBlockManager(piece, buffersCount int) *BlockManager

func (*BlockManager) Buffers

func (b *BlockManager) Buffers() [][]byte

func (*BlockManager) ByteBuffersCount

func (b *BlockManager) ByteBuffersCount() int

func (*BlockManager) HashedSize

func (b *BlockManager) HashedSize() int

func (*BlockManager) PieceHash

func (b *BlockManager) PieceHash() protocol.Hash

func (*BlockManager) PieceIndex

func (b *BlockManager) PieceIndex() int

func (*BlockManager) RegisterBlock

func (b *BlockManager) RegisterBlock(blockIndex int, buffer []byte) [][]byte

type BlockState

type BlockState byte
const (
	StateNone BlockState = iota
	StateRequested
	StateWriting
	StateFinished
)

type BlocksEnumerator

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

func NewBlocksEnumerator

func NewBlocksEnumerator(pieceCount, blocksInLastPiece int) BlocksEnumerator

func (BlocksEnumerator) BlocksInPiece

func (b BlocksEnumerator) BlocksInPiece(pieceIndex int) int

type Category added in v0.1.0

type Category struct {
	Name          string
	OutputDir     string
	AutoExtension string // 逗号分隔扩展名,如 ".mp4,.mkv" 或 "mp4,mkv"
}

Category 按文件扩展名将下载任务路由到指定输出目录。

func MatchCategory added in v0.1.0

func MatchCategory(categories []Category, filename string) *Category

MatchCategory 根据文件名扩展名查找匹配的分类。

func ParseCategoriesConfig added in v0.1.2

func ParseCategoriesConfig(raw string) ([]Category, error)

ParseCategoriesConfig 解析 TUI/CLI 分类配置字符串。 格式:name:ext1,ext2:dir;name2:ext:dir2(扩展名可带或不带点)

type Client

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

func NewClient

func NewClient(settings Settings) *Client
func (c *Client) AddCollectionLink(linkValue, outputDir string) (CollectionAddResult, error)

func (*Client) AddDHTBootstrapNodes

func (c *Client) AddDHTBootstrapNodes(nodes ...string) error

func (*Client) AddDHTv6BootstrapNodes added in v0.1.0

func (c *Client) AddDHTv6BootstrapNodes(nodes ...string) error

func (*Client) AddHttpSource added in v0.1.3

func (c *Client) AddHttpSource(hash protocol.Hash, sourceURL string) error

AddHttpSource 为指定任务添加 HTTP 下载源(支持 Range 请求)。

func (c *Client) AddLink(linkValue, outputDir string) (TransferHandle, string, error)

func (*Client) AddSharedDir

func (c *Client) AddSharedDir(path string) error

AddSharedDir 见 Session.AddSharedDir。

func (*Client) AddTransfer

func (c *Client) AddTransfer(atp AddTransferParams) (TransferHandle, error)

func (*Client) BanPeer added in v0.1.0

func (c *Client) BanPeer(endpoint protocol.Endpoint) error

func (*Client) Close

func (c *Client) Close()

func (*Client) Connect

func (c *Client) Connect(serverAddr string) error

func (*Client) ConnectSavedServer

func (c *Client) ConnectSavedServer() error
func (c *Client) ConnectServerLink(linkValue string) error

func (*Client) ConnectServerMet

func (c *Client) ConnectServerMet(path string) error

func (*Client) ConnectServers

func (c *Client) ConnectServers(serverAddrs ...string) error

func (*Client) DHTStatus

func (c *Client) DHTStatus() DHTStatus

func (*Client) DHTv6Status added in v0.1.0

func (c *Client) DHTv6Status() KADV6Status

func (*Client) EnableDHT

func (c *Client) EnableDHT() *DHTTracker

func (*Client) EnableDHTv6 added in v0.1.0

func (c *Client) EnableDHTv6() *KADV6Tracker

func (*Client) ExportPartMetForTransfer added in v0.1.0

func (c *Client) ExportPartMetForTransfer(hash protocol.Hash) error

func (*Client) FindTransfer

func (c *Client) FindTransfer(hash protocol.Hash) TransferHandle

func (*Client) GetDHTTracker

func (c *Client) GetDHTTracker() *DHTTracker

func (*Client) GetDHTv6Tracker added in v0.1.0

func (c *Client) GetDHTv6Tracker() *KADV6Tracker

func (*Client) ImportEmulePreferences added in v0.1.3

func (c *Client) ImportEmulePreferences(path string) error

ImportEmulePreferences 加载配置文件并应用到 Client。

func (*Client) ImportPartMet added in v0.1.3

func (c *Client) ImportPartMet(path string) (PartMetInfo, error)

ImportPartMet 从 <path>.part.met 导入续传数据(自动识别 eMule 二进制或 goed2k JSON)。

func (*Client) ImportSharedFile

func (c *Client) ImportSharedFile(path string) error

ImportSharedFile 见 Session.ImportSharedFile。

func (*Client) ListSharedDirs

func (c *Client) ListSharedDirs() []string

ListSharedDirs 见 Session.ListSharedDirs。

func (*Client) LoadDHTNodesDat

func (c *Client) LoadDHTNodesDat(path ...string) error

func (*Client) LoadDHTv6NodesDat added in v0.1.0

func (c *Client) LoadDHTv6NodesDat(path ...string) error

func (*Client) LoadIPFilter added in v0.1.0

func (c *Client) LoadIPFilter(path string) error

func (*Client) LoadIdentity added in v0.1.2

func (c *Client) LoadIdentity(path string) error

LoadIdentity 从 PEM 文件加载或创建 Secure Ident 密钥对。

func (*Client) LoadServerMet

func (c *Client) LoadServerMet(path string) ([]serverproto.ServerMetEntry, error)

func (*Client) LoadState

func (c *Client) LoadState(path string) error

func (*Client) PauseTransfer

func (c *Client) PauseTransfer(hash protocol.Hash) error

func (*Client) PeerStatuses

func (c *Client) PeerStatuses() []ClientPeerSnapshot

func (*Client) PublishDHTKeyword

func (c *Client) PublishDHTKeyword(keywordHash protocol.Hash, entries ...kadproto.SearchEntry) bool

func (*Client) PublishDHTNotes

func (c *Client) PublishDHTNotes(fileHash protocol.Hash, entries ...kadproto.SearchEntry) bool

func (*Client) PublishDHTSource

func (c *Client) PublishDHTSource(hash protocol.Hash, endpoint protocol.Endpoint, size int64) bool

func (*Client) PublishDHTv6Keyword added in v0.1.0

func (c *Client) PublishDHTv6Keyword(keywordHash protocol.Hash, entries ...kadv6proto.SearchEntry) bool

func (*Client) PublishDHTv6Notes added in v0.1.0

func (c *Client) PublishDHTv6Notes(fileHash protocol.Hash, entries ...kadv6proto.SearchEntry) bool

func (*Client) PublishDHTv6Source added in v0.1.0

func (c *Client) PublishDHTv6Source(hash protocol.Hash, tcpAddr *net.TCPAddr, size int64) bool

func (*Client) RemoveSharedDir

func (c *Client) RemoveSharedDir(path string) error

RemoveSharedDir 见 Session.RemoveSharedDir。

func (*Client) RemoveSharedFile

func (c *Client) RemoveSharedFile(hash protocol.Hash) bool

RemoveSharedFile 从共享库移除。

func (*Client) RemoveTransfer

func (c *Client) RemoveTransfer(hash protocol.Hash, deleteFile bool) error

func (*Client) RescanSharedDirs

func (c *Client) RescanSharedDirs() error

RescanSharedDirs 见 Session.RescanSharedDirs。

func (*Client) ResumeTransfer

func (c *Client) ResumeTransfer(hash protocol.Hash) error

func (*Client) ResumeUpload

func (c *Client) ResumeUpload(hash protocol.Hash)

func (*Client) SaveState

func (c *Client) SaveState(path string) error

func (*Client) SearchDHTKeywords

func (c *Client) SearchDHTKeywords(keywordHash protocol.Hash, cb func([]kadproto.SearchEntry)) bool

func (*Client) SearchDHTNotes added in v0.1.0

func (c *Client) SearchDHTNotes(fileHash protocol.Hash, cb func([]kadproto.SearchEntry)) bool

func (*Client) SearchDHTv6Keywords added in v0.1.0

func (c *Client) SearchDHTv6Keywords(keywordHash protocol.Hash, cb func([]kadv6proto.SearchEntry)) bool

func (*Client) SearchDHTv6Notes added in v0.1.0

func (c *Client) SearchDHTv6Notes(fileHash protocol.Hash, cb func([]kadv6proto.SearchEntry)) bool

func (*Client) SearchDHTv6Sources added in v0.1.0

func (c *Client) SearchDHTv6Sources(hash protocol.Hash, size int64, cb func([]kadv6proto.SearchEntry)) bool

func (*Client) SearchSnapshot

func (c *Client) SearchSnapshot() SearchSnapshot

func (*Client) ServerAddress

func (c *Client) ServerAddress() string

func (*Client) ServerStatuses

func (c *Client) ServerStatuses() []ServerSnapshot

func (*Client) Session

func (c *Client) Session() *Session

func (*Client) SetAutoSaveInterval

func (c *Client) SetAutoSaveInterval(interval time.Duration)

func (*Client) SetDHTStoragePoint

func (c *Client) SetDHTStoragePoint(address string) error

func (*Client) SetDHTTracker

func (c *Client) SetDHTTracker(tracker *DHTTracker)

func (*Client) SetDHTv6StoragePoint added in v0.1.0

func (c *Client) SetDHTv6StoragePoint(address string) error

func (*Client) SetDHTv6Tracker added in v0.1.0

func (c *Client) SetDHTv6Tracker(tracker *KADV6Tracker)

func (*Client) SetFriendSlot

func (c *Client) SetFriendSlot(hash protocol.Hash, enabled bool)

func (*Client) SetIPFilter added in v0.1.0

func (c *Client) SetIPFilter(filter *IPFilter)

func (*Client) SetStatePath

func (c *Client) SetStatePath(path string)

func (*Client) SetStateStore

func (c *Client) SetStateStore(store ClientStateStore)

func (*Client) SetTransferPriority added in v0.1.0

func (c *Client) SetTransferPriority(hash protocol.Hash, priority TransferPriority) error

func (*Client) SetTransferUploadPriority

func (c *Client) SetTransferUploadPriority(hash protocol.Hash, priority UploadPriority) error

func (*Client) SettingsSnapshot added in v0.1.2

func (c *Client) SettingsSnapshot() PublicSettings

SettingsSnapshot 返回当前设置快照。

func (*Client) SharedFileSnapshots added in v0.1.2

func (c *Client) SharedFileSnapshots() []SharedFileSnapshot

SharedFileSnapshots 返回共享库快照列表。

func (*Client) SharedFiles

func (c *Client) SharedFiles() []*SharedFile

SharedFiles 返回共享库快照。

func (*Client) Start

func (c *Client) Start() error

func (*Client) StartSearch

func (c *Client) StartSearch(params SearchParams) (SearchHandle, error)

func (*Client) StatePath

func (c *Client) StatePath() string

func (*Client) StateStore

func (c *Client) StateStore() ClientStateStore

func (*Client) Status

func (c *Client) Status() ClientStatus

func (*Client) Stop

func (c *Client) Stop() error

func (*Client) StopSearch

func (c *Client) StopSearch() error

func (*Client) SubscribeStatus

func (c *Client) SubscribeStatus() (<-chan ClientStatusEvent, func())

SubscribeStatus registers a non-blocking status listener using the default buffer size.

func (*Client) SubscribeStatusBuffered

func (c *Client) SubscribeStatusBuffered(buffer int) (<-chan ClientStatusEvent, func())

SubscribeStatusBuffered registers a non-blocking status listener.

The returned channel receives snapshots as the client state changes. If the receiver falls behind and the channel buffer is full, newer snapshots may be dropped instead of blocking the client loop.

The returned cancel function unregisters the listener and closes the channel.

func (*Client) SubscribeTransferProgress

func (c *Client) SubscribeTransferProgress() (<-chan TransferProgressEvent, func())

SubscribeTransferProgress subscribes to per-transfer progress changes.

Events are emitted only when a transfer's received bytes, done bytes, state, pause flag, or removal status changes.

func (*Client) SubscribeTransferProgressBuffered

func (c *Client) SubscribeTransferProgressBuffered(buffer int) (<-chan TransferProgressEvent, func())

SubscribeTransferProgressBuffered is the buffered variant of SubscribeTransferProgress.

func (*Client) SuspendUpload

func (c *Client) SuspendUpload(hash protocol.Hash, terminate bool) uint16

func (*Client) TransferSnapshots

func (c *Client) TransferSnapshots() []TransferSnapshot

func (*Client) Transfers

func (c *Client) Transfers() []TransferHandle

func (*Client) Wait

func (c *Client) Wait() error

type ClientCategoryState added in v0.1.2

type ClientCategoryState struct {
	Name          string `json:"name"`
	OutputDir     string `json:"output_dir"`
	AutoExtension string `json:"auto_extension"`
}

type ClientCreditState

type ClientCreditState struct {
	PeerHash   protocol.Hash
	Uploaded   uint64
	Downloaded uint64
}

type ClientDHTNodeState

type ClientDHTNodeState struct {
	ID        protocol.Hash `json:"id,omitempty"`
	Addr      string        `json:"addr"`
	TCPPort   uint16        `json:"tcp_port,omitempty"`
	Version   byte          `json:"version,omitempty"`
	Seed      bool          `json:"seed,omitempty"`
	HelloSent bool          `json:"hello_sent,omitempty"`
	Pinged    bool          `json:"pinged,omitempty"`
	FailCount int           `json:"fail_count,omitempty"`
	FirstSeen int64         `json:"first_seen,omitempty"`
	LastSeen  int64         `json:"last_seen,omitempty"`
}

type ClientDHTState

type ClientDHTState struct {
	SelfID              protocol.Hash        `json:"self_id,omitempty"`
	Firewalled          bool                 `json:"firewalled"`
	LastBootstrap       int64                `json:"last_bootstrap,omitempty"`
	LastRefresh         int64                `json:"last_refresh,omitempty"`
	LastFirewalledCheck int64                `json:"last_firewalled_check,omitempty"`
	StoragePoint        string               `json:"storage_point,omitempty"`
	Nodes               []ClientDHTNodeState `json:"nodes,omitempty"`
	RouterNodes         []string             `json:"router_nodes,omitempty"`
}

type ClientDHTv6NodeState added in v0.1.0

type ClientDHTv6NodeState struct {
	ID        protocol.Hash `json:"id,omitempty"`
	Addr      string        `json:"addr"`
	TCPPort   uint16        `json:"tcp_port,omitempty"`
	Version   byte          `json:"version,omitempty"`
	Seed      bool          `json:"seed,omitempty"`
	HelloSent bool          `json:"hello_sent,omitempty"`
	Pinged    bool          `json:"pinged,omitempty"`
	FailCount int           `json:"fail_count,omitempty"`
	FirstSeen int64         `json:"first_seen,omitempty"`
	LastSeen  int64         `json:"last_seen,omitempty"`
}

type ClientDHTv6State added in v0.1.0

type ClientDHTv6State struct {
	SelfID        protocol.Hash          `json:"self_id,omitempty"`
	LastBootstrap int64                  `json:"last_bootstrap,omitempty"`
	LastRefresh   int64                  `json:"last_refresh,omitempty"`
	StoragePoint  string                 `json:"storage_point,omitempty"`
	Nodes         []ClientDHTv6NodeState `json:"nodes,omitempty"`
	RouterNodes   []string               `json:"router_nodes,omitempty"`
}

type ClientPeerSnapshot

type ClientPeerSnapshot struct {
	TransferHash protocol.Hash
	FileName     string
	FilePath     string
	Peer         PeerInfo
}

type ClientSharedFileState

type ClientSharedFileState struct {
	Hash        protocol.Hash   `json:"hash"`
	Size        int64           `json:"size"`
	Path        string          `json:"path"`
	Name        string          `json:"name"`
	PieceHashes []protocol.Hash `json:"piece_hashes,omitempty"`
	Origin      SharedOrigin    `json:"origin"`
	Completed   bool            `json:"completed"`
	LastHashAt  int64           `json:"last_hash_at,omitempty"`
}

ClientSharedFileState 持久化的共享文件元数据。

type ClientState

type ClientState struct {
	Version         int                     `json:"version"`
	ServerAddress   string                  `json:"server_address,omitempty"`
	IdentityVersion int                     `json:"identity_version,omitempty"`
	IdentityKeyPath string                  `json:"identity_key_path,omitempty"`
	Transfers       []ClientTransferState   `json:"transfers"`
	Credits         []ClientCreditState     `json:"credits,omitempty"`
	FriendSlots     []protocol.Hash         `json:"friend_slots,omitempty"`
	DHT             *ClientDHTState         `json:"dht,omitempty"`
	DHTv6           *ClientDHTv6State       `json:"dhtv6,omitempty"`
	SharedDirs      []string                `json:"shared_dirs,omitempty"`
	SharedFiles     []ClientSharedFileState `json:"shared_files,omitempty"`
	BannedPeers     []protocol.Endpoint     `json:"banned_peers,omitempty"`
	Categories      []ClientCategoryState   `json:"categories,omitempty"`
}

type ClientStateStore

type ClientStateStore interface {
	Load() (*ClientState, error)
	Save(state *ClientState) error
}

type ClientStatus

type ClientStatus struct {
	Servers       []ServerSnapshot
	Peers         []ClientPeerSnapshot
	Transfers     []TransferSnapshot
	TotalDone     int64
	TotalReceived int64
	TotalWanted   int64
	Upload        int64
	DownloadRate  int
	UploadRate    int
}

type ClientStatusEvent

type ClientStatusEvent struct {
	At     time.Time
	Status ClientStatus
	DHT    DHTStatus
}

ClientStatusEvent is a point-in-time snapshot emitted by a Client listener.

func (ClientStatusEvent) TransferSnapshots

func (e ClientStatusEvent) TransferSnapshots() []TransferSnapshot

TransferSnapshots returns the transfer snapshots carried by this event.

func (ClientStatusEvent) TransferState

func (e ClientStatusEvent) TransferState(hash protocol.Hash) (TransferState, bool)

TransferState returns the current state for a transfer hash carried by this event.

func (ClientStatusEvent) TransferStates

func (e ClientStatusEvent) TransferStates() map[protocol.Hash]TransferState

TransferStates returns all transfer states in this event keyed by transfer hash.

type ClientTransferState

type ClientTransferState struct {
	Hash         protocol.Hash                `json:"hash"`
	Size         int64                        `json:"size"`
	CreateTime   int64                        `json:"create_time"`
	TargetPath   string                       `json:"target_path"`
	Paused       bool                         `json:"paused"`
	UploadPrio   UploadPriority               `json:"upload_prio,omitempty"`
	DownloadPrio TransferPriority             `json:"download_prio,omitempty"`
	ResumeData   *protocol.TransferResumeData `json:"resume_data,omitempty"`
	HttpSources  []string                     `json:"http_sources,omitempty"`
}

type CollectionAddResult added in v0.1.0

type CollectionAddResult struct {
	Handles    []TransferHandle
	TargetPath []string
}

type Connection

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

func NewConnection

func NewConnection(session *Session) Connection

func (*Connection) AppendIncoming

func (c *Connection) AppendIncoming(chunk []byte)

func (*Connection) Close

func (c *Connection) Close(ec BaseErrorCode)

func (*Connection) Connect

func (c *Connection) Connect(address net.Addr) error

func (*Connection) ConsumeIncoming

func (c *Connection) ConsumeIncoming(limit int) []byte

func (*Connection) DecodeFrames

func (*Connection) DisconnectCode

func (c *Connection) DisconnectCode() BaseErrorCode

func (*Connection) DoRead

func (c *Connection) DoRead() error

func (*Connection) DrainIncoming

func (c *Connection) DrainIncoming() []byte

func (*Connection) Endpoint

func (c *Connection) Endpoint() protocol.Endpoint

func (*Connection) FlushOutgoing

func (c *Connection) FlushOutgoing() error

func (*Connection) IncomingBytes

func (c *Connection) IncomingBytes() int

func (*Connection) IncomingChunks

func (c *Connection) IncomingChunks() [][]byte

func (*Connection) IsDisconnectHandled

func (c *Connection) IsDisconnectHandled() bool

func (*Connection) IsDisconnecting

func (c *Connection) IsDisconnecting() bool

func (*Connection) MarkDisconnectHandled

func (c *Connection) MarkDisconnectHandled()

func (*Connection) MillisecondsSinceLastReceive

func (c *Connection) MillisecondsSinceLastReceive() int64

func (*Connection) PendingPackets

func (c *Connection) PendingPackets() [][]byte

func (*Connection) PopOutgoing

func (c *Connection) PopOutgoing() []byte

func (*Connection) QueuePacket

func (c *Connection) QueuePacket(packet []byte)

func (*Connection) QueuePacketWithStats

func (c *Connection) QueuePacketWithStats(packet []byte, protocolBytes, payloadBytes int64)

func (*Connection) ReadFrames

func (c *Connection) ReadFrames() ([]protocol.PacketHeader, [][]byte, error)

func (*Connection) ReadFramesWithCombiner

func (c *Connection) ReadFramesWithCombiner(combiner *protocol.PacketCombiner) ([]protocol.PacketHeader, [][]byte, error)

func (*Connection) SecondTick

func (c *Connection) SecondTick(tickIntervalMS int64)

func (*Connection) Statistics

func (c *Connection) Statistics() Statistics

type DHTStatus

type DHTStatus struct {
	Bootstrapped      bool
	Firewalled        bool
	LiveNodes         int
	ReplacementNodes  int
	RouterNodes       int
	RunningTraversals int
	KnownNodes        int
	InitialBootstrap  bool
	ListenPort        int
	StoragePoint      string
}

type DHTTracker

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

func NewDHTTracker

func NewDHTTracker(listenPort int, timeout time.Duration) *DHTTracker

func (*DHTTracker) AddNode

func (t *DHTTracker) AddNode(addr *net.UDPAddr)

func (*DHTTracker) AddNodes

func (t *DHTTracker) AddNodes(addrs ...*net.UDPAddr)

func (*DHTTracker) ApplyNodesDat

func (t *DHTTracker) ApplyNodesDat(nodes *kadproto.NodesDat) error

func (*DHTTracker) ApplyState

func (t *DHTTracker) ApplyState(state *ClientDHTState) error

func (*DHTTracker) Close

func (t *DHTTracker) Close()

func (*DHTTracker) IsFirewalled

func (t *DHTTracker) IsFirewalled() bool

func (*DHTTracker) ListenPort

func (t *DHTTracker) ListenPort() int

func (*DHTTracker) LoadNodesDat

func (t *DHTTracker) LoadNodesDat(path string) error

func (*DHTTracker) PublishKeyword

func (t *DHTTracker) PublishKeyword(keywordHash protocol.Hash, entries ...kadproto.SearchEntry) bool

func (*DHTTracker) PublishNotes

func (t *DHTTracker) PublishNotes(fileHash protocol.Hash, entries ...kadproto.SearchEntry) bool

func (*DHTTracker) PublishSource

func (t *DHTTracker) PublishSource(hash protocol.Hash, endpoint protocol.Endpoint, size int64) bool

func (*DHTTracker) SearchKeywords

func (t *DHTTracker) SearchKeywords(hash protocol.Hash, cb func([]kadproto.SearchEntry)) bool

func (*DHTTracker) SearchNotes added in v0.1.0

func (t *DHTTracker) SearchNotes(hash protocol.Hash, cb func([]kadproto.SearchEntry)) bool

func (*DHTTracker) SearchSources

func (t *DHTTracker) SearchSources(hash protocol.Hash, size int64, cb func([]kadproto.SearchEntry)) bool

func (*DHTTracker) SetED2KUDPHandler added in v0.1.0

func (t *DHTTracker) SetED2KUDPHandler(h func(*net.UDPAddr, []byte))

SetED2KUDPHandler 在非 Kad 包(首字节 0xe3)到达时回调,例如 OP_GLOBSERVSTATRES。

func (*DHTTracker) SetStoragePoint

func (t *DHTTracker) SetStoragePoint(addr *net.UDPAddr)

func (*DHTTracker) SnapshotState

func (t *DHTTracker) SnapshotState() *ClientDHTState

func (*DHTTracker) Start

func (t *DHTTracker) Start() error

func (*DHTTracker) Status

func (t *DHTTracker) Status() DHTStatus

func (*DHTTracker) UDPConn added in v0.1.0

func (t *DHTTracker) UDPConn() *net.UDPConn

UDPConn 返回 Kad 监听的 UDP 套接字(供 Session 发送 GlobServStat 等 eD2k UDP 包)。

type DownloadingBlock

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

func (*DownloadingBlock) Abort

func (b *DownloadingBlock) Abort(p *Peer)

func (*DownloadingBlock) Finish

func (b *DownloadingBlock) Finish()

func (DownloadingBlock) IsFinished

func (b DownloadingBlock) IsFinished() bool

func (DownloadingBlock) IsFree

func (b DownloadingBlock) IsFree() bool

func (DownloadingBlock) IsRequested

func (b DownloadingBlock) IsRequested() bool

func (DownloadingBlock) IsWriting

func (b DownloadingBlock) IsWriting() bool

func (*DownloadingBlock) Request

func (b *DownloadingBlock) Request(p *Peer, speed PeerSpeed)

func (*DownloadingBlock) Write

func (b *DownloadingBlock) Write()

type DownloadingPiece

type DownloadingPiece struct {
	PieceIndex int

	Blocks []DownloadingBlock
	// contains filtered or unexported fields
}

func NewDownloadingPiece

func NewDownloadingPiece(pieceIndex, blocksCount int) DownloadingPiece

func (*DownloadingPiece) AbortDownloading

func (d *DownloadingPiece) AbortDownloading(blockIndex int, p *Peer)

func (DownloadingPiece) BlocksCount

func (d DownloadingPiece) BlocksCount() int

func (DownloadingPiece) DownloadedCount

func (d DownloadingPiece) DownloadedCount() int

func (DownloadingPiece) DownloadingBlocksCount

func (d DownloadingPiece) DownloadingBlocksCount() int

func (*DownloadingPiece) FinishBlock

func (d *DownloadingPiece) FinishBlock(blockIndex int)

func (DownloadingPiece) FinishedBlocksCount

func (d DownloadingPiece) FinishedBlocksCount() int

func (DownloadingPiece) IsDownloaded

func (d DownloadingPiece) IsDownloaded(blockIndex int) bool

func (DownloadingPiece) IsFinished

func (d DownloadingPiece) IsFinished(blockIndex int) bool

func (*DownloadingPiece) PickBlocks

func (d *DownloadingPiece) PickBlocks(rq *[]data.PieceBlock, orderLength int, peer *Peer, speed PeerSpeed, endGame bool) int

func (*DownloadingPiece) RequestBlock

func (d *DownloadingPiece) RequestBlock(blockIndex int, p *Peer, speed PeerSpeed)

func (DownloadingPiece) TotalBlocks

func (d DownloadingPiece) TotalBlocks() int

func (*DownloadingPiece) WriteBlock

func (d *DownloadingPiece) WriteBlock(blockIndex int) bool

func (DownloadingPiece) WritingBlocksCount

func (d DownloadingPiece) WritingBlocksCount() int
type EMuleLink struct {
	Hash         protocol.Hash
	AICHRootHash protocol.AICHHash
	PartHashes   []protocol.Hash
	NumberValue  int64
	StringValue  string
	Type         LinkType
	FileLinks    []EMuleLink
}

func ParseEMuleCollectionContent added in v0.1.0

func ParseEMuleCollectionContent(content string) ([]EMuleLink, error)

func ParseEMuleCollectionFile added in v0.1.0

func ParseEMuleCollectionFile(path string) ([]EMuleLink, error)
func ParseEMuleLink(uri string) (EMuleLink, error)

type EmulePreferences added in v0.1.3

type EmulePreferences struct {
	NickName          string
	ClientName        string
	ModName           string
	ListenPort        int
	UDPPort           int
	MaxUploadRateKB   int
	MaxDownloadRateKB int
	EnableDHT         bool
	EnableKad         bool
	ServerHost        string
	ServerPort        int
	TempDir           string
	IncomingDir       string
	AllocFull         bool
	SparseFiles       bool
}

EmulePreferences 为从 eMule/aMule 文本配置解析出的常用字段。

func LoadEmulePreferences added in v0.1.3

func LoadEmulePreferences(path string) (EmulePreferences, error)

LoadEmulePreferences 从文件加载 eMule/aMule 配置。

func ParseEmulePreferencesINI added in v0.1.3

func ParseEmulePreferencesINI(text string) (EmulePreferences, error)

ParseEmulePreferencesINI 解析 eMule preferences.ini / aMule amule.conf 风格键值。

type ErrorCode

type ErrorCode int
const (
	NoError ErrorCode = iota
	ServerConnUnsupportedPacket
	PeerConnUnsupportedPacket
	PacketHeaderUndefined
	InflateError
	PacketSizeIncorrect
	PacketSizeOverflow
	ServerMetHeaderIncorrect
	GenericInstantiationError
	GenericIllegalAccess

	EndOfStream              ErrorCode = 10
	IOException              ErrorCode = 11
	NoTransfer               ErrorCode = 12
	FileNotFound             ErrorCode = 13
	OutOfParts               ErrorCode = 14
	ConnectionTimeout        ErrorCode = 15
	ChannelClosed            ErrorCode = 16
	QueueRanking             ErrorCode = 17
	FileIOError              ErrorCode = 18
	UnableToDeleteFile       ErrorCode = 19
	InternalError            ErrorCode = 20
	BufferUnderflowException ErrorCode = 21
	BufferGetException       ErrorCode = 22
	WrongHashSet             ErrorCode = 23
	HashMismatch             ErrorCode = 24
	NonWriteableChannel      ErrorCode = 25

	TagTypeUnknown         ErrorCode = 30
	TagToStringInvalid     ErrorCode = 31
	TagToIntInvalid        ErrorCode = 32
	TagToLongInvalid       ErrorCode = 33
	TagToFloatInvalid      ErrorCode = 34
	TagToHashInvalid       ErrorCode = 35
	TagFromStringInvalidCP ErrorCode = 36
	TagToBlobInvalid       ErrorCode = 37
	TagToBSOBInvalid       ErrorCode = 38

	DuplicatePeer           ErrorCode = 40
	DuplicatePeerConnection ErrorCode = 41
	PeerLimitExceeded       ErrorCode = 42
	SecurityException       ErrorCode = 43
	UnsupportedEncoding     ErrorCode = 44
	IllegalArgument         ErrorCode = 45

	TransferFinished ErrorCode = 50
	TransferPaused   ErrorCode = 51
	TransferAborted  ErrorCode = 52

	NoMemory                ErrorCode = 60
	SessionStopping         ErrorCode = 61
	IncomingDirInaccessible ErrorCode = 62
	BufferTooLarge          ErrorCode = 63
	NotConnected            ErrorCode = 64
	Interrupted             ErrorCode = 65

	PortMappingAlreadyMapped   ErrorCode = 70
	PortMappingNoDevice        ErrorCode = 71
	PortMappingError           ErrorCode = 72
	PortMappingIOError         ErrorCode = 73
	PortMappingSAXError        ErrorCode = 74
	PortMappingConfigError     ErrorCode = 75
	PortMappingException       ErrorCode = 76
	PortMappingCommandRejected ErrorCode = 77

	DHTRequestAlreadyRunning ErrorCode = 80
	DHTTrackerAborted        ErrorCode = 81

	LinkMailformed         ErrorCode = 90
	URISyntaxError         ErrorCode = 91
	NumberFormatError      ErrorCode = 92
	UnknownLinkType        ErrorCode = 93
	GithubCfgIPIsNull      ErrorCode = 94
	GithubCfgPortsAreNull  ErrorCode = 95
	GithubCfgPortsAreEmpty ErrorCode = 96
	InvalidPRParameter     ErrorCode = 97
	PeerRequestOverflow    ErrorCode = 98

	Fail ErrorCode = 100
)

func (ErrorCode) Code

func (e ErrorCode) Code() int

func (ErrorCode) Description

func (e ErrorCode) Description() string

func (ErrorCode) String

func (e ErrorCode) String() string

type FileClientStateStore

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

func NewFileClientStateStore

func NewFileClientStateStore(path string) *FileClientStateStore

func (*FileClientStateStore) Load

func (s *FileClientStateStore) Load() (*ClientState, error)

func (*FileClientStateStore) Path

func (s *FileClientStateStore) Path() string

func (*FileClientStateStore) Save

func (s *FileClientStateStore) Save(state *ClientState) error

type IPFilter added in v0.1.0

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

IPFilter 维护 eMule 风格 IP 过滤规则;命中且 AccessLevel < FilterLevel 时拒绝连接。

func LoadIPFilter added in v0.1.0

func LoadIPFilter(path string) (*IPFilter, error)

LoadIPFilter 从文件加载 IP 过滤规则,自动识别 eMule ipfilter.dat 或简单文本格式。

func NewIPFilter added in v0.1.0

func NewIPFilter() *IPFilter

func ParseEmuleIPFilter added in v0.1.3

func ParseEmuleIPFilter(text string, filterLevel int) (*IPFilter, error)

ParseEmuleIPFilter 解析 eMule/aMule PeerGuardian 格式 ipfilter.dat。 格式:RangeStart - RangeEnd , AccessLevel , Description 或 AntiP2P:Description : RangeStart - RangeEnd(AccessLevel 视为 0)

func ParseIPFilter added in v0.1.0

func ParseIPFilter(text string) (*IPFilter, error)

ParseIPFilter 解析简单文本过滤规则(每行 CIDR 或单 IP,无条件拒绝)。

func ParseIPFilterBytes added in v0.1.3

func ParseIPFilterBytes(raw []byte) (*IPFilter, error)

ParseIPFilterBytes 根据内容自动选择解析器。

func (*IPFilter) Contains added in v0.1.0

func (f *IPFilter) Contains(ip net.IP) bool

func (*IPFilter) FilterLevel added in v0.1.3

func (f *IPFilter) FilterLevel() int

FilterLevel 返回当前过滤级别(默认 127)。

func (*IPFilter) IsEmpty added in v0.1.0

func (f *IPFilter) IsEmpty() bool

func (*IPFilter) Ranges added in v0.1.3

func (f *IPFilter) Ranges() []IPFilterRange

Ranges 返回 eMule 格式规则副本。

func (*IPFilter) SetFilterLevel added in v0.1.3

func (f *IPFilter) SetFilterLevel(level int)

SetFilterLevel 设置过滤级别:AccessLevel < level 的区间将被拒绝。

type IPFilterRange added in v0.1.3

type IPFilterRange struct {
	Start       net.IP
	End         net.IP
	AccessLevel int
	Description string
}

IPFilterRange 表示 ipfilter.dat 中的一条 IP 范围规则。

type IdentityState added in v0.1.0

type IdentityState struct {
	Version int
	// contains filtered or unexported fields
}

IdentityState holds the local RSA identity used for SecIdent.

func GenerateIdentityKeyPair added in v0.1.0

func GenerateIdentityKeyPair(path string) (*IdentityState, error)

GenerateIdentityKeyPair creates a new RSA 2048 key pair and writes the private key PEM (0600).

func LoadIdentityState added in v0.1.0

func LoadIdentityState(path string) (*IdentityState, error)

LoadIdentityState loads or creates the identity at path.

func NewIdentityState added in v0.1.0

func NewIdentityState() *IdentityState

func (*IdentityState) Available added in v0.1.0

func (id *IdentityState) Available() bool

func (*IdentityState) Fingerprint added in v0.1.0

func (id *IdentityState) Fingerprint() uint32

func (*IdentityState) KeyPath added in v0.1.0

func (id *IdentityState) KeyPath() string

func (*IdentityState) LinkUserHash added in v0.1.0

func (id *IdentityState) LinkUserHash(hash protocol.Hash)

LinkUserHash associates the identity with an existing protocol.Hash instead of deriving one.

func (*IdentityState) PublicKeyDER added in v0.1.0

func (id *IdentityState) PublicKeyDER() []byte

func (*IdentityState) SignChallenge added in v0.1.0

func (id *IdentityState) SignChallenge(remotePubKey []byte, challenge uint32) ([]byte, error)

SignChallenge signs remotePubKey||challenge with SHA-1 + PKCS1v15 (eMule SecIdent v1).

func (*IdentityState) UserHash added in v0.1.0

func (id *IdentityState) UserHash() protocol.Hash

type JED2KError

type JED2KError struct {
	Cause error
	EC    BaseErrorCode
}

func NewError

func NewError(ec BaseErrorCode) *JED2KError

func WrapError

func WrapError(cause error, ec BaseErrorCode) *JED2KError

func (*JED2KError) Error

func (e *JED2KError) Error() string

func (*JED2KError) ErrorCode

func (e *JED2KError) ErrorCode() BaseErrorCode

func (*JED2KError) Unwrap

func (e *JED2KError) Unwrap() error

type KADV6RoutingNode added in v0.1.0

type KADV6RoutingNode struct {
	ID        kadv6proto.ID
	Addr      *net.UDPAddr
	TCPPort   uint16
	Version   byte
	Seed      bool
	HelloSent bool
	Pinged    bool
	FailCount int
	FirstSeen time.Time
	LastSeen  time.Time
}

func (*KADV6RoutingNode) Key added in v0.1.0

func (n *KADV6RoutingNode) Key() string

func (*KADV6RoutingNode) KnownID added in v0.1.0

func (n *KADV6RoutingNode) KnownID() bool

type KADV6Status added in v0.1.0

type KADV6Status struct {
	Bootstrapped      bool
	LiveNodes         int
	ReplacementNodes  int
	RouterNodes       int
	RunningTraversals int
	KnownNodes        int
	InitialBootstrap  bool
	ListenPort        int
	StoragePoint      string
}

type KADV6Tracker added in v0.1.0

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

func NewKADV6Tracker added in v0.1.0

func NewKADV6Tracker(listenPort int, timeout time.Duration) *KADV6Tracker

func (*KADV6Tracker) AddNode added in v0.1.0

func (t *KADV6Tracker) AddNode(addr *net.UDPAddr)

func (*KADV6Tracker) AddNodes added in v0.1.0

func (t *KADV6Tracker) AddNodes(addrs ...*net.UDPAddr)

func (*KADV6Tracker) ApplyNodesDat added in v0.1.0

func (t *KADV6Tracker) ApplyNodesDat(nodes *kadv6proto.NodesDat) error

func (*KADV6Tracker) ApplyState added in v0.1.0

func (t *KADV6Tracker) ApplyState(state *ClientDHTv6State) error

func (*KADV6Tracker) Close added in v0.1.0

func (t *KADV6Tracker) Close()

func (*KADV6Tracker) ListenPort added in v0.1.0

func (t *KADV6Tracker) ListenPort() int

func (*KADV6Tracker) LoadNodesDat added in v0.1.0

func (t *KADV6Tracker) LoadNodesDat(path string) error

func (*KADV6Tracker) PublishKeyword added in v0.1.0

func (t *KADV6Tracker) PublishKeyword(keywordHash protocol.Hash, entries ...kadv6proto.SearchEntry) bool

func (*KADV6Tracker) PublishNotes added in v0.1.0

func (t *KADV6Tracker) PublishNotes(fileHash protocol.Hash, entries ...kadv6proto.SearchEntry) bool

func (*KADV6Tracker) PublishSource added in v0.1.0

func (t *KADV6Tracker) PublishSource(hash protocol.Hash, tcpAddr *net.TCPAddr, size int64) bool

func (*KADV6Tracker) SearchKeywords added in v0.1.0

func (t *KADV6Tracker) SearchKeywords(hash protocol.Hash, cb func([]kadv6proto.SearchEntry)) bool

func (*KADV6Tracker) SearchNotes added in v0.1.0

func (t *KADV6Tracker) SearchNotes(hash protocol.Hash, cb func([]kadv6proto.SearchEntry)) bool

func (*KADV6Tracker) SearchSources added in v0.1.0

func (t *KADV6Tracker) SearchSources(hash protocol.Hash, size int64, cb func([]kadv6proto.SearchEntry)) bool

func (*KADV6Tracker) SetStoragePoint added in v0.1.0

func (t *KADV6Tracker) SetStoragePoint(addr *net.UDPAddr)

func (*KADV6Tracker) SnapshotState added in v0.1.0

func (t *KADV6Tracker) SnapshotState() *ClientDHTv6State

func (*KADV6Tracker) Start added in v0.1.0

func (t *KADV6Tracker) Start() error

func (*KADV6Tracker) Status added in v0.1.0

func (t *KADV6Tracker) Status() KADV6Status

func (*KADV6Tracker) UDPConn added in v0.1.0

func (t *KADV6Tracker) UDPConn() *net.UDPConn

type KadRoutingNode

type KadRoutingNode struct {
	ID        kadproto.ID
	Addr      *net.UDPAddr
	TCPPort   uint16
	Version   byte
	Seed      bool
	HelloSent bool
	Pinged    bool
	FailCount int
	FirstSeen time.Time
	LastSeen  time.Time
}

func (*KadRoutingNode) Key

func (n *KadRoutingNode) Key() string

func (*KadRoutingNode) KnownID

func (n *KadRoutingNode) KnownID() bool

type LinkType

type LinkType string
const (
	LinkServer     LinkType = "SERVER"
	LinkServers    LinkType = "SERVERS"
	LinkNodes      LinkType = "NODES"
	LinkFile       LinkType = "FILE"
	LinkCollection LinkType = "COLLECTION"
)

type MiscOptions

type MiscOptions struct {
	AICHVersion         int
	UnicodeSupport      int
	UDPVer              int
	DataCompVer         int
	SupportSecIdent     int
	SourceExchange1Ver  int
	ExtendedRequestsVer int
	AcceptCommentVer    int
	NoViewSharedFiles   int
	MultiPacket         int
	SupportsPreview     int
}

func (*MiscOptions) Assign

func (m *MiscOptions) Assign(value int)

func (MiscOptions) IntValue

func (m MiscOptions) IntValue() int

type MiscOptions2

type MiscOptions2 struct {
	Value int
}

func (*MiscOptions2) Assign

func (m *MiscOptions2) Assign(value int)

func (*MiscOptions2) SetCaptcha

func (m *MiscOptions2) SetCaptcha()

func (*MiscOptions2) SetExtMultipacket

func (m *MiscOptions2) SetExtMultipacket()

func (*MiscOptions2) SetLargeFiles

func (m *MiscOptions2) SetLargeFiles()

func (*MiscOptions2) SetSourceExt2

func (m *MiscOptions2) SetSourceExt2()

func (MiscOptions2) SupportCaptcha

func (m MiscOptions2) SupportCaptcha() bool

func (MiscOptions2) SupportExtMultipacket

func (m MiscOptions2) SupportExtMultipacket() bool

func (MiscOptions2) SupportLargeFiles

func (m MiscOptions2) SupportLargeFiles() bool

func (MiscOptions2) SupportSourceExt2

func (m MiscOptions2) SupportSourceExt2() bool

type ObfuscatedConn added in v0.1.0

type ObfuscatedConn struct {
	net.Conn
	// contains filtered or unexported fields
}

ObfuscatedConn wraps a TCP connection with eMule Basic Obfuscation (RC4).

func (*ObfuscatedConn) Read added in v0.1.0

func (o *ObfuscatedConn) Read(p []byte) (int, error)

func (*ObfuscatedConn) Write added in v0.1.0

func (o *ObfuscatedConn) Write(p []byte) (int, error)

type PartMetDocument added in v0.1.0

type PartMetDocument struct {
	Format           string          `json:"format"`
	Version          int             `json:"version"`
	FileHash         protocol.Hash   `json:"file_hash,omitempty"`
	FileSize         int64           `json:"file_size,omitempty"`
	PieceHashes      []protocol.Hash `json:"piece_hashes,omitempty"`
	CompletedPieces  []bool          `json:"completed_pieces,omitempty"`
	DownloadedBlocks []partMetBlock  `json:"downloaded_blocks,omitempty"`
	KnownPeers       []string        `json:"known_peers,omitempty"`
	HttpSources      []string        `json:"http_sources,omitempty"`
}

PartMetDocument 为 <file>.part.met JSON 旁注格式。

type PartMetInfo added in v0.1.3

type PartMetInfo struct {
	Hash        protocol.Hash
	FileSize    int64
	Filename    string
	Resume      *protocol.TransferResumeData
	HttpSources []string
}

PartMetInfo 为导入/导出 .part.met 的统一结构。

func ImportEmulePartMetFromSlot added in v0.1.3

func ImportEmulePartMetFromSlot(partPath string) (PartMetInfo, error)

ImportEmulePartMetFromSlot 从 eMule 风格 NNN.part 旁注导入(若存在)。

func ImportPartMet added in v0.1.3

func ImportPartMet(path string) (PartMetInfo, error)

ImportPartMet 自动识别 eMule 二进制或 goed2k JSON .part.met。

func ParsePartMetBytes added in v0.1.3

func ParsePartMetBytes(raw []byte) (PartMetInfo, error)

ParsePartMetBytes 解析 .part.met 字节内容。

type Peer

type Peer struct {
	LastConnected  int64
	NextConnection int64
	FailCount      int
	Connectable    bool
	SourceFlag     int
	Connection     any
	Endpoint       protocol.Endpoint
	// ServerClientID 非零表示服务器来源的低 ID 用户 ID(Endpoint 的 IP 字段实为 client ID)。
	ServerClientID int32
	// DialAddr 可选;非 nil 时优先用于 TCP 拨号(如 KADV6 纯 IPv6 来源),与 Endpoint 可并存(IPv4 时常同步)。
	DialAddr *net.TCPAddr
	// UserHash / CryptOptions 来自 Source Exchange v4,用于协议混淆拨号。
	UserHash     protocol.Hash
	CryptOptions uint8
}

func NewPeer

func NewPeer(ep protocol.Endpoint) Peer

func NewPeerFromTCPAddr

func NewPeerFromTCPAddr(addr *net.TCPAddr, connectable bool, sourceFlag int) Peer

NewPeerFromTCPAddr 从 TCP 地址构造 Peer:IPv4 时填充 Endpoint;IPv6 时仅填 DialAddr(Policy 排序用 DialAddr 字符串键)。

func NewPeerWithSource

func NewPeerWithSource(ep protocol.Endpoint, conn bool, sourceFlag int) Peer

func PeerFromKADV6SearchEntry

func PeerFromKADV6SearchEntry(se kadv6.SearchEntry, sourceFlag int) (Peer, bool)

PeerFromKADV6SearchEntry 将 KADV6 SearchEntry 中的 TCP 源转为 Policy 用 Peer(Connectable=true)。 若条目不含有效 IPv6 源地址则返回 false。供 KADV6Tracker 接入后调用。

func (Peer) CanEncodeAnswerSources2

func (p Peer) CanEncodeAnswerSources2(sx2Version byte) bool

CanEncodeAnswerSources2 判断是否可编码进 AnswerSources2(IPv4 或 v5 IPv6)。

func (Peer) Compare

func (p Peer) Compare(other Peer) int

func (Peer) EffectiveEndpointForSX

func (p Peer) EffectiveEndpointForSX() (protocol.Endpoint, bool)

EffectiveEndpointForSX 返回用于 SX 条目中 UserID 的 IPv4 Endpoint(含 IPv4-mapped IPv6 映射为 IPv4)。

func (Peer) Equal

func (p Peer) Equal(other Peer) bool

func (Peer) HasDialableAddress

func (p Peer) HasDialableAddress() bool

HasDialableAddress 是否具备可尝试 TCP 的地址(IPv4 Endpoint、DialAddr,或可通过服务器回调的低 ID)。

func (Peer) ToSourceExchangeEntry added in v0.1.3

func (p Peer) ToSourceExchangeEntry(sx1Ver int, sx2Version byte, cryptOptions uint8) (clientproto.SourceExchangeEntry, bool)

ToSourceExchangeEntry 将 Peer 编码为 AnswerSources2 条目。

type PeerConnection

type PeerConnection struct {
	Connection
	// contains filtered or unexported fields
}

func NewIncomingPeerConnection

func NewIncomingPeerConnection(session *Session, conn net.Conn, forceObfuscated bool) *PeerConnection

func NewPeerConnection

func NewPeerConnection(session *Session, point protocol.Endpoint, transfer *Transfer, peerInfo *Peer) *PeerConnection

func (*PeerConnection) AbortAllRequests

func (p *PeerConnection) AbortAllRequests()

func (*PeerConnection) ActiveUploadSource

func (p *PeerConnection) ActiveUploadSource() UploadableResource

func (*PeerConnection) AddUploadRequest

func (p *PeerConnection) AddUploadRequest(req data.PeerRequest)

func (*PeerConnection) ClearUploadBlockRequests

func (p *PeerConnection) ClearUploadBlockRequests()

func (*PeerConnection) ClearUploadWaitStart

func (p *PeerConnection) ClearUploadWaitStart()

func (*PeerConnection) CompleteBlock

func (p *PeerConnection) CompleteBlock(pb *PendingBlock) bool

func (*PeerConnection) Connect

func (p *PeerConnection) Connect() error

func (*PeerConnection) Endpoint

func (p *PeerConnection) Endpoint() protocol.Endpoint

func (*PeerConnection) FlushOutgoing added in v0.1.3

func (p *PeerConnection) FlushOutgoing() error

func (*PeerConnection) FriendSlot

func (p *PeerConnection) FriendSlot() bool

func (*PeerConnection) GetDownloading

func (p *PeerConnection) GetDownloading(block data.PieceBlock) *PendingBlock

func (*PeerConnection) GetInfo

func (p *PeerConnection) GetInfo() PeerInfo

func (*PeerConnection) GetPeer

func (p *PeerConnection) GetPeer() *Peer

func (*PeerConnection) HandleAICHAnswer added in v0.1.0

func (p *PeerConnection) HandleAICHAnswer(value *clientproto.AICHAnswer)

func (*PeerConnection) HandleAICHFileHashAnswer added in v0.1.0

func (p *PeerConnection) HandleAICHFileHashAnswer(value *clientproto.AICHFileHashAnswer)

func (*PeerConnection) HandleAnswerSources added in v0.1.3

func (p *PeerConnection) HandleAnswerSources(ans *clientproto.AnswerSources)

func (*PeerConnection) HandleAnswerSources2

func (p *PeerConnection) HandleAnswerSources2(ans *clientproto.AnswerSources2)

func (*PeerConnection) HandleClientAICHFileHashRequest added in v0.1.0

func (p *PeerConnection) HandleClientAICHFileHashRequest(value *clientproto.AICHFileHashRequest)

func (*PeerConnection) HandleClientAICHRequest added in v0.1.0

func (p *PeerConnection) HandleClientAICHRequest(value *clientproto.AICHRequest)

func (*PeerConnection) HandleClientCancelTransfer

func (p *PeerConnection) HandleClientCancelTransfer()

func (*PeerConnection) HandleClientFileRequest

func (p *PeerConnection) HandleClientFileRequest(value *clientproto.FileRequest)

func (*PeerConnection) HandleClientFileStatusRequest

func (p *PeerConnection) HandleClientFileStatusRequest(value *clientproto.FileStatusRequest)

func (*PeerConnection) HandleClientHashSetRequest

func (p *PeerConnection) HandleClientHashSetRequest(value *clientproto.HashSetRequest)

func (*PeerConnection) HandleClientHello

func (p *PeerConnection) HandleClientHello(value *clientproto.Hello)

func (*PeerConnection) HandleClientRequestParts32

func (p *PeerConnection) HandleClientRequestParts32(value *clientproto.RequestParts32) error

func (*PeerConnection) HandleClientRequestParts64

func (p *PeerConnection) HandleClientRequestParts64(value *clientproto.RequestParts64) error

func (*PeerConnection) HandleClientRequestPreview added in v0.1.3

func (p *PeerConnection) HandleClientRequestPreview(req *clientproto.RequestPreview)

func (*PeerConnection) HandleClientStartUpload

func (p *PeerConnection) HandleClientStartUpload(value *clientproto.StartUpload)

func (*PeerConnection) HandleExtHello

func (p *PeerConnection) HandleExtHello(value *clientproto.ExtHello)

func (*PeerConnection) HandleExtHelloAnswer added in v0.1.0

func (p *PeerConnection) HandleExtHelloAnswer(value *clientproto.ExtHelloAnswer)

func (*PeerConnection) HandleFileAnswer

func (p *PeerConnection) HandleFileAnswer(value *clientproto.FileAnswer)

func (*PeerConnection) HandleFileComment added in v0.1.0

func (p *PeerConnection) HandleFileComment(value *clientproto.FileComment)

func (*PeerConnection) HandleFileStatusAnswer

func (p *PeerConnection) HandleFileStatusAnswer(value *clientproto.FileStatusAnswer)

func (*PeerConnection) HandleHelloAnswer

func (p *PeerConnection) HandleHelloAnswer(value *clientproto.HelloAnswer)

func (*PeerConnection) HandlePreviewAnswer added in v0.1.3

func (p *PeerConnection) HandlePreviewAnswer(ans *clientproto.PreviewAnswer)

func (*PeerConnection) HandlePublicKey added in v0.1.0

func (p *PeerConnection) HandlePublicKey(value *clientproto.PublicKey)

func (*PeerConnection) HandleRequestSources added in v0.1.3

func (p *PeerConnection) HandleRequestSources(req *clientproto.RequestSources)

func (*PeerConnection) HandleRequestSources2

func (p *PeerConnection) HandleRequestSources2(req *clientproto.RequestSources2)

func (*PeerConnection) HandleSecIdentState added in v0.1.0

func (p *PeerConnection) HandleSecIdentState(value *clientproto.SecIdentState)

func (*PeerConnection) HandleSignature added in v0.1.0

func (p *PeerConnection) HandleSignature(value *clientproto.Signature)

func (*PeerConnection) HasEndpoint

func (p *PeerConnection) HasEndpoint() bool

func (*PeerConnection) IdentityVerified added in v0.1.0

func (p *PeerConnection) IdentityVerified() bool

func (*PeerConnection) IsRequesting

func (p *PeerConnection) IsRequesting(block data.PieceBlock) bool

func (*PeerConnection) IsUploadConnected

func (p *PeerConnection) IsUploadConnected() bool

func (*PeerConnection) IsUploadLowID

func (p *PeerConnection) IsUploadLowID() bool

func (*PeerConnection) OnConnect

func (p *PeerConnection) OnConnect()

func (*PeerConnection) OnDisconnect

func (p *PeerConnection) OnDisconnect(ec BaseErrorCode)

func (*PeerConnection) PrepareHello

func (p *PeerConnection) PrepareHello() clientproto.Hello

func (*PeerConnection) PrepareHelloAnswer

func (p *PeerConnection) PrepareHelloAnswer() clientproto.HelloAnswer

func (*PeerConnection) ProcessIncoming

func (p *PeerConnection) ProcessIncoming() error

func (*PeerConnection) ReceiveCompressedData

func (p *PeerConnection) ReceiveCompressedData(header protocol.PacketHeader, offset, compressedLength int64, payloadSize int)

func (*PeerConnection) ReceiveData

func (p *PeerConnection) ReceiveData(req data.PeerRequest, compressed bool)

func (*PeerConnection) ReceivePendingData

func (p *PeerConnection) ReceivePendingData()

func (*PeerConnection) RequestBlocks

func (p *PeerConnection) RequestBlocks()

func (*PeerConnection) ResetUploadSession

func (p *PeerConnection) ResetUploadSession()

func (*PeerConnection) SecondTick

func (p *PeerConnection) SecondTick(tickIntervalMS int64)

func (*PeerConnection) SendAICHAnswer added in v0.1.0

func (p *PeerConnection) SendAICHAnswer(res UploadableResource, requested []protocol.AICHHash)

func (*PeerConnection) SendAICHFileHashAnswer added in v0.1.0

func (p *PeerConnection) SendAICHFileHashAnswer(res UploadableResource)

func (*PeerConnection) SendAICHRequest added in v0.1.0

func (p *PeerConnection) SendAICHRequest(hash protocol.Hash, requested []protocol.AICHHash)

func (*PeerConnection) SendAICHRequestForPiece added in v0.1.0

func (p *PeerConnection) SendAICHRequestForPiece(t *Transfer, pieceIndex int)

func (*PeerConnection) SendAcceptUpload

func (p *PeerConnection) SendAcceptUpload()

func (*PeerConnection) SendBlockData

func (p *PeerConnection) SendBlockData()

func (*PeerConnection) SendCancelTransfer

func (p *PeerConnection) SendCancelTransfer()

func (*PeerConnection) SendCompressedPart added in v0.1.0

func (p *PeerConnection) SendCompressedPart(begin, compressedTotalLen int64, payload []byte) error

func (*PeerConnection) SendExtHello added in v0.1.0

func (p *PeerConnection) SendExtHello()

func (*PeerConnection) SendExtHelloAnswer

func (p *PeerConnection) SendExtHelloAnswer()

func (*PeerConnection) SendFileAnswer

func (p *PeerConnection) SendFileAnswer(res UploadableResource)

func (*PeerConnection) SendFileRequest

func (p *PeerConnection) SendFileRequest(hash protocol.Hash)

func (*PeerConnection) SendFileStatusAnswer

func (p *PeerConnection) SendFileStatusAnswer(res UploadableResource)

func (*PeerConnection) SendFileStatusRequest

func (p *PeerConnection) SendFileStatusRequest(hash protocol.Hash)

func (*PeerConnection) SendHashSetAnswer

func (p *PeerConnection) SendHashSetAnswer(res UploadableResource)

func (*PeerConnection) SendHashSetRequest

func (p *PeerConnection) SendHashSetRequest(hash protocol.Hash)

func (*PeerConnection) SendOutOfPartReqsAndAddToWaitingQueue

func (p *PeerConnection) SendOutOfPartReqsAndAddToWaitingQueue()

func (*PeerConnection) SendOutOfParts

func (p *PeerConnection) SendOutOfParts()

func (*PeerConnection) SendPart

func (p *PeerConnection) SendPart(begin, end int64, payload []byte) error

func (*PeerConnection) SendPublicKey added in v0.1.0

func (p *PeerConnection) SendPublicKey()

func (*PeerConnection) SendQueueRanking

func (p *PeerConnection) SendQueueRanking(rank uint16)

func (*PeerConnection) SendRequestParts32

func (p *PeerConnection) SendRequestParts32(packet *clientproto.RequestParts32)

func (*PeerConnection) SendRequestParts64

func (p *PeerConnection) SendRequestParts64(packet *clientproto.RequestParts64)

func (*PeerConnection) SendRequestPreview added in v0.1.3

func (p *PeerConnection) SendRequestPreview(hash protocol.Hash, pieceIndex uint16)

func (*PeerConnection) SendRequestSources added in v0.1.3

func (p *PeerConnection) SendRequestSources(hash protocol.Hash) error

func (*PeerConnection) SendRequestSources2

func (p *PeerConnection) SendRequestSources2(hash protocol.Hash) error

func (*PeerConnection) SendSecIdentState added in v0.1.0

func (p *PeerConnection) SendSecIdentState()

func (*PeerConnection) SendSignature added in v0.1.0

func (p *PeerConnection) SendSignature()

func (*PeerConnection) SendStartUpload

func (p *PeerConnection) SendStartUpload(hash protocol.Hash)

func (*PeerConnection) SetFriendSlot

func (p *PeerConnection) SetFriendSlot(v bool)

func (*PeerConnection) SetPeer

func (p *PeerConnection) SetPeer(peer *Peer)

func (*PeerConnection) SetTransfer

func (p *PeerConnection) SetTransfer(transfer *Transfer)

func (*PeerConnection) SetUploadAddNextConnect

func (p *PeerConnection) SetUploadAddNextConnect(v bool)

func (*PeerConnection) SetUploadQueueRank

func (p *PeerConnection) SetUploadQueueRank(rank uint16)

func (*PeerConnection) SetUploadResource

func (p *PeerConnection) SetUploadResource(res UploadableResource)

func (*PeerConnection) SetUploadStartTime

func (p *PeerConnection) SetUploadStartTime(ts int64)

func (*PeerConnection) SetUploadState

func (p *PeerConnection) SetUploadState(state UploadState)

func (*PeerConnection) SetUploadWaitStart

func (p *PeerConnection) SetUploadWaitStart(ts int64)

func (*PeerConnection) Speed

func (p *PeerConnection) Speed() PeerSpeed

func (*PeerConnection) UploadAddNextConnect

func (p *PeerConnection) UploadAddNextConnect() bool

func (*PeerConnection) UploadQueueRank

func (p *PeerConnection) UploadQueueRank() uint16

func (*PeerConnection) UploadScore

func (p *PeerConnection) UploadScore() uint32

func (*PeerConnection) UploadSession

func (p *PeerConnection) UploadSession() int64

func (*PeerConnection) UploadStartDelay

func (p *PeerConnection) UploadStartDelay() int64

func (*PeerConnection) UploadState

func (p *PeerConnection) UploadState() UploadState

func (*PeerConnection) UploadWaitStart

func (p *PeerConnection) UploadWaitStart() int64

type PeerCredit

type PeerCredit struct {
	PeerHash   protocol.Hash
	Uploaded   uint64
	Downloaded uint64
}

type PeerCreditManager

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

func NewPeerCreditManager

func NewPeerCreditManager() *PeerCreditManager

func (*PeerCreditManager) AddDownloaded

func (m *PeerCreditManager) AddDownloaded(hash protocol.Hash, bytes int64, verified bool)

func (*PeerCreditManager) AddUploaded

func (m *PeerCreditManager) AddUploaded(hash protocol.Hash, bytes int64, verified bool)

func (*PeerCreditManager) ApplySnapshot

func (m *PeerCreditManager) ApplySnapshot(states []ClientCreditState)

func (*PeerCreditManager) CreditsOnlyVerified added in v0.1.0

func (m *PeerCreditManager) CreditsOnlyVerified() bool

func (*PeerCreditManager) ScoreRatio

func (m *PeerCreditManager) ScoreRatio(hash protocol.Hash) float64

func (*PeerCreditManager) SetCreditsOnlyVerified added in v0.1.0

func (m *PeerCreditManager) SetCreditsOnlyVerified(v bool)

func (*PeerCreditManager) Snapshot

func (m *PeerCreditManager) Snapshot() []ClientCreditState

func (*PeerCreditManager) TotalsForPeer added in v0.0.2

func (m *PeerCreditManager) TotalsForPeer(hash protocol.Hash) (uploaded, downloaded uint64)

TotalsForPeer 返回与对端用户 Hash 关联的累计上传/下载字节(无记录时为 0)。

type PeerInfo

type PeerInfo struct {
	UserHash             protocol.Hash
	NickName             string
	Connected            bool
	TotalUploaded        uint64
	TotalDownloaded      uint64
	DownloadSpeed        int
	PayloadDownloadSpeed int
	UploadSpeed          int
	PayloadUploadSpeed   int
	RemotePieces         protocol.BitField
	FailCount            int
	Endpoint             protocol.Endpoint
	ModName              string
	Version              int
	ModVersion           int
	StrModVersion        string
	SourceFlag           int
	// HelloMisc1 / HelloMisc2 为对端 Hello/HelloAnswer 标签 0xFA / 0xFE 解析后的原始数值(与 eMule Misc 位域一致)。
	HelloMisc1 int
	HelloMisc2 int
}

func (PeerInfo) HasSource

func (p PeerInfo) HasSource(source byte) bool

func (PeerInfo) SourceLabels

func (p PeerInfo) SourceLabels() []string

func (PeerInfo) SourceString

func (p PeerInfo) SourceString() string

type PeerSpeed

type PeerSpeed int
const (
	PeerSpeedSlow PeerSpeed = iota
	PeerSpeedMedium
	PeerSpeedFast
)

type PendingBlock

type PendingBlock struct {
	Block      data.PieceBlock
	DataSize   int64
	CreateTime int64
	Received   int64
	Buffer     []byte
}

func NewPendingBlock

func NewPendingBlock(block data.PieceBlock, totalSize int64) PendingBlock

type PieceManager

type PieceManager struct {
	BlocksEnumerator
	// contains filtered or unexported fields
}

func NewPieceManager

func NewPieceManager(handler disk.FileHandler, pieceCount, blocksInLastPiece int) *PieceManager

func (*PieceManager) Abort

func (p *PieceManager) Abort() [][]byte

func (*PieceManager) DeleteFile

func (p *PieceManager) DeleteFile() error

func (*PieceManager) GetFile

func (p *PieceManager) GetFile() *os.File

func (*PieceManager) HashPiece

func (p *PieceManager) HashPiece(pieceIndex int) protocol.Hash

func (*PieceManager) ReadRange

func (p *PieceManager) ReadRange(begin, end int64) ([]byte, error)

func (*PieceManager) ReleaseFile

func (p *PieceManager) ReleaseFile(deleteFile bool) ([][]byte, error)

func (*PieceManager) RestoreBlock

func (p *PieceManager) RestoreBlock(block data.PieceBlock, fileSize int64) ([][]byte, []byte, error)

func (*PieceManager) WriteBlock

func (p *PieceManager) WriteBlock(block data.PieceBlock, buffer []byte) ([][]byte, error)

type PiecePicker

type PiecePicker struct {
	BlocksEnumerator
	// contains filtered or unexported fields
}

func NewPiecePicker

func NewPiecePicker(pieceCount, blocksInLastPiece int) PiecePicker

func (*PiecePicker) AbortDownload

func (p *PiecePicker) AbortDownload(b data.PieceBlock, peer *Peer)

func (*PiecePicker) ChooseNextPiece

func (p *PiecePicker) ChooseNextPiece() bool

func (*PiecePicker) ChooseNextPieceWithAvailability

func (p *PiecePicker) ChooseNextPieceWithAvailability(available *protocol.BitField) bool

func (*PiecePicker) DownloadPiece

func (p *PiecePicker) DownloadPiece(pieceIndex int)

func (*PiecePicker) GetDownloadingPiece

func (p *PiecePicker) GetDownloadingPiece(index int) *DownloadingPiece

func (PiecePicker) GetDownloadingQueue

func (p PiecePicker) GetDownloadingQueue() []DownloadingPiece

func (PiecePicker) GetPieceCount

func (p PiecePicker) GetPieceCount() int

func (PiecePicker) HavePiece

func (p PiecePicker) HavePiece(pieceIndex int) bool

func (*PiecePicker) IsBlockDownloaded

func (p *PiecePicker) IsBlockDownloaded(b data.PieceBlock) bool

func (PiecePicker) IsEndGame

func (p PiecePicker) IsEndGame() bool

func (PiecePicker) IsPieceFinished

func (p PiecePicker) IsPieceFinished(pieceIndex int) bool

func (*PiecePicker) MarkAsDownloading

func (p *PiecePicker) MarkAsDownloading(b data.PieceBlock, peer *Peer) bool

func (*PiecePicker) MarkAsFinished

func (p *PiecePicker) MarkAsFinished(b data.PieceBlock) bool

func (*PiecePicker) MarkAsWriting

func (p *PiecePicker) MarkAsWriting(b data.PieceBlock) bool

func (PiecePicker) NumDownloadingPieces

func (p PiecePicker) NumDownloadingPieces() int

func (PiecePicker) NumHave

func (p PiecePicker) NumHave() int

func (PiecePicker) NumPieces

func (p PiecePicker) NumPieces() int

func (*PiecePicker) PickPieces

func (p *PiecePicker) PickPieces(rq *[]data.PieceBlock, orderLength int, peer *Peer, speed PeerSpeed)

func (*PiecePicker) PickPiecesWithAvailability

func (p *PiecePicker) PickPiecesWithAvailability(rq *[]data.PieceBlock, orderLength int, peer *Peer, speed PeerSpeed, available *protocol.BitField)

func (*PiecePicker) RestoreHave

func (p *PiecePicker) RestoreHave(pieceIndex int)

func (*PiecePicker) RestorePiece

func (p *PiecePicker) RestorePiece(pieceIndex int)

func (PiecePicker) TotalPieces

func (p PiecePicker) TotalPieces() int

func (*PiecePicker) WeHave

func (p *PiecePicker) WeHave(pieceIndex int)

func (*PiecePicker) WeHaveBlock

func (p *PiecePicker) WeHaveBlock(b data.PieceBlock)

type PieceSnapshot

type PieceSnapshot struct {
	Index         int
	State         PieceSnapshotState
	TotalBytes    int64
	DoneBytes     int64
	ReceivedBytes int64
	BlocksTotal   int
	BlocksDone    int
	BlocksWriting int
	BlocksPending int
}

type PieceSnapshotState

type PieceSnapshotState string
const (
	PieceSnapshotMissing     PieceSnapshotState = "MISSING"
	PieceSnapshotDownloading PieceSnapshotState = "DOWNLOADING"
	PieceSnapshotFinished    PieceSnapshotState = "FINISHED"
)

type PieceState

type PieceState byte
const (
	PieceNone PieceState = iota
	PieceDownloading
	PieceHave
)

type Policy

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

func NewPolicy

func NewPolicy(t *Transfer) Policy

func (*Policy) AddPeer

func (p *Policy) AddPeer(peer Peer) (bool, error)

func (Policy) ComparePeerErase

func (p Policy) ComparePeerErase(lhs, rhs Peer) bool

func (Policy) ComparePeers

func (p Policy) ComparePeers(lhs, rhs Peer) bool

func (*Policy) ConnectOnePeer

func (p *Policy) ConnectOnePeer(sessionTime int64) (bool, error)

func (*Policy) ConnectionClosed

func (p *Policy) ConnectionClosed(c *PeerConnection, sessionTime int64)

func (*Policy) ErasePeers

func (p *Policy) ErasePeers()

func (*Policy) FindConnectCandidate

func (p *Policy) FindConnectCandidate(sessionTime int64) *Peer

func (Policy) FindPeer

func (p Policy) FindPeer(ep protocol.Endpoint) *Peer

func (Policy) Get

func (p Policy) Get(endpoint protocol.Endpoint) *Peer

func (Policy) GetSourceRank

func (p Policy) GetSourceRank(sourceBitmask int) int

func (Policy) IsConnectCandidate

func (p Policy) IsConnectCandidate(pe Peer) bool

func (Policy) IsEraseCandidate

func (p Policy) IsEraseCandidate(pe Peer) bool

func (*Policy) MergeSourceExchangePeers

func (p *Policy) MergeSourceExchangePeers(peers []Peer) int

MergeSourceExchangePeers 将来源交换得到的 Peer 合并进策略表(按 Endpoint 去重,重复时合并 SourceFlag)。

func (*Policy) NewConnection

func (p *Policy) NewConnection(c *PeerConnection) error

func (Policy) NumConnectCandidates

func (p Policy) NumConnectCandidates() int

func (*Policy) PeersForSourceExchange

func (p *Policy) PeersForSourceExchange(exclude protocol.Endpoint, limit int) []Peer

PeersForSourceExchange 返回用于 OP_ANSWERSOURCES2 的候选来源:可连接、非 exclude 端点、限流。

func (*Policy) SetConnection

func (p *Policy) SetConnection(peer *Peer, c *PeerConnection)

func (Policy) Size

func (p Policy) Size() int

type PublicSettings added in v0.1.2

type PublicSettings struct {
	EnableDHT           bool   `json:"enable_dht"`
	EnableDHTv6         bool   `json:"enable_dhtv6"`
	EnableUPnP          bool   `json:"enable_upnp"`
	EnableCryptLayer    bool   `json:"enable_crypt_layer"`
	CryptLayerRequired  bool   `json:"crypt_layer_required"`
	EnableSecIdent      bool   `json:"enable_sec_ident"`
	CreditsOnlyVerified bool   `json:"credits_only_verified"`
	ListenPort          int    `json:"listen_port"`
	UDPPort             int    `json:"udp_port"`
	UDPPortV6           int    `json:"udp_port_v6"`
	MaxDownloadRateKB   int    `json:"max_download_rate_kb"`
	MaxUploadRateKB     int    `json:"max_upload_rate_kb"`
	SecIdentRequired    bool   `json:"sec_ident_required"`
	IdentityKeyPath     string `json:"identity_key_path,omitempty"`
	CategoryCount       int    `json:"category_count"`
}

PublicSettings 是对外暴露的客户端设置快照(不含敏感路径内容)。

type RemotePeerInfo

type RemotePeerInfo struct {
	Point              protocol.Endpoint
	NickName           string
	ModName            string
	Version            int
	ModVersion         string
	ModNumber          int
	Misc1              MiscOptions
	Misc2              MiscOptions2
	SourceExchange2Ver byte
	SecIdentVersion    int
	SecIdentKeyFP      uint32
}

type RequestedUploadBlock

type RequestedUploadBlock struct {
	Begin       int64
	End         int64
	Transferred int64
}

type SearchHandle

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

func (SearchHandle) ID

func (h SearchHandle) ID() uint32

func (SearchHandle) IsValid

func (h SearchHandle) IsValid() bool

func (SearchHandle) Snapshot

func (h SearchHandle) Snapshot() SearchSnapshot

func (SearchHandle) Stop

func (h SearchHandle) Stop() error

type SearchParams

type SearchParams struct {
	Query              string
	Scope              SearchScope
	MinSize            int64
	MaxSize            int64
	MinSources         int
	MinCompleteSources int
	FileType           string
	Extension          string
}

type SearchResult

type SearchResult struct {
	Hash            protocol.Hash
	FileName        string
	FileSize        int64
	Sources         int
	CompleteSources int
	MediaBitrate    int
	MediaLength     int
	MediaCodec      string
	Extension       string
	FileType        string
	Note            string
	Source          SearchResultSource
}
func (r SearchResult) ED2KLink() string

type SearchResultSource

type SearchResultSource uint8
const (
	SearchResultServer SearchResultSource = 1 << iota
	SearchResultKAD
)

type SearchScope

type SearchScope uint8
const (
	SearchScopeServer SearchScope = 1 << iota
	SearchScopeDHT
	SearchScopeAll = SearchScopeServer | SearchScopeDHT
)

type SearchSnapshot

type SearchSnapshot struct {
	ID         uint32
	Params     SearchParams
	State      SearchState
	Results    []SearchResult
	UpdatedAt  int64
	StartedAt  int64
	ServerBusy bool
	DHTBusy    bool
	KadKeyword string
	Error      string
}

type SearchState

type SearchState string
const (
	SearchStateIdle     SearchState = "IDLE"
	SearchStateRunning  SearchState = "RUNNING"
	SearchStateFinished SearchState = "FINISHED"
	SearchStateStopped  SearchState = "STOPPED"
	SearchStateFailed   SearchState = "FAILED"
)

type ServerConnection

type ServerConnection struct {
	Connection
	// contains filtered or unexported fields
}

func NewServerConnection

func NewServerConnection(identifier string, address *net.TCPAddr, session *Session) *ServerConnection

func (*ServerConnection) AuxPort

func (s *ServerConnection) AuxPort() int32

func (*ServerConnection) ClientID

func (s *ServerConnection) ClientID() int32

func (*ServerConnection) Connect

func (s *ServerConnection) Connect() error

func (*ServerConnection) Endpoint

func (s *ServerConnection) Endpoint() protocol.Endpoint

func (*ServerConnection) GetAddress

func (s *ServerConnection) GetAddress() *net.TCPAddr

func (*ServerConnection) GetIdentifier

func (s *ServerConnection) GetIdentifier() string

func (*ServerConnection) IsHandshakeCompleted

func (s *ServerConnection) IsHandshakeCompleted() bool

func (*ServerConnection) OnDisconnect

func (s *ServerConnection) OnDisconnect(ec BaseErrorCode)

func (*ServerConnection) OnServerIDChange

func (s *ServerConnection) OnServerIDChange(clientID, tcpFlags, auxPort int32, reportedIP, obfuscationTCPPort uint32)

func (*ServerConnection) ProcessIncoming

func (s *ServerConnection) ProcessIncoming() error

func (*ServerConnection) SecondTick

func (s *ServerConnection) SecondTick(currentSessionTime int64)

func (*ServerConnection) SendCallbackRequest

func (s *ServerConnection) SendCallbackRequest(clientID int32)

func (*ServerConnection) SendFileSourcesObfuRequest added in v0.1.3

func (s *ServerConnection) SendFileSourcesObfuRequest(hash protocol.Hash, size int64)

func (*ServerConnection) SendFileSourcesRequest

func (s *ServerConnection) SendFileSourcesRequest(hash protocol.Hash, size int64)

func (*ServerConnection) SendGetList

func (s *ServerConnection) SendGetList()

func (*ServerConnection) SendLoginRequest

func (s *ServerConnection) SendLoginRequest()

func (*ServerConnection) SendOfferFiles

func (s *ServerConnection) SendOfferFiles(packet *serverproto.OfferFiles)

func (*ServerConnection) SendSearchMore

func (s *ServerConnection) SendSearchMore()

func (*ServerConnection) SendSearchRequest

func (s *ServerConnection) SendSearchRequest(packet *serverproto.SearchRequest)

func (*ServerConnection) TCPFlags

func (s *ServerConnection) TCPFlags() int32

type ServerConnectionCandidate

type ServerConnectionCandidate struct {
	Identifier string
	Address    *net.TCPAddr
}

type ServerConnectionPolicy

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

func NewServerConnectionPolicy

func NewServerConnectionPolicy(reconnectSecondsTimeout int64, maxReconnects int) ServerConnectionPolicy

func (ServerConnectionPolicy) EffectivePingRTT added in v0.1.0

func (p ServerConnectionPolicy) EffectivePingRTT(now int64) int64

EffectivePingRTT 返回未过期的 ping 时延,未知或已过期返回 -1。

func (ServerConnectionPolicy) GetConnectCandidate

func (p ServerConnectionPolicy) GetConnectCandidate(currentSessionTime int64) *ServerConnectionCandidate

func (ServerConnectionPolicy) HasCandidate

func (p ServerConnectionPolicy) HasCandidate() bool

func (ServerConnectionPolicy) HasIterations

func (p ServerConnectionPolicy) HasIterations() bool

func (*ServerConnectionPolicy) RemoveConnectCandidates

func (p *ServerConnectionPolicy) RemoveConnectCandidates()

func (*ServerConnectionPolicy) SetConnectCandidate

func (p *ServerConnectionPolicy) SetConnectCandidate(identifier string, address *net.TCPAddr, currentSessionTime int64)

func (*ServerConnectionPolicy) SetPingResult added in v0.1.0

func (p *ServerConnectionPolicy) SetPingResult(rttMs, ttlMs, now int64)

SetPingResult 记录 UDP 探测往返时延;ttlMs 为结果有效期(毫秒),0 表示使用默认 TTL。

func (*ServerConnectionPolicy) SetServerConnectionFailed

func (p *ServerConnectionPolicy) SetServerConnectionFailed(identifier string, address *net.TCPAddr, currentSessionTime int64)

type ServerSnapshot

type ServerSnapshot struct {
	Identifier                   string
	Address                      string
	Name                         string
	Description                  string
	Configured                   bool
	Connected                    bool
	HandshakeCompleted           bool
	Primary                      bool
	Disconnecting                bool
	ClientID                     int32
	TCPFlags                     int32
	AuxPort                      int32
	ReportedIP                   uint32
	ObfuscationTCPPort           uint32
	MillisecondsSinceLastReceive int64
	DownloadRate                 int
	UploadRate                   int
	// TCP Status(0x34)用户数 / 文件数
	StatusUsers int32
	StatusFiles int32
	// UDP GlobServStat(需本机 UDP 端口可用;与 DHT 共用)
	UDPUsers       uint32
	UDPFiles       uint32
	MaxUsers       uint32
	SoftFilesLimit uint32
	HardFilesLimit uint32
	UDPStatsValid  bool
}

func (ServerSnapshot) IDClass

func (s ServerSnapshot) IDClass() string

type Session

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

func NewSession

func NewSession(st Settings) *Session

func (*Session) AddSharedDir

func (s *Session) AddSharedDir(path string) error

AddSharedDir 注册一个用于扫描的目录(去重)。

func (*Session) AddTransfer

func (s *Session) AddTransfer(hash protocol.Hash, size int64, file *os.File) (TransferHandle, error)

func (*Session) AddTransferParams

func (s *Session) AddTransferParams(atp AddTransferParams) (TransferHandle, error)

func (*Session) AddTransferWithHandler

func (s *Session) AddTransferWithHandler(hash protocol.Hash, size int64, handler disk.FileHandler) (TransferHandle, error)

func (*Session) BanPeer added in v0.1.0

func (s *Session) BanPeer(endpoint protocol.Endpoint)

func (*Session) BannedPeers added in v0.1.0

func (s *Session) BannedPeers() []protocol.Endpoint

func (*Session) CloseConnection

func (s *Session) CloseConnection(connection *PeerConnection)

func (*Session) CloseListener

func (s *Session) CloseListener()

func (*Session) ConfigureSession

func (s *Session) ConfigureSession(st Settings)

func (*Session) ConnectNewPeers

func (s *Session) ConnectNewPeers()

func (*Session) ConnectTo

func (s *Session) ConnectTo(identifier string, address *net.TCPAddr) error

func (*Session) ConnectedServerID

func (s *Session) ConnectedServerID() string

func (*Session) ConnectedServerIDs

func (s *Session) ConnectedServerIDs() []string

func (*Session) Credits

func (s *Session) Credits() *PeerCreditManager

func (*Session) DisconnectFrom

func (s *Session) DisconnectFrom()

func (*Session) EnsureServerStatUDPListener added in v0.1.0

func (s *Session) EnsureServerStatUDPListener() error

EnsureServerStatUDPListener 在未启用 DHT 时绑定 UDP 端口以收发 GlobServStat(启用 DHT 时由 DHT 的 UDP 套接字接收)。

func (*Session) FindTransfer

func (s *Session) FindTransfer(hash protocol.Hash) TransferHandle

func (*Session) GetAppVersion

func (s *Session) GetAppVersion() int

func (*Session) GetClientID

func (s *Session) GetClientID() int32

func (*Session) GetClientName

func (s *Session) GetClientName() string

func (*Session) GetCompressionVersion

func (s *Session) GetCompressionVersion() int

func (*Session) GetCurrentTime

func (s *Session) GetCurrentTime() int64

func (*Session) GetDHTTracker

func (s *Session) GetDHTTracker() *DHTTracker

func (*Session) GetDHTv6Tracker added in v0.1.0

func (s *Session) GetDHTv6Tracker() *KADV6Tracker

func (*Session) GetListenPort

func (s *Session) GetListenPort() int

func (*Session) GetModBuildVersion

func (s *Session) GetModBuildVersion() int

func (*Session) GetModMajorVersion

func (s *Session) GetModMajorVersion() int

func (*Session) GetModMinorVersion

func (s *Session) GetModMinorVersion() int

func (*Session) GetModName

func (s *Session) GetModName() string

func (*Session) GetTransfers

func (s *Session) GetTransfers() []TransferHandle

func (*Session) GetUDPPort

func (s *Session) GetUDPPort() int

func (*Session) GetUserAgent

func (s *Session) GetUserAgent() protocol.Hash

func (*Session) IPFilter added in v0.1.0

func (s *Session) IPFilter() *IPFilter

func (*Session) Identity added in v0.1.0

func (s *Session) Identity() *IdentityState

func (*Session) ImportSharedFile

func (s *Session) ImportSharedFile(path string) error

ImportSharedFile 计算 ed2k 哈希并将文件加入共享库。

func (*Session) IsFriendSlot

func (s *Session) IsFriendSlot(hash protocol.Hash) bool

func (*Session) IsUDPReachable added in v0.1.3

func (s *Session) IsUDPReachable() bool

IsUDPReachable 返回最近一次 ReAsk 探测是否收到应答。

func (*Session) ListSharedDirs

func (s *Session) ListSharedDirs() []string

ListSharedDirs 返回已注册的共享目录副本。

func (*Session) Listen

func (s *Session) Listen() error

func (*Session) LoadIdentity added in v0.1.0

func (s *Session) LoadIdentity(path string) error

func (*Session) LookupTransfer

func (s *Session) LookupTransfer(hash protocol.Hash) *Transfer

func (*Session) OnCallbackRequestIncoming added in v0.1.0

func (s *Session) OnCallbackRequestIncoming(point protocol.Endpoint)

OnCallbackRequestIncoming 收到服务器转发的回调请求:向对方发起出站 TCP(用于上传)。

func (*Session) OnServerConnectionClosed

func (s *Session) OnServerConnectionClosed(sc *ServerConnection, ec BaseErrorCode)

func (*Session) OnServerIDChange

func (s *Session) OnServerIDChange(sc *ServerConnection, clientID, tcpFlags, auxPort int32)

func (*Session) OnServerSearchResult

func (s *Session) OnServerSearchResult(sc *ServerConnection, result *serverproto.SearchResult)

func (*Session) ProbeServerPing added in v0.1.0

func (s *Session) ProbeServerPing(identifier string, address *net.TCPAddr)

func (*Session) PublishTransferToKAD

func (s *Session) PublishTransferToKAD(t *Transfer)

PublishTransferToKAD 在任务已完成时向 KAD 发布文件源与(可选)关键字索引,需 EnableDHT 且已设置 DHTTracker。

func (*Session) PublishTransferToKADV6 added in v0.1.0

func (s *Session) PublishTransferToKADV6(t *Transfer)

PublishTransferToKADV6 在任务已完成时向 KADV6 发布文件源与(可选)关键字索引,需 EnableDHTv6 且已设置 KADV6Tracker。

func (*Session) PublishTransferToServer

func (s *Session) PublishTransferToServer(t *Transfer)

func (*Session) PumpIO

func (s *Session) PumpIO()

func (*Session) RefreshUPnPMapping

func (s *Session) RefreshUPnPMapping()

func (*Session) RemoveDiskTask

func (s *Session) RemoveDiskTask(transfer *Transfer)

func (*Session) RemoveSharedDir

func (s *Session) RemoveSharedDir(path string) error

RemoveSharedDir 移除扫描目录。

func (*Session) RemoveSharedFile

func (s *Session) RemoveSharedFile(hash protocol.Hash) bool

RemoveSharedFile 从共享库移除指定哈希。

func (*Session) RemoveTransfer

func (s *Session) RemoveTransfer(hash protocol.Hash, deleteFile bool) error

func (*Session) RequestServerCallback added in v0.1.0

func (s *Session) RequestServerCallback(t *Transfer, clientID int32) bool

RequestServerCallback 向已连接服务器请求对低 ID 来源的回调穿透,并记录待关联的传输。

func (*Session) RequestSourcesNow

func (s *Session) RequestSourcesNow(transfer *Transfer) bool

func (*Session) RescanSharedDirs

func (s *Session) RescanSharedDirs() error

RescanSharedDirs 扫描已注册目录下的普通文件并导入。

func (*Session) SearchSnapshot

func (s *Session) SearchSnapshot() SearchSnapshot

func (*Session) SecondTick

func (s *Session) SecondTick(currentSessionTime, tickIntervalMS int64)

func (*Session) SendDHTSourcesRequest

func (s *Session) SendDHTSourcesRequest(hash protocol.Hash, size int64, transfer *Transfer) bool

func (*Session) SendDHTv6SourcesRequest added in v0.1.0

func (s *Session) SendDHTv6SourcesRequest(hash protocol.Hash, size int64, transfer *Transfer) bool

SendDHTv6SourcesRequest 通过 KADV6 搜索文件源,并将 IPv6 来源并入传输策略表。

func (*Session) SendSourcesRequest

func (s *Session) SendSourcesRequest(hash protocol.Hash, size int64) bool

func (*Session) SendUDPReaskPing added in v0.1.3

func (s *Session) SendUDPReaskPing(addr *net.UDPAddr) error

SendUDPReaskPing 向对端 UDP 端口发送 ReAsk 探测(eMule 防火墙检测)。

func (*Session) ServerSnapshots

func (s *Session) ServerSnapshots() []ServerSnapshot

func (*Session) SetDHTTracker

func (s *Session) SetDHTTracker(tracker *DHTTracker)

func (*Session) SetDHTv6Tracker added in v0.1.0

func (s *Session) SetDHTv6Tracker(tracker *KADV6Tracker)

func (*Session) SetFriendSlot

func (s *Session) SetFriendSlot(hash protocol.Hash, enabled bool)

func (*Session) SetIPFilter added in v0.1.0

func (s *Session) SetIPFilter(filter *IPFilter)

func (*Session) SetIdentity added in v0.1.0

func (s *Session) SetIdentity(id *IdentityState)

func (*Session) SetServerMetadata added in v0.1.0

func (s *Session) SetServerMetadata(identifier, name, description string)

SetServerMetadata 记录 server.met 中的名称与描述(identifier 为 host:port)。

func (*Session) SharedFiles

func (s *Session) SharedFiles() []*SharedFile

SharedFiles 返回共享文件快照(只读遍历)。

func (*Session) SharedStore

func (s *Session) SharedStore() *SharedStore

SharedStore 返回会话级共享库(非 nil)。

func (*Session) StartSearch

func (s *Session) StartSearch(params SearchParams) (SearchHandle, error)

func (*Session) StopSearch

func (s *Session) StopSearch(id uint32) error

func (*Session) SubmitDiskTask

func (s *Session) SubmitDiskTask(task TransferCallable)

func (*Session) SyncDHTListenPort

func (s *Session) SyncDHTListenPort()

func (*Session) SyncDHTv6ListenPort added in v0.1.0

func (s *Session) SyncDHTv6ListenPort()

func (*Session) ThrottleDownload added in v0.1.0

func (s *Session) ThrottleDownload(bytes int)

func (*Session) UnbanPeer added in v0.1.0

func (s *Session) UnbanPeer(endpoint protocol.Endpoint)

func (*Session) UploadQueue

func (s *Session) UploadQueue() *UploadQueue

type Settings

type Settings struct {
	Logger                  *slog.Logger
	UserAgent               protocol.Hash
	ModName                 string
	ClientName              string
	ListenPort              int
	UDPPort                 int
	UDPPortV6               int
	EnableDHT               bool
	EnableDHTv6             bool
	EnableUPnP              bool
	Version                 int
	ModMajor                int
	ModMinor                int
	ModBuild                int
	MaxFailCount            int
	MaxPeerListSize         int
	MinPeerReconnectTime    int
	PeerConnectionTimeout   int
	SessionConnectionsLimit int
	UploadSlots             int
	MaxUploadRateKB         int
	MaxDownloadRateKB       int
	SlotAllocationKB        int
	UploadQueueSize         int
	BufferPoolSize          int
	MaxConnectionsPerSecond int
	CompressionVersion      int
	ServerSearchTimeout     int
	DHTSearchTimeout        int
	DHTv6SearchTimeout      int
	ReconnectToServer       bool
	ServerPingTimeout       int64
	EnableCryptLayer        bool
	CryptLayerRequired      bool
	ObfuscationTCPPort      int
	EnableSecIdent          bool
	SecIdentRequired        bool
	CreditsOnlyVerified     bool
	IdentityKeyPath         string
	Categories              []Category
	UseEmuleTempLayout      bool
	PartialKadPublish       bool
	PreallocateDiskSpace    bool
	UseSparseFiles          bool
	EnableWebDownload       bool
	MaxHttpSources          int
	MaxConcurrentHttpBlocks int
	WebCacheDir             string
	HttpRequestTimeoutSec   int
}

func NewSettings

func NewSettings() Settings

func (Settings) String

func (s Settings) String() string

type SharedFile

type SharedFile struct {
	Hash protocol.Hash

	FileSize    int64
	Path        string
	Name        string
	PieceHashes []protocol.Hash
	Origin      SharedOrigin
	Completed   bool
	LastHashAt  int64
	// contains filtered or unexported fields
}

SharedFile 表示可共享的文件资源元数据(与下载任务 Transfer 分离)。 FileSize 为字节大小(与 Transfer.Size() 对应,避免与 Size() 方法同名冲突)。

func (*SharedFile) AICHRootHash added in v0.1.0

func (s *SharedFile) AICHRootHash() (protocol.AICHHash, bool)

func (*SharedFile) AvailablePieces

func (s *SharedFile) AvailablePieces() protocol.BitField

AvailablePieces 已完成文件视为拥有全部分片。

func (*SharedFile) CanUpload

func (s *SharedFile) CanUpload() bool

CanUpload 是否可向其他 peer 上传数据。

func (*SharedFile) CanUploadRange

func (s *SharedFile) CanUploadRange(begin, end int64) bool

CanUploadRange 检查请求区间是否完全落在已拥有分片内。

func (*SharedFile) FileLabel

func (s *SharedFile) FileLabel() string

FileLabel 用于协议中的展示名(通常为文件名)。

func (*SharedFile) GetHash

func (s *SharedFile) GetHash() protocol.Hash

GetHash 返回 ed2k 根哈希。

func (*SharedFile) ReadRange

func (s *SharedFile) ReadRange(begin, end int64) ([]byte, error)

ReadRange 从本地路径读取区间数据。

func (*SharedFile) SetAICHRootHash added in v0.1.0

func (s *SharedFile) SetAICHRootHash(root protocol.AICHHash)

func (*SharedFile) Size

func (s *SharedFile) Size() int64

Size 返回文件大小。

func (*SharedFile) UploadAICHHashes added in v0.1.0

func (s *SharedFile) UploadAICHHashes(requested []protocol.AICHHash) []protocol.AICHHash

func (*SharedFile) UploadHashSet

func (s *SharedFile) UploadHashSet() []protocol.Hash

UploadHashSet 返回分片哈希列表;与 Transfer 行为一致。

func (*SharedFile) UploadPriority

func (s *SharedFile) UploadPriority() UploadPriority

UploadPriority 导入文件默认普通优先级。

type SharedFileSnapshot added in v0.1.2

type SharedFileSnapshot struct {
	Hash      string `json:"hash"`
	Name      string `json:"name"`
	Path      string `json:"path"`
	Size      int64  `json:"size"`
	Completed bool   `json:"completed"`
}

SharedFileSnapshot 是 Web API 用共享文件摘要。

type SharedOrigin

type SharedOrigin int

SharedOrigin 表示共享文件来源:下载完成入库或本地导入。

const (
	SharedOriginDownloaded SharedOrigin = iota
	SharedOriginImported
)

type SharedStore

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

SharedStore 内存中的共享文件索引(按 hash 去重)。

func NewSharedStore

func NewSharedStore() *SharedStore

func (*SharedStore) Add

func (st *SharedStore) Add(f *SharedFile) bool

Add 添加共享文件;若 hash 已存在则返回 false 且不覆盖。

func (*SharedStore) Get

func (st *SharedStore) Get(hash protocol.Hash) *SharedFile

Get 按 hash 查询。

func (*SharedStore) Len

func (st *SharedStore) Len() int

Len 条目数量。

func (*SharedStore) List

func (st *SharedStore) List() []*SharedFile

List 返回当前共享文件列表(稳定排序)。

func (*SharedStore) Remove

func (st *SharedStore) Remove(hash protocol.Hash) bool

Remove 按 hash 删除。

func (*SharedStore) ReplaceAll

func (st *SharedStore) ReplaceAll(files []*SharedFile)

ReplaceAll 用快照替换整个存储(用于从磁盘恢复)。

type SpeedMonitor

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

func NewSpeedMonitor

func NewSpeedMonitor(samplesLimit int) SpeedMonitor

func (*SpeedMonitor) AddSample

func (s *SpeedMonitor) AddSample(speedSample int64)

func (SpeedMonitor) AverageSpeed

func (s SpeedMonitor) AverageSpeed() int64

func (*SpeedMonitor) Clear

func (s *SpeedMonitor) Clear()

func (SpeedMonitor) NumSamples

func (s SpeedMonitor) NumSamples() int

type StatChannel

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

func NewStatChannel

func NewStatChannel() StatChannel

func (*StatChannel) Add

func (s *StatChannel) Add(count int64)

func (*StatChannel) AddChannel

func (s *StatChannel) AddChannel(other StatChannel)

func (*StatChannel) Clear

func (s *StatChannel) Clear()

func (*StatChannel) Counter

func (s *StatChannel) Counter() int64

func (*StatChannel) LowPassRate

func (s *StatChannel) LowPassRate() int64

func (*StatChannel) MergeChannel

func (s *StatChannel) MergeChannel(other StatChannel)

func (*StatChannel) Rate

func (s *StatChannel) Rate() int64

func (*StatChannel) SecondTick

func (s *StatChannel) SecondTick(timeIntervalMS int64)

func (*StatChannel) Total

func (s *StatChannel) Total() int64

type Statistics

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

func NewStatistics

func NewStatistics() Statistics

func (*Statistics) Add

func (s *Statistics) Add(other Statistics) *Statistics

func (*Statistics) Clear

func (s *Statistics) Clear()

func (Statistics) DownloadPayloadRate

func (s Statistics) DownloadPayloadRate() int64

func (Statistics) DownloadRate

func (s Statistics) DownloadRate() int64

func (Statistics) LastDownload

func (s Statistics) LastDownload() int64

func (Statistics) LastUpload

func (s Statistics) LastUpload() int64

func (Statistics) LowPassDownloadRate

func (s Statistics) LowPassDownloadRate() int64

func (Statistics) LowPassUploadRate

func (s Statistics) LowPassUploadRate() int64

func (*Statistics) Merge

func (s *Statistics) Merge(other Statistics) *Statistics

func (*Statistics) ReceiveBytes

func (s *Statistics) ReceiveBytes(protocolBytes, payloadBytes int64)

func (*Statistics) SecondTick

func (s *Statistics) SecondTick(timeIntervalMS int64)

func (*Statistics) SendBytes

func (s *Statistics) SendBytes(protocolBytes, payloadBytes int64)

func (Statistics) TotalPayloadDownload

func (s Statistics) TotalPayloadDownload() int64

func (Statistics) TotalPayloadUpload

func (s Statistics) TotalPayloadUpload() int64

func (Statistics) TotalProtocolDownload

func (s Statistics) TotalProtocolDownload() int64

func (Statistics) TotalProtocolUpload

func (s Statistics) TotalProtocolUpload() int64

func (Statistics) TotalUpload

func (s Statistics) TotalUpload() int64

func (Statistics) UploadPayloadRate

func (s Statistics) UploadPayloadRate() int64

func (Statistics) UploadRate

func (s Statistics) UploadRate() int64

type Transfer

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

func NewTransfer

func NewTransfer(s *Session, atp AddTransferParams) (*Transfer, error)

func (*Transfer) AICHPieceBlocks added in v0.1.0

func (t *Transfer) AICHPieceBlocks(pieceIndex int) []protocol.AICHHash

func (*Transfer) AICHRootHash added in v0.1.0

func (t *Transfer) AICHRootHash() (protocol.AICHHash, bool)

func (*Transfer) Abort

func (t *Transfer) Abort(deleteFile bool) error

func (*Transfer) ActiveConnections

func (t *Transfer) ActiveConnections() int

func (*Transfer) AddHttpSource added in v0.1.3

func (t *Transfer) AddHttpSource(rawURL string) error

func (*Transfer) AddPeer

func (t *Transfer) AddPeer(endpoint protocol.Endpoint, sourceFlag int) error

func (*Transfer) AddPeerFromKADV6Search

func (t *Transfer) AddPeerFromKADV6Search(entry kadv6.SearchEntry) (bool, error)

AddPeerFromKADV6Search 将单条 KADV6 搜索结果并入当前任务策略表(去重规则同 AddPeer)。

func (*Transfer) AddStats

func (t *Transfer) AddStats(s Statistics)

func (*Transfer) AsyncRestoreBlock

func (t *Transfer) AsyncRestoreBlock(block data.PieceBlock)

func (*Transfer) AttachIncomingPeer

func (t *Transfer) AttachIncomingPeer(c *PeerConnection) error

func (*Transfer) AttachPeer

func (t *Transfer) AttachPeer(c *PeerConnection) error

func (*Transfer) AvailablePieces

func (t *Transfer) AvailablePieces() protocol.BitField

func (*Transfer) CanUpload

func (t *Transfer) CanUpload() bool

func (*Transfer) CanUploadRange

func (t *Transfer) CanUploadRange(begin, end int64) bool

func (*Transfer) ConnectToPeer

func (t *Transfer) ConnectToPeer(peerInfo *Peer) (*PeerConnection, error)

func (*Transfer) DownloadPriority added in v0.1.0

func (t *Transfer) DownloadPriority() TransferPriority

func (*Transfer) FileComment added in v0.1.2

func (t *Transfer) FileComment() string

func (*Transfer) FileLabel

func (t *Transfer) FileLabel() string

FileLabel 用于上传时文件名展示。

func (*Transfer) FileName

func (t *Transfer) FileName() string

func (*Transfer) ForceSourceDiscoveryNow

func (t *Transfer) ForceSourceDiscoveryNow()

func (*Transfer) GetCreateTime

func (t *Transfer) GetCreateTime() int64

func (*Transfer) GetFile

func (t *Transfer) GetFile() *os.File

func (*Transfer) GetFilePath

func (t *Transfer) GetFilePath() string

func (*Transfer) GetHash

func (t *Transfer) GetHash() protocol.Hash

func (*Transfer) GetPeersInfo

func (t *Transfer) GetPeersInfo() []PeerInfo

func (*Transfer) GetPieceManager

func (t *Transfer) GetPieceManager() *PieceManager

func (*Transfer) GetStatus

func (t *Transfer) GetStatus() TransferStatus

func (*Transfer) HttpSources added in v0.1.3

func (t *Transfer) HttpSources() []string

func (*Transfer) IsAborted

func (t *Transfer) IsAborted() bool

func (*Transfer) IsFinished

func (t *Transfer) IsFinished() bool

func (*Transfer) IsPaused

func (t *Transfer) IsPaused() bool

func (*Transfer) NeedMoreSources

func (t *Transfer) NeedMoreSources() bool

func (*Transfer) NeedResumeDataSave

func (t *Transfer) NeedResumeDataSave() bool

func (*Transfer) OnBlockRestoreCompleted

func (t *Transfer) OnBlockRestoreCompleted(block data.PieceBlock, ec BaseErrorCode)

func (*Transfer) OnBlockWriteCompleted

func (t *Transfer) OnBlockWriteCompleted(block data.PieceBlock, _ [][]byte, ec BaseErrorCode)

func (*Transfer) OnPieceHashCompleted

func (t *Transfer) OnPieceHashCompleted(pieceIndex int, hash protocol.Hash)

func (*Transfer) OnReleaseFile

func (t *Transfer) OnReleaseFile(_ BaseErrorCode, _ [][]byte, _ bool)

func (*Transfer) Pause

func (t *Transfer) Pause()

func (*Transfer) PauseWithDisconnect

func (t *Transfer) PauseWithDisconnect()

func (*Transfer) PieceSnapshots

func (t *Transfer) PieceSnapshots() []PieceSnapshot

func (*Transfer) PreviewPiece added in v0.1.3

func (t *Transfer) PreviewPiece(index uint16) ([]byte, bool)

PreviewPiece 返回已缓存的预览分片。

func (*Transfer) QueuePieceHash

func (t *Transfer) QueuePieceHash(pieceIndex int) bool

func (*Transfer) ReadRange

func (t *Transfer) ReadRange(begin, end int64) ([]byte, error)

func (*Transfer) RemovePeerConnection

func (t *Transfer) RemovePeerConnection(c *PeerConnection)

func (*Transfer) Resume

func (t *Transfer) Resume()

func (*Transfer) ResumeData

func (t *Transfer) ResumeData() *protocol.TransferResumeData

func (*Transfer) ResumeWithState

func (t *Transfer) ResumeWithState()

func (*Transfer) SecondTick

func (t *Transfer) SecondTick(accumulator *Statistics, tickIntervalMS int64)

func (*Transfer) SetAICHRootHash added in v0.1.0

func (t *Transfer) SetAICHRootHash(root protocol.AICHHash)

func (*Transfer) SetDownloadPriority added in v0.1.0

func (t *Transfer) SetDownloadPriority(priority TransferPriority)

func (*Transfer) SetHashSet

func (t *Transfer) SetHashSet(hash protocol.Hash, hashes []protocol.Hash)

func (*Transfer) SetUploadPriority

func (t *Transfer) SetUploadPriority(priority UploadPriority)

func (*Transfer) Size

func (t *Transfer) Size() int64

func (*Transfer) StoreAICHPieceBlocks added in v0.1.0

func (t *Transfer) StoreAICHPieceBlocks(pieceIndex int, hashes []protocol.AICHHash)

func (*Transfer) StorePreviewPiece added in v0.1.3

func (t *Transfer) StorePreviewPiece(index uint16, data []byte)

StorePreviewPiece 缓存来自对端的预览分片数据。

func (*Transfer) TryConnectPeer

func (t *Transfer) TryConnectPeer(sessionTime int64) (bool, error)

func (*Transfer) UploadAICHHashes added in v0.1.0

func (t *Transfer) UploadAICHHashes(requested []protocol.AICHHash) []protocol.AICHHash

func (*Transfer) UploadHashSet

func (t *Transfer) UploadHashSet() []protocol.Hash

func (*Transfer) UploadPriority

func (t *Transfer) UploadPriority() UploadPriority

func (*Transfer) WantMorePeers

func (t *Transfer) WantMorePeers() bool

func (*Transfer) WeHave

func (t *Transfer) WeHave(pieceIndex int)

type TransferCallable

type TransferCallable interface {
	Transfer() *Transfer
	Call() AsyncOperationResult
}

type TransferHandle

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

func NewTransferHandle

func NewTransferHandle(s *Session) TransferHandle

func NewTransferHandleWithTransfer

func NewTransferHandleWithTransfer(s *Session, t *Transfer) TransferHandle

func (TransferHandle) ActiveConnections

func (h TransferHandle) ActiveConnections() int

func (TransferHandle) DownloadPriority added in v0.1.0

func (h TransferHandle) DownloadPriority() TransferPriority

func (TransferHandle) GetCreateTime

func (h TransferHandle) GetCreateTime() int64

func (TransferHandle) GetFile

func (h TransferHandle) GetFile() *os.File

func (TransferHandle) GetFilePath

func (h TransferHandle) GetFilePath() string

func (TransferHandle) GetHash

func (h TransferHandle) GetHash() protocol.Hash

func (TransferHandle) GetPeersInfo

func (h TransferHandle) GetPeersInfo() []PeerInfo

func (TransferHandle) GetResumeData

func (h TransferHandle) GetResumeData() *protocol.TransferResumeData

func (TransferHandle) GetSize

func (h TransferHandle) GetSize() int64

func (TransferHandle) GetStatus

func (h TransferHandle) GetStatus() TransferStatus

func (TransferHandle) IsFinished

func (h TransferHandle) IsFinished() bool

func (TransferHandle) IsPaused

func (h TransferHandle) IsPaused() bool

func (TransferHandle) IsResumed

func (h TransferHandle) IsResumed() bool

func (TransferHandle) IsValid

func (h TransferHandle) IsValid() bool

func (TransferHandle) NeedResumeDataSave

func (h TransferHandle) NeedResumeDataSave() bool

func (TransferHandle) Pause

func (h TransferHandle) Pause()

func (TransferHandle) PieceSnapshots

func (h TransferHandle) PieceSnapshots() []PieceSnapshot

func (TransferHandle) Resume

func (h TransferHandle) Resume()

type TransferPriority added in v0.1.0

type TransferPriority int

TransferPriority 控制下载任务在会话内分配 peer 连接槽的相对顺序(数值越大越优先)。

const (
	TransferPriorityVeryLow TransferPriority = iota
	TransferPriorityLow
	TransferPriorityNormal
	TransferPriorityHigh
	TransferPriorityVeryHigh
)

func (TransferPriority) Label added in v0.1.0

func (p TransferPriority) Label() string

Label 返回 P0-P4 优先级标记(P4 最高)。

func (TransferPriority) SortKey added in v0.1.0

func (p TransferPriority) SortKey() int

func (TransferPriority) TextLabel added in v0.1.0

func (p TransferPriority) TextLabel() string

TextLabel 返回可读优先级文字。

type TransferProgressEvent

type TransferProgressEvent struct {
	At        time.Time
	Transfers []TransferProgressSnapshot
}

TransferProgressEvent contains only transfers whose progress/state changed.

type TransferProgressSnapshot

type TransferProgressSnapshot struct {
	Hash              protocol.Hash
	FileName          string
	FilePath          string
	State             TransferState
	Paused            bool
	Removed           bool
	TotalDone         int64
	TotalReceived     int64
	TotalWanted       int64
	DownloadingPieces int
	ActivePeers       int
	NumPeers          int
}

TransferProgressSnapshot is a lightweight per-transfer progress snapshot.

type TransferSnapshot

type TransferSnapshot struct {
	Hash             protocol.Hash
	FileName         string
	FilePath         string
	CreateTime       int64
	Size             int64
	ActivePeers      int
	Status           TransferStatus
	Peers            []PeerInfo
	Pieces           []PieceSnapshot
	DownloadPriority TransferPriority
}
func (t TransferSnapshot) ED2KLink() string

type TransferState

type TransferState string
const (
	LoadingResumeData TransferState = "LOADING_RESUME_DATA"
	Downloading       TransferState = "DOWNLOADING"
	PausedState       TransferState = "PAUSED"
	Verifying         TransferState = "VERIFYING"
	Finished          TransferState = "FINISHED"
)

type TransferStatus

type TransferStatus struct {
	Paused            bool
	DownloadRate      int
	Upload            int64
	UploadRate        int
	NumPeers          int
	DownloadingPieces int
	TotalDone         int64
	TotalReceived     int64
	TotalWanted       int64
	ETA               int64
	Pieces            protocol.BitField
	NumPieces         int
	State             TransferState
}

func (TransferStatus) String

func (s TransferStatus) String() string

type UploadPriority

type UploadPriority int
const (
	UploadPriorityVeryLow UploadPriority = iota
	UploadPriorityLow
	UploadPriorityNormal
	UploadPriorityHigh
	UploadPriorityVeryHigh
	UploadPriorityPowerShare
)

func (UploadPriority) ScoreFactor

func (p UploadPriority) ScoreFactor() float64

type UploadQueue

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

func NewUploadQueue

func NewUploadQueue(session *Session) *UploadQueue

func (*UploadQueue) AddClientToQueue

func (q *UploadQueue) AddClientToQueue(client *PeerConnection)

func (*UploadQueue) CheckForTimeOver

func (q *UploadQueue) CheckForTimeOver(client *PeerConnection) bool

func (*UploadQueue) IsOnUploadQueue

func (q *UploadQueue) IsOnUploadQueue(client *PeerConnection) bool

func (*UploadQueue) IsUploading

func (q *UploadQueue) IsUploading(client *PeerConnection) bool

func (*UploadQueue) Process

func (q *UploadQueue) Process()

func (*UploadQueue) RemoveFromUploadQueue

func (q *UploadQueue) RemoveFromUploadQueue(client *PeerConnection) bool

func (*UploadQueue) RemoveFromWaitingQueue

func (q *UploadQueue) RemoveFromWaitingQueue(client *PeerConnection) bool

func (*UploadQueue) ResumeUpload

func (q *UploadQueue) ResumeUpload(hash protocol.Hash)

func (*UploadQueue) SuspendUpload

func (q *UploadQueue) SuspendUpload(hash protocol.Hash, terminate bool) uint16

type UploadState

type UploadState int
const (
	UploadStateNone UploadState = iota
	UploadStateOnQueue
	UploadStateUploading
	UploadStateConnecting
)

type UploadableResource

type UploadableResource interface {
	GetHash() protocol.Hash
	FileLabel() string
	Size() int64
	UploadPriority() UploadPriority
	AvailablePieces() protocol.BitField
	UploadHashSet() []protocol.Hash
	AICHRootHash() (protocol.AICHHash, bool)
	UploadAICHHashes(requested []protocol.AICHHash) []protocol.AICHHash
	CanUpload() bool
	CanUploadRange(begin, end int64) bool
	ReadRange(begin, end int64) ([]byte, error)
}

UploadableResource 上传所需的最小能力(Transfer 与 SharedFile 均实现)。

Directories

Path Synopsis
Package bootstrap 提供 goed2k 客户端的共享初始化逻辑: 配置映射、状态加载、监听启动,以及服务器 / DHT 后台引导。
Package bootstrap 提供 goed2k 客户端的共享初始化逻辑: 配置映射、状态加载、监听启动,以及服务器 / DHT 后台引导。
cmd
goed2k command
examples
basic command
multi command
state_store command
status command
internal
upnp
Package upnp implements UPnP InternetGatewayDevice discovery, querying, and port mapping.
Package upnp implements UPnP InternetGatewayDevice discovery, querying, and port mapping.
kad
tools
genservermet command

Jump to

Keyboard shortcuts

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