aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Startup.cs
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-02-09 09:36:43 -0600
committerJP Dillingham <jpdillingham@gmail.com>2021-02-09 09:36:43 -0600
commit56c4baf89bacf7494f2f304861bae1394dad4e4a (patch)
tree61d8830c5866e90f5cf80975273088ca4670e627 /src/slskd/Startup.cs
parentb4760da1b4f6c3eb0f9df99f5914baa272215ec2 (diff)
downloadslskd-56c4baf89bacf7494f2f304861bae1394dad4e4a.tar.gz
swap argument and envar libs for nuget packages
Diffstat (limited to 'src/slskd/Startup.cs')
-rw-r--r--src/slskd/Startup.cs315
1 files changed, 158 insertions, 157 deletions
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index 41ef747c..d02ec39f 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -48,15 +48,9 @@ namespace slskd
public class Startup
{
- private readonly int MaxReconnectAttempts = 3;
- private int CurrentReconnectAttempts = 0;
private static readonly string XmlDocFile = Path.Combine(AppContext.BaseDirectory, Program.AppName + ".xml");
-
- private SoulseekClient Client { get; set; }
- private ISharedFileCache SharedFileCache { get; set; }
- private string UrlBase { get; set; }
- private string ContentPath { get; set; }
- private SymmetricSecurityKey JwtSigningKey { get; set; }
+ private static readonly int MaxReconnectAttempts = 3;
+ private static int CurrentReconnectAttempts = 0;
public Startup(IConfiguration configuration)
{
@@ -78,110 +72,20 @@ namespace slskd
JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Options.Web.Authentication.Jwt.Key));
}
+ private SoulseekClient Client { get; set; }
private IConfiguration Configuration { get; }
- private Options Options { get; }
+ private string ContentPath { get; set; }
+ private SymmetricSecurityKey JwtSigningKey { get; set; }
private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>();
-
- public void ConfigureServices(IServiceCollection services)
- {
- var logger = Log.ForContext<Startup>();
-
- services.AddOptions<Options>()
- .Bind(Configuration.GetSection("slskd"), o => { o.BindNonPublicProperties = true; });
-
- services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
-
- services.AddSingleton(JwtSigningKey);
-
- if (!Options.Web.Authentication.Disable)
- {
- services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ClockSkew = TimeSpan.FromMinutes(5),
- RequireSignedTokens = true,
- RequireExpirationTime = true,
- ValidateLifetime = true,
- ValidIssuer = "slskd",
- ValidateIssuer = true,
- ValidateAudience = false,
- IssuerSigningKey = JwtSigningKey,
- ValidateIssuerSigningKey = true,
- };
- });
- }
- else
- {
- logger.Warning("Authentication of web requests is DISABLED");
-
- services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme)
- .AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options =>
- {
- options.Username = "n/a";
- });
- }
-
- services.AddRouting(options => options.LowercaseUrls = true);
- services.AddControllers().AddJsonOptions(options =>
- {
- options.JsonSerializerOptions.Converters.Add(new IPAddressConverter());
- options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
- options.JsonSerializerOptions.IgnoreNullValues = true;
- });
-
- services.AddHealthChecks();
-
- services.AddApiVersioning(options => options.ReportApiVersions = true);
- services.AddVersionedApiExplorer(options =>
- {
- options.GroupNameFormat = "'v'VVV";
- options.SubstituteApiVersionInUrl = true;
- });
-
- if (Options.Feature.Swagger)
- {
- services.AddSwaggerGen(options =>
- {
- options.DescribeAllParametersInCamelCase();
- options.SwaggerDoc("v0",
- new OpenApiInfo
- {
- Title = "slskd",
- Version = "v0"
- }
- );
-
- if (System.IO.File.Exists(XmlDocFile))
- {
- options.IncludeXmlComments(XmlDocFile);
- }
- else
- {
- logger.Warning($"Unable to find XML documentation in {XmlDocFile}, Swagger will not include metadata");
- }
- });
- }
-
- if (Options.Feature.Prometheus)
- {
- services.AddSystemMetrics();
- }
-
- services.AddSingleton<ISoulseekClient, SoulseekClient>(serviceProvider => Client);
- services.AddSingleton<ITransferTracker, TransferTracker>();
- services.AddSingleton<ISearchTracker, SearchTracker>();
- services.AddSingleton<IBrowseTracker, BrowseTracker>();
- services.AddSingleton<IConversationTracker, ConversationTracker>();
- services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
- }
+ private Options Options { get; }
+ private ISharedFileCache SharedFileCache { get; set; }
+ private string UrlBase { get; set; }
public void Configure(
- IApplicationBuilder app,
- IApiVersionDescriptionProvider provider,
- ITransferTracker tracker,
- IBrowseTracker browseTracker,
+ IApplicationBuilder app,
+ IApiVersionDescriptionProvider provider,
+ ITransferTracker tracker,
+ IBrowseTracker browseTracker,
IConversationTracker conversationTracker,
IRoomTracker roomTracker)
{
@@ -200,8 +104,7 @@ namespace slskd
app.UsePathBase(UrlBase);
logger.Information("Using base url {UrlBase}", UrlBase);
- // remove any errant double forward slashes which may have been introduced
- // by a reverse proxy or having the base path removed
+ // remove any errant double forward slashes which may have been introduced by a reverse proxy or having the base path removed
app.Use(async (context, next) =>
{
var path = context.Request.Path.ToString();
@@ -225,9 +128,9 @@ namespace slskd
fileServerOptions = new FileServerOptions
{
FileProvider = new PhysicalFileProvider(ContentPath),
- RequestPath = "",
+ RequestPath = string.Empty,
EnableDirectoryBrowsing = false,
- EnableDefaultFiles = true
+ EnableDefaultFiles = true,
};
app.UseFileServer(fileServerOptions);
@@ -266,8 +169,8 @@ namespace slskd
logger.Information("Publishing Swagger documentation to /swagger");
}
- // if we made it this far and the route still wasn't matched, return the index unless it's an api route
- // this is required so that SPA routing (React Router, etc) can work properly
+ // if we made it this far and the route still wasn't matched, return the index unless it's an api route this is
+ // required so that SPA routing (React Router, etc) can work properly
app.Use(async (context, next) =>
{
// exclude API routes which are not matched or return a 404
@@ -279,16 +182,15 @@ namespace slskd
await next();
});
- // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be returned
- // otherwise it will throw a final 404 back to the client.
+ // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be
+ // returned otherwise it will throw a final 404 back to the client.
if (System.IO.Directory.Exists(ContentPath))
{
app.UseFileServer(fileServerOptions);
}
// ---------------------------------------------------------------------------------------------------------------------------------------------
- // begin SoulseekClient implementation
- // ---------------------------------------------------------------------------------------------------------------------------------------------
+ // begin SoulseekClient implementation ---------------------------------------------------------------------------------------------------------------------------------------------
var connectionOptions = new ConnectionOptions(
readBufferSize: Options.Soulseek.Connection.Buffer.Read,
writeBufferSize: Options.Soulseek.Connection.Buffer.Write,
@@ -297,8 +199,7 @@ namespace slskd
var defaults = new SoulseekClientOptions();
- // create options for the client.
- // see the implementation of Func<> and Action<> options for detailed info.
+ // create options for the client. see the implementation of Func<> and Action<> options for detailed info.
var clientOptions = new SoulseekClientOptions(
listenPort: Options.Soulseek.ListenPort ?? defaults.ListenPort,
enableListener: Options.Soulseek.ListenPort.HasValue,
@@ -327,8 +228,8 @@ namespace slskd
Client = new SoulseekClient(options: clientOptions);
- // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the event
- // isn't bound the minimumDiagnosticLevel should be set to None.
+ // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the
+ // event isn't bound the minimumDiagnosticLevel should be set to None.
Client.DiagnosticGenerated += (e, args) =>
{
static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch
@@ -345,7 +246,7 @@ namespace slskd
logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message);
};
- // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs.
+ // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs.
Client.TransferStateChanged += (e, args) =>
{
var direction = args.Transfer.Direction.ToString().ToUpper();
@@ -361,12 +262,13 @@ namespace slskd
Client.TransferProgressUpdated += (e, args) =>
{
- // this is really verbose.
- // Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s");
+ // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}]
+ // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}]
+ // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s");
};
- // bind BrowseProgressUpdated to track progress of browse response payload transfers.
- // these can take a while depending on number of files shared.
+ // bind BrowseProgressUpdated to track progress of browse response payload transfers. these can take a while depending
+ // on number of files shared.
Client.BrowseProgressUpdated += (e, args) =>
{
browseTracker.AddOrUpdate(args.Username, args);
@@ -416,9 +318,9 @@ namespace slskd
{
Console.WriteLine($"Disconnected from Soulseek server: {args.Message}");
- // don't reconnect if the disconnecting Exception is either of these types.
- // if KickedFromServerException, another client was most likely signed in, and retrying will cause a connect loop.
- // if ObjectDisposedException, the client is shutting down.
+ // don't reconnect if the disconnecting Exception is either of these types. if KickedFromServerException, another
+ // client was most likely signed in, and retrying will cause a connect loop. if ObjectDisposedException, the
+ // client is shutting down.
if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException))
{
Interlocked.Increment(ref CurrentReconnectAttempts);
@@ -447,22 +349,99 @@ namespace slskd
logger.Information("Connected and logged in as {Username}", username);
}
- /// <summary>
- /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request.
- /// </summary>
- /// <param name="username">The username of the requesting user.</param>
- /// <param name="endpoint">The IP endpoint of the requesting user.</param>
- /// <returns>A Task resolving the UserInfo instance.</returns>
- private Task<UserInfo> UserInfoResponseResolver(string username, IPEndPoint endpoint)
+ public void ConfigureServices(IServiceCollection services)
{
- var info = new UserInfo(
- description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}",
- picture: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"),
- uploadSlots: 1,
- queueLength: 0,
- hasFreeUploadSlot: false);
+ var logger = Log.ForContext<Startup>();
- return Task.FromResult(info);
+ services.AddOptions<Options>()
+ .Bind(Configuration.GetSection("slskd"), o => { o.BindNonPublicProperties = true; });
+
+ services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
+
+ services.AddSingleton(JwtSigningKey);
+
+ if (!Options.Web.Authentication.Disable)
+ {
+ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
+ .AddJwtBearer(options =>
+ {
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ClockSkew = TimeSpan.FromMinutes(5),
+ RequireSignedTokens = true,
+ RequireExpirationTime = true,
+ ValidateLifetime = true,
+ ValidIssuer = "slskd",
+ ValidateIssuer = true,
+ ValidateAudience = false,
+ IssuerSigningKey = JwtSigningKey,
+ ValidateIssuerSigningKey = true,
+ };
+ });
+ }
+ else
+ {
+ logger.Warning("Authentication of web requests is DISABLED");
+
+ services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme)
+ .AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options =>
+ {
+ options.Username = "n/a";
+ });
+ }
+
+ services.AddRouting(options => options.LowercaseUrls = true);
+ services.AddControllers().AddJsonOptions(options =>
+ {
+ options.JsonSerializerOptions.Converters.Add(new IPAddressConverter());
+ options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
+ options.JsonSerializerOptions.IgnoreNullValues = true;
+ });
+
+ services.AddHealthChecks();
+
+ services.AddApiVersioning(options => options.ReportApiVersions = true);
+ services.AddVersionedApiExplorer(options =>
+ {
+ options.GroupNameFormat = "'v'VVV";
+ options.SubstituteApiVersionInUrl = true;
+ });
+
+ if (Options.Feature.Swagger)
+ {
+ services.AddSwaggerGen(options =>
+ {
+ options.DescribeAllParametersInCamelCase();
+ options.SwaggerDoc(
+ "v0",
+ new OpenApiInfo
+ {
+ Title = "slskd",
+ Version = "v0",
+ });
+
+ if (System.IO.File.Exists(XmlDocFile))
+ {
+ options.IncludeXmlComments(XmlDocFile);
+ }
+ else
+ {
+ logger.Warning($"Unable to find XML documentation in {XmlDocFile}, Swagger will not include metadata");
+ }
+ });
+ }
+
+ if (Options.Feature.Prometheus)
+ {
+ services.AddSystemMetrics();
+ }
+
+ services.AddSingleton<ISoulseekClient, SoulseekClient>(serviceProvider => Client);
+ services.AddSingleton<ITransferTracker, TransferTracker>();
+ services.AddSingleton<ISearchTracker, SearchTracker>();
+ services.AddSingleton<IBrowseTracker, BrowseTracker>();
+ services.AddSingleton<IConversationTracker, ConversationTracker>();
+ services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
}
/// <summary>
@@ -498,15 +477,20 @@ namespace slskd
}
/// <summary>
- /// Invoked upon a remote request to download a file.
+ /// Invoked upon a remote request to download a file.
/// </summary>
/// <param name="username">The username of the requesting user.</param>
/// <param name="endpoint">The IP endpoint of the requesting user.</param>
/// <param name="filename">The filename of the requested file.</param>
/// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
- /// <exception cref="DownloadEnqueueException">Thrown when the download is rejected. The Exception message will be passed to the remote user.</exception>
- /// <exception cref="Exception">Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for security reasons.</exception>
+ /// <exception cref="DownloadEnqueueException">
+ /// Thrown when the download is rejected. The Exception message will be passed to the remote user.
+ /// </exception>
+ /// <exception cref="Exception">
+ /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for
+ /// security reasons.
+ /// </exception>
private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker)
{
_ = endpoint;
@@ -521,8 +505,7 @@ namespace slskd
if (tracker.TryGet(TransferDirection.Upload, username, filename, out _))
{
- // in this case, a re-requested file is a no-op. normally we'd want to respond with a
- // PlaceInQueueResponse
+ // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse
Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]");
return Task.CompletedTask;
}
@@ -531,8 +514,8 @@ namespace slskd
var cts = new CancellationTokenSource();
var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c));
- // accept all download requests, and begin the upload immediately.
- // normally there would be an internal queue, and uploads would be handled separately.
+ // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and
+ // uploads would be handled separately.
Task.Run(async () =>
{
using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
@@ -557,14 +540,14 @@ namespace slskd
{
var defaultResponse = Task.FromResult<SearchResponse>(null);
- // some bots continually query for very common strings. blacklist known names here.
+ // some bots continually query for very common strings. blacklist known names here.
var blacklist = new[] { "Lola45", "Lolo51", "rajah" };
if (blacklist.Contains(username))
{
return defaultResponse;
}
- // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans.
+ // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans.
if (query.Query.Length < 3)
{
return defaultResponse;
@@ -585,12 +568,30 @@ namespace slskd
fileList: results));
}
- // if no results, either return null or an instance of SearchResponse with a fileList of length 0
- // in either case, no response will be sent to the requestor.
+ // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no
+ // response will be sent to the requestor.
return Task.FromResult<SearchResponse>(null);
}
- class IPAddressConverter : JsonConverter<IPAddress>
+ /// <summary>
+ /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request.
+ /// </summary>
+ /// <param name="username">The username of the requesting user.</param>
+ /// <param name="endpoint">The IP endpoint of the requesting user.</param>
+ /// <returns>A Task resolving the UserInfo instance.</returns>
+ private Task<UserInfo> UserInfoResponseResolver(string username, IPEndPoint endpoint)
+ {
+ var info = new UserInfo(
+ description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}",
+ picture: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"),
+ uploadSlots: 1,
+ queueLength: 0,
+ hasFreeUploadSlot: false);
+
+ return Task.FromResult(info);
+ }
+
+ private class IPAddressConverter : JsonConverter<IPAddress>
{
public override bool CanConvert(Type objectType) => (objectType == typeof(IPAddress));
@@ -599,7 +600,7 @@ namespace slskd
public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString());
}
- class UserEndPointCache : IUserEndPointCache
+ private class UserEndPointCache : IUserEndPointCache
{
public UserEndPointCache()
{