-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathLispReplTcpServer.cs
More file actions
366 lines (313 loc) · 14.2 KB
/
Copy pathLispReplTcpServer.cs
File metadata and controls
366 lines (313 loc) · 14.2 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using ServiceStack.Logging;
using ServiceStack.Script;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack
{
public class LispReplTcpServer : IPlugin, IPreInitPlugin, IAfterInitAppHost, IDisposable, Model.IHasStringId
{
public string Id { get; set; } = Plugins.LispTcpServer;
private static ILog Log = LogManager.GetLogger(typeof(LispReplTcpServer));
private int port;
private IPAddress localIp;
public LispReplTcpServer() : this(IPAddress.Loopback, 5005) {}
public LispReplTcpServer(int port) : this(IPAddress.Loopback, port) {}
public LispReplTcpServer(string localIp, int port) : this(IPAddress.Parse(localIp), port) {}
private TcpListener listener;
public LispReplTcpServer(IPAddress localIp, int port)
{
this.port = port;
this.localIp = localIp ?? IPAddress.Loopback;
}
/// <summary>
/// Load the Lisp TCP Repl within this ScriptContext (falls back to SharpPagesFeature)
/// </summary>
public ScriptContext ScriptContext { get; set; }
/// <summary>
/// Whether to Require Config.AdminAuthSecret to Access REPL
/// </summary>
public bool RequireAuthSecret { get; set; }
/// <summary>
/// Additional Script Methods you want to add to the ScriptContext when Lisp TCP Repl is running
/// </summary>
public List<ScriptMethods> ScriptMethods { get; set; } = new List<ScriptMethods>();
/// <summary>
/// Additional Script Blocks you want to add to the ScriptContext when Lisp TCP Repl is running
/// </summary>
public List<ScriptBlock> ScriptBlocks { get; set; } = new List<ScriptBlock>();
/// <summary>
/// Scan Types and auto-register any Script Methods, Blocks and Code Pages
/// </summary>
public List<Type> ScanTypes { get; set; } = new List<Type>();
/// <summary>
/// Scan Assemblies and auto-register any Script Methods, Blocks and Code Pages
/// </summary>
public List<Assembly> ScanAssemblies { get; set; } = new List<Assembly>();
/// <summary>
/// Allow scripting of Types from specified Assemblies
/// </summary>
public List<Assembly> ScriptAssemblies { get; set; } = new List<Assembly>();
/// <summary>
/// Allow scripting of the specified Types
/// </summary>
public List<Type> ScriptTypes { get; set; } = new List<Type>();
/// <summary>
/// Lookup Namespaces for resolving Types in Scripts
/// </summary>
public List<string> ScriptNamespaces { get; set; } = new List<string>();
/// <summary>
/// Allow scripting of all Types in loaded Assemblies
/// </summary>
public bool? AllowScriptingOfAllTypes { get; set; }
public void BeforePluginsLoaded(IAppHost appHost)
{
if (ScriptContext == null)
ScriptContext = appHost.AssertPlugin<SharpPagesFeature>();
if (!ScriptContext.ScriptLanguages.Contains(ScriptLisp.Language))
ScriptContext.ScriptLanguages.Add(ScriptLisp.Language);
if (AllowScriptingOfAllTypes != null)
ScriptContext.AllowScriptingOfAllTypes = AllowScriptingOfAllTypes.Value;
if (!ScriptMethods.IsEmpty())
ScriptContext.ScriptMethods.AddRange(ScriptMethods);
if (!ScriptBlocks.IsEmpty())
ScriptContext.ScriptBlocks.AddRange(ScriptBlocks);
if (!ScanTypes.IsEmpty())
ScriptContext.ScanTypes.AddRange(ScanTypes);
if (!ScanAssemblies.IsEmpty())
ScriptContext.ScanAssemblies.AddRange(ScanAssemblies);
if (!ScriptAssemblies.IsEmpty())
ScriptContext.ScriptAssemblies.AddRange(ScriptAssemblies);
if (!ScriptTypes.IsEmpty())
ScriptContext.ScriptTypes.AddRange(ScriptTypes);
if (!ScriptNamespaces.IsEmpty())
ScriptContext.ScriptNamespaces.AddRange(ScriptNamespaces);
}
public void Register(IAppHost appHost)
{
if (RequireAuthSecret && string.IsNullOrEmpty(appHost.Config.AdminAuthSecret))
throw new NotSupportedException($"LISP REPL requires AuthSecret but Config.AdminAuthSecret is not configured");
}
public void AfterInit(IAppHost appHost) => Start();
private Thread bgThread = null;
object olock = new object();
public void Start()
{
if (bgThread != null)
Stop();
lock (olock)
{
Log.Info($"Starting LISP REPL on {localIp}:{port} ...");
listener = new TcpListener(localIp, port);
listener.Start();
bgThread = new Thread(StartListening) {
IsBackground = true,
Name = nameof(LispReplTcpServer) + " #" + Interlocked.Increment(ref serverStarts)
};
bgThread.Start();
}
}
private static int serverStarts;
private static int connections;
public void StartListening()
{
try
{
while (listener != null)
{
var client = listener?.AcceptTcpClient();
if (listener == null)
return;
if (Log.IsDebugEnabled)
Log.Debug("Waiting for connection");
var id = Interlocked.Increment(ref connections);
var remoteEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;
var remoteIp = remoteEndPoint.Address + ":" + remoteEndPoint.Port;
if (Log.IsDebugEnabled)
{
Log.Debug($"#{id} client connected from {remoteIp}!");
}
var thread = new Thread(() => HandleConnection(client, id, remoteIp)) {
IsBackground = true
};
thread.Start();
}
}
catch (Exception ex)
{
Log.Error($"{nameof(LispReplTcpServer)} TcpListener error: {ex.Message}", ex);
}
finally
{
Stop();
}
}
public void Stop()
{
lock (olock)
{
var hold = listener;
listener = null;
hold?.Stop();
KillBgThreadIfExists();
}
}
private void KillBgThreadIfExists()
{
if (bgThread != null && bgThread.IsAlive)
{
//give it a small chance to die gracefully
if (!bgThread.Join(500))
{
#if !NETCORE
//Ideally we shouldn't get here, but lets try our hardest to clean it up
Log.Warn("Interrupting previous Background Thread: " + bgThread.Name);
bgThread.Interrupt();
if (!bgThread.Join(TimeSpan.FromSeconds(3)))
{
Log.Warn(bgThread.Name + " just wont die, so we're now aborting it...");
bgThread.Abort();
}
#endif
}
bgThread = null;
}
}
public void Dispose() => Stop();
private void HandleConnection(TcpClient client, int id, string remoteIp)
{
try
{
using (client)
{
var interp = Lisp.CreateInterpreter();
var CMD_CLEAR = "\u001B[2J";
var sb = new StringBuilder();
var networkStream = client.GetStream();
var remoteUrl = $"tcp://{remoteIp}";
void write(string msg) => MemoryProvider.Instance.Write(networkStream, msg.AsMemory());
using (var reader = new StreamReader(networkStream, Encoding.UTF8))
{
string line;
if (RequireAuthSecret)
{
MemoryProvider.Instance.Write(networkStream,
$"Authentication required:\n> ".AsMemory());
line = reader.ReadLine();
var authSuccess = !string.IsNullOrEmpty(line) && line == HostContext.Config.AdminAuthSecret;
if (!authSuccess)
{
write($"Authentication failed.\n\n");
client.Close();
return;
}
write(CMD_CLEAR);
}
MemoryProvider.Instance.Write(networkStream,
$"\nWelcome to #Script Lisp! The Server time is: {DateTime.Now.ToShortTimeString()}, type ? for help.\n\n".AsMemory());
while (true)
{
if (listener == null)
return;
prompt:
write("> ");
sb.Clear();
while ((line = reader.ReadLine()) != null)
{
if (line == "quit" || line == "exit")
{
write($"Goodbye.\n\n");
client.Close();
return;
}
if (line == "verbose")
{
var toggle = interp.GetSymbolValue("verbose") is bool v && v
? null
: Lisp.TRUE;
interp.SetSymbolValue("verbose", toggle);
var mode = toggle != null ? "on" : "off";
write($"verbose mode {mode}\n\n");
goto prompt;
}
if (line == "mode")
{
var toggle = interp.GetSymbolValue("multi-line") is bool v && v
? null
: Lisp.TRUE;
interp.SetSymbolValue("multi-line", toggle);
var mode = toggle != null ? "off" : "on";
write($"single-line mode {mode}\n\n");
goto prompt;
}
if (line == "clear")
{
write(CMD_CLEAR);
goto prompt;
}
if (line == "?")
{
var usage = @"
; verbose - toggle output to indent complex responses
; mode - toggle between single and multi-line modes
; clear - clear screen
; quit - exit session
Learn more about #Script Lisp at: https://sharpscript.net/lisp
";
write(usage);
goto prompt;
}
sb.AppendLine(line);
var multiLine = interp.GetSymbolValue("multi-line");
if (multiLine == null || multiLine is bool b && !b)
break;
if (line == "") // evaluate on empty new line
break;
}
var lisp = sb.ToString();
if (lisp.Trim().Length == 0)
continue;
string output = null;
try
{
var requestArgs = CreateBasicRequest(remoteUrl);
output = interp.ReplEval(ScriptContext, networkStream, lisp, requestArgs);
}
catch (Exception e)
{
var str = (e.InnerException ?? e) + "\n";
MemoryProvider.Instance.Write(networkStream, str.AsMemory());
}
if (!string.IsNullOrEmpty(output))
{
MemoryProvider.Instance.Write(networkStream, output.AsMemory());
MemoryProvider.Instance.Write(networkStream, "\n\n".AsMemory());
networkStream.Flush();
}
}
}
}
}
catch (Exception ex)
{
if (Log.IsDebugEnabled)
Log.Debug($"{remoteIp} connection was disconnected. " + ex.Message);
}
}
private Dictionary<string, object> CreateBasicRequest(string remoteUrl)
{
var requestArgs = SharpPagesFeatureExtensions.CreateRequestArgs(new Dictionary<string, object> {
[ScriptConstants.BaseUrl] = $"tcp://{localIp}:{port}/",
[nameof(IRequest.UrlReferrer)] = remoteUrl,
});
return requestArgs;
}
}
}