constant

package
v1.19.31-hako.2 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTCPTimeout = dialer.DefaultTCPTimeout
	DefaultUDPTimeout = dialer.DefaultUDPTimeout
	DefaultDropTime   = 12 * DefaultTCPTimeout
	DefaultTLSTimeout = DefaultTCPTimeout
	DefaultTestURL    = "https://www.gstatic.com/generate_204"
)
View Source
const Name = "mihomo"

Variables

View Source
var (
	GeositeName   = "GeoSite.dat"
	GeoipName     = "GeoIP.dat"
	ASNName       = "ASN.mmdb"
	BundleMRSName = "BundleMRS.7z"
)
View Source
var (
	Meta       = true
	Version    = "1.10.0"
	BuildTime  = "unknown time"
	MihomoName = "mihomo"
)
View Source
var DNSModeMapping = map[string]DNSMode{
	DNSNormal.String():  DNSNormal,
	DNSFakeIP.String():  DNSFakeIP,
	DNSMapping.String(): DNSMapping,
}

DNSModeMapping is a mapping for EnhancedMode enum

View Source
var ErrNotSupport = errors.New("no support")
View Source
var FilterModeMapping = map[string]FilterMode{
	FilterBlackList.String(): FilterBlackList,
	FilterWhiteList.String(): FilterWhiteList,
	FilterRule.String():      FilterRule,
}

FilterModeMapping is a mapping for FilterMode enum

View Source
var Path = func() *path {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		homeDir, _ = os.Getwd()
	}
	allowUnsafePath, _ := strconv.ParseBool(os.Getenv("SKIP_SAFE_PATH_CHECK"))
	homeDir = P.Join(homeDir, ".config", Name)

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

	var safePaths []string
	for _, safePath := range filepath.SplitList(os.Getenv("SAFE_PATHS")) {
		safePath = strings.TrimSpace(safePath)
		if len(safePath) == 0 {
			continue
		}
		safePaths = append(safePaths, safePath)
	}

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

Path is used to get the configuration path

on Unix systems, `$HOME/.config/mihomo`. on Windows, `%USERPROFILE%/.config/mihomo`.

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

Functions

func ReportUDPUnreachable

func ReportUDPUnreachable(packet UDPPacket) error

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

Types

type AdapterType

type AdapterType int

AdapterType is enum of adapter type

const (
	Direct AdapterType = iota
	Reject
	RejectDrop
	Compatible
	Pass
	PassRule
	Rematch
	Dns

	Relay
	Selector
	Fallback
	URLTest
	LoadBalance

	Shadowsocks
	ShadowsocksR
	Snell
	Socks5
	Http
	Vmess
	Vless
	Trojan
	Hysteria
	Hysteria2
	WireGuard
	Tuic
	Ssh
	Mieru
	AnyTLS
	Sudoku
	Masque
	TrustTunnel
	ShadowQuic
	OpenVPN
	Tailscale
	ZeroTier
	EasyTier
	GostRelay
)

Adapter Type

func (AdapterType) String

func (at AdapterType) String() string

type AddrType

type AddrType byte
const (
	AtypIPv4       AddrType = 1
	AtypDomainName AddrType = 3
	AtypIPv6       AddrType = 4
)

SOCKS address types as defined in RFC 1928 section 5.

func (AddrType) String

func (a AddrType) String() string

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 {
	N.ExtendedConn
	Connection
}

type ConnContext

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

type Connection

type Connection interface {
	Chains() Chain
	ProviderChains() Chain
	AppendToChains(adapter ProxyAdapter)
	RemoteDestination() string
}

type DNSMode

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

func (DNSMode) MarshalText

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

MarshalText serialize EnhancedMode

func (DNSMode) String

func (e DNSMode) String() string

func (*DNSMode) UnmarshalText

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

UnmarshalText unserialize EnhancedMode

type DNSPrefer

type DNSPrefer int
const (
	DualStack DNSPrefer = iota
	IPv4Only
	IPv6Only
	IPv4Prefer
	IPv6Prefer
)

func (DNSPrefer) MarshalText

func (d DNSPrefer) MarshalText() ([]byte, error)

func (DNSPrefer) String

func (d DNSPrefer) String() string

func (*DNSPrefer) UnmarshalText

