Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
439 lines (380 loc) · 15.3 KB
/
Copy pathProgram.cs
File metadata and controls
439 lines (380 loc) · 15.3 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
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
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Iap2Loc.Engine;
using Iap2Loc.Protocol;
using Iap2Loc.Transport;
using Iap2Loc.Web;
namespace Iap2Loc;
internal static class Program
{
private static int Main(string[] args)
{
// IOBluetooth delivers its callbacks on the main thread's runloop, so on macOS the
// main thread runs that loop and the application runs on a worker thread.
return OperatingSystem.IsMacOS()
? MacBtRfcommTransport.RunWithMainLoop(() => RunApplication(args))
: RunApplication(args);
}
private static int RunApplication(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
var launchedByDoubleClick = args.Length == 0;
try
{
if (launchedByDoubleClick)
{
// Double-clicking the exe opens the control page; no console arguments to type.
return RunWeb(Options.Parse(Array.Empty<string>()), openBrowser: true);
}
if (args[0] is "-h" or "--help" or "help")
{
Help();
return 0;
}
var command = args[0];
var options = Options.Parse(args.Skip(1).ToArray());
Log.Verbose = options.Flag("verbose") || options.Flag("v");
return command switch
{
"run" => Run(options),
"devices" => Devices(),
"inspect-identity" => InspectIdentity(options),
"serve" or "web" => RunWeb(options),
_ => Unknown(command),
};
}
catch (Exception ex)
{
Log.Error(ex.Message);
if (ex.InnerException is not null)
{
Log.Error(" " + ex.InnerException.Message);
}
// A double-clicked console closes instantly; keep the message readable.
if (launchedByDoubleClick)
{
Pause();
}
return 1;
}
}
private static void Pause()
{
Console.WriteLine();
Console.WriteLine("按回车退出…");
try
{
Console.ReadLine();
}
catch
{
// No console attached.
}
}
private static int RunWeb(Options options, bool openBrowser = false)
{
var port = options.Int("port", 8737);
var config = AppConfig.Load(options.Text("config"));
config.RotateIdentityOnStart = !options.Flag("fixed-identity");
config.UseAdapterOverride = !options.Flag("fixed-adapter");
config.PrepareForRun(BluetoothDevices.TryGetLocalAdapterAddress());
var manager = new SessionManager(
options.Double("lat", 31.2304),
options.Double("lon", 121.4737),
config);
var favorites = new FavoriteStore(config);
// Let a custom build warm up its identity source before any session starts.
IdentitySource.Prime();
using var server = new WebServer(port, manager, favorites);
server.Start();
if (openBrowser)
{
OpenBrowser($"http://localhost:{server.Port}/");
}
Log.Info("控制页面已就绪,Ctrl+C 退出");
var stop = new ManualResetEventSlim();
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
stop.Set();
};
stop.Wait();
server.Dispose();
manager.Dispose();
return 0;
}
/// <summary>Opens the control page. IAP2LOC_NO_BROWSER=1 suppresses it (useful for tests).</summary>
private static void OpenBrowser(string url)
{
if (Environment.GetEnvironmentVariable("IAP2LOC_NO_BROWSER") == "1")
{
return;
}
try
{
if (OperatingSystem.IsWindows())
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (OperatingSystem.IsMacOS())
{
Process.Start("open", url);
}
else
{
Process.Start("xdg-open", url);
}
}
catch (Exception ex)
{
Log.Warn("无法自动打开浏览器:" + ex.Message);
}
}
private static int Unknown(string command)
{
Log.Error($"unknown command '{command}'");
Help();
return 2;
}
private static int Devices()
{
BluetoothDevices.List();
return 0;
}
private static int Run(Options options)
{
var transportName = options.Text("transport", "bt").ToLowerInvariant();
var identityDirectory = options.Text("identity");
var signer = IdentitySource.Resolve(identityDirectory, out var identitySource);
if (signer is not null)
{
Log.Info($"MFi material: {identitySource}, certificate {signer.Certificate.Length} bytes");
}
else
{
Log.Warn("no identity available: identification and the link will work, authentication will not. " +
"The phone ignores location data from an unauthenticated accessory.");
}
var config = AppConfig.Load(options.Text("config"));
config.RotateIdentityOnStart = !options.Flag("fixed-identity");
config.UseAdapterOverride = !options.Flag("fixed-adapter");
var localAdapter = BluetoothDevices.TryGetLocalAdapterAddress();
config.PrepareForRun(localAdapter);
// Command line overrides apply to this run only; the file keeps the generated identity.
var effective = config.EffectiveProfile;
var profile = effective with
{
Name = options.Text("name", effective.Name),
Model = options.Text("model", effective.Model),
Manufacturer = options.Text("manufacturer", effective.Manufacturer),
Serial = options.Text("serial", effective.Serial),
Firmware = options.Text("firmware", effective.Firmware),
Hardware = options.Text("hardware", effective.Hardware),
};
var identity = profile.ToIdentity();
using var transport = OpenTransport(transportName, options);
byte[]? bluetoothAdapter = null;
if (transportName is "bt" or "bluetooth")
{
var reported = profile.AdapterOverride();
bluetoothAdapter = reported ?? localAdapter;
if (bluetoothAdapter is null)
{
Log.Warn("could not read the local Bluetooth adapter address; iOS rejects identification " +
"without transport component 17");
}
else if (reported is not null)
{
Log.Info($"reported Bluetooth address {string.Join(':', reported.Select(b => b.ToString("X2")))} " +
"(generated on first run, stored in the config file)");
}
else
{
Log.Info($"local Bluetooth adapter {string.Join(':', bluetoothAdapter.Select(b => b.ToString("X2")))}");
}
}
var target = new LocationTarget(
options.Double("lat", 31.2304),
options.Double("lon", 121.4737));
target.Apply(new TargetUpdate
{
Altitude = options.NullableDouble("alt"),
Speed = options.NullableDouble("speed"),
Bearing = options.NullableDouble("bearing"),
Accuracy = options.NullableDouble("accuracy"),
Quality = options.NullableInt("quality"),
Satellites = options.NullableInt("satellites"),
});
var rate = Math.Max(10, options.Int("rate", 250));
using var link = new Iap2Link(transport, initiate: true, "accessory");
using var session = new LocationSession(
link,
target,
identity,
signer,
rate,
bluetoothAdapter);
var stop = new ManualResetEventSlim();
if (options.Flag("probe"))
{
session.IdentificationFinished += (accepted, detail) =>
{
if (accepted)
{
Log.Ok("PROBE: identification accepted; stopping before authentication");
}
else
{
Log.Error($"PROBE: identification rejected ({detail})");
}
stop.Set();
};
}
link.Ready += () =>
{
Log.Ok("iAP2 link ready, waiting for the phone to identify the accessory");
};
link.Failed += reason =>
{
if (!stop.IsSet)
{
Log.Error("link failed: " + reason);
}
stop.Set();
};
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
stop.Set();
};
var snapshot = target.Snapshot();
Log.Step($"accessory '{identity.Name}' ({identity.Model} / {identity.Serial}) over {transport.Describe}, " +
$"target {snapshot.Latitude:F6},{snapshot.Longitude:F6} every {rate} ms");
link.Start();
var duration = options.Int("duration", 0);
if (duration > 0)
{
stop.Wait(TimeSpan.FromSeconds(duration));
}
else
{
Log.Info("press Ctrl+C to stop");
stop.Wait();
}
Log.Info($"stopped: rx={link.BytesIn}B tx={link.BytesOut}B, control messages={link.CsmMessages}, " +
$"location updates={session.MessagesPushed}, authenticated={session.Authenticated}");
return 0;
}
private static ITransport OpenTransport(string name, Options options) => name switch
{
"bt" or "bluetooth" => OperatingSystem.IsMacOS()
? MacBtRfcommTransport.Connect(
options.Text("mac") ?? throw new ArgumentException("--mac AA:BB:CC:DD:EE:FF is required for --transport bt"),
options.Int("connect-timeout", 20))
: BtRfcommTransport.Connect(
options.Text("mac") ?? throw new ArgumentException("--mac AA:BB:CC:DD:EE:FF is required for --transport bt"),
options.Int("connect-timeout", 20)),
"tcp" or "wifi" => TcpTransport.Connect(
options.Text("host", "127.0.0.1"),
options.Int("port", 0) is var port && port > 0
? port
: throw new ArgumentException("--port is required for --transport tcp")),
_ => throw new ArgumentException($"unknown transport '{name}', use bt or tcp"),
};
/// <summary>
/// Dumps the MFi material. The certificate's subject and extensions are what tell iOS which
/// kind of accessory this is (CarPlay head unit, GPS accessory, ...), which decides whether
/// accessory-supplied location is honoured outside a CarPlay session.
/// </summary>
private static int InspectIdentity(Options options)
{
var directory = options.Text("identity") ?? options.Positional.FirstOrDefault() ?? "identity";
var keyPath = Path.Combine(directory, "identity.pk8");
var certificatePath = Path.Combine(directory, "certificate.p7b");
if (!File.Exists(keyPath) || !File.Exists(certificatePath))
{
Log.Error($"expected {keyPath} and {certificatePath}");
return 1;
}
var pk8 = File.ReadAllBytes(keyPath);
var certificateBytes = File.ReadAllBytes(certificatePath);
Log.Info($"source : files in {Path.GetFullPath(directory)}");
using (var key = ECDsa.Create())
{
key.ImportPkcs8PrivateKey(pk8, out _);
Log.Info($"private key : {key.KeySize} bit, curve {key.ExportParameters(false).Curve.Oid.FriendlyName ?? "unknown"}");
}
var certificates = new X509Certificate2Collection();
try
{
certificates.Import(certificateBytes);
}
catch (Exception ex)
{
Log.Error($"certificate.p7b is not a parseable PKCS#7: {ex.Message}");
return 1;
}
Log.Info($"certificates: {certificates.Count}");
foreach (var certificate in certificates)
{
Log.Info($"subject : {certificate.Subject}");
Log.Info($"issuer : {certificate.Issuer}");
Log.Info($"valid : {certificate.NotBefore:yyyy-MM-dd} .. {certificate.NotAfter:yyyy-MM-dd}");
Log.Info($"serial : {certificate.SerialNumber}");
foreach (var extension in certificate.Extensions)
{
var raw = extension.RawData;
Log.Info($"ext {extension.Oid?.Value} ({extension.Oid?.FriendlyName}) {raw.Length} bytes");
var printable = Printable(raw);
if (printable.Length > 0)
{
Log.Info(" " + (printable.Length > 220 ? printable[..220] + "..." : printable));
}
}
}
return 0;
}
private static string Printable(byte[] data)
{
var builder = new StringBuilder();
foreach (var value in data)
{
builder.Append(value is >= 32 and < 127 ? (char)value : '.');
}
var text = builder.ToString();
return text.Count(character => character != '.') >= 6 ? text : string.Empty;
}
private static void Help()
{
Console.WriteLine("""
iap2loc - 通过 iAP2 给 iPhone 下发定位
不带参数运行程序,会启动控制页面并自动打开浏览器,端口 8737。
用法:
iap2loc run --transport bt --mac AA:BB:CC:DD:EE:FF [--identity 目录] [选项]
iap2loc run --transport tcp --host 127.0.0.1 --port 12345 [--identity 目录] [选项]
iap2loc devices
iap2loc inspect-identity [--identity 目录]
iap2loc serve [--port 8737] [--identity 目录] [--config 文件] 启动本地控制页面
运行选项:
--lat / --lon 目标坐标(默认 31.2304, 121.4737)
--alt --speed --bearing --accuracy NMEA 附加字段
--quality GGA 定位质量 0-8(默认 1)
--satellites GGA 卫星数 0-99(默认 8)
--rate 上报周期,毫秒(默认 250,最小 10)
--identity identity.pk8 + certificate.p7b 所在目录(默认 ./identity)
--config 配置文件(默认 iap2loc.json,位于程序目录)
--fixed-identity 不轮换配件身份(默认每次启动换一个 serial)
--fixed-adapter 不随机蓝牙地址,上报本机适配器地址
--name --model --manufacturer --serial --firmware --hardware 覆盖本次运行的身份字段
--probe 只跑到识别为止(收到 0x1D02/0x1D03 即退出)
--duration 多少秒后自动退出,便于脚本测试
-v, --verbose 打印协议级细节
说明:
蓝牙模式需要先在对应系统的蓝牙设置中配对 iPhone。
身份材料放在 --identity 指向的目录里,本程序不包含任何 MFi 材料。
""");
}
}