common

package
v0.34.7 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: GPL-3.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CONN_DATA_SEQ     = "*#*" // Separator
	VERIFY_EER        = "vkey"
	VERIFY_SUCCESS    = "sucs"
	WORK_MAIN         = "main"
	WORK_CHAN         = "chan"
	WORK_VISITOR      = "vstr"
	WORK_CONFIG       = "conf"
	WORK_REGISTER     = "rgst"
	WORK_SECRET       = "sert"
	WORK_FILE         = "file"
	WORK_P2P          = "p2pm"
	WORK_P2P_VISITOR  = "p2pv"
	WORK_P2P_PROVIDER = "p2pp"
	WORK_P2P_CONNECT  = "p2pc"
	WORK_P2P_SUCCESS  = "p2ps"
	WORK_P2P_END      = "p2pe"
	WORK_P2P_LAST     = "p2pl"
	WORK_STATUS       = "stus"
	RES_MSG           = "msg0"
	RES_CLOSE         = "clse"
	NEW_UDP_CONN      = "udpc" // p2p udp conn
	NEW_TASK          = "task"
	NEW_CONF          = "conf"
	NEW_HOST          = "host"
	CONN_ALL          = "all"
	CONN_TCP          = "tcp"
	CONN_UDP          = "udp"
	CONN_KCP          = "kcp"
	CONN_TLS          = "tls"
	CONN_QUIC         = "quic"
	CONN_WEB          = "web"
	CONN_WS           = "ws"
	CONN_WSS          = "wss"
	CONN_TEST         = "TST"
	CONN_ACK          = "ACK"
	PING              = "ping"
	PONG              = "pong"
	TEST              = "test"

	TOTP_SEQ = "totp:" // TOTP Separator

	UnauthorizedBytes = "HTTP/1.1 401 Unauthorized\r\n" +
		"Content-Type: text/plain; charset=utf-8\r\n" +
		"WWW-Authenticate: Basic realm=\"easyProxy\"\r\n" +
		"\r\n" +
		"401 Unauthorized"

	ProxyAuthRequiredBytes = "HTTP/1.1 407 Proxy Authentication Required\r\n" +
		"Proxy-Authenticate: Basic realm=\"Proxy\"\r\n" +
		"Content-Length: 0\r\n" +
		"Connection: close\r\n" +
		"\r\n"

	ConnectionFailBytes = "HTTP/1.1 404 Not Found\r\n" +
		"\r\n"

	IPv4DNS = "8.8.8.8:53"
	IPv6DNS = "[2400:3200::1]:53"
)
View Source
const (
	PoolSize      = 64 << 10
	PoolSizeSmall = 255
	PoolSizeUdp   = 1472 + 200
	PoolSizeCopy  = 32 << 10
)

Variables

View Source
var (
	BufPool      = newBytePool64K()
	BufPoolUdp   = newBytePoolUDP()
	BufPoolSmall = newBytePoolSmall()
	BufPoolCopy  = newBytePoolCopy()
)
View Source
var ConfPath string
View Source
var DefaultPort = map[string]string{
	"tcp":  "8024",
	"kcp":  "8024",
	"tls":  "8025",
	"quic": "8025",
	"ws":   "80",
	"wss":  "443",
}
View Source
var StartTime = time.Now()

Functions

func BinaryWrite

func BinaryWrite(raw *bytes.Buffer, v ...string)

BinaryWrite Write length and individual byte data Length prevents sticking # Characters are used to separate data

func BuildAddress added in v0.26.51

func BuildAddress(host string, port string) string

func BuildTCPBindAddr added in v0.34.2

func BuildTCPBindAddr(localIP string) net.Addr

func BuildUDPBindAddr added in v0.34.2

func BuildUDPBindAddr(localIP string) *net.UDPAddr

func BuildUdpBindAddr added in v0.33.9

func BuildUdpBindAddr(serverIP string, clientIP net.IP) (network string, addr *net.UDPAddr)