func (d *DNSPrefer) UnmarshalText(data []byte) error

type DelayHistory

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

type DelayHistoryStoreType

type DelayHistoryStoreType int

type Dialer

type Dialer interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
	ListenPacket(ctx context.Context, network, address string, rAddrPort netip.AddrPort) (net.PacketConn, error)
}

type DomainMatcher

type DomainMatcher interface {
	MatchDomain(domain string) bool
}

type ErrNotSafePath

type ErrNotSafePath struct {
	Path      string
	SafePaths []string
}

func (ErrNotSafePath) Error

func (e ErrNotSafePath) Error() string

type FilterMode

type FilterMode int
const (
	FilterBlackList FilterMode = iota
	FilterWhiteList
	FilterRule
)

func (FilterMode) MarshalText

func (e FilterMode) MarshalText() ([]byte, error)

func (FilterMode) String

func (e FilterMode) String() string

func (*FilterMode) UnmarshalText

func (e *FilterMode) UnmarshalText(data []byte) error

type HTTPVersion

type HTTPVersion string
const (
	// HTTPVersion11 is HTTP/1.1.
	HTTPVersion11 HTTPVersion = "http/1.1"
	// HTTPVersion2 is HTTP/2.
	HTTPVersion2 HTTPVersion = "h2"
	// HTTPVersion3 is HTTP/3.
	HTTPVersion3 HTTPVersion = "h3"
)

type InboundConfig

type InboundConfig interface {
	Name() string
	Equal(config InboundConfig) bool
}

type InboundListenConfig

type InboundListenConfig interface {
	Listen(ctx context.Context, network, address string) (net.Listener, error)
	ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error)
}

type InboundListener

type InboundListener interface {
	Name() string
	Listen(tunnel Tunnel) error
	Close() error
	Address() string
	RawAddress() string
	Config() InboundConfig
}

type IpMatcher

type IpMatcher interface {
	MatchIp(ip netip.Addr) bool
}

type Listener

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

type Metadata

type Metadata struct {
	NetWork                    NetWork    `json:"network"`
	Type                       Type       `json:"type"`
	SrcIP                      netip.Addr `json:"sourceIP"`
	DstIP                      netip.Addr `json:"destinationIP"`
	SrcGeoIP                   []string   `json:"sourceGeoIP"`      // can be nil if never queried, empty slice if got no result
	DstGeoIP                   []string   `json:"destinationGeoIP"` // can be nil if never queried, empty slice if got no result
	SrcIPASN                   string     `json:"sourceIPASN"`
	DstIPASN                   string     `json:"destinationIPASN"`
	SrcPort                    uint16     `json:"sourcePort,string"`      // `,string` is used to compatible with old version json output
	DstPort                    uint16     `json:"destinationPort,string"` // `,string` is used to compatible with old version json output
	InIP                       netip.Addr `json:"inboundIP"`
	InPort                     uint16     `json:"inboundPort,string"` // `,string` is used to compatible with old version json output
	InName                     string     `json:"inboundName"`
	InUser                     string     `json:"inboundUser"`
	RematchName                string     `json:"rematchName"`
	Host                       string     `json:"host"`
	DNSMode                    DNSMode    `json:"dnsMode"`
	Uid                        uint32     `json:"uid"`
	UidKnown                   bool       `json:"uidKnown"`
	Process                    string     `json:"process"`
	ProcessPath                string     `json:"processPath"`
	SourceIdentityKnown        bool       `json:"sourceIdentityKnown"`
	SourceAppSigningIdentifier string     `json:"sourceAppSigningIdentifier"`
	SourceAppTeamIdentifier    string     `json:"sourceAppTeamIdentifier"`
	SpecialProxy               string     `json:"specialProxy"`
	SpecialRules               string     `json:"specialRules"`
	RemoteDst                  string     `json:"remoteDestination"`
	DSCP                       uint8      `json:"dscp"`

	RawSrcAddr net.Addr `json:"-"`
	RawDstAddr net.Addr `json:"-"`
	// Only domain rule
	SniffHost string `json:"sniffHost"`
}

Metadata is used to store connection address

func (*Metadata) AddrPort

func (m *Metadata) AddrPort() netip.AddrPort

func (*Metadata) AddrType

func (m *Metadata) AddrType() AddrType

func (*Metadata) Clone

