constant

package
v1.31.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2023 License: GPL-3.0 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 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

func BackupScriptState()

func DecodeLatin1

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

func EncodeLatin1

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

func GetScriptRuleProviders

func GetScriptRuleProviders() map[string]Rule

func NewErrorResponse

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

func NewResponse

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

func ProxyURL

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

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

func RestoreScriptState

func RestoreScriptState()

func SetConfig

func SetConfig(file string)

SetConfig is used to set the configuration file

func SetHomeDir

func SetHomeDir(root string)

SetHomeDir is used to set the configuration path

func SetLastTunConf

func SetLastTunConf(conf *Tun)

func SetProxyInbound

func SetProxyInbound(tcpInbounds map[string]Inbound)

SetProxyInbound assigns a http or socks inbound to proxyInbound

func SetScriptRuleProviders

func SetScriptRuleProviders(rp map[string]Rule)

Types

type AdapterType

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

func (at AdapterType) String() string

type AuthenticatorListener

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

type Chain

type Chain []string

func (Chain) Last

func (c Chain) Last() string

func (Chain) String

func (c Chain) String() string

type Conn

type Conn interface {
	net.Conn
	Connection
}

type ConnContext

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

type Connection

type Connection interface {
	Chains() Chain
	AppendToChains(adapter ProxyAdapter)
	SetChains(chains []string)
	MarshalObject(e *log.Entry)
}

type DNSAddrPort

type DNSAddrPort struct {
	netip.AddrPort
}

func (DNSAddrPort) String

func (p DNSAddrPort) String() string

func (*DNSAddrPort) UnmarshalText

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

type DNSMode

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

func (DNSMode) MarshalJSON

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

MarshalJSON serialize EnhancedMode with json

func (DNSMode) MarshalYAML

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

MarshalYAML serialize EnhancedMode with yaml

func (DNSMode) String

func (e DNSMode) String() string

func (*DNSMode) UnmarshalJSON

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

UnmarshalJSON unserialize EnhancedMode with json

func (*DNSMode) UnmarshalYAML

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

UnmarshalYAML unserialize EnhancedMode with yaml

type DNSUrl

type DNSUrl struct {
	Network  string
	AddrPort DNSAddrPort
}

func (DNSUrl) MarshalJSON

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

func (DNSUrl) MarshalYAML

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

func (DNSUrl) String

func (d DNSUrl) String() string

func (*DNSUrl) UnmarshalJSON

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

func (*DNSUrl) UnmarshalYAML

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

type DelayHistory

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

type EBpf

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

type Inbound

type Inbound inbound

func (*Inbound) Key

func (i *Inbound) Key() string

func (*Inbound) MarshalJSON

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

MarshalJSON implements encoding/json.Marshaler

func (*Inbound) ToAlias

func (i *Inbound) ToAlias() string

func (*Inbound) UnmarshalJSON

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

UnmarshalJSON implements encoding/json.Unmarshaler

func (*Inbound) UnmarshalYAML

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

UnmarshalYAML implements yaml.Unmarshaler

type InboundType

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

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

type Matcher

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

type Metadata

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

func (m *Metadata) AddrType() int

func (*Metadata) MarshalObject

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

func (*Metadata) NetworkFromString

func (m *Metadata) NetworkFromString(s string)

func (*Metadata) RemoteAddress

func (m *Metadata) RemoteAddress() string

func (*Metadata) Resolved

func (m *Metadata) Resolved() bool

func (*Metadata) SourceAddress

func (m *Metadata) SourceAddress() string

func (*Metadata) String

func (m *Metadata) String() string

func (*Metadata) TypeFromString

func (m *Metadata) TypeFromString(s string)

func (*Metadata) UDPAddr

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

func (*Metadata) Valid

func (m *Metadata) Valid() bool

type MitmOption

type MitmOption struct {
	ApiHost string

	TLSConfig  *tls.Config
	CertConfig *cert.Config

	Handler RewriteHandler
}

type MitmSession

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

func NewMitmSession

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

func (*MitmSession) GetProperties

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

func (*MitmSession) NewErrorResponse

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

func (*MitmSession) NewResponse

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

func (*MitmSession) SetProperties

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

func (*MitmSession) WriteResponse

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

type NetWork

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

Socks addr type

func (NetWork) MarshalJSON

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

func (NetWork) String

func (n NetWork) String() string

type PacketConn

type PacketConn interface {
	net.PacketConn
	Connection
}

type PacketConnContext

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

type PlainContext

type PlainContext interface {
	ID() uuid.UUID
}

type Port

type Port uint16

Port is used to compatible with old version

func (Port) MarshalJSON

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

func (Port) String

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

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

func (m *RawProxy) Init()

type Rewrite

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

type RewriteHandler

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

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

type RewriteType

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

	Mitm302
	Mitm307

	MitmRequestHeader
	MitmRequestBody

	MitmResponseHeader
	MitmResponseBody
)

func (RewriteType) String

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

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

func (*RuleExtra) NotMatchNetwork

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

func (*RuleExtra) NotMatchProcessName

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

func (*RuleExtra) NotMatchSourceIP

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

type RuleGeoSite

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

type RuleGroup

type RuleGroup []string

func (RuleGroup) String

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

func (rt RuleType) String() string

type TUNChangeCallback

type TUNChangeCallback interface {
	Pause()
	Resume()
}

type TUNStack

type TUNStack int
const (
	TunGvisor TUNStack = iota
	TunSystem
)

func (TUNStack) MarshalJSON

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

MarshalJSON serialize TUNStack with json

func (TUNStack) MarshalYAML

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

MarshalYAML serialize TUNStack with yaml

func (TUNStack) String

func (e TUNStack) String() string

func (*TUNStack) UnmarshalJSON

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

UnmarshalJSON unserialize TUNStack with json

func (*TUNStack) UnmarshalYAML

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

UnmarshalYAML unserialize TUNStack with yaml

type TUNState

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

type Tun

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

func GetLastTunConf() *Tun

func GetTunConf

func GetTunConf() Tun

GetTunConf returns the last tun config

type Type

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

func (Type) MarshalJSON

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

func (Type) String

func (t Type) String() string

type UDPPacket

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