func BytesToNum

func BytesToNum(b []byte) int

BytesToNum convert bytes to num

func BytesToTimestamp added in v0.27.0

func BytesToTimestamp(b []byte) int64

BytesToTimestamp 8bit

func CalibrateTimeOffset added in v0.30.0

func CalibrateTimeOffset(server string) (time.Duration, error)

func CheckAuth

func CheckAuth(r *http.Request, user, passwd string, accountMap, authMap map[string]string) bool

CheckAuth Check if the Request request is validated

func CheckAuthWithAccountMap

func CheckAuthWithAccountMap(u, p, user, passwd string, accountMap, authMap map[string]string) bool

CheckAuthWithAccountMap u current login user p current login passwd user global user passwd global passwd accountMap enable multi user auth

func ChooseLocalAddrForPeer added in v0.34.0

func ChooseLocalAddrForPeer(selfLocal, peerLocal string) string

ChooseLocalAddrForPeer chooses ONE address from selfLocal to return to peer. Rule: - If both sides contain IPv6 -> return self IPv6 (best, public preferred) - Else -> return self IPv4 (best, public preferred) - Else -> return self IPv6 if any - Else -> return fallback (first valid) or ""

func ContainsFold added in v0.26.45

func ContainsFold(s, substr string) bool

func DealMultiUser added in v0.26.47

func DealMultiUser(s string) map[string]string

func DecodeIP added in v0.27.0

func DecodeIP(data []byte) net.IP

DecodeIP decodes a [1-byte ATYP] + [16-byte Address] to net.IP

func DomainCheck

func DomainCheck(domain string) bool

DomainCheck Check the legality of domain

func EncodeIP added in v0.27.0

func EncodeIP(ip net.IP) []byte

EncodeIP encodes a net.IP to [1-byte ATYP] + [16-byte Address]

func ExtendArrs added in v0.26.48

func ExtendArrs(arrays ...*[]string) int

func ExtractHost

func ExtractHost(input string) string

ExtractHost return "[2001:db8::1]:80"

func FetchExternalIp added in v0.26.46

func FetchExternalIp() string

func FileExists

func FileExists(name string) bool

FileExists reports whether the named file or directory exists.

func FixUdpListenAddrForRemote added in v0.34.0

func FixUdpListenAddrForRemote(remoteAddr, localAddr string) (string, string, error)

FixUdpListenAddrForRemote makes sure localAddr is a concrete address (not wildcard) and matches the IP family of remoteAddr. Returns (network, fixedLocalAddr).

func FormatAddress

func FormatAddress(s string) string

FormatAddress if the s is just a port,return 127.0.0.1:s

func GetAppPath

func GetAppPath() string

GetAppPath Get the absolute path to the running directory

func GetBoolByStr

func GetBoolByStr(s string) bool

GetBoolByStr get bool by str

func GetCertContent

func GetCertContent(filePath, header string) (string, error)

func GetCertType added in v0.29.9

func GetCertType(s string) string

func GetConfigPath

func GetConfigPath() string

GetConfigPath config file path

func GetCustomDNS added in v0.26.46

func GetCustomDNS() string

func GetEnvMap

func GetEnvMap() map[string]string

GetEnvMap get env

func GetExtFromPath

func GetExtFromPath(path string) string

func GetExternalIp

func GetExternalIp() string

func GetFastAddr added in v0.26.51

func GetFastAddr(addr string, testType string) (string, error)

func GetHostByName

func GetHostByName(hostname string) string

GetHostByName Get the corresponding IP address through domain name

func GetInstallPath

func GetInstallPath() string

GetInstallPath Different systems get different installation paths

func GetIntNoErrByStr

func GetIntNoErrByStr(str string) int

GetIntNoErrByStr int

func GetIntranetIp

func GetIntranetIp() string

func GetIpByAddr

func GetIpByAddr(host string) string

