constant

package
v1.53.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTCPTimeout = 8 * time.Second
	DefaultUDPTimeout = DefaultTCPTimeout
	DefaultTLSTimeout = DefaultTCPTimeout
)
View Source
const (
	BpfFSPath = "/sys/fs/bpf/clash"

	TcpAutoRedirPort = 't'<<8 | 'r'<<0
	ClashTrafficMark = 'c'<<24 | 'l'<<16 | 't'<<8 | 'm'<<0
)
View Source
const IsNoGVisor = false
View Source
const Name = "clash"
View Source
const ScriptRuleGeoSiteTarget = "__WhateverTarget__"

Variables

View Source
var (
	ErrInvalidResponse = errors.New("invalid response")
	ErrInvalidURL      = errors.New("invalid URL")
)
View Source
var (
	Version   = "unknown version"
	BuildTime = "unknown time"
)
View Source
var DNSModeMapping = map[string]DNSMode{
	DNSNormal.String(): DNSNormal,
	DNSFakeIP.String(): DNSFakeIP,
}

DNSModeMapping is a mapping for EnhancedMode enum

View Source
var (
	GetScriptProxyProviders = defaultProxyProvidersGetter
)
View Source
var MetadataTypeMapping = map[string]Type{
	strings.ToLower(HTTP.String()):        HTTP,
	strings.ToLower(HTTPCONNECT.String()): HTTPCONNECT,
	strings.ToLower(SOCKS4.String()):      SOCKS4,
	strings.ToLower(SOCKS5.String()):      SOCKS5,
	strings.ToLower(REDIR.String()):       REDIR,
	strings.ToLower(TPROXY.String()):      TPROXY,
	strings.ToLower(TUN.String()):         TUN,
	strings.ToLower(MITM.String()):        MITM,
	strings.ToLower(TUNNEL.String()):      TUNNEL,
}
View Source
var Path = func() *path {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		homeDir, _ = os.Getwd()
	}

	homeDir = P.Join(homeDir, ".config", Name)
	if _, err = os.Stat(homeDir); err != nil {
		if home, ok := os.LookupEnv("XDG_CONFIG_HOME"); ok {
			homeDir = P.Join(home, Name)
		}
	}

	return &path{homeDir: homeDir, configFile: "config.yaml"}
}()

Path is used to get the configuration path

View Source
var StackTypeMapping = map[string]TUNStack{
	strings.ToUpper(TunGvisor.String()): TunGvisor,
	strings.ToUpper(TunSystem.String()): TunSystem,
}

Functions

func BackupScriptState added in v1.50.0

func BackupScriptState()

func DecodeLatin1 added in v1.50.0

func DecodeLatin1(reader io.Reader) (string, error)

func EncodeLatin1 added in v1.50.0

func EncodeLatin1(str string) ([]byte, error)

func GetScriptRuleProviders added in v1.50.0

func GetScriptRuleProviders() map[string]Rule

func NewErrorResponse added in v1.50.0

func NewErrorResponse(req *http.Request, err error) *http.Response

func NewResponse added in v1.50.0

func NewResponse(code int, body io.Reader, req *http.Request) *http.Response

func ProxyURL added in v1.50.0

func ProxyURL(auth auth.Authenticator) func(*http.Request) (*url.URL, error)

ProxyURL returns a proxy function (for use in a http.Transport), nil if no inbound ports are set

func ReadDecompressedBody added in v1.50.0

func ReadDecompressedBody(res *http.Response) ([]byte, error)

func RestoreScriptState added in v1.50.0

func RestoreScriptState()

func SetConfig added in v1.50.0

func SetConfig(file string)

SetConfig is used to set the configuration file

func SetHomeDir added in v1.50.0

func SetHomeDir(root string)

SetHomeDir is used to set the configuration path

func SetLastTunConf added in v1.50.0

func SetLastTunConf(conf *Tun)

func SetProxyInbound added in v1.50.0

func SetProxyInbound(tcpInbounds map[string]Inbound)

SetProxyInbound assigns a http or socks inbound to proxyInbound

func SetScriptRuleProviders added in v1.50.0

func SetScriptRuleProviders(rp map[string]Rule)

Types

type AdapterType added in v0.5.0

type AdapterType int

AdapterType is enum of adapter type