func (m *Metadata) Clone() *Metadata

func (*Metadata) HasUID

func (m *Metadata) HasUID() bool

func (*Metadata) Pure

func (m *Metadata) Pure() *Metadata

Pure is used to solve unexpected behavior when dialing proxy connection in DNSMapping mode.

func (*Metadata) RemoteAddress

func (m *Metadata) RemoteAddress() string

func (*Metadata) Resolved

func (m *Metadata) Resolved() bool

func (*Metadata) RuleHost

func (m *Metadata) RuleHost() string

func (*Metadata) SetRemoteAddr

func (m *Metadata) SetRemoteAddr(addr net.Addr) error

func (*Metadata) SetRemoteAddress

func (m *Metadata) SetRemoteAddress(rawAddress string) error

func (*Metadata) SourceAddrPort

func (m *Metadata) SourceAddrPort() netip.AddrPort

func (*Metadata) SourceAddress

func (m *Metadata) SourceAddress() string

func (*Metadata) SourceDetail

func (m *Metadata) SourceDetail() string

func (*Metadata) SourceValid

func (m *Metadata) SourceValid() bool

func (*Metadata) String

func (m *Metadata) String() string

func (*Metadata) SwapSrcDst

func (m *Metadata) SwapSrcDst()

func (*Metadata) UDPAddr

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

func (*Metadata) Valid

func (m *Metadata) Valid() bool

type MultiAddrListener

type MultiAddrListener interface {
	Close() error
	Config() string
	AddrList() (addrList []net.Addr)
}

type NatTable

type NatTable interface {
	GetOrCreate(key string, maker func() PacketSender) (PacketSender, bool)

	Delete(key string)

	GetForLocalConn(lAddr, rAddr string) *net.UDPConn

	AddForLocalConn(lAddr, rAddr string, conn *net.UDPConn) bool

	RangeForLocalConn(lAddr string, f func(key string, value *net.UDPConn) bool)

	GetOrCreateLockForLocalConn(lAddr string, key string) (*sync.Cond, bool)

	DeleteForLocalConn(lAddr, key string)

	DeleteLockForLocalConn(lAddr, key string)
}

type NetWork

type NetWork int
const (
	TCP NetWork = iota
	UDP
	ALLNet
	InvalidNet = 0xff
)

func (NetWork) MarshalJSON

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

func (NetWork) String

func (n NetWork) String() string

type PacketAdapter

type PacketAdapter interface {
	UDPPacket
	// Metadata returns destination metadata
	Metadata() *Metadata
	// Key is a SNAT key
	Key() string
}

PacketAdapter is a UDP Packet adapter for socks/redir/tun

func NewPacketAdapter

func NewPacketAdapter(packet UDPPacket, metadata *Metadata) PacketAdapter

type PacketConn

type PacketConn interface {
	N.EnhancePacketConn
	Connection
	ResolveUDP(ctx context.Context, metadata *Metadata) error
}

type PacketConnContext

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

type PacketSender

type PacketSender interface {
	// Send will send PacketAdapter nonblocking
	// the implement must call UDPPacket.Drop() inside Send
	Send(PacketAdapter)
	// Process is a blocking loop to send PacketAdapter to PacketConn and update the WriteBackProxy
	Process(PacketConn, WriteBackProxy)
	// Close stop the Process loop
	Close()
	// DoSniff will blocking after sniffer work done
	DoSniff(*Metadata) error
	// AddMapping add a destination NAT record
	AddMapping(originMetadata *Metadata, metadata *Metadata)
	// RestoreReadFrom restore destination NAT for ReadFrom
	// the implement must ensure returned netip.Add is valid (or just return input addr)
	RestoreReadFrom(addr netip.Addr) netip.Addr
}

type PlainContext

type PlainContext interface {
	ID() uuid.UUID
}

type Proxy

type Proxy interface {
	ProxyAdapter
	Adapter() ProxyAdapter
	AliveForTestUrl(url string) bool
	DelayHistory() []DelayHistory
	ExtraDelayHistories() map[string]ProxyState
	LastDelayForTestUrl(url string) uint16
	URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (uint16, error)
}

type ProxyAdapter

