Repository navigation
Expand file tree
/
Copy pathAdbSocket.cs
More file actions
612 lines (540 loc) · 20.7 KB
/
Copy pathAdbSocket.cs
File metadata and controls
612 lines (540 loc) · 20.7 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
// <copyright file="AdbSocket.cs" company="The Android Open Source Project, Ryan Conrad, Quamotion, yungd1plomat, wherewhere">
// Copyright (c) The Android Open Source Project, Ryan Conrad, Quamotion, yungd1plomat, wherewhere. All rights reserved.
// </copyright>
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
namespace AdvancedSharpAdbClient
{
/// <summary>
/// <para>Implements a client for the Android Debug Bridge client-server protocol. Using the client, you
/// can send messages to and receive messages from the Android Debug Bridge.</para>
/// <para>The <see cref="AdbSocket"/> class implements the raw messaging protocol; that is,
/// sending and receiving messages. For interacting with the services the Android Debug
/// Bridge exposes, use the <see cref="AdbClient"/>.</para>
/// <para>For more information about the protocol that is implemented here, see chapter
/// II Protocol Details, section 1. Client <->Server protocol at
/// <see href="https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/dev/overview.md"/>.</para>
/// </summary>
/// <param name="socket">The <see cref="ITcpSocket"/> at which the Android Debug Bridge is listening for clients.</param>
/// <param name="logger">The logger to use when logging.</param>
[DebuggerDisplay($"{{{nameof(GetType)}().{nameof(Type.ToString)}(),nq}} \\{{ {nameof(Connected)} = {{{nameof(Connected)}}}, {nameof(Socket)} = {{{nameof(Socket)}}} }}")]
public partial class AdbSocket(ITcpSocket socket, ILogger<AdbSocket>? logger = null) : IAdbSocket, ICloneable<AdbSocket>, ICloneable
{
/// <summary>
/// The logger to use when logging messages.
/// </summary>
private readonly ILogger<AdbSocket> logger = logger ?? LoggerProvider.CreateLogger<AdbSocket>();
/// <summary>
/// Initializes a new instance of the <see cref="AdbSocket"/> class.
/// </summary>
/// <param name="logger">The logger to use when logging.</param>
public AdbSocket(ILogger<AdbSocket>? logger = null)
: this(AdbClient.AdbServerEndPoint, logger)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AdbSocket"/> class.
/// </summary>
/// <param name="endPoint">The <see cref="EndPoint"/> at which the Android Debug Bridge is listening for clients.</param>
/// <param name="logger">The logger to use when logging.</param>
public AdbSocket(EndPoint endPoint, ILogger<AdbSocket>? logger = null)
: this(CreateTcpSocket(endPoint), logger)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AdbSocket"/> class.
/// </summary>
/// <param name="host">The host address at which the Android Debug Bridge is listening for clients.</param>
/// <param name="port">The port at which the Android Debug Bridge is listening for clients.</param>
/// <param name="logger">The logger to use when logging.</param>
public AdbSocket(string host, int port, ILogger<AdbSocket>? logger = null)
: this(Extensions.CreateDnsEndPoint(host, port), logger)
{
}
/// <summary>
/// Gets or sets the size of the receive buffer
/// </summary>
public static int ReceiveBufferSize { get; set; } = 40960;
/// <summary>
/// Gets or sets the size of the write buffer.
/// </summary>
public static int WriteBufferSize { get; set; } = 1024;
/// <summary>
/// Gets the underlying TCP socket that manages the connection with the ADB server.
/// </summary>
public ITcpSocket Socket { get; } = socket ?? throw new ArgumentNullException(nameof(socket));
/// <summary>
/// Determines whether the specified reply is okay.
/// </summary>
/// <param name="reply">The reply.</param>
/// <returns><see langword="true"/> if the specified reply is okay; otherwise, <see langword="false"/>.</returns>
public static bool IsOkay(byte[] reply) => AdbClient.Encoding.GetString(reply).Equals("OKAY");
#if HAS_BUFFERS
/// <summary>
/// Determines whether the specified reply is okay.
/// </summary>
/// <param name="reply">The reply.</param>
/// <returns><see langword="true"/> if the specified reply is okay; otherwise, <see langword="false"/>.</returns>
public static bool IsOkay(scoped ReadOnlySpan<byte> reply) => AdbClient.Encoding.GetString(reply).Equals("OKAY");
#endif
/// <inheritdoc/>
public bool Connected => Socket.Connected;
/// <inheritdoc/>
public void Reconnect(bool isForce = false) => Socket.Reconnect(isForce);
/// <inheritdoc/>
public virtual void Send(byte[] data)
{
try
{
int count = Socket.Send(data, SocketFlags.None);
if (count < 0)
{
throw new AdbException("channel EOF");
}
}
catch (SocketException sex)
{
logger.LogError(sex, sex.Message);
throw;
}
}
/// <inheritdoc/>
public virtual void Send(byte[] data, int length)
{
try
{
int count = Socket.Send(data, length != -1 ? length : data.Length, SocketFlags.None);
if (count < 0)
{
throw new AdbException("channel EOF");
}
}
catch (SocketException sex)
{
logger.LogError(sex, sex.Message);
throw;
}
}
/// <inheritdoc/>
public virtual void Send(byte[] data, int offset, int length)
{
try
{
int count = Socket.Send(data, offset, length != -1 ? length : data.Length, SocketFlags.None);
if (count < 0)
{
throw new AdbException("channel EOF");
}
}
catch (SocketException sex)
{
logger.LogError(sex, sex.Message);
throw;
}
}
/// <inheritdoc/>
public void SendSyncRequest(SyncCommand command, UnixFileStatus permissions, SyncFlags flags)
{
byte[] commandBytes = command.GetBytes();
byte[] modeBytes = BitConverter.GetBytes((uint)permissions.GetPermissions());
byte[] flagsBytes = BitConverter.GetBytes((int)flags);
if (!BitConverter.IsLittleEndian)
{
// Convert from big endian to little endian
Array.Reverse(modeBytes);
Array.Reverse(flagsBytes);
}
_ = Write(commandBytes);
_ = Write(modeBytes);
_ = Write(flagsBytes);
}
/// <inheritdoc/>
public void SendSyncRequest(SyncCommand command, string path, UnixFileStatus permissions) =>
SendSyncRequest(command, $"{path},{(int)permissions.GetPermissions()}");
/// <inheritdoc/>
public void SendSyncRequest(SyncCommand command, string path)
{
ArgumentNullException.ThrowIfNull(path);
byte[] pathBytes = AdbClient.Encoding.GetBytes(path);
SendSyncRequest(command, pathBytes.Length);
_ = Write(pathBytes);
}
/// <inheritdoc/>
public void SendSyncRequest(SyncCommand command, int value)
{
// The message structure is:
// First four bytes: command
// Next four bytes: length of the path
// Final bytes: path
byte[] commandBytes = command.GetBytes();
byte[] lengthBytes = BitConverter.GetBytes(value);
if (!BitConverter.IsLittleEndian)
{
// Convert from big endian to little endian
Array.Reverse(lengthBytes);
}
_ = Write(commandBytes);
_ = Write(lengthBytes);
}
/// <inheritdoc/>
public void SendAdbRequest(string request)
{
byte[] data = AdbClient.FormAdbRequest(request);
if (!Write(data))
{
throw new IOException($"Failed sending the request '{request}' to ADB");
}
}
#if NET10_0_OR_GREATER
/// <inheritdoc/>
public void SendAdbRequest(scoped DefaultInterpolatedStringHandler request)
{
byte[] data = AdbClient.FormAdbRequest(request.Text);
if (!Write(data))
{
throw new IOException($"Failed sending the request '{request.Text}' to ADB");
}
}
#endif
/// <inheritdoc/>
public virtual int Read(byte[] data) => Read(data, 0, data.Length);
/// <inheritdoc/>
public virtual int Read(byte[] data, int length) => Read(data, 0, length);
/// <inheritdoc/>
public virtual int Read(byte[] data, int offset, int length)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentOutOfRangeException.ThrowIfNegative(offset);
length = length != -1 ? length : data.Length;
ArgumentOutOfRangeException.ThrowIfLessThan(data.Length, length, nameof(data));
int count = -1;
int totalRead = offset;
while (count != 0 && totalRead < length)
{
try
{
int left = length - totalRead;
int bufferLength = left < ReceiveBufferSize ? left : ReceiveBufferSize;
count = Socket.Receive(data, totalRead, bufferLength, SocketFlags.None);
if (count < 0)
{
logger.LogError("read: channel EOF");
throw new AdbException("EOF");
}
else if (count == 0)
{
logger.LogInformation("DONE with Read");
}
else
{
totalRead += count;
}
}
catch (SocketException ex)
{
throw new AdbException($"An error occurred while receiving data from the adb server: {ex.Message}.", ex);
}
}
return totalRead;
}
/// <inheritdoc/>
public virtual string ReadString()
{
start:
// The first 4 bytes contain the length of the string
byte[] reply = new byte[4];
int read = Read(reply);
if (read == 0)
{
// There is no data to read
return string.Empty;
}
// Convert the bytes to a hex string
string lenHex = AdbClient.Encoding.GetString(reply);
if (int.TryParse(lenHex, NumberStyles.HexNumber, null, out int len))
{
// And get the string
reply = new byte[len];
_ = Read(reply);
string value = AdbClient.Encoding.GetString(reply);
return value;
}
else
{
goto start;
}
}
/// <inheritdoc/>
public virtual string ReadSyncString()
{
// The first 4 bytes contain the length of the string
byte[] reply = new byte[4];
int read = Read(reply);
if (read == 0)
{
// There is no data to read
return string.Empty;
}
// Get the length of the string
int len = BitConverter.ToInt32(reply);
// And get the string
reply = new byte[len];
_ = Read(reply);
string value = AdbClient.Encoding.GetString(reply);
return value;
}
/// <inheritdoc/>
public SyncCommand ReadSyncResponse()
{
byte[] data = new byte[4];
_ = Read(data);
return SyncCommandConverter.GetCommand(data);
}
/// <inheritdoc/>
public AdbResponse ReadAdbResponse()
{
AdbResponse response = ReadAdbResponseInner();
if (!response.IOSuccess || !response.Okay)
{
Socket.Dispose();
throw new AdbException($"An error occurred while reading a response from ADB: {response.Message}", response);
}
return response;
}
#if COMP_NETSTANDARD2_1
/// <inheritdoc/>
public virtual void Send(scoped ReadOnlySpan<byte> data)
{
try
{
int count = Socket.Send(data, SocketFlags.None);
if (count < 0)
{
throw new AdbException("channel EOF");
}
}
catch (SocketException sex)
{
logger.LogError(sex, sex.Message);
throw;
}
}
/// <inheritdoc/>
public virtual int Read(scoped Span<byte> data)
{
int count = -1;
int totalRead = 0;
int length = data.Length;
while (count != 0 && totalRead < length)
{
try
{
int left = length - totalRead;
int bufferLength = left < ReceiveBufferSize ? left : ReceiveBufferSize;
count = Socket.Receive(data.Slice(totalRead, bufferLength), SocketFlags.None);
if (count < 0)
{
logger.LogError("read: channel EOF");
throw new AdbException("EOF");
}
else if (count == 0)
{
logger.LogInformation("DONE with Read");
}
else
{
totalRead += count;
}
}
catch (SocketException ex)
{
throw new AdbException($"An error occurred while receiving data from the adb server: {ex.Message}.", ex);
}
}
return totalRead;
}
#endif
/// <inheritdoc/>
public virtual Stream GetShellStream()
{
Stream stream = Socket.GetStream();
return new ShellStream(stream, closeStream: true);
}
/// <inheritdoc/>
public void SetDevice(DeviceData device)
{
// if the device is not null, then we first tell adb we're looking to talk
// to a specific device
if (!device.IsEmpty)
{
if (uint.TryParse(device.TransportId, out uint tid))
{
SendAdbRequest($"host:transport-id:{tid}");
}
else
{
SendAdbRequest($"host:transport:{device.Serial}");
}
try
{
AdbResponse response = ReadAdbResponse();
}
catch (AdbException e)
{
if (string.Equals("device not found", e.AdbError, StringComparison.OrdinalIgnoreCase))
{
throw new DeviceNotFoundException(device.Serial);
}
else
{
throw;
}
}
}
}
/// <summary>
/// Write until all data in "data" is written or the connection fails or times out.
/// </summary>
/// <param name="data">The data to send.</param>
/// <returns>Returns <see langword="true"/> if all data was written; otherwise, <see langword="false"/>.</returns>
/// <remarks>This uses the default time out value.</remarks>
protected virtual bool Write(byte[] data)
{
try
{
Send(data);
}
catch (IOException e)
{
logger.LogError(e, e.Message);
return false;
}
return true;
}
#if COMP_NETSTANDARD2_1
/// <summary>
/// Write until all data in "data" is written or the connection fails or times out.
/// </summary>
/// <param name="data">The data to send.</param>
/// <returns>Returns <see langword="true"/> if all data was written; otherwise, <see langword="false"/>.</returns>
/// <remarks>This uses the default time out value.</remarks>
protected virtual bool Write(scoped ReadOnlySpan<byte> data)
{
try
{
Send(data);
}
catch (IOException e)
{
logger.LogError(e, e.Message);
return false;
}
return true;
}
#endif
/// <summary>
/// Reads the response from ADB after a command.
/// </summary>
/// <returns>A <see cref="AdbResponse"/> that represents the response received from ADB.</returns>
protected virtual AdbResponse ReadAdbResponseInner()
{
byte[] reply = new byte[4];
Read(reply);
if (IsOkay(reply))
{
return AdbResponse.OK;
}
else
{
string message = ReadString();
logger.LogError("Got reply '{0}', diag='{1}'", ReplyToString(reply), message);
return AdbResponse.FromError(message);
}
}
/// <summary>
/// Converts an ADB reply to a string.
/// </summary>
/// <param name="reply">A <see cref="byte"/> array that represents the ADB reply.</param>
/// <returns>A <see cref="string"/> that represents the ADB reply.</returns>
protected string ReplyToString(byte[] reply)
{
string result;
try
{
result = AdbClient.Encoding.GetString(reply);
}
catch (DecoderFallbackException e)
{
logger.LogError(e, e.Message);
result = string.Empty;
}
return result;
}
#if HAS_BUFFERS
/// <summary>
/// Converts an ADB reply to a string.
/// </summary>
/// <param name="reply">A <see cref="byte"/> array that represents the ADB reply.</param>
/// <returns>A <see cref="string"/> that represents the ADB reply.</returns>
protected string ReplyToString(scoped ReadOnlySpan<byte> reply)
{
string result;
try
{
result = AdbClient.Encoding.GetString(reply);
}
catch (DecoderFallbackException e)
{
logger.LogError(e, e.Message);
result = string.Empty;
}
return result;
}
#endif
/// <summary>
/// Releases all resources used by the current instance of the <see cref="AdbSocket"/> class.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Socket.Dispose();
}
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
/// <inheritdoc/>
public override string ToString() => $"{GetType()} {{ {nameof(Socket)} = {Socket} }}";
/// <inheritdoc/>
public void Close() => Socket.Dispose();
/// <inheritdoc/>
public virtual AdbSocket Clone() =>
Socket is ICloneable<ITcpSocket> cloneable
? new AdbSocket(cloneable.Clone(), logger)
: throw new NotSupportedException($"{Socket.GetType()} does not support cloning.");
/// <inheritdoc/>
object ICloneable.Clone() => Clone();
/// <summary>
/// Creates a new <see cref="TcpSocket"/> instance based on the specified <see cref="EndPoint"/>.
/// </summary>
/// <param name="endPoint">The <see cref="EndPoint"/> at which the Android Debug Bridge is listening for clients.</param>
/// <returns>The new <see cref="TcpSocket"/> instance.</returns>
private static TcpSocket CreateTcpSocket(EndPoint endPoint)
{
TcpSocket socket = new();
socket.Connect(endPoint);
socket.ReceiveBufferSize = ReceiveBufferSize;
return socket;
}
}
}