This repository was archived by the owner on Dec 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathAdbClient.cs
More file actions
711 lines (595 loc) · 24.3 KB
/
AdbClient.cs
File metadata and controls
711 lines (595 loc) · 24.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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// <copyright file="AdbClient.cs" company="The Android Open Source Project, Ryan Conrad, Quamotion">
// Copyright (c) The Android Open Source Project, Ryan Conrad, Quamotion. All rights reserved.
// </copyright>
namespace SharpAdbClient
{
using SharpAdbClient.Exceptions;
using SharpAdbClient.Logs;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// <para>
/// Implements the <see cref="IAdbClient"/> interface, and allows you to interact with the
/// adb server and devices that are connected to that adb server.
/// </para>
/// <para>
/// For example, to fetch a list of all devices that are currently connected to this PC, you can
/// call the <see cref="GetDevices"/> method.
/// </para>
/// <para>
/// To run a command on a device, you can use the <see cref="ExecuteRemoteCommandAsync(string, DeviceData, IShellOutputReceiver, CancellationToken, int)"/>
/// method.
/// </para>
/// </summary>
/// <seealso href="https://github.com/android/platform_system_core/blob/master/adb/SERVICES.TXT">SERVICES.TXT</seealso>
/// <seealso href="https://github.com/android/platform_system_core/blob/master/adb/adb_client.c">adb_client.c</seealso>
/// <seealso href="https://github.com/android/platform_system_core/blob/master/adb/adb.c">adb.c</seealso>
public class AdbClient : IAdbClient
{
/// <summary>
/// The default encoding
/// </summary>
public const string DefaultEncoding = "UTF-8";
/// <summary>
/// The port at which the Android Debug Bridge server listens by default.
/// </summary>
public const int AdbServerPort = 5037;
/// <summary>
/// The default port to use when connecting to a device over TCP/IP.
/// </summary>
public const int DefaultPort = 5555;
/// <summary>
/// The singleton instance of the <see cref="AdbClient"/> class.
/// </summary>
private static IAdbClient instance = null;
private Func<EndPoint, IAdbSocket> adbSocketFactory;
/// <summary>
/// Initializes a new instance of the <see cref="AdbClient"/> class.
/// </summary>
public AdbClient()
: this(new IPEndPoint(IPAddress.Loopback, AdbServerPort), Factories.AdbSocketFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AdbClient"/> class.
/// </summary>
/// <param name="endPoint">
/// The <see cref="EndPoint"/> at which the adb server is listening.
/// </param>
public AdbClient(EndPoint endPoint, Func<EndPoint, IAdbSocket> adbSocketFactory)
{
if (endPoint == null)
{
throw new ArgumentNullException();
}
if (!(endPoint is IPEndPoint || endPoint is DnsEndPoint))
{
throw new NotSupportedException("Only TCP endpoints are supported");
}
if (adbSocketFactory == null)
{
throw new ArgumentNullException(nameof(adbSocketFactory));
}
this.EndPoint = endPoint;
this.adbSocketFactory = adbSocketFactory;
}
/// <summary>
/// Gets the encoding used when communicating with adb.
/// </summary>
public static Encoding Encoding
{ get; } = Encoding.GetEncoding(DefaultEncoding);
/// <summary>
/// Gets or sets the current global instance of the <see cref="IAdbClient"/> interface.
/// </summary>
public static IAdbClient Instance
{
get
{
if (instance == null)
{
instance = new AdbClient();
}
return instance;
}
set
{
instance = value;
}
}
public static EndPoint DefaultEndPoint
{
get
{
return new IPEndPoint(IPAddress.Loopback, DefaultPort);
}
}
/// <summary>
/// Gets the <see cref="EndPoint"/> at which the adb server is listening.
/// </summary>
public EndPoint EndPoint
{
get;
private set;
}
/// <summary>
/// Create an ASCII string preceded by four hex digits. The opening "####"
/// is the length of the rest of the string, encoded as ASCII hex(case
/// doesn't matter).
/// </summary>
/// <param name="req">The request to form.
/// </param>
/// <returns>
/// An array containing <c>####req</c>.
/// </returns>
public static byte[] FormAdbRequest(string req)
{
string resultStr = string.Format("{0}{1}", req.Length.ToString("X4"), req);
byte[] result = Encoding.GetBytes(resultStr);
return result;
}
/// <summary>
/// Creates the adb forward request.
/// </summary>
/// <param name="address">The address.</param>
/// <param name="port">The port.</param>
/// <returns>
/// This returns an array containing <c>"####tcp:{port}:{addStr}"</c>.
/// </returns>
public static byte[] CreateAdbForwardRequest(string address, int port)
{
string request;
if (address == null)
{
request = "tcp:" + port;
}
else
{
request = "tcp:" + port + ":" + address;
}
return FormAdbRequest(request);
}
/// <inheritdoc/>
public int GetAdbVersion()
{
using (var socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest("host:version");
var response = socket.ReadAdbResponse();
var version = socket.ReadString();
return int.Parse(version, NumberStyles.HexNumber);
}
}
/// <inheritdoc/>
public void KillAdb()
{
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest("host:kill");
// The host will immediately close the connection after the kill
// command has been sent; no need to read the response.
}
}
/// <inheritdoc/>
public List<DeviceData> GetDevices()
{
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest("host:devices-l");
socket.ReadAdbResponse();
var reply = socket.ReadString();
string[] data = reply.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
return data.Select(d => DeviceData.CreateFromAdbData(d)).ToList();
}
}
/// <inheritdoc/>
public void SetDevice(IAdbSocket socket, DeviceData device)
{
// if the device is not null, then we first tell adb we're looking to talk
// to a specific device
if (device != null)
{
socket.SendAdbRequest($"host:transport:{device.Serial}");
try
{
var response = socket.ReadAdbResponse();
}
catch (AdbException e)
{
if (string.Equals("device not found", e.AdbError, StringComparison.OrdinalIgnoreCase))
{
throw new DeviceNotFoundException(device.Serial);
}
else
{
throw;
}
}
}
}
/// <inheritdoc/>
public int CreateReverseForward(DeviceData device, string remote, string local, bool allowRebind)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
string rebind = allowRebind ? string.Empty : "norebind:";
socket.SendAdbRequest($"reverse:forward:{rebind}{remote};{local}");
var response = socket.ReadAdbResponse();
response = socket.ReadAdbResponse();
var portString = socket.ReadString();
if (portString != null && int.TryParse(portString, out int port))
{
return port;
}
return 0;
}
}
public void RemoveReverseForward(DeviceData device, string remote)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
socket.SendAdbRequest($"reverse:killforward:{remote}");
var response = socket.ReadAdbResponse();
}
}
public void RemoveAllReverseForwards(DeviceData device)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
socket.SendAdbRequest($"reverse:killforward-all");
var response = socket.ReadAdbResponse();
}
}
/// <inheritdoc/>
public int CreateForward(DeviceData device, string local, string remote, bool allowRebind)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
string rebind = allowRebind ? string.Empty : "norebind:";
socket.SendAdbRequest($"host-serial:{device.Serial}:forward:{rebind}{local};{remote}");
var response = socket.ReadAdbResponse();
response = socket.ReadAdbResponse();
var portString = socket.ReadString();
if (portString != null && int.TryParse(portString, out int port))
{
return port;
}
return 0;
}
}
/// <inheritdoc/>
public int CreateForward(DeviceData device, ForwardSpec local, ForwardSpec remote, bool allowRebind)
{
return this.CreateForward(device, local?.ToString(), remote?.ToString(), allowRebind);
}
/// <inheritdoc/>
public void RemoveForward(DeviceData device, int localPort)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest($"host-serial:{device.Serial}:killforward:tcp:{localPort}");
var response = socket.ReadAdbResponse();
}
}
/// <inheritdoc/>
public void RemoveAllForwards(DeviceData device)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest($"host-serial:{device.Serial}:killforward-all");
var response = socket.ReadAdbResponse();
}
}
/// <inheritdoc/>
public IEnumerable<ForwardData> ListForward(DeviceData device)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest($"host-serial:{device.Serial}:list-forward");
var response = socket.ReadAdbResponse();
var data = socket.ReadString();
var parts = data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return parts.Select(p => ForwardData.FromString(p));
}
}
public IEnumerable<ForwardData> ListReverseForward(DeviceData device)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
socket.SendAdbRequest($"reverse:list-forward");
var response = socket.ReadAdbResponse();
var data = socket.ReadString();
var parts = data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return parts.Select(p => ForwardData.FromString(p));
}
}
/// <inheritdoc/>
public Task ExecuteRemoteCommandAsync(string command, DeviceData device, IShellOutputReceiver receiver, CancellationToken cancellationToken, int maxTimeToOutputResponse)
{
return this.ExecuteRemoteCommandAsync(command, device, receiver, cancellationToken, maxTimeToOutputResponse, Encoding);
}
/// <inheritdoc/>
public async Task ExecuteRemoteCommandAsync(string command, DeviceData device, IShellOutputReceiver receiver, CancellationToken cancellationToken, int maxTimeToOutputResponse, Encoding encoding)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
cancellationToken.Register(() => socket.Dispose());
this.SetDevice(socket, device);
socket.SendAdbRequest($"shell:{command}");
var response = socket.ReadAdbResponse();
try
{
using (StreamReader reader = new StreamReader(socket.GetShellStream(), encoding))
{
// Previously, we would loop while reader.Peek() >= 0. Turns out that this would
// break too soon in certain cases (about every 10 loops, so it appears to be a timing
// issue). Checking for reader.ReadLine() to return null appears to be much more robust
// -- one of the integration test fetches output 1000 times and found no truncations.
while (!cancellationToken.IsCancellationRequested)
{
var line = await reader.ReadLineAsync().ConfigureAwait(false);
if (line == null)
{
break;
}
if (receiver != null)
{
receiver.AddOutput(line);
}
}
}
}
catch (Exception e)
{
// If a cancellation was requested, this main loop is interrupted with an exception
// because the socket is closed. In that case, we don't need to throw a ShellCommandUnresponsiveException.
// In all other cases, something went wrong, and we want to report it to the user.
if (!cancellationToken.IsCancellationRequested)
{
throw new ShellCommandUnresponsiveException(e);
}
}
finally
{
if (receiver != null)
{
receiver.Flush();
}
}
}
}
/// <inheritdoc/>
public Framebuffer CreateRefreshableFramebuffer(DeviceData device)
{
this.EnsureDevice(device);
return new Framebuffer(device, this);
}
/// <inheritdoc/>
public async Task<Image> GetFrameBufferAsync(DeviceData device, CancellationToken cancellationToken)
{
this.EnsureDevice(device);
using (Framebuffer framebuffer = this.CreateRefreshableFramebuffer(device))
{
await framebuffer.RefreshAsync(cancellationToken).ConfigureAwait(false);
// Convert the framebuffer to an image, and return that.
return framebuffer.ToImage();
}
}
/// <inheritdoc/>
public async Task RunLogServiceAsync(DeviceData device, Action<LogEntry> messageSink, CancellationToken cancellationToken, params LogId[] logNames)
{
if (messageSink == null)
{
throw new ArgumentException(nameof(messageSink));
}
this.EnsureDevice(device);
// The 'log' service has been deprecated, see
// https://android.googlesource.com/platform/system/core/+/7aa39a7b199bb9803d3fd47246ee9530b4a96177
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
StringBuilder request = new StringBuilder();
request.Append("shell:logcat -B");
foreach (var logName in logNames)
{
request.Append($" -b {logName.ToString().ToLowerInvariant()}");
}
socket.SendAdbRequest(request.ToString());
var response = socket.ReadAdbResponse();
using (Stream stream = socket.GetShellStream())
{
LogReader reader = new LogReader(stream);
while (!cancellationToken.IsCancellationRequested)
{
LogEntry entry = null;
try
{
entry = await reader.ReadEntry(cancellationToken).ConfigureAwait(false);
}
catch (EndOfStreamException)
{
// This indicates the end of the stream; the entry will remain null.
}
if (entry != null)
{
messageSink(entry);
}
else
{
break;
}
}
}
}
}
/// <inheritdoc/>
public void Reboot(string into, DeviceData device)
{
this.EnsureDevice(device);
var request = $"reboot:{into}";
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
socket.SendAdbRequest(request);
var response = socket.ReadAdbResponse();
}
}
/// <inheritdoc/>
public void Connect(DnsEndPoint endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest($"host:connect:{endpoint.Host}:{endpoint.Port}");
var response = socket.ReadAdbResponse();
}
}
/// <inheritdoc/>
public void Root(DeviceData device)
{
this.Root("root:", device);
}
/// <inheritdoc/>
public void Unroot(DeviceData device)
{
this.Root("unroot:", device);
}
/// <inheritdoc/>
protected void Root(string request, DeviceData device)
{
this.EnsureDevice(device);
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
socket.SendAdbRequest(request);
var response = socket.ReadAdbResponse();
// ADB will send some additional data
byte[] buffer = new byte[1024];
int read = socket.Read(buffer);
var responseMessage = Encoding.UTF8.GetString(buffer, 0, read);
// See https://android.googlesource.com/platform/system/core/+/master/adb/commandline.cpp#1026 (adb_root)
// for more information on how upstream does this.
if (!string.Equals(responseMessage, "restarting", StringComparison.OrdinalIgnoreCase))
{
throw new AdbException(responseMessage);
}
else
{
// Give adbd some time to kill itself and come back up.
// We can't use wait-for-device because devices (e.g. adb over network) might not come back.
Task.Delay(3000).GetAwaiter().GetResult();
}
}
}
/// <inheritdoc/>
public List<string> GetFeatureSet(DeviceData device)
{
using (var socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest($"host-serial:{device.Serial}:features");
var response = socket.ReadAdbResponse();
var features = socket.ReadString();
var featureList = features.Split(new char[] { '\n', ',' }).ToList();
return featureList;
}
}
/// <inheritdoc/>
public void Install(DeviceData device, Stream apk, params string[] arguments)
{
this.EnsureDevice(device);
if (apk == null)
{
throw new ArgumentNullException(nameof(apk));
}
if (!apk.CanRead || !apk.CanSeek)
{
throw new ArgumentOutOfRangeException(nameof(apk), "The apk stream must be a readable and seekable stream");
}
StringBuilder requestBuilder = new StringBuilder();
requestBuilder.Append("exec:cmd package 'install' ");
if (arguments != null)
{
foreach (var argument in arguments)
{
requestBuilder.Append(" ");
requestBuilder.Append(argument);
}
}
// add size parameter [required for streaming installs]
// do last to override any user specified value
requestBuilder.Append($" -S {apk.Length}");
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
this.SetDevice(socket, device);
socket.SendAdbRequest(requestBuilder.ToString());
var response = socket.ReadAdbResponse();
byte[] buffer = new byte[32 * 1024];
int read = 0;
while ((read = apk.Read(buffer, 0, buffer.Length)) > 0)
{
socket.Send(buffer, read);
}
read = socket.Read(buffer);
var value = Encoding.UTF8.GetString(buffer, 0, read);
if (!string.Equals(value, "Success\n"))
{
throw new AdbException(value);
}
}
}
public void Disconnect(DnsEndPoint endpoint)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
using (IAdbSocket socket = this.adbSocketFactory(this.EndPoint))
{
socket.SendAdbRequest($"host:disconnect:{endpoint.Host}:{endpoint.Port}");
var response = socket.ReadAdbResponse();
}
}
/// <summary>
/// Throws an <see cref="ArgumentNullException"/> if the <paramref name="device"/>
/// parameter is <see langword="null"/>, and a <see cref="ArgumentOutOfRangeException"/>
/// if <paramref name="device"/> does not have a valid serial number.
/// </summary>
/// <param name="device">
/// A <see cref="DeviceData"/> object to validate.
/// </param>
protected void EnsureDevice(DeviceData device)
{
if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
if (string.IsNullOrEmpty(device.Serial))
{
throw new ArgumentOutOfRangeException(nameof(device), "You must specific a serial number for the device");
}
}
}
}