forked from barlowhaydnb/tpclash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
189 lines (151 loc) · 4.64 KB
/
Copy pathmain.go
File metadata and controls
189 lines (151 loc) · 4.64 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"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 printVer bool
var build string
var commit string
var version string
var clash string
var rootCmd = &cobra.Command{
Use: "tpclash",
Short: "Transparent proxy tool for Clash",
Run: func(_ *cobra.Command, _ []string) {
if printVer {
return
}
var err error
logrus.Info("[main] starting tpclash...")
cmd := exec.Command(filepath.Join(conf.ClashHome, clashBiName), "-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{
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 local path or remote url")
rootCmd.PersistentFlags().StringVarP(&conf.ClashUI, "ui", "u", "yacd", "clash dashboard(official|yacd)")
rootCmd.PersistentFlags().BoolVar(&conf.Debug, "debug", false, "enable debug log")
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")
rootCmd.PersistentFlags().BoolVarP(&printVer, "version", "v", false, "version for tpclash")
}
func main() {
cobra.CheckErr(rootCmd.Execute())
}
func tpClashInit() {
if printVer {
showVersion()
return
}
// copy static files
ensureClashFiles()
ensureSysctl()
// download remote config
if strings.HasPrefix(conf.ClashConfig, "http://") ||
strings.HasPrefix(conf.ClashConfig, "https://") {
logrus.Info("[main] use remote config...")
resp, err := http.Get(conf.ClashConfig)
if err != nil {
logrus.Fatalf("failed to download remote config: %v", err)
}
conf.ClashConfig = filepath.Join(conf.ClashHome, clashRemoteConfig)
cf, err := os.OpenFile(conf.ClashConfig, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil {
logrus.Fatalf("failed to create local config file: %v", err)
}
defer func() { _ = cf.Close() }()
_, err = io.Copy(cf, resp.Body)
if err != nil {
logrus.Fatalf("failed to save remote config: %v", err)
}
}
// 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
}
}
func showVersion() {
fmt.Printf("%s\nVersion: %s\nBuild: %s\nClash Core: %s\nCommit: %s\n", logo, version, build, clash, commit)
}