/
LaunchAgentUtils.swift
394 lines (346 loc) · 13.7 KB
/
LaunchAgentUtils.swift
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//
// BGUtils.swift
// ShadowsocksX-NG
//
// Created by 邱宇舟 on 16/6/6.
// Copyright © 2016年 qiuyuzhou. All rights reserved.
//
import Foundation
let SS_LOCAL_VERSION = "3.1.3"
let KCPTUN_CLIENT_VERSION = "v20170718"
let V2RAY_PLUGIN_VERSION = "master"
let PRIVOXY_VERSION = "3.0.26.static"
let SIMPLE_OBFS_VERSION = "0.0.5_1"
let APP_SUPPORT_DIR = "/Library/Application Support/ShadowsocksX-NG/"
let LAUNCH_AGENT_DIR = "/Library/LaunchAgents/"
let LAUNCH_AGENT_CONF_SSLOCAL_NAME = "com.qiuyuzhou.shadowsocksX-NG.local.plist"
let LAUNCH_AGENT_CONF_PRIVOXY_NAME = "com.qiuyuzhou.shadowsocksX-NG.http.plist"
let LAUNCH_AGENT_CONF_KCPTUN_NAME = "com.qiuyuzhou.shadowsocksX-NG.kcptun.plist"
func getFileSHA1Sum(_ filepath: String) -> String {
if let data = try? Data(contentsOf: URL(fileURLWithPath: filepath)) {
return data.sha1()
}
return ""
}
// Ref: https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
// Genarate the mac launch agent service plist
// MARK: sslocal
func generateSSLocalLauchAgentPlist() -> Bool {
let sslocalPath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-latest/ss-local"
let logFilePath = NSHomeDirectory() + "/Library/Logs/ss-local.log"
let launchAgentDirPath = NSHomeDirectory() + LAUNCH_AGENT_DIR
let plistFilepath = launchAgentDirPath + LAUNCH_AGENT_CONF_SSLOCAL_NAME
// Ensure launch agent directory is existed.
let fileMgr = FileManager.default
if !fileMgr.fileExists(atPath: launchAgentDirPath) {
try! fileMgr.createDirectory(atPath: launchAgentDirPath, withIntermediateDirectories: true, attributes: nil)
}
let oldSha1Sum = getFileSHA1Sum(plistFilepath)
let defaults = UserDefaults.standard
let enableUdpRelay = defaults.bool(forKey: "LocalSocks5.EnableUDPRelay")
let enableVerboseMode = defaults.bool(forKey: "LocalSocks5.EnableVerboseMode")
var arguments = [sslocalPath, "-c", "ss-local-config.json", "--fast-open"]
if enableUdpRelay {
arguments.append("-u")
}
if enableVerboseMode {
arguments.append("-v")
}
arguments.append("--reuse-port")
// For a complete listing of the keys, see the launchd.plist manual page.
let dyld_library_paths = [
NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-latest/",
NSHomeDirectory() + APP_SUPPORT_DIR + "plugins/",
]
let dict: NSMutableDictionary = [
"Label": "com.qiuyuzhou.shadowsocksX-NG.local",
"WorkingDirectory": NSHomeDirectory() + APP_SUPPORT_DIR,
"StandardOutPath": logFilePath,
"StandardErrorPath": logFilePath,
"ProgramArguments": arguments,
"EnvironmentVariables": ["DYLD_LIBRARY_PATH": dyld_library_paths.joined(separator: ":")]
]
dict.write(toFile: plistFilepath, atomically: true)
let Sha1Sum = getFileSHA1Sum(plistFilepath)
if oldSha1Sum != Sha1Sum {
NSLog("generateSSLocalLauchAgentPlist - File has been changed.")
return true
} else {
NSLog("generateSSLocalLauchAgentPlist - File has not been changed.")
return false
}
}
func StartSSLocal() {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "start_ss_local.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Start ss-local succeeded.")
} else {
NSLog("Start ss-local failed.")
}
}
func StopSSLocal() {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "stop_ss_local.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Stop ss-local succeeded.")
} else {
NSLog("Stop ss-local failed.")
}
}
func InstallSSLocal() {
let fileMgr = FileManager.default
let homeDir = NSHomeDirectory()
let appSupportDir = homeDir+APP_SUPPORT_DIR
if !fileMgr.fileExists(atPath: appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/ss-local")
|| !fileMgr.fileExists(atPath: appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/libmbedcrypto.0.dylib") {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "install_ss_local.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Install ss-local succeeded.")
} else {
NSLog("Install ss-local failed.")
}
}
}
func writeSSLocalConfFile(_ conf:[String:AnyObject]) -> Bool {
do {
let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json"
let data: Data = try JSONSerialization.data(withJSONObject: conf, options: .prettyPrinted)
let oldSum = getFileSHA1Sum(filepath)
try data.write(to: URL(fileURLWithPath: filepath), options: .atomic)
let newSum = data.sha1()
if oldSum == newSum {
NSLog("writeSSLocalConfFile - File has not been changed.")
return false
}
NSLog("writeSSLocalConfFile - File has been changed.")
return true
} catch {
NSLog("Write ss-local file failed.")
}
return false
}
func removeSSLocalConfFile() {
do {
let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json"
try FileManager.default.removeItem(atPath: filepath)
} catch {
}
}
func SyncSSLocal() {
var changed: Bool = false
changed = changed || generateSSLocalLauchAgentPlist()
let mgr = ServerProfileManager.instance
if mgr.activeProfileId != nil {
if let profile = mgr.getActiveProfile() {
changed = changed || writeSSLocalConfFile((profile.toJsonConfig()))
}
let on = UserDefaults.standard.bool(forKey: "ShadowsocksOn")
if on {
if changed {
StopSSLocal()
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + DispatchTimeInterval.seconds(1),
execute: {
() in
StartSSLocal()
})
} else {
StartSSLocal()
}
} else {
StopSSLocal()
}
} else {
removeSSLocalConfFile()
StopSSLocal()
}
SyncPac()
SyncPrivoxy()
}
// --------------------------------------------------------------------------------
// MARK: simple-obfs
func InstallSimpleObfs() {
let fileMgr = FileManager.default
let homeDir = NSHomeDirectory()
let appSupportDir = homeDir + APP_SUPPORT_DIR
if !fileMgr.fileExists(atPath: appSupportDir + "simple-obfs-\(SIMPLE_OBFS_VERSION)/obfs-local")
|| !fileMgr.fileExists(atPath: appSupportDir + "plugins/obfs-local") {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "install_simple_obfs.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: "/bin/sh", arguments: [installerPath!])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Install simple-obfs succeeded.")
} else {
NSLog("Install simple-obfs failed.")
}
}
}
// --------------------------------------------------------------------------------
// MARK: kcptun
func InstallKcptun() {
let fileMgr = FileManager.default
let homeDir = NSHomeDirectory()
let appSupportDir = homeDir+APP_SUPPORT_DIR
if !fileMgr.fileExists(atPath: appSupportDir + "kcptun_\(KCPTUN_CLIENT_VERSION)/kcptun_client") {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "install_kcptun", ofType: "sh")
let task = Process.launchedProcess(launchPath: "/bin/sh", arguments: [installerPath!])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Install kcptun succeeded.")
} else {
NSLog("Install kcptun failed.")
}
}
}
// --------------------------------------------------------------------------------
// MARK: v2ray-plugin
func InstallV2rayPlugin() {
let fileMgr = FileManager.default
let homeDir = NSHomeDirectory()
let appSupportDir = homeDir+APP_SUPPORT_DIR
if !fileMgr.fileExists(atPath: appSupportDir + "v2ray-plugin_\(V2RAY_PLUGIN_VERSION)/v2ray-plugin") {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "install_v2ray_plugin", ofType: "sh")
let task = Process.launchedProcess(launchPath: "/bin/sh", arguments: [installerPath!])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Install v2ray-plugin succeeded.")
} else {
NSLog("Install v2ray-plugin failed.")
}
}
}
// --------------------------------------------------------------------------------
// MARK: privoxy
func generatePrivoxyLauchAgentPlist() -> Bool {
let privoxyPath = NSHomeDirectory() + APP_SUPPORT_DIR + "privoxy"
let logFilePath = NSHomeDirectory() + "/Library/Logs/privoxy.log"
let launchAgentDirPath = NSHomeDirectory() + LAUNCH_AGENT_DIR
let plistFilepath = launchAgentDirPath + LAUNCH_AGENT_CONF_PRIVOXY_NAME
// Ensure launch agent directory is existed.
let fileMgr = FileManager.default
if !fileMgr.fileExists(atPath: launchAgentDirPath) {
try! fileMgr.createDirectory(atPath: launchAgentDirPath, withIntermediateDirectories: true, attributes: nil)
}
let oldSha1Sum = getFileSHA1Sum(plistFilepath)
let arguments = [privoxyPath, "--no-daemon", "privoxy.config"]
// For a complete listing of the keys, see the launchd.plist manual page.
let dict: NSMutableDictionary = [
"Label": "com.qiuyuzhou.shadowsocksX-NG.http",
"WorkingDirectory": NSHomeDirectory() + APP_SUPPORT_DIR,
"StandardOutPath": logFilePath,
"StandardErrorPath": logFilePath,
"ProgramArguments": arguments
]
dict.write(toFile: plistFilepath, atomically: true)
let Sha1Sum = getFileSHA1Sum(plistFilepath)
if oldSha1Sum != Sha1Sum {
return true
} else {
return false
}
}
func StartPrivoxy() {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "start_privoxy.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Start privoxy succeeded.")
} else {
NSLog("Start privoxy failed.")
}
}
func StopPrivoxy() {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "stop_privoxy.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Stop privoxy succeeded.")
} else {
NSLog("Stop privoxy failed.")
}
}
func InstallPrivoxy() {
let fileMgr = FileManager.default
let homeDir = NSHomeDirectory()
let appSupportDir = homeDir+APP_SUPPORT_DIR
if !fileMgr.fileExists(atPath: appSupportDir + "privoxy-\(PRIVOXY_VERSION)/privoxy") {
let bundle = Bundle.main
let installerPath = bundle.path(forResource: "install_privoxy.sh", ofType: nil)
let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""])
task.waitUntilExit()
if task.terminationStatus == 0 {
NSLog("Install privoxy succeeded.")
} else {
NSLog("Install privoxy failed.")
}
}
}
func writePrivoxyConfFile() -> Bool {
do {
let defaults = UserDefaults.standard
let bundle = Bundle.main
let examplePath = bundle.path(forResource: "privoxy.config.example", ofType: nil)
var example = try String(contentsOfFile: examplePath!, encoding: .utf8)
example = example.replacingOccurrences(of: "{http}", with: defaults.string(forKey: "LocalHTTP.ListenAddress")! + ":" + String(defaults.integer(forKey: "LocalHTTP.ListenPort")))
example = example.replacingOccurrences(of: "{socks5}", with: defaults.string(forKey: "LocalSocks5.ListenAddress")! + ":" + String(defaults.integer(forKey: "LocalSocks5.ListenPort")))
let data = example.data(using: .utf8)
let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "privoxy.config"
let oldSum = getFileSHA1Sum(filepath)
try data?.write(to: URL(fileURLWithPath: filepath), options: .atomic)
let newSum = getFileSHA1Sum(filepath)
if oldSum == newSum {
return false
}
return true
} catch {
NSLog("Write privoxy file failed.")
}
return false
}
func removePrivoxyConfFile() {
do {
let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "privoxy.config"
try FileManager.default.removeItem(atPath: filepath)
} catch {
}
}
func SyncPrivoxy() {
var changed: Bool = false
changed = changed || generatePrivoxyLauchAgentPlist()
let mgr = ServerProfileManager.instance
if mgr.activeProfileId != nil {
changed = changed || writePrivoxyConfFile()
let on = UserDefaults.standard.bool(forKey: "LocalHTTPOn")
if on {
if changed {
StopPrivoxy()
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + DispatchTimeInterval.seconds(1),
execute: {
() in
StartPrivoxy()
})
} else {
StartPrivoxy()
}
} else {
StopPrivoxy()
}
} else {
removePrivoxyConfFile()
StopPrivoxy()
}
}