mirror of
https://github.com/ehang-io/nps.git
synced 2025-09-08 00:26:52 +00:00
remove old file
This commit is contained in:
@@ -1,38 +0,0 @@
|
||||
package common
|
||||
|
||||
const (
|
||||
CONN_DATA_SEQ = "*#*" //Separator
|
||||
VERIFY_EER = "vkey"
|
||||
VERIFY_SUCCESS = "sucs"
|
||||
WORK_MAIN = "main"
|
||||
WORK_CHAN = "chan"
|
||||
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_TCP = "tcp"
|
||||
CONN_UDP = "udp"
|
||||
CONN_TEST = "TST"
|
||||
UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
WWW-Authenticate: Basic realm="easyProxy"
|
||||
|
||||
401 Unauthorized`
|
||||
ConnectionFailBytes = `HTTP/1.1 404 Not Found
|
||||
|
||||
`
|
||||
)
|
@@ -1,48 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego/logs"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxMsgLen = 5000
|
||||
|
||||
var logMsgs string
|
||||
|
||||
func init() {
|
||||
logs.Register("store", func() logs.Logger {
|
||||
return new(StoreMsg)
|
||||
})
|
||||
}
|
||||
|
||||
func GetLogMsg() string {
|
||||
return logMsgs
|
||||
}
|
||||
|
||||
type StoreMsg struct {
|
||||
}
|
||||
|
||||
func (lg *StoreMsg) Init(config string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lg *StoreMsg) WriteMsg(when time.Time, msg string, level int) error {
|
||||
m := when.Format("2006-01-02 15:04:05") + " " + msg + "\r\n"
|
||||
if len(logMsgs) > MaxMsgLen {
|
||||
start := MaxMsgLen - len(m)
|
||||
if start <= 0 {
|
||||
start = MaxMsgLen
|
||||
}
|
||||
logMsgs = logMsgs[start:]
|
||||
}
|
||||
logMsgs += m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (lg *StoreMsg) Destroy() {
|
||||
return
|
||||
}
|
||||
|
||||
func (lg *StoreMsg) Flush() {
|
||||
return
|
||||
}
|
@@ -1,219 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type NetPackager interface {
|
||||
Pack(writer io.Writer) (err error)
|
||||
UnPack(reader io.Reader) (err error)
|
||||
}
|
||||
|
||||
const (
|
||||
ipV4 = 1
|
||||
domainName = 3
|
||||
ipV6 = 4
|
||||
)
|
||||
|
||||
type UDPHeader struct {
|
||||
Rsv uint16
|
||||
Frag uint8
|
||||
Addr *Addr
|
||||
}
|
||||
|
||||
func NewUDPHeader(rsv uint16, frag uint8, addr *Addr) *UDPHeader {
|
||||
return &UDPHeader{
|
||||
Rsv: rsv,
|
||||
Frag: frag,
|
||||
Addr: addr,
|
||||
}
|
||||
}
|
||||
|
||||
type Addr struct {
|
||||
Type uint8
|
||||
Host string
|
||||
Port uint16
|
||||
}
|
||||
|
||||
func (addr *Addr) String() string {
|
||||
return net.JoinHostPort(addr.Host, strconv.Itoa(int(addr.Port)))
|
||||
}
|
||||
|
||||
func (addr *Addr) Decode(b []byte) error {
|
||||
addr.Type = b[0]
|
||||
pos := 1
|
||||
switch addr.Type {
|
||||
case ipV4:
|
||||
addr.Host = net.IP(b[pos : pos+net.IPv4len]).String()
|
||||
pos += net.IPv4len
|
||||
case ipV6:
|
||||
addr.Host = net.IP(b[pos : pos+net.IPv6len]).String()
|
||||
pos += net.IPv6len
|
||||
case domainName:
|
||||
addrlen := int(b[pos])
|
||||
pos++
|
||||
addr.Host = string(b[pos : pos+addrlen])
|
||||
pos += addrlen
|
||||
default:
|
||||
return errors.New("decode error")
|
||||
}
|
||||
|
||||
addr.Port = binary.BigEndian.Uint16(b[pos:])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (addr *Addr) Encode(b []byte) (int, error) {
|
||||
b[0] = addr.Type
|
||||
pos := 1
|
||||
switch addr.Type {
|
||||
case ipV4:
|
||||
ip4 := net.ParseIP(addr.Host).To4()
|
||||
if ip4 == nil {
|
||||
ip4 = net.IPv4zero.To4()
|
||||
}
|
||||
pos += copy(b[pos:], ip4)
|
||||
case domainName:
|
||||
b[pos] = byte(len(addr.Host))
|
||||
pos++
|
||||
pos += copy(b[pos:], []byte(addr.Host))
|
||||
case ipV6:
|
||||
ip16 := net.ParseIP(addr.Host).To16()
|
||||
if ip16 == nil {
|
||||
ip16 = net.IPv6zero.To16()
|
||||
}
|
||||
pos += copy(b[pos:], ip16)
|
||||
default:
|
||||
b[0] = ipV4
|
||||
copy(b[pos:pos+4], net.IPv4zero.To4())
|
||||
pos += 4
|
||||
}
|
||||
binary.BigEndian.PutUint16(b[pos:], addr.Port)
|
||||
pos += 2
|
||||
|
||||
return pos, nil
|
||||
}
|
||||
|
||||
func (h *UDPHeader) Write(w io.Writer) error {
|
||||
b := BufPoolUdp.Get().([]byte)
|
||||
defer BufPoolUdp.Put(b)
|
||||
|
||||
binary.BigEndian.PutUint16(b[:2], h.Rsv)
|
||||
b[2] = h.Frag
|
||||
|
||||
addr := h.Addr
|
||||
if addr == nil {
|
||||
addr = &Addr{}
|
||||
}
|
||||
length, _ := addr.Encode(b[3:])
|
||||
|
||||
_, err := w.Write(b[:3+length])
|
||||
return err
|
||||
}
|
||||
|
||||
type UDPDatagram struct {
|
||||
Header *UDPHeader
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func ReadUDPDatagram(r io.Reader) (*UDPDatagram, error) {
|
||||
b := BufPoolUdp.Get().([]byte)
|
||||
defer BufPoolUdp.Put(b)
|
||||
|
||||
// when r is a streaming (such as TCP connection), we may read more than the required data,
|
||||
// but we don't know how to handle it. So we use io.ReadFull to instead of io.ReadAtLeast
|
||||
// to make sure that no redundant data will be discarded.
|
||||
n, err := io.ReadFull(r, b[:5])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
header := &UDPHeader{
|
||||
Rsv: binary.BigEndian.Uint16(b[:2]),
|
||||
Frag: b[2],
|
||||
}
|
||||
|
||||
atype := b[3]
|
||||
hlen := 0
|
||||
switch atype {
|
||||
case ipV4:
|
||||
hlen = 10
|
||||
case ipV6:
|
||||
hlen = 22
|
||||
case domainName:
|
||||
hlen = 7 + int(b[4])
|
||||
default:
|
||||
return nil, errors.New("addr not support")
|
||||
}
|
||||
dlen := int(header.Rsv)
|
||||
if dlen == 0 { // standard SOCKS5 UDP datagram
|
||||
extra, err := ioutil.ReadAll(r) // we assume no redundant data
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
copy(b[n:], extra)
|
||||
n += len(extra) // total length
|
||||
dlen = n - hlen // data length
|
||||
} else { // extended feature, for UDP over TCP, using reserved field as data length
|
||||
if _, err := io.ReadFull(r, b[n:hlen+dlen]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n = hlen + dlen
|
||||
}
|
||||
header.Addr = new(Addr)
|
||||
if err := header.Addr.Decode(b[3:hlen]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data := make([]byte, dlen)
|
||||
copy(data, b[hlen:n])
|
||||
d := &UDPDatagram{
|
||||
Header: header,
|
||||
Data: data,
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func NewUDPDatagram(header *UDPHeader, data []byte) *UDPDatagram {
|
||||
return &UDPDatagram{
|
||||
Header: header,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func (d *UDPDatagram) Write(w io.Writer) error {
|
||||
h := d.Header
|
||||
if h == nil {
|
||||
h = &UDPHeader{}
|
||||
}
|
||||
buf := bytes.Buffer{}
|
||||
if err := h.Write(&buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := buf.Write(d.Data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func ToSocksAddr(addr net.Addr) *Addr {
|
||||
host := "0.0.0.0"
|
||||
port := 0
|
||||
if addr != nil {
|
||||
h, p, _ := net.SplitHostPort(addr.String())
|
||||
host = h
|
||||
port, _ = strconv.Atoi(p)
|
||||
}
|
||||
return &Addr{
|
||||
Type: ipV4,
|
||||
Host: host,
|
||||
Port: uint16(port),
|
||||
}
|
||||
}
|
@@ -1,95 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const PoolSize = 64 * 1024
|
||||
const PoolSizeSmall = 100
|
||||
const PoolSizeUdp = 1472 + 200
|
||||
const PoolSizeCopy = 32 << 10
|
||||
|
||||
var BufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSize)
|
||||
},
|
||||
}
|
||||
|
||||
var BufPoolUdp = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeUdp)
|
||||
},
|
||||
}
|
||||
var BufPoolMax = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSize)
|
||||
},
|
||||
}
|
||||
var BufPoolSmall = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeSmall)
|
||||
},
|
||||
}
|
||||
var BufPoolCopy = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeCopy)
|
||||
},
|
||||
}
|
||||
|
||||
func PutBufPoolUdp(buf []byte) {
|
||||
if cap(buf) == PoolSizeUdp {
|
||||
BufPoolUdp.Put(buf[:PoolSizeUdp])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolCopy(buf []byte) {
|
||||
if cap(buf) == PoolSizeCopy {
|
||||
BufPoolCopy.Put(buf[:PoolSizeCopy])
|
||||
}
|
||||
}
|
||||
|
||||
func GetBufPoolCopy() []byte {
|
||||
return (BufPoolCopy.Get().([]byte))[:PoolSizeCopy]
|
||||
}
|
||||
|
||||
func PutBufPoolMax(buf []byte) {
|
||||
if cap(buf) == PoolSize {
|
||||
BufPoolMax.Put(buf[:PoolSize])
|
||||
}
|
||||
}
|
||||
|
||||
type copyBufferPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (Self *copyBufferPool) New() {
|
||||
Self.pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeCopy, PoolSizeCopy)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *copyBufferPool) Get() []byte {
|
||||
buf := Self.pool.Get().([]byte)
|
||||
return buf[:PoolSizeCopy] // just like make a new slice, but data may not be 0
|
||||
}
|
||||
|
||||
func (Self *copyBufferPool) Put(x []byte) {
|
||||
if len(x) == PoolSizeCopy {
|
||||
Self.pool.Put(x)
|
||||
} else {
|
||||
x = nil // buf is not full, not allowed, New method returns a full buf
|
||||
}
|
||||
}
|
||||
|
||||
var once = sync.Once{}
|
||||
var CopyBuff = copyBufferPool{}
|
||||
|
||||
func newPool() {
|
||||
CopyBuff.New()
|
||||
}
|
||||
|
||||
func init() {
|
||||
once.Do(newPool)
|
||||
}
|
@@ -1,29 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
)
|
||||
|
||||
func InitPProfFromFile() {
|
||||
ip := beego.AppConfig.String("pprof_ip")
|
||||
p := beego.AppConfig.String("pprof_port")
|
||||
if len(ip) > 0 && len(p) > 0 && IsPort(p) {
|
||||
runPProf(ip + ":" + p)
|
||||
}
|
||||
}
|
||||
|
||||
func InitPProfFromArg(arg string) {
|
||||
if len(arg) > 0 {
|
||||
runPProf(arg)
|
||||
}
|
||||
}
|
||||
|
||||
func runPProf(ipPort string) {
|
||||
go func() {
|
||||
_ = http.ListenAndServe(ipPort, nil)
|
||||
}()
|
||||
logs.Info("PProf debug listen on", ipPort)
|
||||
}
|
@@ -1,89 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
//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 GetRunPath() string {
|
||||
var path string
|
||||
if path = GetInstallPath(); !FileExists(path) {
|
||||
return GetAppPath()
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//Different systems get different installation paths
|
||||
func GetInstallPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = `C:\Program Files\nps`
|
||||
} else {
|
||||
path = "/etc/nps"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//Get the absolute path to the running directory
|
||||
func GetAppPath() string {
|
||||
if path, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
|
||||
return path
|
||||
}
|
||||
return os.Args[0]
|
||||
}
|
||||
|
||||
//Determine whether the current system is a Windows system?
|
||||
func IsWindows() bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//interface log file path
|
||||
func GetLogPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = filepath.Join(GetAppPath(), "nps.log")
|
||||
} else {
|
||||
path = "/var/log/nps.log"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//interface npc log file path
|
||||
func GetNpcLogPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = filepath.Join(GetAppPath(), "npc.log")
|
||||
} else {
|
||||
path = "/var/log/npc.log"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//interface pid file path
|
||||
func GetTmpPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = GetAppPath()
|
||||
} else {
|
||||
path = "/tmp"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//config file path
|
||||
func GetConfigPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = filepath.Join(GetAppPath(), "conf/npc.conf")
|
||||
} else {
|
||||
path = "conf/npc.conf"
|
||||
}
|
||||
return path
|
||||
}
|
@@ -1,469 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"ehang.io/nps/lib/version"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"ehang.io/nps/lib/crypt"
|
||||
)
|
||||
|
||||
//Get the corresponding IP address through domain name
|
||||
func GetHostByName(hostname string) string {
|
||||
if !DomainCheck(hostname) {
|
||||
return hostname
|
||||
}
|
||||
ips, _ := net.LookupIP(hostname)
|
||||
if ips != nil {
|
||||
for _, v := range ips {
|
||||
if v.To4() != nil {
|
||||
return v.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//Check the legality of domain
|
||||
func DomainCheck(domain string) bool {
|
||||
var match bool
|
||||
IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
|
||||
NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
|
||||
match, _ = regexp.MatchString(IsLine, domain)
|
||||
if !match {
|
||||
match, _ = regexp.MatchString(NotLine, domain)
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
//Check if the Request request is validated
|
||||
func CheckAuth(r *http.Request, user, passwd string) bool {
|
||||
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
||||
if len(s) != 2 {
|
||||
s = strings.SplitN(r.Header.Get("Proxy-Authorization"), " ", 2)
|
||||
if len(s) != 2 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
b, err := base64.StdEncoding.DecodeString(s[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pair := strings.SplitN(string(b), ":", 2)
|
||||
if len(pair) != 2 {
|
||||
return false
|
||||
}
|
||||
return pair[0] == user && pair[1] == passwd
|
||||
}
|
||||
|
||||
//get bool by str
|
||||
func GetBoolByStr(s string) bool {
|
||||
switch s {
|
||||
case "1", "true":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//get str by bool
|
||||
func GetStrByBool(b bool) string {
|
||||
if b {
|
||||
return "1"
|
||||
}
|
||||
return "0"
|
||||
}
|
||||
|
||||
//int
|
||||
func GetIntNoErrByStr(str string) int {
|
||||
i, _ := strconv.Atoi(strings.TrimSpace(str))
|
||||
return i
|
||||
}
|
||||
|
||||
//Get verify value
|
||||
func Getverifyval(vkey string) string {
|
||||
return crypt.Md5(vkey)
|
||||
}
|
||||
|
||||
//Change headers and host of request
|
||||
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string, addOrigin bool) {
|
||||
if host != "" {
|
||||
r.Host = host
|
||||
}
|
||||
if header != "" {
|
||||
h := strings.Split(header, "\n")
|
||||
for _, v := range h {
|
||||
hd := strings.Split(v, ":")
|
||||
if len(hd) == 2 {
|
||||
r.Header.Set(hd[0], hd[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
addr = strings.Split(addr, ":")[0]
|
||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
||||
addr = strings.Join(prior, ", ") + ", " + addr
|
||||
}
|
||||
if addOrigin {
|
||||
r.Header.Set("X-Forwarded-For", addr)
|
||||
r.Header.Set("X-Real-IP", addr)
|
||||
}
|
||||
}
|
||||
|
||||
//Read file content by file path
|
||||
func ReadAllFromFile(filePath string) ([]byte, error) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return ioutil.ReadAll(f)
|
||||
}
|
||||
|
||||
// FileExists reports whether the named file or directory exists.
|
||||
func FileExists(name string) bool {
|
||||
if _, err := os.Stat(name); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//Judge whether the TCP port can open normally
|
||||
func TestTcpPort(port int) bool {
|
||||
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer func() {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//Judge whether the UDP port can open normally
|
||||
func TestUdpPort(port int) bool {
|
||||
l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer func() {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//Write length and individual byte data
|
||||
//Length prevents sticking
|
||||
//# Characters are used to separate data
|
||||
func BinaryWrite(raw *bytes.Buffer, v ...string) {
|
||||
b := GetWriteStr(v...)
|
||||
binary.Write(raw, binary.LittleEndian, int32(len(b)))
|
||||
binary.Write(raw, binary.LittleEndian, b)
|
||||
}
|
||||
|
||||
// get seq str
|
||||
func GetWriteStr(v ...string) []byte {
|
||||
buffer := new(bytes.Buffer)
|
||||
var l int32
|
||||
for _, v := range v {
|
||||
l += int32(len([]byte(v))) + int32(len([]byte(CONN_DATA_SEQ)))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte(v))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte(CONN_DATA_SEQ))
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
//inArray str interface
|
||||
func InStrArr(arr []string, val string) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//inArray int interface
|
||||
func InIntArr(arr []int, val int) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//format ports str to a int array
|
||||
func GetPorts(p string) []int {
|
||||
var ps []int
|
||||
arr := strings.Split(p, ",")
|
||||
for _, v := range arr {
|
||||
fw := strings.Split(v, "-")
|
||||
if len(fw) == 2 {
|
||||
if IsPort(fw[0]) && IsPort(fw[1]) {
|
||||
start, _ := strconv.Atoi(fw[0])
|
||||
end, _ := strconv.Atoi(fw[1])
|
||||
for i := start; i <= end; i++ {
|
||||
ps = append(ps, i)
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
} else if IsPort(v) {
|
||||
p, _ := strconv.Atoi(v)
|
||||
ps = append(ps, p)
|
||||
}
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
//is the string a port
|
||||
func IsPort(p string) bool {
|
||||
pi, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if pi > 65536 || pi < 1 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//if the s is just a port,return 127.0.0.1:s
|
||||
func FormatAddress(s string) string {
|
||||
if strings.Contains(s, ":") {
|
||||
return s
|
||||
}
|
||||
return "127.0.0.1:" + s
|
||||
}
|
||||
|
||||
//get address from the complete address
|
||||
func GetIpByAddr(addr string) string {
|
||||
arr := strings.Split(addr, ":")
|
||||
return arr[0]
|
||||
}
|
||||
|
||||
//get port from the complete address
|
||||
func GetPortByAddr(addr string) int {
|
||||
arr := strings.Split(addr, ":")
|
||||
if len(arr) < 2 {
|
||||
return 0
|
||||
}
|
||||
p, err := strconv.Atoi(arr[1])
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, err error) {
|
||||
buf := CopyBuff.Get()
|
||||
defer CopyBuff.Put(buf)
|
||||
for {
|
||||
nr, er := src.Read(buf)
|
||||
//if len(pr)>0 && pr[0] && nr > 50 {
|
||||
// logs.Warn(string(buf[:50]))
|
||||
//}
|
||||
if nr > 0 {
|
||||
nw, ew := dst.Write(buf[0:nr])
|
||||
if nw > 0 {
|
||||
written += int64(nw)
|
||||
}
|
||||
if ew != nil {
|
||||
err = ew
|
||||
break
|
||||
}
|
||||
if nr != nw {
|
||||
err = io.ErrShortWrite
|
||||
break
|
||||
}
|
||||
}
|
||||
if er != nil {
|
||||
err = er
|
||||
break
|
||||
}
|
||||
}
|
||||
return written, err
|
||||
}
|
||||
|
||||
//send this ip forget to get a local udp port
|
||||
func GetLocalUdpAddr() (net.Conn, error) {
|
||||
tmpConn, err := net.Dial("udp", "114.114.114.114:53")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tmpConn, tmpConn.Close()
|
||||
}
|
||||
|
||||
//parse template
|
||||
func ParseStr(str string) (string, error) {
|
||||
tmp := template.New("npc")
|
||||
var err error
|
||||
w := new(bytes.Buffer)
|
||||
if tmp, err = tmp.Parse(str); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = tmp.Execute(w, GetEnvMap()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return w.String(), nil
|
||||
}
|
||||
|
||||
//get env
|
||||
func GetEnvMap() map[string]string {
|
||||
m := make(map[string]string)
|
||||
environ := os.Environ()
|
||||
for i := range environ {
|
||||
tmp := strings.Split(environ[i], "=")
|
||||
if len(tmp) == 2 {
|
||||
m[tmp[0]] = tmp[1]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
//throw the empty element of the string array
|
||||
func TrimArr(arr []string) []string {
|
||||
newArr := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
if v != "" {
|
||||
newArr = append(newArr, v)
|
||||
}
|
||||
}
|
||||
return newArr
|
||||
}
|
||||
|
||||
//
|
||||
func IsArrContains(arr []string, val string) bool {
|
||||
if arr == nil {
|
||||
return false
|
||||
}
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//remove value from string array
|
||||
func RemoveArrVal(arr []string, val string) []string {
|
||||
for k, v := range arr {
|
||||
if v == val {
|
||||
arr = append(arr[:k], arr[k+1:]...)
|
||||
return arr
|
||||
}
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
//convert bytes to num
|
||||
func BytesToNum(b []byte) int {
|
||||
var str string
|
||||
for i := 0; i < len(b); i++ {
|
||||
str += strconv.Itoa(int(b[i]))
|
||||
}
|
||||
x, _ := strconv.Atoi(str)
|
||||
return int(x)
|
||||
}
|
||||
|
||||
//get the length of the sync map
|
||||
func GeSynctMapLen(m sync.Map) int {
|
||||
var c int
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
c++
|
||||
return true
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
func GetExtFromPath(path string) string {
|
||||
s := strings.Split(path, ".")
|
||||
re, err := regexp.Compile(`(\w+)`)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(re.Find([]byte(s[0])))
|
||||
}
|
||||
|
||||
var externalIp string
|
||||
|
||||
func GetExternalIp() string {
|
||||
if externalIp != "" {
|
||||
return externalIp
|
||||
}
|
||||
resp, err := http.Get("http://myexternalip.com/raw")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
content, _ := ioutil.ReadAll(resp.Body)
|
||||
externalIp = string(content)
|
||||
return externalIp
|
||||
}
|
||||
|
||||
func GetIntranetIp() (error, string) {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return nil, ""
|
||||
}
|
||||
for _, address := range addrs {
|
||||
// 检查ip地址判断是否回环地址
|
||||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||
if ipnet.IP.To4() != nil {
|
||||
return nil, ipnet.IP.To4().String()
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.New("get intranet ip error"), ""
|
||||
}
|
||||
|
||||
func IsPublicIP(IP net.IP) bool {
|
||||
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
if ip4 := IP.To4(); ip4 != nil {
|
||||
switch true {
|
||||
case ip4[0] == 10:
|
||||
return false
|
||||
case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
|
||||
return false
|
||||
case ip4[0] == 192 && ip4[1] == 168:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func GetServerIpByClientIp(clientIp net.IP) string {
|
||||
if IsPublicIP(clientIp) {
|
||||
return GetExternalIp()
|
||||
}
|
||||
_, ip := GetIntranetIp()
|
||||
return ip
|
||||
}
|
||||
|
||||
func PrintVersion() {
|
||||
fmt.Printf("Version: %s\nCore version: %s\nSame core version of client and server can connect each other\n", version.VERSION, version.GetVersion())
|
||||
}
|
Reference in New Issue
Block a user