const (
	Direct AdapterType = iota
	Reject
	Mitm

	Shadowsocks
	ShadowsocksR
	Snell
	Socks5
	Http
	Vmess
	Vless
	Trojan
	WireGuard

	Relay
	Selector
	Fallback
	URLTest
	LoadBalance
)

Adapter Type

func (AdapterType) String added in v0.5.0

func (at AdapterType) String() string

type AuthenticatorListener added in v1.50.0

type AuthenticatorListener interface {
	SetAuthenticator([]auth.AuthUser)
}

type Chain added in v1.50.0

type Chain []string

func (Chain) Last added in v1.50.0

func (c Chain) Last() string

func (Chain) String added in v1.50.0

func (c Chain) String() string

type Conn added in v1.50.0

type Conn interface {
	net.Conn
	Connection
}

type ConnContext added in v1.50.0

type ConnContext interface {
	PlainContext
	Metadata() *Metadata
	Conn() net.Conn
}

type Connection added in v1.50.0

type Connection interface {
	Chains() Chain
	AppendToChains(adapter ProxyAdapter)
	SetChains(chains []string)
	String() string
}

type DNSAddrPort added in v1.50.0

type DNSAddrPort struct {
	netip.AddrPort
}

func (DNSAddrPort) String added in v1.50.0

func (p DNSAddrPort) String() string

func (*DNSAddrPort) UnmarshalText added in v1.50.0

func (p *DNSAddrPort) UnmarshalText(text []byte) error

type DNSMode added in v1.50.0

type DNSMode int
const (
	DNSNormal DNSMode = iota
	DNSFakeIP
	DNSMapping
)

func (DNSMode) MarshalJSON added in v1.50.0

func (e DNSMode) MarshalJSON() ([]byte, error)

MarshalJSON serialize EnhancedMode with json

func (DNSMode) MarshalYAML added in v1.50.0

func (e DNSMode) MarshalYAML() (any, error)

MarshalYAML serialize EnhancedMode with yaml

func (DNSMode) String added in v1.50.0

func (e DNSMode) String() string

func (*DNSMode) UnmarshalJSON added in v1.50.0

func (e *DNSMode) UnmarshalJSON(data []byte) error

UnmarshalJSON unserialize EnhancedMode with json

func (*DNSMode) UnmarshalYAML added in v1.50.0

func (e *DNSMode) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML unserialize EnhancedMode with yaml

type DNSUrl added in v1.50.0

type DNSUrl struct {
	Network  string
	AddrPort DNSAddrPort
}

func (DNSUrl) MarshalJSON added in v1.50.0

func (d DNSUrl) MarshalJSON() ([]byte, error)

func (DNSUrl) MarshalYAML added in v1.50.0

func (d DNSUrl) MarshalYAML() (any, error)

func (DNSUrl) String added in v1.50.0

func (d DNSUrl) String() string

func (*DNSUrl) UnmarshalJSON added in v1.50.0

func (d *DNSUrl) UnmarshalJSON(data []byte) error

func (*DNSUrl) UnmarshalYAML added in v1.50.0

func (d *DNSUrl) UnmarshalYAML(unmarshal func(any) error) error

type DelayHistory added in v1.50.0

type DelayHistory struct {
	Time     time.Time `json:"time"`
	Delay    uint16    `json:"delay"`
	AvgDelay uint16    `json:"meanDelay"`
}

type EBpf added in v1.50.0

type EBpf interface {
	Start() error
	Close()
	Lookup(srcAddrPort netip.AddrPort) (socks5.Addr, error)
}

type Inbound added in v1.50.0

type Inbound inbound

func (*Inbound) Key added in v1.50.0

func (i *Inbound) Key() string

func (*Inbound) MarshalJSON added in v1.50.0

func (i *Inbound) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler

func (*Inbound) ToAlias added in v1.50.0

func (i *Inbound) ToAlias() string

func (*Inbound) UnmarshalJSON added in v1.50.0

func (i *Inbound) UnmarshalJSON(data []byte) error

UnmarshalJSON implements encoding/json.Unmarshaler

func (*Inbound) UnmarshalYAML added in v1.50.0

func (i *Inbound) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements yaml.Unmarshaler

type InboundType added in v1.50.0