GetIpByAddr return "2001:db8::1"

func GetLocalUdp4Addr added in v0.26.47

func GetLocalUdp4Addr() (*net.UDPAddr, error)

func GetLocalUdp4IP added in v0.34.0

func GetLocalUdp4IP() (net.IP, error)

GetLocalUdp4IP returns the preferred local IPv4 egress IP.

func GetLocalUdp6Addr added in v0.26.47

func GetLocalUdp6Addr() (*net.UDPAddr, error)

func GetLocalUdp6IP added in v0.34.0

func GetLocalUdp6IP() (net.IP, error)

GetLocalUdp6IP returns the preferred local IPv6 egress IP.

func GetLocalUdpAddr

func GetLocalUdpAddr() (*net.UDPAddr, error)

GetLocalUdpAddr send this ip forget to get a local udp port

func GetLogPath

func GetLogPath() string

GetLogPath interface log file path

func GetMatchingLocalAddr added in v0.30.4

func GetMatchingLocalAddr(remoteAddr, localAddr string) (string, error)

func GetNpcLogPath

func GetNpcLogPath() string

GetNpcLogPath interface npc log file path

func GetOutboundIP added in v0.26.46

func GetOutboundIP() net.IP

func GetOutboundIPv4 added in v0.34.7

func GetOutboundIPv4() net.IP

func GetOutboundIPv6 added in v0.29.3

func GetOutboundIPv6() net.IP

func GetPath added in v0.29.15

func GetPath(filePath string) string

func GetPort added in v0.26.51

func GetPort(value int) int

func GetPortByAddr

func GetPortByAddr(addr string) int

GetPortByAddr return int or 0

func GetPortStrByAddr added in v0.29.20

func GetPortStrByAddr(addr string) string

func GetPorts

func GetPorts(s string) []int

GetPorts format ports str to an int array

func GetRunPath

func GetRunPath() string

GetRunPath Get the currently selected configuration file directory For non-Windows systems, select the /etc/nps as config directory if exist, or select ./ windows system, select the C:\Program Files\nps as config directory if exist, or select ./

func GetRunSecs added in v0.29.5

func GetRunSecs() int64

func GetRunTime added in v0.29.3

func GetRunTime() string

func GetServerIp added in v0.26.46

func GetServerIp(ip string) string

func GetServerIpByClientIp

func GetServerIpByClientIp(clientIp net.IP) string

func GetSni added in v0.33.7

func GetSni(host string) string

func GetStartTime added in v0.29.5

func GetStartTime() int64

func GetStrByBool

func GetStrByBool(b bool) string

GetStrByBool get str by bool

func GetSyncMapLen added in v0.30.4

func GetSyncMapLen(m *sync.Map) int

GetSyncMapLen get the length of the sync map

func GetTimeNoErrByStr

func GetTimeNoErrByStr(str string) time.Time

GetTimeNoErrByStr time

func GetTmpPath

func GetTmpPath() string

GetTmpPath interface pid file path

func GetWriteStr

func GetWriteStr(v ...string) []byte

GetWriteStr get seq str

func HandleArrEmptyVal added in v0.26.48

func HandleArrEmptyVal(list []string) []string

func HasIPv6InLocalList added in v0.34.0

func HasIPv6InLocalList(localStr string) bool

HasIPv6InLocalList reports whether localStr contains at least one valid IPv6 "[...]:port".

func InIntArr

func InIntArr(arr []int, val int) bool

InIntArr inArray int interface

func InStrArr

func InStrArr(arr []string, val string) bool

InStrArr inArray str interface

func InitPProfByAddr added in v0.32.2

func InitPProfByAddr(addr string)

func IsArrContains

func IsArrContains(arr []string, val string) bool

func IsBlackIp

func IsBlackIp(ipPort, vkey string, blackIpList []string) bool

func IsDomain added in v0.28.0

func IsDomain(s string) bool

func IsPort

