-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathV8DebugAgent.cs
More file actions
336 lines (293 loc) · 12 KB
/
V8DebugAgent.cs
File metadata and controls
336 lines (293 loc) · 12 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ClearScript.Properties;
using Microsoft.ClearScript.Util;
using Microsoft.ClearScript.Util.Web;
namespace Microsoft.ClearScript.V8
{
internal sealed class V8DebugAgent : IDisposable
{
#region data
private const string faviconUrl = "https://clearscript.clearfoundry.net/favicon.png";
private readonly Guid targetId = Guid.NewGuid();
private readonly string name;
private readonly string version;
private readonly int port;
private readonly IV8DebugListener listener;
private TcpListener tcpListener;
private V8DebugClient activeClient;
private readonly InterlockedOneWayFlag disposedFlag = new();
#endregion
#region constructors
public V8DebugAgent(string name, string version, int port, bool remote, IV8DebugListener listener)
{
this.name = name;
this.version = version;
this.port = port;
this.listener = listener;
var started = false;
if (remote)
{
started = MiscHelpers.Try(
static ctx =>
{
ctx.self.tcpListener = new TcpListener(IPAddress.Any, ctx.port);
ctx.self.tcpListener.Start();
},
(self: this, port)
);
}
if (!started)
{
started = MiscHelpers.Try(
static ctx =>
{
ctx.self.tcpListener = new TcpListener(IPAddress.Loopback, ctx.port);
ctx.self.tcpListener.Start();
},
(self: this, port)
);
}
if (started)
{
StartAcceptWebClient();
}
}
#endregion
#region public members
public void SendCommand(V8DebugClient client, string command)
{
if (client == activeClient)
{
listener.SendCommand(command);
}
}
public void SendMessage(string message)
{
if (!disposedFlag.IsSet)
{
var client = activeClient;
client?.SendMessage(message);
}
}
public void OnClientFailed(V8DebugClient client)
{
if (Interlocked.CompareExchange(ref activeClient, null, client) == client)
{
listener.DisconnectClient();
ThreadPool.QueueUserWorkItem(_ => V8Runtime.OnDebuggerDisconnected(new V8RuntimeDebuggerEventArgs(name, port)));
}
}
#endregion
#region Web endpoint
private void StartAcceptWebClient()
{
tcpListener.AcceptSocketAsync().ContinueWith(OnWebClientAccepted);
}
private void OnWebClientAccepted(Task<Socket> task)
{
var succeeded = MiscHelpers.Try(out var socket, static task => task.Result, task);
if (!disposedFlag.IsSet)
{
if (succeeded)
{
WebContext.CreateAsync(socket).ContinueWith(OnWebContextCreated);
}
StartAcceptWebClient();
}
}
private void OnWebContextCreated(Task<WebContext> task)
{
if (MiscHelpers.Try(out var webContext, static task => task.Result, task) && !disposedFlag.IsSet)
{
if (!webContext.Request.IsWebSocketRequest)
{
HandleWebRequest(webContext);
}
else if (!webContext.Request.RawUrl.Equals("/" + targetId, StringComparison.OrdinalIgnoreCase))
{
webContext.Response.Close(404);
}
else
{
StartAcceptWebSocket(webContext);
}
}
}
private void HandleWebRequest(WebContext webContext)
{
// https://github.com/buggerjs/bugger-daemon/blob/master/README.md#api,
// https://github.com/nodejs/node/blob/master/src/inspector_socket_server.cc
if (webContext.Request.RawUrl.Equals("/json", StringComparison.OrdinalIgnoreCase) ||
webContext.Request.RawUrl.Equals("/json/list", StringComparison.OrdinalIgnoreCase))
{
if (activeClient is not null)
{
SendWebResponse(webContext, MiscHelpers.FormatInvariant(
"[ {{\r\n" +
" \"id\": \"{0}\",\r\n" +
" \"type\": \"node\",\r\n" +
" \"description\": \"ClearScript V8 runtime: {1}\",\r\n" +
" \"title\": \"{2}\",\r\n" +
" \"url\": \"{3}\",\r\n" +
" \"faviconUrl\": \"{4}\"\r\n" +
"}} ]\r\n",
targetId,
JsonEscape(name),
JsonEscape(AppDomain.CurrentDomain.FriendlyName),
JsonEscape(new Uri(Process.GetCurrentProcess().MainModule.FileName)),
faviconUrl
));
}
else
{
SendWebResponse(webContext, MiscHelpers.FormatInvariant(
"[ {{\r\n" +
" \"id\": \"{0}\",\r\n" +
" \"type\": \"node\",\r\n" +
" \"description\": \"ClearScript V8 runtime: {1}\",\r\n" +
" \"title\": \"{2}\",\r\n" +
" \"url\": \"{3}\",\r\n" +
" \"faviconUrl\": \"{6}\",\r\n" +
" \"devtoolsFrontendUrl\": \"devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws={4}:{5}/{0}\",\r\n" +
" \"devtoolsFrontendUrlCompat\": \"devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws={4}:{5}/{0}\",\r\n" +
" \"webSocketDebuggerUrl\": \"ws://{4}:{5}/{0}\"\r\n" +
"}} ]\r\n",
targetId,
JsonEscape(name),
JsonEscape(AppDomain.CurrentDomain.FriendlyName),
JsonEscape(new Uri(Process.GetCurrentProcess().MainModule.FileName)),
webContext.Request.Uri.Host,
webContext.Request.Uri.Port,
faviconUrl
));
}
}
else if (webContext.Request.RawUrl.Equals("/json/version", StringComparison.OrdinalIgnoreCase))
{
SendWebResponse(webContext, MiscHelpers.FormatInvariant(
"{{\r\n" +
" \"Browser\": \"ClearScript/v{0}, V8 {1}\",\r\n" +
" \"Protocol-Version\": \"1.1\"\r\n" +
"}}\r\n",
ClearScriptVersion.Informational,
version
));
}
else if (webContext.Request.RawUrl.StartsWith("/json/activate/", StringComparison.OrdinalIgnoreCase))
{
var requestTargetId = webContext.Request.RawUrl.Substring(15);
if (requestTargetId.Equals(targetId.ToString(), StringComparison.OrdinalIgnoreCase))
{
SendWebResponse(webContext, "Target activated", "text/plain");
}
else
{
SendWebResponse(webContext, "No such target id: " + requestTargetId, "text/plain", 404);
}
}
else if (webContext.Request.RawUrl.StartsWith("/json/close/", StringComparison.OrdinalIgnoreCase))
{
var requestTargetId = webContext.Request.RawUrl.Substring(12);
if (requestTargetId.Equals(targetId.ToString(), StringComparison.OrdinalIgnoreCase))
{
SendWebResponse(webContext, "Target is closing", "text/plain");
}
else
{
SendWebResponse(webContext, "No such target id: " + requestTargetId, "text/plain", 404);
}
}
else if (webContext.Request.RawUrl.StartsWith("/json/new?", StringComparison.OrdinalIgnoreCase) ||
webContext.Request.RawUrl.Equals("/json/protocol", StringComparison.OrdinalIgnoreCase))
{
webContext.Response.Close(501);
}
else
{
webContext.Response.Close(404);
}
}
#endregion
#region WebSocket client connection
private void StartAcceptWebSocket(WebContext webContext)
{
webContext.AcceptWebSocketAsync().ContinueWith(task => OnWebSocketAccepted(webContext, task));
}
private void OnWebSocketAccepted(WebContext webContext, Task<WebSocket> task)
{
if (MiscHelpers.Try(out var webSocket, static task => task.Result, task))
{
if (!ConnectClient(webSocket))
{
webSocket.Close(WebSocket.ErrorCode.PolicyViolation, "A debugger is already connected");
}
}
else
{
webContext.Response.Close(500);
}
}
private bool ConnectClient(WebSocket webSocket)
{
var client = new V8DebugClient(this, webSocket);
if (Interlocked.CompareExchange(ref activeClient, client, null) is null)
{
listener.ConnectClient();
client.Start();
ThreadPool.QueueUserWorkItem(_ => V8Runtime.OnDebuggerConnected(new V8RuntimeDebuggerEventArgs(name, port)));
return true;
}
return false;
}
private void DisconnectClient(WebSocket.ErrorCode errorCode, string message)
{
var client = Interlocked.Exchange(ref activeClient, null);
if (client is not null)
{
client.Dispose(errorCode, message);
listener.DisconnectClient();
ThreadPool.QueueUserWorkItem(_ => V8Runtime.OnDebuggerDisconnected(new V8RuntimeDebuggerEventArgs(name, port)));
}
}
#endregion
#region IDisposable implementation
public void Dispose()
{
if (disposedFlag.Set())
{
if (tcpListener is not null)
{
MiscHelpers.Try(static tcpListener => tcpListener.Stop(), tcpListener);
}
DisconnectClient(WebSocket.ErrorCode.EndpointUnavailable, "The V8 runtime has been destroyed");
listener.Dispose();
}
}
#endregion
#region protocol utilities
private static void SendWebResponse(WebContext webContext, string content, string contentType = "application/json", int statusCode = 200)
{
using (webContext.Response)
{
var contentBytes = Encoding.UTF8.GetBytes(content);
webContext.Response.ContentType = contentType + "; charset=UTF-8";
webContext.Response.OutputStream.Write(contentBytes, 0, contentBytes.Length);
webContext.Response.StatusCode = statusCode;
}
}
private static string JsonEscape(object value)
{
return new string(value.ToString().Select(ch => ((ch == '\"') || (ch == '\\')) ? '_' : ch).ToArray());
}
#endregion
}
}