type InboundType string
const (
	InboundTypeSocks  InboundType = "socks"
	InboundTypeSocks4 InboundType = "socks4"
	InboundTypeSocks5 InboundType = "socks5"
	InboundTypeRedir  InboundType = "redir"
	InboundTypeTproxy InboundType = "tproxy"
	InboundTypeHTTP   InboundType = "http"
	InboundTypeMixed  InboundType = "mixed"
	InboundTypeMitm   InboundType = "mitm"
)

type Listener added in v1.50.0

type Listener interface {
	RawAddress() string
	Address() string
	Close() error
}

type LogAddr added in v1.51.0

type LogAddr struct {
	M        Metadata
	Src      bool
	HostOnly bool
}

func (LogAddr) String added in v1.51.0

func (l LogAddr) String() string

type LogRule added in v1.51.0

type LogRule struct {
	R Rule
}

func (LogRule) String added in v1.51.0

func (l LogRule) String() string

type Matcher added in v1.50.0

type Matcher interface {
	Name() string
	Eval(metadata *Metadata) (string, error)
	Match(metadata *Metadata) (bool, error)
}

type Metadata added in v1.50.0

type Metadata struct {
	NetWork      NetWork    `json:"network"`
	Type         Type       `json:"type"`
	SrcIP        netip.Addr `json:"sourceIP"`
	DstIP        netip.Addr `json:"destinationIP"`
	SrcPort      Port       `json:"sourcePort"`
	DstPort      Port       `json:"destinationPort"`
	Host         string     `json:"host"`
	DNSMode      DNSMode    `json:"dnsMode"`
	Process      string     `json:"process"`
	ProcessPath  string     `json:"processPath"`
	UserAgent    string     `json:"userAgent"`
	SpecialProxy string     `json:"specialProxy"`

	OriginDst netip.AddrPort `json:"-"`
}

Metadata is used to store connection address

func (*Metadata) AddrType added in v1.50.0

func (m *Metadata) AddrType() int

func (*Metadata) MarshalObject added in v1.50.0

func (m *Metadata) MarshalObject(e *log.Entry)

func (*Metadata) NetworkFromString added in v1.50.0

func (m *Metadata) NetworkFromString(s string)

func (*Metadata) RemoteAddress added in v1.50.0

func (m *Metadata) RemoteAddress() string

func (*Metadata) Resolved added in v1.50.0

func (m *Metadata) Resolved() bool

func (*Metadata) SourceAddress added in v1.50.0

func (m *Metadata) SourceAddress() string

func (*Metadata) String added in v1.50.0

func (m *Metadata) String() string

func (*Metadata) TypeFromString added in v1.50.0

func (m *Metadata) TypeFromString(s string)

func (*Metadata) UDPAddr added in v1.50.0

func (m *Metadata) UDPAddr() *net.UDPAddr

func (*Metadata) Valid added in v1.50.0

func (m *Metadata) Valid() bool

type MitmOption added in v1.50.0

type MitmOption struct {
	ApiHost string

	TLSConfig  *tls.Config
	CertConfig *cert.Config

	Handler RewriteHandler
}

type MitmSession added in v1.50.0

type MitmSession struct {
	Conn     net.Conn
	Request  *http.Request
	Response *http.Response
	// contains filtered or unexported fields
}

func NewMitmSession added in v1.50.0

func NewMitmSession(conn net.Conn, request *http.Request, response *http.Response) *MitmSession

func (*MitmSession) GetProperties added in v1.50.0

func (s *MitmSession) GetProperties(key string) (any, bool)

func (*MitmSession) NewErrorResponse added in v1.50.0

func (s *MitmSession) NewErrorResponse(err error) *http.Response

func (*MitmSession) NewResponse added in v1.50.0

func (s *MitmSession) NewResponse(code int, body io.Reader) *http.Response

func (*MitmSession) SetProperties added in v1.50.0

func (s *MitmSession) SetProperties(key string, val any)

func (*MitmSession) WriteResponse added in v1.50.0

func (s *MitmSession) WriteResponse() (err error)

type NetWork

type NetWork int
const (
	TCP NetWork = iota
	UDP
	ALLNet
)

Socks addr type

func (NetWork) MarshalJSON added in v1.50.0

func (n NetWork) MarshalJSON() ([]byte, error)

func (NetWork) String

func (n NetWork) String() string

type PacketConn added in v1.50.0

type PacketConn interface {
	net.PacketConn
	Connection
}

type PacketConnContext added in v1.50.0

type PacketConnContext interface {
	PlainContext
	Metadata() *Metadata
	PacketConn() net.PacketConn
}

