-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathclash.go
81 lines (63 loc) · 1.6 KB
/
clash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//go:build linux
// +build linux
package main
import (
"context"
"os"
"os/exec"
"os/signal"
"os/user"
"path/filepath"
"strconv"
"syscall"
"time"
"github.com/sirupsen/logrus"
)
func run() {
logrus.Info("[main] starting clash...")
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
defer cancel()
copyFiles()
if err := applySysctl(); err != nil {
logrus.Fatalf("Fix Sysctl Error: %s", err)
}
if err := applyRoute(); err != nil {
logrus.Fatalf("Fix IP Route Error: %s", err)
}
if err := applyIPTables(); err != nil {
logrus.Fatalf("Fix IPTables Error: %s", err)
}
u, err := user.Lookup(clashUser)
if err != nil {
logrus.Fatalf("failed to get tpclash user: %v", err)
}
uid, _ := strconv.Atoi(u.Uid)
gid, _ := strconv.Atoi(u.Gid)
cmds := []string{filepath.Join(clashHome, "xclash"), "-f", clashConfig, "-d", clashHome, "-ext-ui", filepath.Join(clashHome, clashUI)}
logrus.Debugf("[clash] running cmds: %v", cmds)
cmd := exec.Command(cmds[0], cmds[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Credential: &syscall.Credential{
Uid: uint32(uid),
Gid: uint32(gid),
},
AmbientCaps: []uintptr{CAP_NET_BIND_SERVICE, CAP_NET_ADMIN, CAP_NET_RAW},
}
if err = cmd.Start(); err != nil {
logrus.Error(err)
cancel()
}
<-time.After(3 * time.Second)
logrus.Info("[main] 🍄 提莫队长正在待命...")
<-ctx.Done()
cleanIPTables()
cleanRoute()
if cmd.Process != nil {
if err = cmd.Process.Kill(); err != nil {
logrus.Error(err)
}
}
logrus.Info("TPClash exit...")
}