func IsPort(p string) bool

IsPort is the string a port

func IsPublicHost added in v0.34.3

func IsPublicHost(addr string) bool

func IsPublicIP

func IsPublicIP(ip net.IP) bool

func IsPublicIPStrict added in v0.34.0

func IsPublicIPStrict(ip net.IP) bool

IsPublicIPStrict checks if IP is globally routable on the Internet. It excludes RFC1918, loopback, link-local, multicast, unspecified, and also excludes CGNAT / TEST-NET / benchmarking / documentation ranges.

func IsSameIPType added in v0.26.47

func IsSameIPType(addr1, addr2 string) bool

func IsTrustedProxy added in v0.33.3

func IsTrustedProxy(list, ipStr string) bool

func IsValidIP added in v0.26.46

func IsValidIP(ip string) bool

func IsWindows

func IsWindows() bool

IsWindows Determine whether the current system is a Windows system?

func IsZeroIP added in v0.33.9

func IsZeroIP(ip net.IP) bool

func LoadCert added in v0.26.48

func LoadCert(certFile, keyFile string) (tls.Certificate, bool)

func LoadCertPair added in v0.26.48

func LoadCertPair(certFile, keyFile string) (certContent, keyContent string, ok bool)

func Max added in v0.26.51

func Max(values ...int) int

func Min added in v0.26.51

func Min(values ...int) int

func NormalizeIP added in v0.33.9

func NormalizeIP(ip net.IP) net.IP

func ParseIPFromAddr added in v0.34.0

func ParseIPFromAddr(addr string) net.IP

ParseIPFromAddr parses IP from an "ip:port" (supports "[v6]:port"). Returns nil if cannot parse.

func ParseProxyACLEntries added in v0.34.0

func ParseProxyACLEntries(raw string) []string

ParseProxyACLEntries parses newline-separated text, trims and lowercases. Lines starting with '#' or ';' are ignored.

func ParseStr

func ParseStr(str string) (string, error)

ParseStr parse template

func PickBestV4V6FromLocalList added in v0.34.0

func PickBestV4V6FromLocalList(localStr string) (bestV4 string, bestV6 string, fallback string)

PickBestV4V6FromLocalList picks best IPv4/IPv6 address from localStr (comma-separated). Rules within each family: - First seen becomes candidate. - If later a "public" address appears and current is not public, replace it. Returns: - bestV4: best IPv4 "ip:port" if any - bestV6: best IPv6 "[ip]:port" if any - fallback: first valid address from list (stable)

func PickEgressIPFor added in v0.33.9

func PickEgressIPFor(dstIP net.IP) net.IP

func RandomBytes added in v0.27.0

func RandomBytes(maxLen int) ([]byte, error)

func ReadAllFromFile

func ReadAllFromFile(filePath string) ([]byte, error)

ReadAllFromFile Read file content by file path

func RemoveArrVal

func RemoveArrVal(arr []string, val string) []string

RemoveArrVal remove value from string array

func RemovePortFromHost

func RemovePortFromHost(host string) string

RemovePortFromHost return "[2001:db8::1]"

func ResolvePath added in v0.29.11

func ResolvePath(path string) string

func SetCustomDNS added in v0.26.45

func SetCustomDNS(dnsAddr string)

func SetNtpInterval added in v0.30.1

func SetNtpInterval(d time.Duration)

func SetNtpServer added in v0.30.0

func SetNtpServer(server string)

func SetTimezone added in v0.32.3

func SetTimezone(tz string) error

func SplitAddrAndHost added in v0.33.6

func SplitAddrAndHost(s string) (addr, host, sni string)

func SplitCommaAddrList added in v0.34.0

func SplitCommaAddrList(s string) []string

SplitCommaAddrList splits "ip:port,ip:port,..." into a de-duplicated list of valid IP:port. - Accepts single item without comma. - Ignores invalid entries. - Keeps first valid one as stable fallback.

