This repository has been archived by the owner on Feb 13, 2024. It is now read-only.
forked from barlowhaydnb/tpclash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
152 lines (122 loc) · 3.79 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package main
import (
"context"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/irai/packet/fastlog"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
_ "github.com/mritd/logrus"
)
var (
conf TPClashConf
clashConf *ClashConf
proxyMode ProxyMode
arpHijacker *ARPHijacker
)
var commit string
var rootCmd = &cobra.Command{
Use: "tpclash",
Short: "Transparent proxy tool for Clash",
Version: commit,
Run: func(_ *cobra.Command, _ []string) {
var err error
logrus.Info("[main] starting tpclash...")
uid, gid := getUserIDs(conf.ClashUser)
cmd := exec.Command(filepath.Join(conf.ClashHome, "xclash"), "-f", conf.ClashConfig, "-d", conf.ClashHome, "-ext-ui", filepath.Join(conf.ClashHome, conf.ClashUI))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Credential: &syscall.Credential{
Uid: uid,
Gid: gid,
},
AmbientCaps: []uintptr{CAP_NET_BIND_SERVICE, CAP_NET_ADMIN, CAP_NET_RAW},
}
logrus.Debugf("[clash] running cmds: %v", cmd.Args)
parent, pCancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer pCancel()
if !conf.AutoExit {
parent = context.Background()
}
ctx, cancel := signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
defer cancel()
if err = cmd.Start(); err != nil {
logrus.Error(err)
cancel()
}
if cmd.Process == nil {
logrus.Errorf("failed to start clash process: %v", cmd.Args)
cancel()
}
if err = proxyMode.EnableProxy(); err != nil {
logrus.Fatalf("failed to enable proxy: %v", err)
}
if conf.HijackIP != nil {
if err = arpHijacker.hijack(ctx); err != nil {
logrus.Fatalf("failed to start arp hijack: %v", err)
}
}
<-time.After(3 * time.Second)
logrus.Info("[main] 🍄 提莫队长正在待命...")
<-ctx.Done()
logrus.Info("[main] 🛑 TPClash 正在停止...")
if err = proxyMode.DisableProxy(); err != nil {
logrus.Error(err)
}
if cmd.Process != nil {
if err = cmd.Process.Kill(); err != nil {
logrus.Error(err)
}
}
logrus.Info("[main] 🛑 TPClash 已关闭!")
},
}
func init() {
cobra.EnableCommandSorting = false
cobra.OnInitialize(tpClashInit)
rootCmd.PersistentFlags().StringVarP(&conf.ClashHome, "home", "d", "/data/clash", "clash home dir")
rootCmd.PersistentFlags().StringVarP(&conf.ClashConfig, "config", "c", "/etc/clash.yaml", "clash config path")
rootCmd.PersistentFlags().StringVarP(&conf.ClashUI, "ui", "u", "yacd", "clash dashboard(official|yacd)")
rootCmd.PersistentFlags().BoolVar(&conf.Debug, "debug", false, "enable debug log")
rootCmd.PersistentFlags().StringVar(&conf.ClashUser, "clash-user", defaultClashUser, "clash runtime user")
rootCmd.PersistentFlags().IPSliceVar(&conf.HijackIP, "hijack-ip", nil, "hijack target IP traffic")
rootCmd.PersistentFlags().BoolVar(&conf.DisableExtract, "disable-extract", false, "disable extract files")
rootCmd.PersistentFlags().BoolVar(&conf.AutoExit, "test", false, "run in test mode, exit automatically after 5 minutes")
}
func main() {
cobra.CheckErr(rootCmd.Execute())
}
func tpClashInit() {
// load clash config
viper.SetConfigFile(conf.ClashConfig)
viper.SetEnvPrefix("TPCLASH")
viper.AutomaticEnv()
logrus.Info("[main] loading config...")
err := viper.ReadInConfig()
if err != nil {
logrus.Fatalf("failed to load clash config: %v", err)
}
if clashConf, err = ParseClashConf(); err != nil {
logrus.Fatal(err)
}
if proxyMode, err = NewProxyMode(clashConf, &conf); err != nil {
logrus.Fatal(err)
}
arpHijacker = NewARPHijacker(clashConf, &conf)
if clashConf.Debug || conf.Debug {
logrus.SetLevel(logrus.DebugLevel)
} else {
fastlog.DefaultIOWriter = io.Discard
}
// copy static files
ensureUser()
ensureClashFiles()
ensureSysctl()
}