github.com/xxf098/lite-proxy@v0.15.1-0.20230422081941-12c69f323218/utils/utils.go (about)

     1  package utils
     2  
     3  import (
     4  	"context"
     5  	"net"
     6  	"os"
     7  	"reflect"
     8  	"regexp"
     9  	"runtime"
    10  	"strconv"
    11  	"strings"
    12  	"unsafe"
    13  
    14  	"github.com/xxf098/lite-proxy/common"
    15  	"github.com/xxf098/lite-proxy/log"
    16  )
    17  
    18  func CheckLink(link string) ([]string, error) {
    19  	r := regexp.MustCompile("(?i)^(vmess|trojan|vless|ss|ssr|http)://.+")
    20  	matches := r.FindStringSubmatch(link)
    21  	if len(matches) < 2 {
    22  		return nil, common.NewError("Not Suported Link")
    23  	}
    24  	return matches, nil
    25  }
    26  
    27  func getMaxProcs() int {
    28  	if runtime.GOOS != "linux" {
    29  		return 1
    30  	}
    31  	return runtime.NumCPU()
    32  }
    33  
    34  func GetListens(ctx context.Context, network, address string) ([]net.Listener, error) {
    35  	maxProcs := getMaxProcs() / 2
    36  	if maxProcs < 1 {
    37  		maxProcs = 1
    38  	}
    39  	listens := make([]net.Listener, maxProcs)
    40  	for i := 0; i < maxProcs; i++ {
    41  		listen, err := Listen(ctx, network, address)
    42  		if err != nil {
    43  			return nil, err
    44  		}
    45  		log.D("server", i, "pid", os.Getpid(), "serving on", listen.Addr())
    46  		listens[i] = listen
    47  	}
    48  	return listens, nil
    49  }
    50  
    51  // nolint
    52  func B2s(b []byte) string { return *(*string)(unsafe.Pointer(&b)) } // tricks
    53  
    54  // fastrandn returns a pseudorandom uint32 in [0,n).
    55  //
    56  //go:noescape
    57  //go:linkname Fastrandn runtime.fastrandn
    58  func Fastrandn(x uint32) uint32
    59  
    60  func U16toa(i uint16) string {
    61  	return strconv.FormatUint(uint64(i), 10)
    62  }
    63  
    64  func IsUrl(message string) bool {
    65  	matched, err := regexp.MatchString(`^(?:https?:\/\/)(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)`, message)
    66  	return matched && err == nil
    67  }
    68  
    69  func IsFilePath(message string) bool {
    70  	if len(message) < 1024 &&
    71  		!strings.HasPrefix(message, "vmess://") &&
    72  		!strings.HasPrefix(message, "trojan://") &&
    73  		!strings.HasPrefix(message, "ssr://") &&
    74  		!strings.HasPrefix(message, "ss://") {
    75  		_, err := os.Stat(message)
    76  		return err == nil
    77  	}
    78  	return false
    79  }
    80  
    81  func UnsafeGetBytes(s string) []byte {
    82  	return unsafe.Slice((*byte)(unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data)), len(s))
    83  }