func SplitServerAndPath added in v0.27.0

func SplitServerAndPath(s string) (server, path string)

func SyncTime added in v0.30.0

func SyncTime()

func TestLatency added in v0.26.51

func TestLatency(addr string, testType string) (time.Duration, error)

func TestTcpPort

func TestTcpPort(port int) bool

TestTcpPort Judge whether the TCP port can open normally

func TestUdpPort

func TestUdpPort(port int) bool

TestUdpPort Judge whether the UDP port can open normally

func TimeNow added in v0.30.0

func TimeNow() time.Time

func TimeOffset added in v0.30.0

func TimeOffset() time.Duration

func TimestampToBytes added in v0.27.0

func TimestampToBytes(ts int64) []byte

TimestampToBytes 8bit

func TrimArr

func TrimArr(arr []string) []string

TrimArr throw the empty element of the string array

func ValidateAddr added in v0.30.2

func ValidateAddr(s string) string

func ValidatePoW added in v0.29.30

func ValidatePoW(bits int, parts ...string) bool

Types

type Addr

type Addr struct {
	Type uint8
	Host string
	Port uint16
}

func ToSocksAddr

func ToSocksAddr(addr net.Addr) *Addr

func (*Addr) Decode

func (addr *Addr) Decode(b []byte) error

func (*Addr) Encode

func (addr *Addr) Encode(b []byte) (int, error)

func (*Addr) String

func (addr *Addr) String() string

type NetPackager

type NetPackager interface {
	Pack(writer io.Writer) (err error)
	UnPack(reader io.Reader) (err error)
}

type ProxyACL added in v0.34.0

type ProxyACL struct {
	Entries []string

	ExactIPs  map[string]struct{} // ip.String() => {}
	CIDRs     []*net.IPNet
	Hostnames map[string]struct{} // exact hostname (lower)

	// ".a.com" => subdomain-only (from "*.a.com")
	// "a.com"  => include root + subdomains (from "*a.com")
	WildcardSuffixes []string
}

ProxyACL is an allow-list matcher for proxy destinations. Enabled when Entries is non-empty; deny-by-default.

Entry formats (one per line): - IP: 1.2.3.4, 2001:db8::1 - CIDR: 10.0.0.0/8, 2001:db8::/32 - Hostname: example.com - Host:Port: example.com:443, [2001:db8::1]:443 (port is ignored) - Wildcard: *.example.com (subdomains only; NOT include example.com) - Wildcard: *example.com (include example.com + subdomains)

func ParseProxyACL added in v0.34.0

func ParseProxyACL(raw string) *ProxyACL

ParseProxyACL builds a matcher from raw entries. Note: it does NOT resolve DNS; hostnames match only hostname/wildcard rules.

func (*ProxyACL) Allows added in v0.34.0

func (a *ProxyACL) Allows(addr string) bool

Allows checks whether addr is allowed by ACL. addr can be: "host:port", "[ipv6]:port", "host", or URL-like forms supported by ExtractHost().

func (*ProxyACL) Enabled added in v0.34.0

func (a *ProxyACL) Enabled() bool

type UDPDatagram

type UDPDatagram struct {
	Header *UDPHeader
	Data   []byte
}

func NewUDPDatagram

func NewUDPDatagram(header *UDPHeader, data []byte) *UDPDatagram

func ReadUDPDatagram

func ReadUDPDatagram(r io.Reader) (*UDPDatagram, error)

func (*UDPDatagram) Write

func (d *UDPDatagram) Write(w io.Writer) error

type UDPHeader

type UDPHeader struct {
	Rsv  uint16
	Frag uint8
	Addr *Addr
}

func NewUDPHeader

func NewUDPHeader(rsv uint16, frag uint8, addr *Addr) *UDPHeader

func (*UDPHeader) Write

func (h *UDPHeader) Write(w io.Writer) error

Jump to

Keyboard shortcuts

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