forked from Duet3D/DuetSoftwareFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
343 lines (321 loc) · 14.5 KB
/
Program.cs
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
using DuetAPI.Commands;
using DuetAPI.Connection;
using DuetAPI.Machine;
using DuetAPIClient;
using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace CustomHttpEndpoint
{
public static class Program
{
/// <summary>
/// HTTP method to provide
/// </summary>
private static HttpEndpointType _method = HttpEndpointType.GET;
/// <summary>
/// Command binary to start when an HTTP query is received
/// </summary>
private static string _cmd = null;
/// <summary>
/// Command arguments for the binary to start
/// </summary>
private static string _args = null;
/// <summary>
/// True if no info texts are printed
/// </summary>
private static bool _quiet = false;
/// <summary>
/// Entry point
/// </summary>
/// <param name="args">Command-line arguments</param>
/// <returns>Asynchronous task</returns>
public static async Task Main(string[] args)
{
// Parse the command line arguments
string lastArg = null, socketPath = Defaults.FullSocketPath, ns = "custom-http-endpoint", path = "demo";
foreach (string arg in args)
{
if (lastArg == "-s" || lastArg == "--socket")
{
socketPath = arg;
}
else if (lastArg == "-m" || lastArg == "--method")
{
if (!Enum.TryParse(arg, true, out _method))
{
Console.WriteLine("Error: Invalid HTTP method");
return;
}
}
else if (lastArg == "-n" || lastArg == "--namespace")
{
ns = arg;
}
else if (lastArg == "-p" || lastArg == "--path")
{
path = arg;
}
else if (lastArg == "-e" || lastArg == "--exec")
{
_cmd = arg;
}
else if (lastArg == "-a" || lastArg == "--args")
{
_args = arg;
}
else if (arg == "-q" || lastArg == "--quiet")
{
_quiet = true;
}
else if (arg == "-h" || arg == "--help")
{
Console.WriteLine("Create a custom HTTP endpoint in the format /machine/{namespace}/{path}");
Console.WriteLine("Available command line options:");
Console.WriteLine("-s, --socket <socket>: UNIX socket to connect to");
Console.WriteLine("-m, --method [GET, POST, PUT, PATCH, TRACE, DELETE, OPTIONS, WebSocket]: HTTP method to use (defaults to GET)");
Console.WriteLine("-n, --namespace <namespace>: Namespace to use (defaults to custom-http-endpoint)");
Console.WriteLine("-p, --path <path>: HTTP query path (defaults to demo)");
Console.WriteLine("-e, --exec <executable>: Command to execute when an HTTP query is received, stdout and stderr are returned as the response body");
Console.WriteLine("-a, --args <arguments>: Arguments for the executable command. Query values in % chars are replaced with query options (e.g. %myvalue%). Not applicable for WebSockets");
Console.WriteLine("-q, --quiet: Do not display info text");
Console.WriteLine("-h, --help: Displays this text");
return;
}
lastArg = arg;
}
if (_method == HttpEndpointType.WebSocket && (!string.IsNullOrWhiteSpace(_cmd) || !string.IsNullOrWhiteSpace(_args)))
{
Console.WriteLine("Error: Cannot use --exec parameter if method equals WebSocket");
}
// Create a new Command connection
CommandConnection connection = new CommandConnection();
await connection.Connect(socketPath);
// Create a new HTTP GET endpoint and keep listening for new requests
try
{
using HttpEndpointUnixSocket socket = await connection.AddHttpEndpoint(_method, ns, path);
socket.OnEndpointRequestReceived += OnHttpRequestReceived;
// Display a message
if (!_quiet)
{
Console.WriteLine("{0} endpoint has been created and is now accessible via /machine/{1}/{2}", _method, ns, path);
if (_method == HttpEndpointType.WebSocket)
{
Console.WriteLine("IO from the first WebSocket connection will be redirected to stdio. Additional connections will be automatically closed.");
}
else if (string.IsNullOrWhiteSpace(_cmd))
{
Console.WriteLine("Press RETURN to close this program again");
}
}
// Wait forever (or for Ctrl+C) in WebSocket mode or for the user to press RETURN in interactive REST mode.
// If the connection is terminated while waiting, continue as well
if (_method == HttpEndpointType.WebSocket || string.IsNullOrWhiteSpace(_cmd))
{
Task primaryTask = (_method == HttpEndpointType.WebSocket) ? Task.Delay(-1) : Task.Run(() => Console.ReadLine());
await Task.WhenAny(primaryTask, PollConnection(connection));
}
}
catch (SocketException)
{
// You may want to try to unregister your endpoint here and try again...
Console.WriteLine("Failed to create new HTTP socket. Perhaps another instance of this program is already running?");
}
finally
{
if (connection.IsConnected)
{
// Remove the endpoint again when the plugin is being unloaded
await connection.RemoveHttpEndpoint(_method, ns, path);
}
}
}
/// <summary>
/// Poll the connection every two seconds to notice if the server has closed the connection
/// </summary>
/// <param name="connection">Connection to poll</param>
/// <returns>Asynchronous task</returns>
private static async Task PollConnection(BaseConnection connection)
{
try
{
do
{
await Task.Delay(2000);
connection.Poll();
}
while (true);
}
catch (SocketException)
{
Console.WriteLine("Server has closed the connection");
throw new OperationCanceledException();
}
}
/// <summary>
/// Indicates if a connection is alive
/// </summary>
private static bool _websocketConnected = false;
/// <summary>
/// Called when a new HTTP or WebSocket request has been received
/// </summary>
/// <param name="unixSocket">UNIX socket for HTTP endpoints</param>
/// <param name="requestConnection">Connection from the UNIX socket representing the HTTP or WebSocket request</param>
private static async void OnHttpRequestReceived(HttpEndpointUnixSocket unixSocket, HttpEndpointConnection requestConnection)
{
// Note that a call to ReadRequest can throw an exception in case DCS only created a test connection!
// DCS may do that when an application attempts to register an existing endpoint twice
if (_method == HttpEndpointType.WebSocket)
{
if (_websocketConnected)
{
await requestConnection.SendResponse(1000, "Demo application only supports one WebSocket connection");
return;
}
_websocketConnected = true;
if (!_quiet)
{
Console.WriteLine("WebSocket connected, type 'close' to close this connection");
}
try
{
using CancellationTokenSource cts = new CancellationTokenSource();
Task webSocketTask = ReadFromWebSocket(requestConnection, cts.Token);
Task consoleTask = ReadFromConsole(requestConnection, cts.Token);
await Task.WhenAny(webSocketTask, consoleTask);
cts.Cancel();
}
catch (Exception e)
{
if (!(e is OperationCanceledException) && !(e is SocketException))
{
Console.WriteLine("Unexpected error:");
Console.WriteLine(e);
}
}
finally
{
_websocketConnected = false;
if (!_quiet)
{
Console.WriteLine("WebSocket disconnected");
}
}
}
else
{
// Read the HTTP response from the client
ReceivedHttpRequest request = await requestConnection.ReadRequest();
if (string.IsNullOrWhiteSpace(_cmd))
{
// Write this event to the console if possible
if (!_quiet)
{
Console.WriteLine("Got new HTTP request from session {0}", request.SessionId);
}
// Only print a demo response in case no process is supposed to be started
string response = $"This demo text has been returned from a third-party application.\n\nMethod: {_method}\nSession ID: {request.SessionId}";
if (request.Headers.Count > 0)
{
response += "\n\nHeaders:";
foreach (var kv in request.Headers)
{
response += $"\n{kv.Key} = {kv.Value}";
}
}
if (request.Queries.Count > 0)
{
response += "\n\nQueries:";
foreach (var kv in request.Queries)
{
response += $"\n{kv.Key} = {kv.Value}";
}
}
if (!string.IsNullOrWhiteSpace(request.Body))
{
response += "\n\nBody:\n" + request.Body;
}
await requestConnection.SendResponse(200, response, HttpResponseType.PlainText);
}
else
{
// Replace query values in the arguments
string args = _cmd;
foreach (var kv in request.Queries)
{
args.Replace($"%{kv.Key}%", kv.Value);
}
// Prepare the process start info
using Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = _cmd,
Arguments = args,
RedirectStandardOutput = true
}
};
// Start a process and wait for it to exit
string output = "";
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => output += e.Data;
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => output += e.Data;
if (process.Start())
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
await requestConnection.SendResponse(200, output, HttpResponseType.PlainText);
}
else
{
await requestConnection.SendResponse(501, "Failed to start process", HttpResponseType.StatusCode);
}
}
}
}
/// <summary>
/// Read another message from the web socket and print it to the console
/// </summary>
/// <param name="connection">WebSocket connection</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Asynchronous task</returns>
private static async Task ReadFromWebSocket(HttpEndpointConnection connection, CancellationToken cancellationToken)
{
// Note that no content has been received when we get here for the first time.
// In this case, it may take a while before/if data can be received from the client
do
{
ReceivedHttpRequest websocketRequest = await connection.ReadRequest(cancellationToken);
Console.WriteLine(websocketRequest.Body);
}
while (!cancellationToken.IsCancellationRequested);
}
/// <summary>
/// Read a message from the console and send it to the client
/// </summary>
/// <param name="connection">WebSocket connection</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Asynchronous task</returns>
private static async Task ReadFromConsole(HttpEndpointConnection connection, CancellationToken cancellationToken)
{
do
{
string input = await Task.Run(() => Console.ReadLine(), cancellationToken);
if (input == "close")
{
// Sending codes greater than or equal to 1000 closes the connection
await connection.SendResponse(1000, "Connection closed", HttpResponseType.StatusCode, cancellationToken);
}
else
{
// Send input to the client
await connection.SendResponse(200, input, HttpResponseType.PlainText, cancellationToken);
}
}
while (!cancellationToken.IsCancellationRequested);
}
}
}