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
|
// <copyright file="ScriptService.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program is distributed in the hope that it will be useful,
// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// │ GNU Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
using Microsoft.Extensions.Options;
namespace slskd.Integrations.Scripts;
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Serilog;
using slskd.Events;
/// <summary>
/// Handles the invocation of shell scripts.
/// </summary>
public class ScriptService
{
public ScriptService(EventBus eventBus, IOptionsMonitor<Options> optionsMonitor)
{
Events = eventBus;
OptionsMonitor = optionsMonitor;
var json = new JsonSerializerOptions();
json.Converters.Add(new IPAddressConverter());
json.Converters.Add(new JsonStringEnumConverter());
json.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
json.DefaultIgnoreCondition = JsonIgnoreCondition.Never; // include properties with null values
json.Encoder = JavaScriptEncoder.Default; // IMPORTANT! don't change this to 'UnsafeRelaxedJsonEscaping'; as the name implies, it's unsafe!
JsonSerializerOptions = json;
Events.Subscribe<Event>(nameof(ScriptService), HandleEvent);
if (OperatingSystem.IsWindows())
{
DefaultExecutable = "cmd.exe";
DefaultCommandPrefix = "/c";
}
else
{
DefaultExecutable = Environment.GetEnvironmentVariable("SHELL");
DefaultCommandPrefix = "-c";
if (string.IsNullOrEmpty(DefaultExecutable))
{
Log.Warning("Unable to determine default script executable ($SHELL is missing or blank); any user-defined scripts that do not specify an executable will fail");
}
}
Log.Information("Set default script executable to '{DefaultExecutable}'", DefaultExecutable);
Log.Debug("{Service} initialized", nameof(ScriptService));
}
private ILogger Log { get; } = Serilog.Log.ForContext<ScriptService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
private EventBus Events { get; }
private string DefaultExecutable { get; }
private string DefaultCommandPrefix { get; }
private JsonSerializerOptions JsonSerializerOptions { get; }
private async Task HandleEvent(Event data)
{
await Task.Yield();
Log.Debug("Handling event {Event}", data);
bool EqualsThisEvent(string type) => type.Equals(data.Type.ToString(), StringComparison.OrdinalIgnoreCase);
bool EqualsLiterallyAnyEvent(string type) => type.Equals(EventType.Any.ToString(), StringComparison.OrdinalIgnoreCase);
var options = OptionsMonitor.CurrentValue;
var scriptsTriggeredByThisEventType = options.Integrations.Scripts
.Where(kvp => kvp.Value.On.Any(EqualsThisEvent) || kvp.Value.On.Any(EqualsLiterallyAnyEvent));
foreach (var script in scriptsTriggeredByThisEventType)
{
_ = Task.Run(async () =>
{
Process process = default;
var processId = Guid.NewGuid();
// there are three 'modes' that we can use to execute a script, which are detailed below.
// the mode is negotiated based on the script config, and we rely on the validation in Options
// to enforce mututal exclusivity and prevent a user from supplying an invalid config
try
{
var run = script.Value.Run;
var executable = run.Executable ?? DefaultExecutable;
if (string.IsNullOrEmpty(executable))
{
Log.Warning("Script '{Script}' will not be run: unable to determine script executable. Update the script configuration, or set your operating system's SHELL envar.", script.Key);
return;
}
if (!string.IsNullOrEmpty(run.Command))
{
// 'command' mode takes precedence over 'executable' mode
// run the system shell and ensure the specified command is prefixed with the correct flag
// this is designed to be the 'pit of success' for this feature that will work for most users,
// who most likely have not read the docs and expect this to work like a command line.
// users are on the hook for properly (and safely) quoting arguments
Log.Debug("Running script '{Script}' in 'command mode'", script.Key);
process = new Process()
{
StartInfo = new ProcessStartInfo(fileName: executable)
{
WorkingDirectory = Program.ScriptDirectory,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = run.Command.StartsWith(DefaultCommandPrefix) ? run.Command : $"{DefaultCommandPrefix} \"{run.Command.Trim('"')}\"",
},
};
}
else if (run.Arglist is not null)
{
// 'args list' mode takes precedence over 'args' mode
// the supplied list of args will be passed to the constructor of ProcessStartInfo, which is
// curiously the only way to pass a list of args (instead of a string). if no executable has been
// specified, the system shell is used. this mode is for maximalists who know what they are doing
// and want granular control
Log.Debug("Running script '{Script}' in 'args list mode'", script.Key);
process = new Process()
{
StartInfo = new ProcessStartInfo(
fileName: executable,
arguments: run.Arglist)
{
WorkingDirectory = Program.ScriptDirectory,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
},
};
}
else
{
// 'args' mode is the default mode
// run the specified executable, or if not specified, the system shell. pass the args string
// (which may be empty or null) to ProcessStartInfo
Log.Debug("Running script '{Script}' in 'args mode'", script.Key);
process = new Process()
{
StartInfo = new ProcessStartInfo(fileName: executable)
{
WorkingDirectory = Program.ScriptDirectory,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = run.Args,
},
};
}
Log.Debug("Running script '{Script}': \"{Executable}\" {Args} (id: {ProcessId})", script.Key, executable, run.Args ?? string.Join(' ', run.Arglist ?? []), processId);
var sw = Stopwatch.StartNew();
process.StartInfo.EnvironmentVariables["SLSKD_SCRIPT_DATA"] = JsonSerializer.Serialize(
value: data,
inputType: data.GetType(), // if omitted object is serialized as EventType, losing everything else
options: JsonSerializerOptions);
process.Start();
var errorTask = process.StandardError.ReadToEndAsync();
var outputTask = process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
sw.Stop();
var error = await errorTask;
if (!string.IsNullOrEmpty(error))
{
throw new Exception($"STDERR: {Regex.Replace(error, @"\r\n?|\n", " ", RegexOptions.Compiled)}");
}
var result = await outputTask;
var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output} (id: {ProcessId})", script.Key, sw.ElapsedMilliseconds, resultAsLines, processId);
}
catch (Exception ex)
{
Log.Warning("Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId);
Log.Debug(ex, "Failed to run script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId);
}
finally
{
try
{
process?.Close();
process?.Dispose();
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message} (id: {ProcessId})", script.Key, data.Type, ex.Message, processId);
}
}
});
}
}
}
|