type PlainContext added in v1.50.0

type PlainContext interface {
	ID() uuid.UUID
}

type Port added in v1.50.0

type Port uint16

Port is used to compatible with old version

func (Port) MarshalJSON added in v1.50.0

func (n Port) MarshalJSON() ([]byte, error)

func (Port) String added in v1.50.0

func (n Port) String() string

type Proxy

type Proxy interface {
	ProxyAdapter
	Alive() bool
	HasV6() bool
	DelayHistory() []DelayHistory
	LastDelay() uint16
	URLTest(ctx context.Context, url string) (uint16, uint16, error)
}

type ProxyAdapter

type ProxyAdapter interface {
	Name() string
	Type() AdapterType
	Addr() string
	SupportUDP() bool
	DisableDnsResolve() bool
	MarshalJSON() ([]byte, error)

	// StreamConn wraps a protocol around net.Conn with Metadata.
	//
	// Examples:
	//	conn, _ := net.DialContext(context.Background(), "tcp", "host:port")
	//	conn, _ = adapter.StreamConn(conn, metadata)
	//
	// It returns a C.Conn with protocol which start with
	// a new session (if any)
	StreamConn(c net.Conn, metadata *Metadata) (net.Conn, error)

	// StreamPacketConn wraps a UDP protocol around net.Conn with Metadata.
	StreamPacketConn(c net.Conn, metadata *Metadata) (net.Conn, error)

	// DialContext return a C.Conn with protocol which
	// contains multiplexing-related reuse logic (if any)
	DialContext(ctx context.Context, metadata *Metadata, opts ...dialer.Option) (Conn, error)

	// ListenPacketContext listen for a PacketConn
	ListenPacketContext(ctx context.Context, metadata *Metadata, opts ...dialer.Option) (PacketConn, error)

	// Unwrap extracts the proxy from a proxy-group. It returns nil when nothing to extract.
	Unwrap(metadata *Metadata) Proxy

	// Cleanup released resources.
	Cleanup()
}

type RawProxy added in v1.50.0

type RawProxy struct {
	Name     string         `yaml:"name"`
	Type     string         `yaml:"type"`
	Server   string         `yaml:"server"`
	UUID     string         `yaml:"uuid,omitempty"`
	Password string         `yaml:"password,omitempty"`
	M        map[string]any `yaml:",inline"`
}

func (*RawProxy) Init added in v1.50.0

func (m *RawProxy) Init()

type Rewrite added in v1.50.0

type Rewrite interface {
	URLRegx() *regexp.Regexp
	RuleType() RewriteType
	RuleRegx() []*regexp.Regexp
	RulePayload() []string
	ReplaceURLPayload([]string) string
	ReplaceSubPayload(string) (string, bool)
}

type RewriteHandler added in v1.50.0

type RewriteHandler interface {
	HandleRequest(*MitmSession) (*http.Request, *http.Response) // session.Response maybe nil
	HandleResponse(*MitmSession) *http.Response
	HandleApiRequest(*MitmSession) bool
	HandleError(*MitmSession, error) // session maybe nil
}

type RewriteRule added in v1.50.0

type RewriteRule interface {
	SearchInRequest(func(Rewrite) bool) bool
	SearchInResponse(func(Rewrite) bool) bool
}

type RewriteType added in v1.50.0

type RewriteType int
const (
	MitmReject RewriteType = iota + 1
	MitmReject200
	MitmReject204
	MitmRejectImg
	MitmRejectDict
	MitmRejectArray

	Mitm302
	Mitm307

	MitmRequestHeader
	MitmRequestBody

	MitmResponseHeader
	MitmResponseBody
)

func (RewriteType) String added in v1.50.0

func (rt RewriteType) String() string

type Rule

type Rule interface {
	RuleType() RuleType
	Match(metadata *Metadata) bool
	Adapter() string
	Payload() string
	ShouldResolveIP() bool
	RuleExtra() *RuleExtra
	SetRuleExtra(re *RuleExtra)
	ShouldFindProcess() bool
	SubRules() []Rule
	RuleGroups() RuleGroup
	AppendGroup(group string)
}

type RuleExtra added in v1.50.0

type RuleExtra struct {
	Network      NetWork
	SourceIPs    []*netip.Prefix
	ProcessNames []string
}