type ProxyAdapter interface {
	Name() string
	Type() AdapterType
	Addr() string
	SupportUDP() bool

	// ProxyInfo contains some extra information maybe useful for MarshalJSON
	ProxyInfo() ProxyInfo
	MarshalJSON() ([]byte, error)

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

	// SupportUOT return UDP over TCP support
	SupportUOT() bool

	// IsL3Protocol return ProxyAdapter working in L3 (tell dns module not pass the domain to avoid loopback)
	IsL3Protocol(metadata *Metadata) bool

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

	// Close releasing associated resources
	Close() error
}

type ProxyInfo

type ProxyInfo struct {
	XUDP         bool
	TFO          bool
	MPTCP        bool
	SMUX         bool
	Interface    string
	RoutingMark  int
	ProviderName string
	DialerProxy  string
}

type ProxyState

type ProxyState struct {
	Alive   bool           `json:"alive"`
	History []DelayHistory `json:"history"`
}

type Rule

type Rule interface {
	RuleType() RuleType
	Match(metadata *Metadata, helper RuleMatchHelper) (bool, string)
	Adapter() string
	Payload() string
	ProviderNames() []string
}

type RuleGroup

type RuleGroup interface {
	Rule
	GetRecodeSize() int
}

type RuleMatchHelper

type RuleMatchHelper struct {
	ResolveIP     func()
	FindProcess   func()
	CheckPassRule func(adapterName string) bool
}

type RuleType

type RuleType int
const (
	Domain RuleType = iota
	DomainSuffix
	DomainKeyword
	DomainRegex
	DomainWildcard
	GEOSITE
	GEOIP
	SrcGEOIP
	IPASN
	SrcIPASN
	IPCIDR
	SrcIPCIDR
	IPSuffix
	SrcIPSuffix
	SrcPort
	DstPort
	InPort
	DSCP
	InUser
	InName
	InType
	ProcessName
	ProcessPath
	ProcessNameRegex
	ProcessPathRegex
	ProcessNameWildcard
	ProcessPathWildcard
	RematchName
	RuleSet
	Network
	Uid
	SubRules
	MATCH
	AND
	OR
	NOT
	SourceAppSigningID
	SourceAppTeamID
)

Rule Type

func (RuleType) String

func (rt RuleType) String() string

type RuleWrapper

type RuleWrapper interface {
	Rule

	// SetDisabled to set enable/disable rule
	SetDisabled(v bool)
	// IsDisabled return rule is disabled or not
	IsDisabled() bool

	// HitCount for statistics
	HitCount() uint64
	// HitAt for statistics
	HitAt() time.Time
	// MissCount for statistics
	MissCount() uint64
	// MissAt for statistics
	MissAt() time.Time

	// Unwrap return Rule
	Unwrap() Rule
}

type TUNStack

type TUNStack int
const (
	TunGvisor TUNStack = iota
	TunSystem
	TunMixed
	TunMips
)

func (TUNStack) MarshalText

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

MarshalText serialize TUNStack with json

func (TUNStack) String

func (e TUNStack) String() string

func (*TUNStack) UnmarshalText

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

UnmarshalText unserialize TUNStack

type Tunnel

type Tunnel interface {
	// HandleTCPConn will handle a tcp connection blocking
	HandleTCPConn(conn net.Conn, metadata *Metadata)
	// HandleUDPPacket will handle a udp packet nonblocking
	HandleUDPPacket(packet UDPPacket, metadata *Metadata)
	// NatTable return nat table
	NatTable() NatTable
}

type Type

type Type int
const (
	HTTP Type = iota
	HTTPS
	SOCKS4
	SOCKS5
	SHADOWSOCKS
	SNELL
	VMESS
	VLESS
	REDIR
	TPROXY
	TROJAN
	TUNNEL
	TUN
	TUIC
	HYSTERIA2
	ANYTLS
	MIERU
	SUDOKU
	TRUSTTUNNEL
	SHADOWQUIC
	INNER
)

func ParseType

func ParseType(t string) (*Type, error)

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

	// 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

type UDPPacketInAddr

type UDPPacketInAddr interface {
	InAddr() net.Addr
}

type WriteBack

type WriteBack interface {
	WriteBack(b []byte, addr net.Addr) (n int, err error)
}

type WriteBackProxy

type WriteBackProxy interface {
	WriteBack
	UpdateWriteBack(wb WriteBack)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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