-
Notifications
You must be signed in to change notification settings - Fork 11
/
Program.cs
567 lines (482 loc) · 19.8 KB
/
Program.cs
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using sttz.CLI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace sttz.expresso
{
/// <summary>
/// Command line interface for <see cref="ExpressVPNClient"/>.
/// </summary>
class ExpressoCLI
{
/// <summary>
/// The selected action.
/// </summary>
public string action;
// -------- Options --------
/// <summary>
/// Wether to show the help.
/// </summary>
public bool help;
/// <summary>
/// Wether to print the program version.
/// </summary>
public bool version;
/// <summary>
/// Verbosity of the output (0 = default, 1 = verbose, 3 = extra verbose)
/// </summary>
public int verbose;
/// <summary>
/// Only log errors.
/// </summary>
public bool quiet;
/// <summary>
/// Operation timeout (ms).
/// </summary>
public int timeout = 10000;
// -------- Connect --------
/// <summary>
/// Change server if already connected.
/// </summary>
public bool changeConnection;
/// <summary>
/// Randomize location inside of countries.
/// </summary>
public bool randomize;
/// <summary>
/// Disconnect when already connected to the given location.
/// </summary>
public bool toggle;
/// <summary>
/// The VPN location to connect to.
/// </summary>
public string location;
// -------- Alfred --------
/// <summary>
/// Wether to list all locations for the Alfred workflow.
/// </summary>
public bool alfredLocations;
// -------- CLI --------
/// <summary>
/// Name of program used in output.
/// </summary>
public const string PROGRAM_NAME = "expresso";
public static ILoggerFactory LoggerFactory { get; set; }
public static ILogger Logger;
public static bool enableColors;
/// <summary>
/// The definition of the program's arguments.
/// </summary>
public static Arguments<ExpressoCLI> ArgumentsDefinition {
get {
if (_arguments != null) return _arguments;
_arguments = new Arguments<ExpressoCLI>()
.Action(null, (t, a) => t.action = a)
.Option((ExpressoCLI t, bool v) => t.help = v, "h", "?", "help")
.Description("Show this help")
.Option((ExpressoCLI t, bool v) => t.version = v, "version")
.Description("Print the version of this program")
.Option((ExpressoCLI t, bool v) => t.verbose++, "v", "verbose").Repeatable()
.Description("Increase verbosity of output, can be repeated")
.Option((ExpressoCLI t, bool v) => t.quiet = v, "q", "quiet")
.Description("Only output necessary information and errors")
.Option((ExpressoCLI t, string v) => t.timeout = int.Parse(v), "t", "timeout")
.Description("Override the default connect/disconnect timeout (in milliseconds)")
.Action("locations", (t, a) => t.action = a)
.Description("List all available VPN locations")
.Action("status", (t, a) => t.action = a)
.Description("Show the current VPN connection status")
.Action("connect", (t, a) => t.action = a)
.Description("Connect to a VPN location")
.Option((ExpressoCLI t, bool v) => t.changeConnection = v, "c", "change")
.Description("Change current location when already connected")
.Option((ExpressoCLI t, bool v) => t.randomize = v, "random")
.Description("Choose a random location in the given country")
.Option((ExpressoCLI t, bool v) => t.toggle = v, "toggle")
.Description("Disconnect instead when already connected (to the given location with --change)")
.Option((ExpressoCLI t , string a) => t.location = a, 0)
.ArgumentName("<location>")
.Description("Location to connect to, either location id, country or keyword")
.Action("disconnect", (t, a) => t.action = a)
.Description("Disconnect from the current VPN location")
.Action("alfred", (t, a) => t.action = a)
.Description("Output the main options for the Alfred workflow")
.Option((ExpressoCLI t, bool a) => t.alfredLocations = a, "locations")
.Description("Output the locations for the Alfred workflow")
.Action("repl", (t, a) => t.action = a)
.Description("Interactively communicate with the helper")
;
return _arguments;
}
}
static Arguments<ExpressoCLI> _arguments;
/// <summary>
/// Main entry method.
/// </summary>
public static async Task<int> Main(string[] args)
{
var cli = new ExpressoCLI();
AppDomain.CurrentDomain.UnhandledException += (s, a) => {
if (a.ExceptionObject is Exception e) {
if (e.InnerException is System.Threading.ThreadAbortException) {
// Woarkround for a bug in mono: https://github.com/mono/mono/issues/15418
Logger.LogDebug($"Ignoring exception: {e.Message}");
Environment.Exit(0);
} else {
Arguments<ExpressoCLI>.WriteException(e, args, cli.verbose > 0, enableColors);
}
} else {
Logger.LogWarning($"Unknown unhandled exception object: {a.ExceptionObject}");
}
Environment.Exit(1);
};
try {
ArgumentsDefinition.Parse(cli, args);
if (cli.help) {
cli.PrintHelp();
return 0;
} else if (cli.version) {
cli.PrintVersion();
return 0;
}
await cli.Setup();
switch (cli.action) {
case "locations":
await cli.Locations();
break;
case "status":
cli.Status();
break;
case "connect":
await cli.Connect();
break;
case "disconnect":
await cli.Disconnect();
break;
case "repl":
await cli.Repl();
break;
case "alfred":
await cli.Alfred();
break;
default:
Logger.LogError("No action specified");
cli.PrintHelp();
return 1;
}
return 0;
} catch (Exception e) {
Arguments<ExpressoCLI>.WriteException(e, args, cli.verbose > 0, enableColors);
return 1;
}
}
/// <summary>
/// Print the help for this program.
/// </summary>
public void PrintHelp()
{
PrintVersion();
Console.WriteLine();
Console.WriteLine(ArgumentsDefinition.Help(PROGRAM_NAME, null, null));
}
/// <summary>
/// Return the version of this program.
/// </summary>
public string GetVersion()
{
var assembly = Assembly.GetExecutingAssembly();
return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
}
/// <summary>
/// Print the program name and version to the console.
/// </summary>
public void PrintVersion()
{
Console.WriteLine($"{PROGRAM_NAME} v{GetVersion()}");
}
// -------- Implementation --------
const string ExpressVPNHelperPath = "/Applications/ExpressVPN.app/Contents/MacOS/expressvpn-browser-helper";
const string DummyManifest = "com.expressvpn.helper.json";
const string ExtensionId = "[email protected]";
ExpressVPNClient client;
string input;
async Task Setup()
{
enableColors = Environment.GetEnvironmentVariable("CLICOLORS") != "0";
var level = LogLevel.Warning;
if (quiet) {
level = LogLevel.Error;
} else if (verbose >= 3) {
level = LogLevel.Trace;
} else if (verbose == 2) {
level = LogLevel.Debug;
} else if (verbose == 1) {
level = LogLevel.Information;
}
LoggerFactory = new LoggerFactory()
.AddNiceConsole(level, false);
Logger = LoggerFactory.CreateLogger<ExpressoCLI>();
Logger.LogInformation($"{PROGRAM_NAME} v{GetVersion()}");
if (level != LogLevel.Warning) Logger.LogInformation($"Log level set to {level}");
client = new ExpressVPNClient(LoggerFactory.CreateLogger<ExpressVPNClient>());
await client.WaitForConnection();
Logger.LogInformation($"Connected to ExpressVPN version {client.AppVersion}");
await client.UpdateStatus();
}
async Task Locations()
{
await client.GetLocations();
string lastRegion = null;
string lastCountry = null;
foreach (var loc in client.Locations
.OrderBy(l => l.region)
.ThenBy(l => l.country)
.ThenBy(l => l.name)
) {
if (lastRegion != loc.region) {
Console.WriteLine("");
Console.WriteLine($"--- {loc.region} ---");
lastRegion = loc.region;
}
if (lastCountry != loc.country) {
Console.WriteLine("");
Console.WriteLine($"{loc.country} ({loc.country_code})");
lastCountry = loc.country;
}
Console.WriteLine($"- {loc.name} ({loc.id})");
}
}
void Status()
{
if (client.LatestStatus.state == ExpressVPNClient.State.connected) {
var current = client.LatestStatus.current_location;
Console.WriteLine($"VPN connected to '{current.name}' ({current.id})");
} else if (client.LatestStatus.state == ExpressVPNClient.State.ready) {
Console.WriteLine("VPN not connected");
} else {
Console.WriteLine($"ExpressVPN in exceptional state: {client.LatestStatus.state}");
}
}
async Task Connect()
{
await client.GetLocations();
if (client.Locations == null) {
throw new Exception("Could not load location list");
}
var args = new ExpressVPNClient.ConnectArgs();
// No location -> Connect to default location
ExpressVPNClient.Location connectCountry = default;
if (string.IsNullOrEmpty(location)) {
if (string.IsNullOrEmpty(client.DefaultLocationId)) {
throw new Exception("No default location returned");
}
var defaultLoc = client.GetLocation(client.DefaultLocationId);
if (defaultLoc == null) {
throw new Exception($"Default location with id {client.DefaultLocationId} not found in locations list");
}
Logger.LogInformation($"Connecting to default location '{defaultLoc.Value.name}'");
args.id = defaultLoc.Value.id;
args.name = defaultLoc.Value.name;
args.is_default = true;
} else {
// Connect to any location in a country
var countryLocs = client.Locations.Where(l =>
string.Equals(l.country, location, StringComparison.OrdinalIgnoreCase)
|| string.Equals(l.country_code, location, StringComparison.OrdinalIgnoreCase)
);
if (countryLocs.Any()) {
connectCountry = countryLocs.Skip(new Random().Next(countryLocs.Count() - 1)).First();
if (randomize) {
Logger.LogInformation($"Connecting to random location in country '{connectCountry.country}'");
args.id = connectCountry.id;
args.name = connectCountry.name;
} else {
Logger.LogInformation($"Connecting to default location in country '{connectCountry.country}'");
args.country = connectCountry.country;
}
// Look up specific location
} else {
ExpressVPNClient.Location selected = default;
int selectedPriority = 0;
foreach (var loc in client.Locations) {
// ID-match has the highest priority
if (selectedPriority < 2 && location == loc.id) {
selected = loc;
selectedPriority = 2;
// Name-match has lower priority
} else if (selectedPriority < 1 && loc.name.IndexOf(location, StringComparison.OrdinalIgnoreCase) >= 0) {
selected = loc;
selectedPriority = 1;
}
}
if (selected.name == null) {
throw new Exception($"Could not find a location for the query '{location}'");
}
Logger.LogInformation($"Connecting to location '{selected.name}'");
args.id = selected.id;
args.name = selected.name;
}
}
if (client.LatestStatus.state == ExpressVPNClient.State.connected) {
var current = client.LatestStatus.current_location;
if (toggle && (!changeConnection || current.id == args.id || (connectCountry.country != null && current.country == connectCountry.country))) {
// Toggle: Disconnect instead of already connected
Logger.LogInformation($"Already connected to '{current.name}', disconnecting instead");
await Disconnect();
return;
}
if (!changeConnection) {
throw new Exception($"Already connected to '{current.name}'.\n"
+ $"Use --change or -c to change the currently connected location.");
} else {
args.change_connected_location = true;
}
}
await client.Connect(args, timeout);
await client.UpdateStatus();
Console.WriteLine($"Connected to '{client.LatestStatus.current_location.name}'");
}
async Task Disconnect()
{
await client.Disconnect(timeout);
Console.WriteLine($"Disconnected");
}
async Task ReadInput()
{
while (true) {
await Task.Run(() => input = Console.ReadLine());
}
}
public async Task Repl()
{
_ = ReadInput();
while (true) {
await Task.Delay(20);
if (input != null) {
client.Send(input);
input = null;
}
// {"jsonrpc": "2.0", "method": "XVPN.GetStatus", "params": {}, "id": 1}
// {"jsonrpc": "2.0", "method": "XVPN.GetLocations", "params": { "include_default_location": true, "include_recent_connections": true }, "id": 1}
// {"jsonrpc": "2.0", "method": "XVPN.SelectLocation", "params": { "selected_location": { "name": "Germany", "is_country": true } }, "id": 1}
// {"jsonrpc": "2.0", "method": "XVPN.Connect", "params": { "country": "Germany" }, "id": 1}
// {"jsonrpc": "2.0", "method": "XVPN.Disconnect", "params": {}, "id": 1}
}
}
#pragma warning disable CS0649
[Serializable]
struct AlfredResult
{
public IEnumerable<AlfredItem> items;
public Dictionary<string, string> variables;
public float? rerun;
}
[Serializable]
struct AlfredIcon
{
public string type;
public string path;
}
[Serializable]
struct AlfredMods
{
public AlfredMod alt;
public AlfredMod cmd;
}
[Serializable]
struct AlfredMod
{
public bool valid;
public string arg;
public string subtitle;
public AlfredIcon icon;
}
[Serializable]
struct AlfredItem
{
public string uid;
public string title;
public string subtitle;
public string arg;
public AlfredIcon icon;
public bool valid;
public string match;
public string autocomplete;
public string type;
public AlfredMods mods;
// mods…
// text…
public static AlfredItem FromLocation(ExpressVPNClient client, ExpressVPNClient.Location loc, bool withUid = true)
{
var prefix = "";
var action = $"connect --change {loc.id}";
var connectedId = client.LatestStatus.current_location.id;
if (loc.id == connectedId) {
prefix = "⚡️ ";
action = "disconnect";
} else {
if (loc.favorite)
prefix += "❤️";
if (client.RecentLocationIds.Contains(loc.id))
prefix += "🕙";
if (client.DefaultLocationId == loc.id)
prefix += "👍";
if (prefix.Length > 0) prefix = prefix + " ";
}
string uid = null;
if (withUid) uid = loc.id;
return new AlfredItem() {
uid = uid,
title = loc.name,
subtitle = $"{prefix}{loc.region} - {loc.country}",
arg = action,
icon = new AlfredIcon() {
path = $"./flags/{loc.country_code}.png",
},
valid = true,
match = $"{loc.name} {loc.region} {loc.country_code}",
};
}
}
#pragma warning restore CS0649
async Task Alfred()
{
await client.GetLocations();
var items = new List<AlfredItem>();
if (alfredLocations) {
foreach (var loc in client.Locations) {
items.Add(AlfredItem.FromLocation(client, loc));
}
} else {
if (client.LatestStatus.state == ExpressVPNClient.State.connected) {
var loc = client.LatestStatus.current_location;
items.Add(AlfredItem.FromLocation(client, loc, withUid: false));
}
foreach (var loc in client.Locations.Where(l => l.favorite)) {
if (loc.id == client.LatestStatus.current_location.id) continue;
items.Add(AlfredItem.FromLocation(client, loc, withUid: false));
}
foreach (var id in client.RecentLocationIds) {
var loc = client.GetLocation(id);
if (loc.Value.favorite) continue;
if (loc.Value.id == client.LatestStatus.current_location.id) continue;
items.Add(AlfredItem.FromLocation(client, loc.Value, withUid: false));
}
var defaultLoc = client.GetLocation(client.DefaultLocationId);
items.Add(AlfredItem.FromLocation(client, defaultLoc.Value, withUid: false));
}
var result = new AlfredResult() {
items = items
};
var json = JsonConvert.SerializeObject(result, new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
});
Console.WriteLine(json);
}
}
}