diff --git a/gui/src/App.vue b/gui/src/App.vue
index b1737bcd..47da89a4 100644
--- a/gui/src/App.vue
+++ b/gui/src/App.vue
@@ -243,7 +243,7 @@ export default {
duration: 10000
});
} else {
- localStorage["iptablesMode"] = res.data.data.iptablesMode;
+ localStorage["lite"] = res.data.data.lite;
localStorage["dohValid"] = res.data.data.dohValid;
localStorage["vlessValid"] = res.data.data.vlessValid;
localStorage["observatorySidebarValid"] = isVersionGreaterEqual(
diff --git a/gui/src/components/modalSetting.vue b/gui/src/components/modalSetting.vue
index d844731b..4a776dae 100644
--- a/gui/src/components/modalSetting.vue
+++ b/gui/src/components/modalSetting.vue
@@ -57,21 +57,21 @@
-
-
+
-
-
+
@@ -85,10 +85,7 @@
-
+
{{ $t("setting.transparentType") }}
@@ -399,7 +396,6 @@ export default {
localGFWListVersion: "checking...",
showAntipollution: false,
showSpecialMode: false,
- showTransparentType: false,
showAdvanced: false,
showDns: false,
showDoh: false,
@@ -409,6 +405,11 @@ export default {
showDnsForceMode: false
}),
computed: {
+ lite() {
+ return (
+ window.localStorage["lite"] && parseInt(window.localStorage["lite"]) > 0
+ );
+ },
dockerMode() {
return window.localStorage["docker"] === "true";
},
@@ -420,9 +421,6 @@ export default {
U.protocol === "http" ? "80" : U.protocol === "https" ? "443" : "";
}
return toInt(port);
- },
- iptablesMode() {
- return localStorage["iptablesMode"] || "tproxy";
}
},
watch: {
@@ -459,10 +457,6 @@ export default {
localStorage["version"],
"1.4.0"
);
- this.showTransparentType = isVersionGreaterEqual(
- localStorage["version"],
- "1.4.0"
- );
this.showAdvanced = isVersionGreaterEqual(
localStorage["version"],
"1.4.0"
@@ -490,6 +484,10 @@ export default {
localStorage["version"],
"0.6.8"
);
+ if (this.lite) {
+ this.transparent = "close";
+ this.showSpecialMode = false;
+ }
});
});
//白名单有没有项,没有就post一下
diff --git a/service/common/netTools/interface.go b/service/common/netTools/interface.go
index e1f98e04..467d90f1 100644
--- a/service/common/netTools/interface.go
+++ b/service/common/netTools/interface.go
@@ -8,6 +8,7 @@ import (
var NoDefaultInterface = fmt.Errorf("default interfaces not found")
+// only for linux
func GetDefaultInterfaceName() ([]string, error) {
b, err := exec.Command("sh", "-c", "awk '$2 == 00000000 { print $1 }' /proc/net/route").Output()
if err != nil {
diff --git a/service/common/netTools/netstat/netstat.go b/service/common/netTools/netstat/netstat.go
index cc34897f..10517344 100644
--- a/service/common/netTools/netstat/netstat.go
+++ b/service/common/netTools/netstat/netstat.go
@@ -1,30 +1,12 @@
package netstat
import (
- "bufio"
- "bytes"
- "encoding/binary"
- "errors"
"fmt"
- "io"
"net"
- "os"
- "path/filepath"
- "strconv"
- "strings"
"sync"
)
-// Socket states
-type SkState uint8
-
-const (
- pathNet = "/proc/net"
- pathProc = "/proc"
-
- ipv4StrLen = 8
- ipv6StrLen = 32
-)
+var ErrorNotSupportOSErr = fmt.Errorf("netstat: operating system is not supported")
const (
Established SkState = 0x01
@@ -55,6 +37,9 @@ var skStates = [...]string{
"CLOSING",
}
+// Socket states
+type SkState uint8
+
func (sk SkState) String() string {
return skStates[sk]
}
@@ -64,58 +49,6 @@ type Address struct {
Port int
}
-func parseIPv4(s string) (net.IP, error) {
- v, err := strconv.ParseUint(s, 16, 32)
- if err != nil {
- return nil, fmt.Errorf("parseIPv4: %w", err)
- }
- ip := make(net.IP, net.IPv4len)
- binary.LittleEndian.PutUint32(ip, uint32(v))
- return ip, nil
-}
-
-func parseIPv6(s string) (net.IP, error) {
- ip := make(net.IP, net.IPv6len)
- const grpLen = 4
- i, j := 0, 4
- for len(s) != 0 {
- grp := s[0:8]
- u, err := strconv.ParseUint(grp, 16, 32)
- binary.LittleEndian.PutUint32(ip[i:j], uint32(u))
- if err != nil {
- return nil, fmt.Errorf("parseIPv6: %w", err)
- }
- i, j = i+grpLen, j+grpLen
- s = s[8:]
- }
- return ip, nil
-}
-
-func parseAddr(s string) (*Address, error) {
- fields := strings.Split(s, ":")
- if len(fields) < 2 {
- return nil, fmt.Errorf("netstat: not enough fields: %v", s)
- }
- var ip net.IP
- var err error
- switch len(fields[0]) {
- case ipv4StrLen:
- ip, err = parseIPv4(fields[0])
- case ipv6StrLen:
- ip, err = parseIPv6(fields[0])
- default:
- return nil, fmt.Errorf("parseAddr: Bad formatted string")
- }
- if err != nil {
- return nil, fmt.Errorf("parseAddr: %w", err)
- }
- v, err := strconv.ParseUint(fields[1], 16, 16)
- if err != nil {
- return nil, fmt.Errorf("parseAddr: %w", err)
- }
- return &Address{IP: ip, Port: int(v)}, nil
-}
-
type Socket struct {
LocalAddress *Address
RemoteAddress *Address
@@ -130,334 +63,4 @@ type Process struct {
PID string
PPID string
Name string
-}
-
-var (
- SocketFreedErr = fmt.Errorf("process not found, correspond socket was freed")
- ProcOpenFailedErr = fmt.Errorf("cannot open the directory /proc")
-)
-
-func FillProcesses(sockets []*Socket) error {
- f, err := os.ReadDir(pathProc)
- if err != nil {
- return ProcOpenFailedErr
- }
- mapInodeSocket := make(map[string]*Socket)
- iNodes := make(map[string]struct{})
- for i, s := range sockets {
- s.processMutex.Lock()
- defer s.processMutex.Unlock()
- mapInodeSocket[s.inode] = sockets[i]
- iNodes[s.inode] = struct{}{}
- }
-loop1:
- for _, fi := range f {
- fn := fi.Name()
- if !fi.IsDir() {
- continue
- }
- for _, t := range fn {
- if t > '9' || t < '0' {
- continue loop1
- }
- }
- for _, s := range sockets {
- if s.Proc != nil {
- continue
- }
- }
- if inode := isProcessSocket(fn, iNodes); inode != "" {
- pn, ppid := getProcessInfo(fn)
- mapInodeSocket[inode].Proc = &Process{
- PID: fn,
- PPID: ppid,
- Name: pn,
- }
- delete(iNodes, inode)
- }
- }
- return nil
-}
-
-/*
-较为消耗资源
-*/
-func (s *Socket) Process() (*Process, error) {
- s.processMutex.Lock()
- s.processMutex.Unlock()
- if s.Proc != nil {
- return s.Proc, nil
- }
- f, err := os.ReadDir(pathProc)
- if err != nil {
- return nil, nil
- }
-loop1:
- for _, fi := range f {
- fn := fi.Name()
- if !fi.IsDir() {
- continue
- }
- for _, t := range fn {
- if t > '9' || t < '0' {
- continue loop1
- }
- }
- if isProcessSocket(fn, map[string]struct{}{s.inode: {}}) != "" {
- pn, ppid := getProcessInfo(fn)
- s.Proc = &Process{
- PID: fn,
- PPID: ppid,
- Name: pn,
- }
- return s.Proc, nil
- }
- }
- return nil, SocketFreedErr
-}
-
-/*
-没有做缓存,每次调用都会扫描,消耗资源
-*/
-
-var ErrorNotFound = fmt.Errorf("process not found")
-
-func findProcessID(pname string) (pids []string, err error) {
- f, err := os.ReadDir(pathProc)
- if err != nil {
- err = fmt.Errorf("findProcessID: %w", err)
- return
- }
-loop1:
- for _, fi := range f {
- if !fi.IsDir() {
- continue
- }
- fn := fi.Name()
- for _, t := range fn {
- if t > '9' || t < '0' {
- continue loop1
- }
- }
- if pn, _ := getProcessInfo(fn); pn == pname {
- pids = append(pids, fn)
- }
- }
- if len(pids) > 0 {
- return pids, nil
- }
- return nil, ErrorNotFound
-}
-
-func getProcName(s string) string {
- i := strings.Index(s, "(")
- if i < 0 {
- return ""
- }
- s = s[i+1:]
- j := strings.LastIndex(s, ")")
- if j < 0 {
- return ""
- }
- return s[:j]
-}
-
-func getProcessInfo(pid string) (pn string, ppid string) {
- p := filepath.Join(pathProc, pid, "stat")
- b, err := os.ReadFile(p)
- if err != nil {
- err = fmt.Errorf("getProcessInfo: %w", err)
- return
- }
- sp := bytes.Fields(b)
- pn = string(sp[1])
- return getProcName(pn), string(sp[3])
-}
-
-func isProcessSocket(pid string, socketInode map[string]struct{}) string {
- // link name is of the form socket:[5860846]
- p := filepath.Join(pathProc, pid, "fd")
- f, err := os.Open(p)
- fns, err := f.Readdirnames(-1)
- f.Close()
- if err != nil {
- return ""
- }
- for _, fn := range fns {
- lk, err := os.Readlink(filepath.Join(p, fn))
- if err != nil {
- continue
- }
- for inode := range socketInode {
- target := "socket:[" + inode + "]"
- if lk == target {
- return inode
- }
- }
- }
- return ""
-}
-
-func getProcessSocketSet(pid string) (set []string) {
- // link name is of the form socket:[5860846]
- p := filepath.Join(pathProc, pid, "fd")
- f, err := os.Open(p)
- fns, err := f.Readdirnames(-1)
- f.Close()
- if err != nil {
- err = fmt.Errorf("getProcessSocketSet: %w", err)
- return
- }
- for _, fn := range fns {
- lk, err := os.Readlink(filepath.Join(p, fn))
- if err != nil {
- continue
- }
- if strings.HasPrefix(lk, "socket:[") {
- set = append(set, lk[8:len(lk)-1])
- }
- }
- return
-}
-
-func parseSocktab(r io.Reader) (map[int][]*Socket, error) {
- br := bufio.NewScanner(r)
- tab := make(map[int][]*Socket)
-
- // Discard title
- br.Scan()
-
- for br.Scan() {
- var s Socket
- line := br.Text()
- // Skip comments
- if i := strings.Index(line, "#"); i >= 0 {
- line = line[:i]
- }
- fields := strings.Fields(line)
- if len(fields) < 12 {
- return tab, fmt.Errorf("netstat: not enough fields: %v, %v", len(fields), fields)
- }
- addr, err := parseAddr(fields[1])
- if err != nil {
- return tab, err
- }
- s.LocalAddress = addr
- addr, err = parseAddr(fields[2])
- if err != nil {
- return tab, err
- }
- s.RemoteAddress = addr
- u, err := strconv.ParseUint(fields[3], 16, 8)
- if err != nil {
- err = fmt.Errorf("parseSocktab: %w", err)
- return tab, err
- }
- s.State = SkState(u)
- s.UID = fields[7]
- s.inode = fields[9]
- tab[s.LocalAddress.Port] = append(tab[s.LocalAddress.Port], &s)
- }
- if br.Err() != nil {
- return nil, fmt.Errorf("parseSocktab: %w", br.Err())
- }
- return tab, nil
-}
-func ToPortMap(protocols []string) (map[string]map[int][]*Socket, error) {
- m := make(map[string]map[int][]*Socket)
- for _, proto := range protocols {
- switch proto {
- case "tcp", "tcp6", "udp", "udp6":
- b, err := os.Open(filepath.Join(pathNet, proto))
- if err != nil {
- continue
- }
- m[proto], err = parseSocktab(b)
- if err != nil {
- return nil, err
- }
- default:
- }
- }
-
- return m, nil
-}
-
-func IsProcessListenPort(pname string, port int) (is bool, err error) {
- protocols := []string{"tcp", "tcp6"}
- m, err := ToPortMap(protocols)
- if err != nil {
- return
- }
- iNodes := make(map[string]struct{})
- for _, proto := range protocols {
- for _, v := range m[proto][port] {
- if v.State == Listen || v.State == Established {
- iNodes[v.inode] = struct{}{}
- }
- }
- }
- if len(iNodes) == 0 {
- return false, nil
- }
- pids, err := findProcessID(pname)
- if err != nil {
- if errors.Is(err, ErrorNotFound) {
- return false, nil
- }
- return
- }
- for _, pid := range pids {
- if isProcessSocket(pid, iNodes) != "" {
- return true, nil
- }
- }
- return false, nil
-}
-
-func Print(protocols []string) string {
- var buffer strings.Builder
- protos := make([]string, 0, 4)
- for _, proto := range protocols {
- switch proto {
- case "tcp", "tcp6", "udp", "udp6":
- protos = append(protos, proto)
- }
- }
- m, err := ToPortMap(protos)
- if err != nil {
- return ""
- }
- buffer.WriteString(fmt.Sprintf("%-6v%-25v%-25v%-15v%-6v%-9v%v\n", "Proto", "Local Address", "Foreign Address", "State", "User", "Inode", "PID/Program name"))
- var sockets []*Socket
- for _, proto := range protos {
- for _, v := range m[proto] {
- sockets = append(sockets, v...)
- }
- }
- _ = FillProcesses(sockets)
- for _, proto := range protos {
- for _, sockets := range m[proto] {
- for _, v := range sockets {
- process, err := v.Process()
- var pstr string
- if err != nil {
- pstr = ""
- } else {
- pstr = process.PID + "/" + process.Name
- }
- buffer.WriteString(fmt.Sprintf(
- "%-6v%-25v%-25v%-15v%-6v%-9v%v\n",
- proto,
- v.LocalAddress.IP.String()+"/"+strconv.Itoa(v.LocalAddress.Port),
- v.RemoteAddress.IP.String()+"/"+strconv.Itoa(v.RemoteAddress.Port),
- v.State.String(),
- v.UID,
- v.inode,
- pstr,
- ))
- }
- }
- }
- return buffer.String()
-}
+}
\ No newline at end of file
diff --git a/service/common/netTools/netstat/netstat_other.go b/service/common/netTools/netstat/netstat_other.go
new file mode 100644
index 00000000..e6819b7b
--- /dev/null
+++ b/service/common/netTools/netstat/netstat_other.go
@@ -0,0 +1,28 @@
+// +build !linux,!plan9,!freebsd,!solaris
+
+package netstat
+
+import (
+ "fmt"
+)
+
+func FillProcesses(sockets []*Socket) error {
+ return ErrorNotSupportOSErr
+}
+
+func (s *Socket) Process() (*Process, error) {
+ return nil, ErrorNotSupportOSErr
+}
+
+
+func ToPortMap(protocols []string) (map[string]map[int][]*Socket, error) {
+ return nil, ErrorNotSupportOSErr
+}
+
+func IsProcessListenPort(pname string, port int) (is bool, err error) {
+ return false, ErrorNotSupportOSErr
+}
+
+func Print(protocols []string) string {
+ return ""
+}
diff --git a/service/common/netTools/netstat/netstat_unix.go b/service/common/netTools/netstat/netstat_unix.go
new file mode 100644
index 00000000..ff07bc98
--- /dev/null
+++ b/service/common/netTools/netstat/netstat_unix.go
@@ -0,0 +1,408 @@
+// +build linux plan9 freebsd solaris
+
+package netstat
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+
+const (
+ pathNet = "/proc/net"
+ pathProc = "/proc"
+
+ ipv4StrLen = 8
+ ipv6StrLen = 32
+)
+
+func parseIPv4(s string) (net.IP, error) {
+ v, err := strconv.ParseUint(s, 16, 32)
+ if err != nil {
+ return nil, fmt.Errorf("parseIPv4: %w", err)
+ }
+ ip := make(net.IP, net.IPv4len)
+ binary.LittleEndian.PutUint32(ip, uint32(v))
+ return ip, nil
+}
+
+func parseIPv6(s string) (net.IP, error) {
+ ip := make(net.IP, net.IPv6len)
+ const grpLen = 4
+ i, j := 0, 4
+ for len(s) != 0 {
+ grp := s[0:8]
+ u, err := strconv.ParseUint(grp, 16, 32)
+ binary.LittleEndian.PutUint32(ip[i:j], uint32(u))
+ if err != nil {
+ return nil, fmt.Errorf("parseIPv6: %w", err)
+ }
+ i, j = i+grpLen, j+grpLen
+ s = s[8:]
+ }
+ return ip, nil
+}
+
+func parseAddr(s string) (*Address, error) {
+ fields := strings.Split(s, ":")
+ if len(fields) < 2 {
+ return nil, fmt.Errorf("netstat: not enough fields: %v", s)
+ }
+ var ip net.IP
+ var err error
+ switch len(fields[0]) {
+ case ipv4StrLen:
+ ip, err = parseIPv4(fields[0])
+ case ipv6StrLen:
+ ip, err = parseIPv6(fields[0])
+ default:
+ return nil, fmt.Errorf("parseAddr: Bad formatted string")
+ }
+ if err != nil {
+ return nil, fmt.Errorf("parseAddr: %w", err)
+ }
+ v, err := strconv.ParseUint(fields[1], 16, 16)
+ if err != nil {
+ return nil, fmt.Errorf("parseAddr: %w", err)
+ }
+ return &Address{IP: ip, Port: int(v)}, nil
+}
+
+var (
+ SocketFreedErr = fmt.Errorf("process not found, correspond socket was freed")
+ ProcOpenFailedErr = fmt.Errorf("cannot open the directory /proc")
+)
+
+func FillProcesses(sockets []*Socket) error {
+ f, err := os.ReadDir(pathProc)
+ if err != nil {
+ return ProcOpenFailedErr
+ }
+ mapInodeSocket := make(map[string]*Socket)
+ iNodes := make(map[string]struct{})
+ for i, s := range sockets {
+ s.processMutex.Lock()
+ defer s.processMutex.Unlock()
+ mapInodeSocket[s.inode] = sockets[i]
+ iNodes[s.inode] = struct{}{}
+ }
+loop1:
+ for _, fi := range f {
+ fn := fi.Name()
+ if !fi.IsDir() {
+ continue
+ }
+ for _, t := range fn {
+ if t > '9' || t < '0' {
+ continue loop1
+ }
+ }
+ for _, s := range sockets {
+ if s.Proc != nil {
+ continue
+ }
+ }
+ if inode := isProcessSocket(fn, iNodes); inode != "" {
+ pn, ppid := getProcessInfo(fn)
+ mapInodeSocket[inode].Proc = &Process{
+ PID: fn,
+ PPID: ppid,
+ Name: pn,
+ }
+ delete(iNodes, inode)
+ }
+ }
+ return nil
+}
+
+/*
+较为消耗资源
+*/
+func (s *Socket) Process() (*Process, error) {
+ s.processMutex.Lock()
+ s.processMutex.Unlock()
+ if s.Proc != nil {
+ return s.Proc, nil
+ }
+ f, err := os.ReadDir(pathProc)
+ if err != nil {
+ return nil, nil
+ }
+loop1:
+ for _, fi := range f {
+ fn := fi.Name()
+ if !fi.IsDir() {
+ continue
+ }
+ for _, t := range fn {
+ if t > '9' || t < '0' {
+ continue loop1
+ }
+ }
+ if isProcessSocket(fn, map[string]struct{}{s.inode: {}}) != "" {
+ pn, ppid := getProcessInfo(fn)
+ s.Proc = &Process{
+ PID: fn,
+ PPID: ppid,
+ Name: pn,
+ }
+ return s.Proc, nil
+ }
+ }
+ return nil, SocketFreedErr
+}
+
+/*
+没有做缓存,每次调用都会扫描,消耗资源
+*/
+
+var ErrorNotFound = fmt.Errorf("process not found")
+
+func findProcessID(pname string) (pids []string, err error) {
+ f, err := os.ReadDir(pathProc)
+ if err != nil {
+ err = fmt.Errorf("findProcessID: %w", err)
+ return
+ }
+loop1:
+ for _, fi := range f {
+ if !fi.IsDir() {
+ continue
+ }
+ fn := fi.Name()
+ for _, t := range fn {
+ if t > '9' || t < '0' {
+ continue loop1
+ }
+ }
+ if pn, _ := getProcessInfo(fn); pn == pname {
+ pids = append(pids, fn)
+ }
+ }
+ if len(pids) > 0 {
+ return pids, nil
+ }
+ return nil, ErrorNotFound
+}
+
+func getProcName(s string) string {
+ i := strings.Index(s, "(")
+ if i < 0 {
+ return ""
+ }
+ s = s[i+1:]
+ j := strings.LastIndex(s, ")")
+ if j < 0 {
+ return ""
+ }
+ return s[:j]
+}
+
+func getProcessInfo(pid string) (pn string, ppid string) {
+ p := filepath.Join(pathProc, pid, "stat")
+ b, err := os.ReadFile(p)
+ if err != nil {
+ err = fmt.Errorf("getProcessInfo: %w", err)
+ return
+ }
+ sp := bytes.Fields(b)
+ pn = string(sp[1])
+ return getProcName(pn), string(sp[3])
+}
+
+func isProcessSocket(pid string, socketInode map[string]struct{}) string {
+ // link name is of the form socket:[5860846]
+ p := filepath.Join(pathProc, pid, "fd")
+ f, err := os.Open(p)
+ fns, err := f.Readdirnames(-1)
+ f.Close()
+ if err != nil {
+ return ""
+ }
+ for _, fn := range fns {
+ lk, err := os.Readlink(filepath.Join(p, fn))
+ if err != nil {
+ continue
+ }
+ for inode := range socketInode {
+ target := "socket:[" + inode + "]"
+ if lk == target {
+ return inode
+ }
+ }
+ }
+ return ""
+}
+
+func getProcessSocketSet(pid string) (set []string) {
+ // link name is of the form socket:[5860846]
+ p := filepath.Join(pathProc, pid, "fd")
+ f, err := os.Open(p)
+ fns, err := f.Readdirnames(-1)
+ f.Close()
+ if err != nil {
+ err = fmt.Errorf("getProcessSocketSet: %w", err)
+ return
+ }
+ for _, fn := range fns {
+ lk, err := os.Readlink(filepath.Join(p, fn))
+ if err != nil {
+ continue
+ }
+ if strings.HasPrefix(lk, "socket:[") {
+ set = append(set, lk[8:len(lk)-1])
+ }
+ }
+ return
+}
+
+func parseSocktab(r io.Reader) (map[int][]*Socket, error) {
+ br := bufio.NewScanner(r)
+ tab := make(map[int][]*Socket)
+
+ // Discard title
+ br.Scan()
+
+ for br.Scan() {
+ var s Socket
+ line := br.Text()
+ // Skip comments
+ if i := strings.Index(line, "#"); i >= 0 {
+ line = line[:i]
+ }
+ fields := strings.Fields(line)
+ if len(fields) < 12 {
+ return tab, fmt.Errorf("netstat: not enough fields: %v, %v", len(fields), fields)
+ }
+ addr, err := parseAddr(fields[1])
+ if err != nil {
+ return tab, err
+ }
+ s.LocalAddress = addr
+ addr, err = parseAddr(fields[2])
+ if err != nil {
+ return tab, err
+ }
+ s.RemoteAddress = addr
+ u, err := strconv.ParseUint(fields[3], 16, 8)
+ if err != nil {
+ err = fmt.Errorf("parseSocktab: %w", err)
+ return tab, err
+ }
+ s.State = SkState(u)
+ s.UID = fields[7]
+ s.inode = fields[9]
+ tab[s.LocalAddress.Port] = append(tab[s.LocalAddress.Port], &s)
+ }
+ if br.Err() != nil {
+ return nil, fmt.Errorf("parseSocktab: %w", br.Err())
+ }
+ return tab, nil
+}
+func ToPortMap(protocols []string) (map[string]map[int][]*Socket, error) {
+ m := make(map[string]map[int][]*Socket)
+ for _, proto := range protocols {
+ switch proto {
+ case "tcp", "tcp6", "udp", "udp6":
+ b, err := os.Open(filepath.Join(pathNet, proto))
+ if err != nil {
+ continue
+ }
+ m[proto], err = parseSocktab(b)
+ if err != nil {
+ return nil, err
+ }
+ default:
+ }
+ }
+
+ return m, nil
+}
+
+func IsProcessListenPort(pname string, port int) (is bool, err error) {
+ protocols := []string{"tcp", "tcp6"}
+ m, err := ToPortMap(protocols)
+ if err != nil {
+ return
+ }
+ iNodes := make(map[string]struct{})
+ for _, proto := range protocols {
+ for _, v := range m[proto][port] {
+ if v.State == Listen || v.State == Established {
+ iNodes[v.inode] = struct{}{}
+ }
+ }
+ }
+ if len(iNodes) == 0 {
+ return false, nil
+ }
+ pids, err := findProcessID(pname)
+ if err != nil {
+ if errors.Is(err, ErrorNotFound) {
+ return false, nil
+ }
+ return
+ }
+ for _, pid := range pids {
+ if isProcessSocket(pid, iNodes) != "" {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+func Print(protocols []string) string {
+ var buffer strings.Builder
+ protos := make([]string, 0, 4)
+ for _, proto := range protocols {
+ switch proto {
+ case "tcp", "tcp6", "udp", "udp6":
+ protos = append(protos, proto)
+ }
+ }
+ m, err := ToPortMap(protos)
+ if err != nil {
+ return ""
+ }
+ buffer.WriteString(fmt.Sprintf("%-6v%-25v%-25v%-15v%-6v%-9v%v\n", "Proto", "Local Address", "Foreign Address", "State", "User", "Inode", "PID/Program name"))
+ var sockets []*Socket
+ for _, proto := range protos {
+ for _, v := range m[proto] {
+ sockets = append(sockets, v...)
+ }
+ }
+ _ = FillProcesses(sockets)
+ for _, proto := range protos {
+ for _, sockets := range m[proto] {
+ for _, v := range sockets {
+ process, err := v.Process()
+ var pstr string
+ if err != nil {
+ pstr = ""
+ } else {
+ pstr = process.PID + "/" + process.Name
+ }
+ buffer.WriteString(fmt.Sprintf(
+ "%-6v%-25v%-25v%-15v%-6v%-9v%v\n",
+ proto,
+ v.LocalAddress.IP.String()+"/"+strconv.Itoa(v.LocalAddress.Port),
+ v.RemoteAddress.IP.String()+"/"+strconv.Itoa(v.RemoteAddress.Port),
+ v.State.String(),
+ v.UID,
+ v.inode,
+ pstr,
+ ))
+ }
+ }
+ }
+ return buffer.String()
+}
diff --git a/service/common/netTools/netstat/netstat_test.go b/service/common/netTools/netstat/netstat_unix_test.go
similarity index 100%
rename from service/common/netTools/netstat/netstat_test.go
rename to service/common/netTools/netstat/netstat_unix_test.go
diff --git a/service/common/resolv/resolv.go b/service/common/resolv/resolv.go
index 358d2ff4..98dc1021 100644
--- a/service/common/resolv/resolv.go
+++ b/service/common/resolv/resolv.go
@@ -1,6 +1,7 @@
package resolv
import (
+ "github.com/v2rayA/v2rayA/conf"
"os"
"strings"
)
@@ -16,6 +17,9 @@ func WriteResolvConf(servers []string) {
}
func CheckResolvConf() {
+ if conf.GetEnvironmentConfig().Lite {
+ return
+ }
if _, err := os.Stat(resolvConf); os.IsNotExist(err) {
WriteResolvConf([]string{"223.6.6.6"})
}
diff --git a/service/conf/environmentConfig.go b/service/conf/environmentConfig.go
index 2413163c..5627a6d6 100644
--- a/service/conf/environmentConfig.go
+++ b/service/conf/environmentConfig.go
@@ -13,7 +13,7 @@ import (
type Params struct {
Address string `id:"address" short:"a" default:"0.0.0.0:2017" desc:"Listening address"`
- Config string `id:"config" short:"c" default:"/etc/v2raya" desc:"v2rayA configuration directory"`
+ Config string `id:"config" short:"c" desc:"v2rayA configuration directory"`
V2rayBin string `id:"v2ray-bin" desc:"Executable v2ray binary path. Auto-detect if put it empty."`
V2rayConfigDirectory string `id:"v2ray-confdir" desc:"Additional v2ray config directory, files in it will be combined with config generated by v2rayA"`
WebDir string `id:"webdir" desc:"v2rayA web files directory. use embedded files if not specify."`
@@ -27,6 +27,7 @@ type Params struct {
LogFile string `id:"log-file" desc:"The path of log file"`
LogMaxDays int64 `id:"log-max-days" default:"3" desc:"Maximum number of days to keep log files"`
LogDisableColor bool `id:"log-disable-color"`
+ Lite bool `id:"lite" desc:"Lite mode for non-root and non-linux users"`
ShowVersion bool `id:"version"`
}
@@ -53,6 +54,16 @@ func initFunc() {
fmt.Println(Version)
os.Exit(0)
}
+ if params.Lite {
+ params.PassCheckRoot = true
+ }
+ if params.Config == "" {
+ if params.Lite {
+ params.Config = "$HOME/.config/v2raya"
+ } else {
+ params.Config = "/etc/v2raya"
+ }
+ }
// replace all dots of the filename with underlines
params.Config = filepath.Join(
filepath.Dir(params.Config),
diff --git a/service/core/specialMode/infra/dialer.go b/service/core/specialMode/infra/dialer.go
index 16282308..7b76ae92 100644
--- a/service/core/specialMode/infra/dialer.go
+++ b/service/core/specialMode/infra/dialer.go
@@ -1,65 +1,17 @@
package infra
import (
- "fmt"
- "github.com/v2rayA/v2rayA/pkg/util/log"
- "golang.org/x/sys/unix"
+ "github.com/v2rayA/v2rayA/pkg/plugin/infra"
"net"
"syscall"
"time"
)
-func bindAddr(fd uintptr, ip []byte, port uint32) error {
- if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
- return fmt.Errorf("failed to set resuse_addr")
- }
-
- if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
- return fmt.Errorf("failed to set resuse_port")
- }
-
- var sockaddr syscall.Sockaddr
-
- switch len(ip) {
- case net.IPv4len:
- a4 := &syscall.SockaddrInet4{
- Port: int(port),
- }
- copy(a4.Addr[:], ip)
- sockaddr = a4
- case net.IPv6len:
- a6 := &syscall.SockaddrInet6{
- Port: int(port),
- }
- copy(a6.Addr[:], ip)
- sockaddr = a6
- default:
- return fmt.Errorf("unexpected length of ip")
- }
-
- return syscall.Bind(int(fd), sockaddr)
-}
-
func newDialer(laddr string, lport uint32, timeout time.Duration) (dialer *net.Dialer) {
return &net.Dialer{
Timeout: timeout,
Control: func(network, address string, c syscall.RawConn) error {
- return c.Control(func(fd uintptr) {
- err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, 0xff)
- if err != nil {
- log.Warn("control: %s", err)
- return
- }
- if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
- log.Warn("control: failed to set IP_TRANSPARENT")
- return
- }
- ip := net.ParseIP(laddr).To4()
- if err := bindAddr(fd, ip, lport); err != nil {
- log.Warn("control: %s", err)
- return
- }
- })
+ return infra.BindControl(c, laddr, lport)
},
}
}
diff --git a/service/core/specialMode/specialMode.go b/service/core/specialMode/specialMode.go
index 60982266..c70d9aa3 100644
--- a/service/core/specialMode/specialMode.go
+++ b/service/core/specialMode/specialMode.go
@@ -4,6 +4,7 @@ import (
"fmt"
"github.com/v2rayA/v2rayA/common/netTools/netstat"
"github.com/v2rayA/v2rayA/common/netTools/ports"
+ "github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/db/configure"
"net"
"os"
@@ -28,6 +29,9 @@ func ShouldLocalDnsListen() bool {
if setting.TransparentType == configure.TransparentTproxy {
return false
}
+ if conf.GetEnvironmentConfig().Lite {
+ return false
+ }
return true
}
diff --git a/service/core/specialMode/supervisor.go b/service/core/specialMode/supervisor_linux.go
similarity index 91%
rename from service/core/specialMode/supervisor.go
rename to service/core/specialMode/supervisor_linux.go
index be06bebd..ad07988b 100644
--- a/service/core/specialMode/supervisor.go
+++ b/service/core/specialMode/supervisor_linux.go
@@ -3,10 +3,11 @@ package specialMode
import (
"fmt"
"github.com/v2fly/v2ray-core/v4/app/router"
- "github.com/v2rayA/v2rayA/common/netTools"
+ "github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/specialMode/infra"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/pkg/util/log"
+ "net"
"sync"
"time"
)
@@ -29,10 +30,14 @@ type ExtraInfo struct {
}
func CouldUseSupervisor() bool {
+ // TODO
return true
}
func ShouldUseSupervisor() bool {
+ if conf.GetEnvironmentConfig().Lite {
+ return false
+ }
return configure.GetSettingNotNil().SpecialMode == configure.SpecialModeSupervisor
}
@@ -75,12 +80,16 @@ func StartDNSSupervisor(externWhiteDnsServers []*router.CIDR, externWhiteDomains
defer func() { <-limit }()
out:
for {
- //随时准备应对default interface变化
+ //随时准备应对interface变化
f := func() {
- ifnames, err := netTools.GetDefaultInterfaceName()
+ ifces, err := net.Interfaces()
if err != nil {
return
}
+ var ifnames = make([]string, 0, len(ifces))
+ for _, ifce := range ifces {
+ ifnames = append(ifnames, ifce.Name)
+ }
mIfnames := make(map[string]interface{})
mHandles := make(map[string]interface{})
needToAdd := false
diff --git a/service/core/specialMode/supervisor_other.go b/service/core/specialMode/supervisor_other.go
new file mode 100644
index 00000000..2185b3d2
--- /dev/null
+++ b/service/core/specialMode/supervisor_other.go
@@ -0,0 +1,27 @@
+//go:build !linux
+// +build !linux
+
+package specialMode
+
+type ExtraInfo struct {
+ DohIps []string
+ DohDomains []string
+ ServerIps []string
+ ServerDomain string
+}
+
+func CouldUseSupervisor() bool {
+ // TODO
+ return true
+}
+
+func ShouldUseSupervisor() bool {
+ return false
+}
+
+func CheckAndSetupDNSSupervisor() {
+ return
+}
+func StopDNSSupervisor() {
+ return
+}
diff --git a/service/core/v2ray/api.go b/service/core/v2ray/api.go
index ede3be66..036323b1 100644
--- a/service/core/v2ray/api.go
+++ b/service/core/v2ray/api.go
@@ -44,7 +44,6 @@ func init() {
for _, product := range ApiProducts {
ApiFeed.RegisterProduct(product)
}
- go observatoryProducer()
}
func getObservatoryResponse(conn *grpc.ClientConn) (r *pb.GetOutboundStatusResponse, err error) {
@@ -59,50 +58,61 @@ func getObservatoryResponse(conn *grpc.ClientConn) (r *pb.GetOutboundStatusRespo
return r, nil
}
-func observatoryProducer() {
- const product = "observatory"
- var conn *grpc.ClientConn
-nextLoop:
- for {
- if ApiPort() == 0 {
- time.Sleep(ApiFeedInterval)
- continue
- }
- // Set up a connection to the server.
- if conn == nil {
- c, err := grpc.Dial(net.JoinHostPort("127.0.0.1", strconv.Itoa(ApiPort())), grpc.WithInsecure(), grpc.WithBlock())
- if err != nil {
- log.Warn("observatoryProducer: did not connect: %v", err)
+func ObservatoryProducer() (closeFunc func()) {
+ closed := make(chan struct{})
+ go func() {
+ const product = "observatory"
+ var conn *grpc.ClientConn
+ nextLoop:
+ for {
+ select {
+ case <-closed:
+ return
+ default:
}
- defer c.Close()
- conn = c
- }
- r, err := getObservatoryResponse(conn)
- if err != nil {
- if status.Code(err) == codes.Unavailable {
- // the connection is reliable, and reconnect
- conn = nil
+ if ApiPort() == 0 {
+ time.Sleep(ApiFeedInterval)
continue
}
- log.Warn("observatoryProducer: %v", err)
- } else {
- outboundStatus := r.GetStatus().GetStatus()
- os := make([]OutboundStatus, len(outboundStatus))
- css := configure.GetConnectedServers()
- for i := range outboundStatus {
- _ = mapper.AutoMapper(outboundStatus[i], &os[i])
- index := tag2WhichIndex[os[i].OutboundTag]
- if index >= css.Len() {
- continue nextLoop
- }
- os[i].Which = css.Get()[index]
- var w []configure.Which
- for _, v := range css.Get() {
- w = append(w, *v)
+ // Set up a connection to the server.
+ if conn == nil {
+ c, err := grpc.Dial(net.JoinHostPort("127.0.0.1", strconv.Itoa(ApiPort())), grpc.WithInsecure(), grpc.WithBlock())
+ if err != nil {
+ log.Warn("ObservatoryProducer: did not connect: %v", err)
}
+ defer c.Close()
+ conn = c
}
- ApiFeed.ProductMessage(product, os)
+ r, err := getObservatoryResponse(conn)
+ if err != nil {
+ if status.Code(err) == codes.Unavailable {
+ // the connection is reliable, and reconnect
+ conn = nil
+ continue
+ }
+ log.Warn("ObservatoryProducer: %v", err)
+ } else {
+ outboundStatus := r.GetStatus().GetStatus()
+ os := make([]OutboundStatus, len(outboundStatus))
+ css := configure.GetConnectedServers()
+ for i := range outboundStatus {
+ _ = mapper.AutoMapper(outboundStatus[i], &os[i])
+ index := tag2WhichIndex[os[i].OutboundTag]
+ if index >= css.Len() {
+ continue nextLoop
+ }
+ os[i].Which = css.Get()[index]
+ var w []configure.Which
+ for _, v := range css.Get() {
+ w = append(w, *v)
+ }
+ }
+ ApiFeed.ProductMessage(product, os)
+ }
+ time.Sleep(ApiFeedInterval)
}
- time.Sleep(ApiFeedInterval)
+ }()
+ return func() {
+ close(closed)
}
}
diff --git a/service/core/v2ray/status.go b/service/core/v2ray/status.go
index 33e81720..7de99956 100644
--- a/service/core/v2ray/status.go
+++ b/service/core/v2ray/status.go
@@ -4,11 +4,8 @@ import (
"errors"
"fmt"
"github.com/json-iterator/go"
- "github.com/v2rayA/v2rayA/common/netTools/netstat"
- "github.com/v2rayA/v2rayA/common/netTools/ports"
"github.com/v2rayA/v2rayA/common/ntp"
"github.com/v2rayA/v2rayA/common/resolv"
- "github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/specialMode"
"github.com/v2rayA/v2rayA/core/v2ray/asset"
"github.com/v2rayA/v2rayA/core/v2ray/where"
@@ -16,8 +13,10 @@ import (
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
+ "net"
"os"
"path"
+ "strconv"
"strings"
"time"
)
@@ -25,6 +24,7 @@ import (
var v2RayPID *os.Process
var tag2WhichIndex map[string]int
var apiPort int
+var apiCloseFuncs []func()
func SetCoreProcess(p *os.Process) {
configure.SetRunning(p != nil)
@@ -75,8 +75,9 @@ func RestartV2rayService(saveStatus bool) (process *os.Process, err error) {
"XRAY_LOCATION_ASSET="+assetDir,
),
Files: []*os.File{
- os.Stderr,
+ nil,
os.Stdout,
+ os.Stderr,
},
})
if err != nil {
@@ -101,32 +102,18 @@ func RestartV2rayService(saveStatus bool) (process *os.Process, err error) {
if err != nil {
return
}
- bPortOpen := false
- var port int
- for _, v := range tmplJson.Inbounds {
- if v.Port != 0 {
- if v.Settings != nil && v.Settings.Network != "" && !strings.Contains(v.Settings.Network, "tcp") {
- continue
- }
- bPortOpen = true
- port = v.Port
- break
- }
- }
+
startTime := time.Now()
for {
- if bPortOpen {
- var is bool
- is, err = netstat.IsProcessListenPort(path.Base(v2rayBinPath), port)
- if err != nil {
- return process, err
- }
- if is {
+ if ApiPort() != 0 {
+ conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(ApiPort())))
+ if err == nil {
+ conn.Close()
break
}
} else {
if IsV2RayRunning() {
- time.Sleep(1000 * time.Millisecond) //距离v2ray进程启动到端口绑定可能需要一些时间
+ time.Sleep(1000 * time.Millisecond)
break
}
}
@@ -140,26 +127,23 @@ func RestartV2rayService(saveStatus bool) (process *os.Process, err error) {
}
func findAvailablePluginPorts(vms []vmessInfo.VmessInfo) (pluginPortMap map[int]int, err error) {
- nsmap, err := netstat.ToPortMap([]string{"tcp", "tcp6"})
- if err != nil {
- return nil, err
- }
pluginPortMap = make(map[int]int)
- checkingPort := conf.GetEnvironmentConfig().PluginListenPort - 1
for i, v := range vms {
if !plugin.HasProperPlugin(v) {
continue
}
//find a port that not be occupied
- checkingPort++
+ var port int
for {
- if !ports.IsOccupiedTCPPort(nsmap, checkingPort) {
- // this port is available
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err == nil {
+ defer l.Close()
+ port = l.Addr().(*net.TCPAddr).Port
break
}
- checkingPort++
+ time.Sleep(100 * time.Millisecond)
}
- pluginPortMap[i] = checkingPort
+ pluginPortMap[i] = port
}
return pluginPortMap, nil
}
diff --git a/service/core/v2ray/v2rayTmpl.go b/service/core/v2ray/v2rayTmpl.go
index b29027dd..2b1eabdb 100644
--- a/service/core/v2ray/v2rayTmpl.go
+++ b/service/core/v2ray/v2rayTmpl.go
@@ -4,6 +4,7 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
+ "errors"
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/v2rayA/routingA"
@@ -1752,14 +1753,21 @@ func (t *Template) ResolveOutbounds(
}
func (t *Template) SetAPI() (port int) {
- if t.Observatory == nil {
- return 0
+ // TODO: refine code
+ for _, closeFunc := range apiCloseFuncs {
+ closeFunc()
+ }
+ apiCloseFuncs = []func(){}
+ services := []string{
+ "LoggerService",
+ }
+ if t.Observatory != nil {
+ services = append(services, "ObservatoryService")
+ apiCloseFuncs = append(apiCloseFuncs, ObservatoryProducer())
}
t.API = &APIObject{
- Tag: "api-out",
- Services: []string{
- "ObservatoryService",
- },
+ Tag: "api-out",
+ Services: services,
}
// find a valid port
for {
@@ -1768,7 +1776,7 @@ func (t *Template) SetAPI() (port int) {
_ = l.Close()
break
}
- time.Sleep(300 * time.Millisecond)
+ time.Sleep(100 * time.Millisecond)
}
t.Inbounds = append(t.Inbounds, Inbound{
@@ -1936,10 +1944,18 @@ var OccupiedErr = fmt.Errorf("port is occupied")
func PortOccupied(syntax []string) (err error) {
occupied, sockets, err := ports.IsPortOccupied(syntax)
if err != nil {
+ if errors.Is(err, netstat.ErrorNotSupportOSErr) {
+ log.Trace("PortOccupied: %v", err)
+ return nil
+ }
return
}
if occupied {
if err = netstat.FillProcesses(sockets); err != nil {
+ if errors.Is(err, netstat.ErrorNotSupportOSErr) {
+ log.Warn("cannot judge port occupation: %v", err)
+ return nil
+ }
return fmt.Errorf("failed to check if port is occupied: %w", err)
}
for _, s := range sockets {
diff --git a/service/core/v2ray/where/where.go b/service/core/v2ray/where/where.go
index 22d9b0a9..54e04bfd 100644
--- a/service/core/v2ray/where/where.go
+++ b/service/core/v2ray/where/where.go
@@ -3,7 +3,9 @@ package where
import (
"fmt"
"github.com/v2rayA/v2rayA/conf"
+ "os"
"os/exec"
+ "path"
"strings"
"sync"
"time"
@@ -29,7 +31,7 @@ func GetV2rayServiceVersion() (ver string, err error) {
if err != nil || len(v2rayPath) <= 0 {
return "", fmt.Errorf("cannot find v2ray executable binary")
}
- out, err := exec.Command("sh", "-c", fmt.Sprintf("%v -version", v2rayPath)).Output()
+ out, err := exec.Command(v2rayPath, "-version").Output()
var fields []string
if fields = strings.Fields(strings.TrimSpace(string(out))); len(fields) < 2 {
return "", fmt.Errorf("cannot parse version of v2ray")
@@ -64,8 +66,17 @@ func getV2rayBinPath(target string) (string, error) {
var pa string
//从环境变量里找
pa, err := exec.LookPath(target)
+ if err == nil {
+ return pa, nil
+ }
+ //从 pwd 里找
+ pwd, err := os.Getwd()
if err != nil {
return "", NotFoundErr
}
- return pa, nil
+ pa = path.Join(pwd, target)
+ if _, err := os.Stat(pa); err == nil {
+ return pa, nil
+ }
+ return "", NotFoundErr
}
diff --git a/service/main.go b/service/main.go
index d31ca823..f73ad9a7 100644
--- a/service/main.go
+++ b/service/main.go
@@ -8,12 +8,15 @@ import (
_ "github.com/v2rayA/v2rayA/pkg/plugin/ssrpluginSimpleobfs"
_ "github.com/v2rayA/v2rayA/pkg/plugin/trojan-go"
"github.com/v2rayA/v2rayA/pkg/util/log"
+ "runtime"
)
func main() {
gin.SetMode(gin.ReleaseMode)
checkEnvironment()
- checkTProxySupportability()
+ if runtime.GOOS == "linux" {
+ checkTProxySupportability()
+ }
initConfigure()
checkUpdate()
hello()
diff --git a/service/pkg/plugin/infra/direct.go b/service/pkg/plugin/infra/direct.go
index b1c1aa25..8a94f10e 100644
--- a/service/pkg/plugin/infra/direct.go
+++ b/service/pkg/plugin/infra/direct.go
@@ -79,16 +79,7 @@ func dial(network, addr string, localIP net.IP) (net.Conn, error) {
dialer := &net.Dialer{
LocalAddr: la,
Control: func(network, address string, c syscall.RawConn) error {
- return c.Control(func(fd uintptr) {
- //TODO: force to set 0xff. any chances to customize this value?
- err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, 0xff)
- if err != nil {
- //if conf.IsDebug() {
- // log.Printf("control: %s", err)
- //}
- return
- }
- })
+ return SoMarkControl(c)
},
}
c, err := dialer.Dial(network, addr)
diff --git a/service/pkg/plugin/infra/setsockopt_linux.go b/service/pkg/plugin/infra/setsockopt_linux.go
new file mode 100644
index 00000000..32afbf4f
--- /dev/null
+++ b/service/pkg/plugin/infra/setsockopt_linux.go
@@ -0,0 +1,69 @@
+package infra
+
+import (
+ "fmt"
+ "github.com/v2rayA/v2rayA/pkg/util/log"
+ "golang.org/x/sys/unix"
+ "net"
+ "syscall"
+)
+
+func SoMarkControl(c syscall.RawConn) error {
+ return c.Control(func(fd uintptr) {
+ //TODO: force to set 0xff. any chances to customize this value?
+ err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, 0xff)
+ if err != nil {
+ return
+ }
+ })
+}
+func BindControl(c syscall.RawConn, laddr string, lport uint32) error {
+ return c.Control(func(fd uintptr) {
+ err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, 0xff)
+ if err != nil {
+ log.Warn("control: %s", err)
+ return
+ }
+ if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
+ log.Warn("control: failed to set IP_TRANSPARENT")
+ return
+ }
+ ip := net.ParseIP(laddr).To4()
+ if err := bindAddr(fd, ip, lport); err != nil {
+ log.Warn("control: %s", err)
+ return
+ }
+ })
+}
+
+
+func bindAddr(fd uintptr, ip []byte, port uint32) error {
+ if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
+ return fmt.Errorf("failed to set resuse_addr")
+ }
+
+ if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
+ return fmt.Errorf("failed to set resuse_port")
+ }
+
+ var sockaddr syscall.Sockaddr
+
+ switch len(ip) {
+ case net.IPv4len:
+ a4 := &syscall.SockaddrInet4{
+ Port: int(port),
+ }
+ copy(a4.Addr[:], ip)
+ sockaddr = a4
+ case net.IPv6len:
+ a6 := &syscall.SockaddrInet6{
+ Port: int(port),
+ }
+ copy(a6.Addr[:], ip)
+ sockaddr = a6
+ default:
+ return fmt.Errorf("unexpected length of ip")
+ }
+
+ return syscall.Bind(int(fd), sockaddr)
+}
\ No newline at end of file
diff --git a/service/pkg/plugin/infra/setsockopt_other.go b/service/pkg/plugin/infra/setsockopt_other.go
new file mode 100644
index 00000000..a8efa7d6
--- /dev/null
+++ b/service/pkg/plugin/infra/setsockopt_other.go
@@ -0,0 +1,13 @@
+//go:build !linux
+// +build !linux
+
+package infra
+
+import "syscall"
+
+func SoMarkControl(c syscall.RawConn) error {
+ return nil
+}
+func BindControl(c syscall.RawConn, laddr string, lport uint32) error {
+ return nil
+}
\ No newline at end of file
diff --git a/service/pkg/plugin/pingtunnel/pingtunnel.go b/service/pkg/plugin/pingtunnel/pingtunnel.go
index c43fea89..c7dde724 100644
--- a/service/pkg/plugin/pingtunnel/pingtunnel.go
+++ b/service/pkg/plugin/pingtunnel/pingtunnel.go
@@ -4,9 +4,11 @@
package pingtunnel
import (
+ "errors"
"fmt"
"github.com/mzz2017/go-engine/src/loggo"
"github.com/mzz2017/go-engine/src/pingtunnel"
+ "github.com/v2rayA/v2rayA/common/netTools/netstat"
"github.com/v2rayA/v2rayA/common/netTools/ports"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/vmessInfo"
@@ -80,7 +82,7 @@ func (tunnel *PingTunnel) Close() (err error) {
for {
var o bool
o, _, err := ports.IsPortOccupied([]string{port + ":tcp"})
- if err != nil {
+ if err != nil && !errors.Is(err, netstat.ErrorNotSupportOSErr) {
return err
}
if !o {
diff --git a/service/pkg/plugin/server.go b/service/pkg/plugin/server.go
index b2109cf3..69deef3e 100644
--- a/service/pkg/plugin/server.go
+++ b/service/pkg/plugin/server.go
@@ -1,7 +1,9 @@
package plugin
import (
+ "errors"
"fmt"
+ "github.com/v2rayA/v2rayA/common/netTools/netstat"
"github.com/v2rayA/v2rayA/common/netTools/ports"
"github.com/v2rayA/v2rayA/pkg/plugin/infra"
"github.com/v2rayA/v2rayA/pkg/plugin/infra/socks5"
@@ -87,7 +89,7 @@ out:
}
var o bool
o, _, err := ports.IsPortOccupied([]string{port + ":tcp"})
- if err != nil {
+ if err != nil && !errors.Is(err, netstat.ErrorNotSupportOSErr) {
return err
}
if !o {
diff --git a/service/pkg/util/gopeed/down_test.go b/service/pkg/util/gopeed/down_test.go
index e7ffa9b8..68886013 100644
--- a/service/pkg/util/gopeed/down_test.go
+++ b/service/pkg/util/gopeed/down_test.go
@@ -4,7 +4,7 @@ import (
"crypto/md5"
"encoding/hex"
"fmt"
- "github.com/v2rayA/v2rayA/pkg/util/log"
+ "log"
"io"
"os"
"reflect"
diff --git a/service/pre.go b/service/pre.go
index e5655786..837ebc8c 100644
--- a/service/pre.go
+++ b/service/pre.go
@@ -33,14 +33,11 @@ import (
)
func checkEnvironment() {
- if runtime.GOOS == "windows" {
- fmt.Println("v2rayA cannot run on windows")
- fmt.Println("Press any key to continue...")
- _, _ = fmt.Scanf("\n")
- os.Exit(1)
+ if runtime.GOOS != "linux" {
+ fmt.Println("v2rayA has not been fully tested on non-linux platform")
}
- conf := conf.GetEnvironmentConfig()
- if !conf.PassCheckRoot || conf.ResetPassword {
+ config := conf.GetEnvironmentConfig()
+ if !config.PassCheckRoot || config.ResetPassword {
if os.Getegid() != 0 {
log.Fatal("Please execute this program with sudo or as a root user for the best experience.\n" +
"If you don't want to run as root, use the --passcheckroot parameter to skip the check.\n" +
@@ -48,7 +45,7 @@ func checkEnvironment() {
"$ v2raya --passcheckroot --config ~/.config/v2raya")
}
}
- if conf.ResetPassword {
+ if config.ResetPassword {
err := configure.ResetAccounts()
if err != nil {
log.Fatal("checkEnvironment: %v", err)
@@ -56,7 +53,7 @@ func checkEnvironment() {
fmt.Println("It will work after you restart v2rayA")
os.Exit(0)
}
- _, v2rayAListeningPort, err := net.SplitHostPort(conf.Address)
+ _, v2rayAListeningPort, err := net.SplitHostPort(config.Address)
if err != nil {
log.Fatal("checkEnvironment: %v", err)
}
@@ -74,6 +71,9 @@ func checkEnvironment() {
}
func checkTProxySupportability() {
+ if conf.GetEnvironmentConfig().Lite {
+ return
+ }
//检查tproxy是否可以启用
if err := v2ray.CheckAndProbeTProxy(); err != nil {
log.Info("Cannot load TPROXY module: %v", err)
@@ -195,6 +195,10 @@ func hello() {
color.Red.Println("V2Ray binary is", v2rayPath)
wd, _ := os.Getwd()
color.Red.Println("v2rayA working directory is", wd)
+ color.Red.Println("v2rayA configuration directory is", conf.GetEnvironmentConfig().Config)
+ color.Red.Println("OS:", runtime.GOOS)
+ color.Red.Println("Arch:", runtime.GOARCH)
+ color.Red.Println("Lite:", conf.GetEnvironmentConfig().Lite)
color.Red.Println("Version:", conf.Version)
color.Red.Println("Starting...")
}
diff --git a/service/server/controller/version.go b/service/server/controller/version.go
index 248cc335..f6b747d2 100644
--- a/service/server/controller/version.go
+++ b/service/server/controller/version.go
@@ -7,14 +7,13 @@ import (
"github.com/v2rayA/v2rayA/core/v2ray"
"github.com/v2rayA/v2rayA/core/v2ray/asset/gfwlist"
"github.com/v2rayA/v2rayA/core/v2ray/where"
- "github.com/v2rayA/v2rayA/db/configure"
"net/http"
)
func GetVersion(ctx *gin.Context) {
var dohValid string
var vlessValid int
- var iptablesMode string
+ var lite int
ver, err := where.GetV2rayServiceVersion()
if err == nil {
@@ -37,10 +36,8 @@ func GetVersion(ctx *gin.Context) {
} else {
dohValid = err.Error()
}
- setting := configure.GetSettingNotNil()
- switch setting.TransparentType {
- case configure.TransparentTproxy, configure.TransparentRedirect:
- iptablesMode = string(setting.TransparentType)
+ if conf.GetEnvironmentConfig().Lite{
+ lite = 1
}
common.ResponseSuccess(ctx, gin.H{
"version": conf.Version,
@@ -49,7 +46,7 @@ func GetVersion(ctx *gin.Context) {
"serviceValid": v2ray.IsV2rayServiceValid(),
"dohValid": dohValid,
"vlessValid": vlessValid,
- "iptablesMode": iptablesMode, //仅代表是否支持tproxy,真实iptables所使用的表还要看是否是增强模式
+ "lite": lite,
})
}
diff --git a/service/server/service/latency.go b/service/server/service/latency.go
index f7546cec..c1960949 100644
--- a/service/server/service/latency.go
+++ b/service/server/service/latency.go
@@ -3,8 +3,6 @@ package service
import (
"fmt"
"github.com/v2rayA/v2rayA/common/httpClient"
- "github.com/v2rayA/v2rayA/common/netTools/netstat"
- "github.com/v2rayA/v2rayA/common/netTools/ports"
"github.com/v2rayA/v2rayA/common/resolv"
"github.com/v2rayA/v2rayA/core/specialMode"
"github.com/v2rayA/v2rayA/core/v2ray"
@@ -125,37 +123,34 @@ func TestHttpLatency(which []*configure.Which, timeout time.Duration, maxParalle
}
inboundPortMap := make([]string, len(vms))
pluginPortMap := make(map[int]int)
- port := 0
- nsmap, err := netstat.ToPortMap([]string{"tcp", "tcp6"})
- if err != nil {
- return nil, err
- }
+ var toClose []net.Listener
for i, v := range vms {
if which[i].Latency != "" {
continue
}
//find a port for the inbound
- if port == 0 {
- port = 14321 //starting port
- } else {
- port = port + 1
- }
+ var port int
for {
- if !ports.IsOccupiedTCPPort(nsmap, port) {
+ l, err := net.Listen("tcp", "0.0.0.0:0")
+ if err == nil {
+ toClose = append(toClose, l)
+ port = l.Addr().(*net.TCPAddr).Port
break
}
- port++
+ time.Sleep(100*time.Millisecond)
}
v2rayInboundPort := strconv.Itoa(port)
pluginPort := 0
if plugin.HasProperPlugin(v) {
// find a port for the plugin
- port++
for {
- if !ports.IsOccupiedTCPPort(nsmap, port) {
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err == nil {
+ toClose = append(toClose, l)
+ port = l.Addr().(*net.TCPAddr).Port
break
}
- port++
+ time.Sleep(100*time.Millisecond)
}
pluginPort = port
pluginPortMap[i] = port
@@ -176,7 +171,7 @@ func TestHttpLatency(which []*configure.Which, timeout time.Duration, maxParalle
for i, localPort := range pluginPortMap {
v := vms[i]
var plu plugin.Plugin
- plu, err = plugin.NewPluginAndServe(localPort, v)
+ plu, err := plugin.NewPluginAndServe(localPort, v)
if err != nil {
return nil, err
}
@@ -186,7 +181,7 @@ func TestHttpLatency(which []*configure.Which, timeout time.Duration, maxParalle
tmpl.Routing.DomainStrategy = "AsIs"
addHosts(&tmpl, vms)
- err = v2ray.WriteV2rayConfig(tmpl.ToConfigBytes())
+ err := v2ray.WriteV2rayConfig(tmpl.ToConfigBytes())
if err != nil {
return nil, err
}