func (*RuleExtra) NotMatchNetwork added in v1.50.0

func (re *RuleExtra) NotMatchNetwork(network NetWork) bool

func (*RuleExtra) NotMatchProcessName added in v1.50.0

func (re *RuleExtra) NotMatchProcessName(processName string) bool

func (*RuleExtra) NotMatchSourceIP added in v1.50.0

func (re *RuleExtra) NotMatchSourceIP(srcIP netip.Addr) bool

type RuleGeoSite added in v1.50.0

type RuleGeoSite interface {
	GetDomainMatcher() *router.DomainMatcher
}

type RuleGroup added in v1.50.0

type RuleGroup []string

func (RuleGroup) String added in v1.50.0

func (rg RuleGroup) String() string

type RuleType

type RuleType int
const (
	Domain RuleType = iota
	DomainSuffix
	DomainKeyword
	GEOSITE
	GEOIP
	IPCIDR
	SrcIPCIDR
	SrcPort
	DstPort
	InboundPort
	Process
	ProcessPath
	Script
	UserAgent
	IPSet
	MATCH
	Group
)

Rule Type

func (RuleType) String added in v0.5.0

func (rt RuleType) String() string

type TUNChangeCallback added in v1.50.0

type TUNChangeCallback interface {
	Pause()
	Resume()
}

type TUNStack added in v1.50.0

type TUNStack int
const (
	TunGvisor TUNStack = iota
	TunSystem
)

func (TUNStack) MarshalJSON added in v1.50.0

func (e TUNStack) MarshalJSON() ([]byte, error)

MarshalJSON serialize TUNStack with json

func (TUNStack) MarshalYAML added in v1.50.0

func (e TUNStack) MarshalYAML() (any, error)

MarshalYAML serialize TUNStack with yaml

func (TUNStack) String added in v1.50.0

func (e TUNStack) String() string

func (*TUNStack) UnmarshalJSON added in v1.50.0

func (e *TUNStack) UnmarshalJSON(data []byte) error

UnmarshalJSON unserialize TUNStack with json

func (*TUNStack) UnmarshalYAML added in v1.50.0

func (e *TUNStack) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML unserialize TUNStack with yaml

type TUNState added in v1.50.0

type TUNState int
const (
	TunDisabled TUNState = iota
	TunEnabled
	TunPaused
)

type Tun added in v1.50.0

type Tun struct {
	Enable              bool          `yaml:"enable" json:"enable"`
	Device              string        `yaml:"device" json:"device"`
	Stack               TUNStack      `yaml:"stack" json:"stack"`
	DNSHijack           []DNSUrl      `yaml:"dns-hijack" json:"dns-hijack"`
	AutoRoute           bool          `yaml:"auto-route" json:"auto-route"`
	AutoDetectInterface bool          `yaml:"auto-detect-interface" json:"auto-detect-interface"`
	TunAddressPrefix    *netip.Prefix `yaml:"-" json:"-"`
	RedirectToTun       []string      `yaml:"-" json:"-"`
	StopRouteListener   bool          `yaml:"-" json:"-"`
}

Tun config

func GetLastTunConf added in v1.50.0

func GetLastTunConf() *Tun

func GetTunConf added in v1.50.0

func GetTunConf() Tun

GetTunConf returns the last tun config

type Type added in v1.50.0

type Type int
const (
	HTTP Type = iota
	HTTPCONNECT
	SOCKS4
	SOCKS5
	REDIR
	TPROXY
	TUN
	MITM
	TUNNEL
)

func (Type) MarshalJSON added in v1.50.0

func (t Type) MarshalJSON() ([]byte, error)

func (Type) String added in v1.50.0

func (t Type) String() string

type UDPPacket added in v1.50.0

type UDPPacket interface {
	// Data get the payload of UDP Packet
	Data() *[]byte

	// WriteBack writes the payload with source IP/Port equals addr
	// - variable source IP/Port is important to STUN
	// - if addr is not provided, WriteBack will write out UDP packet with SourceIP/Port equals to original Target,
	//   this is important when using Fake-IP.
	WriteBack(b []byte, addr net.Addr) (n int, err error)

	// Drop call after packet is used, could recycle buffer in this function.
	Drop()

	// LocalAddr returns the source IP/Port of packet
	LocalAddr() net.Addr
}

UDPPacket contains the data of UDP packet, and offers control/info of UDP packet's source

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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