2using System.Collections.Frozen;
3using System.Collections.Generic;
4using System.Globalization;
5using System.Threading.Tasks;
7using Cyberboss.AspNetCore.AsyncInitializer;
9using Elastic.CommonSchema.Serilog;
11using Microsoft.AspNetCore.Authentication;
12using Microsoft.AspNetCore.Authentication.JwtBearer;
13using Microsoft.AspNetCore.Builder;
14using Microsoft.AspNetCore.Cors.Infrastructure;
15using Microsoft.AspNetCore.Hosting;
16using Microsoft.AspNetCore.Http;
17using Microsoft.AspNetCore.Http.Connections;
18using Microsoft.AspNetCore.Identity;
19using Microsoft.AspNetCore.Mvc.Infrastructure;
20using Microsoft.AspNetCore.SignalR;
21using Microsoft.Extensions.Configuration;
22using Microsoft.Extensions.DependencyInjection;
23using Microsoft.Extensions.Hosting;
24using Microsoft.Extensions.Logging;
25using Microsoft.Extensions.Options;
31using Serilog.Formatting.Display;
32using Serilog.Sinks.Elasticsearch;
70#pragma warning disable CA1506
92 assemblyInformationProvider,
105 if (postSetupServices.GeneralConfiguration.UseBasicWatchdog)
117 IConfiguration configuration,
119 : base(configuration)
132 IServiceCollection services,
139 ArgumentNullException.ThrowIfNull(postSetupServices);
148 services.AddOptions();
151 services.Configure<HostOptions>(
154 static LogEventLevel? ConvertSeriLogLevel(LogLevel logLevel) =>
157 LogLevel.Critical => LogEventLevel.Fatal,
158 LogLevel.Debug => LogEventLevel.Debug,
159 LogLevel.Error => LogEventLevel.Error,
160 LogLevel.Information => LogEventLevel.Information,
161 LogLevel.Trace => LogEventLevel.Verbose,
162 LogLevel.Warning => LogEventLevel.Warning,
163 LogLevel.None =>
null,
164 _ =>
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
"Invalid log level {0}", logLevel)),
169 services.SetupLogging(
172 if (microsoftEventLevel.HasValue)
174 config.MinimumLevel.Override(
"Microsoft", microsoftEventLevel.Value);
175 config.MinimumLevel.Override(
"System.Net.Http.HttpClient", microsoftEventLevel.Value);
185 assemblyInformationProvider,
190 var formatter =
new MessageTemplateTextFormatter(
193 +
"): [{Level:u3}] {SourceContext:l}: {Message} ({EventId:x8}){NewLine}{Exception}",
196 logPath = ioManager.
ConcatPath(logPath,
"tgs-.log");
197 var rollingFileConfig = sinkConfig.File(
200 logEventLevel ?? LogEventLevel.Verbose,
202 flushToDiskInterval: TimeSpan.FromSeconds(2),
203 rollingInterval: RollingInterval.Day,
204 rollOnFileSizeLimit:
true);
206 elasticsearchConfiguration.Enable
207 ?
new ElasticsearchSinkOptions(elasticsearchConfiguration.Host ??
throw new InvalidOperationException($
"Missing {ElasticsearchConfiguration.Section}:{nameof(elasticsearchConfiguration.Host)}!"))
211 ModifyConnectionSettings = connectionConfigration => (!String.IsNullOrWhiteSpace(elasticsearchConfiguration.Username) && !String.IsNullOrWhiteSpace(elasticsearchConfiguration.Password))
212 ? connectionConfigration
213 .BasicAuthentication(
214 elasticsearchConfiguration.Username,
215 elasticsearchConfiguration.Password)
216 .ServerCertificateValidationCallback((o, certificate, chain, errors) =>
true)
218 CustomFormatter =
new EcsTextFormatter(),
219 AutoRegisterTemplate =
true,
220 AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
221 IndexFormat =
"tgs-logs",
231 var jsonVersionConverterList =
new List<JsonConverter>
236 void ConfigureNewtonsoftJsonSerializerSettingsForApi(JsonSerializerSettings settings)
238 settings.NullValueHandling = NullValueHandling.Ignore;
239 settings.CheckAdditionalContent =
true;
240 settings.MissingMemberHandling = MissingMemberHandling.Error;
241 settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
242 settings.Converters = jsonVersionConverterList;
248 options.ReturnHttpNotAcceptable =
true;
249 options.RespectBrowserAcceptHeader =
true;
251 .AddNewtonsoftJson(options =>
253 options.AllowInputFormatterExceptionMessages =
true;
254 ConfigureNewtonsoftJsonSerializerSettingsForApi(options.SerializerSettings);
262 .AddNewtonsoftJsonProtocol(options =>
264 ConfigureNewtonsoftJsonSerializerSettingsForApi(options.PayloadSerializerSettings);
272 var assemblyDocumentationPath = GetDocumentationFilePath(GetType().Assembly.Location);
273 var apiDocumentationPath = GetDocumentationFilePath(typeof(
ApiHeaders).Assembly.Location);
275 services.AddSwaggerGenNewtonsoftSupport();
282 services.AddHttpClient();
285 void AddTypedContext<TContext>()
290 services.AddDbContextPool<TContext>((serviceProvider, builder) =>
293 builder.EnableSensitiveDataLogging();
295 var databaseConfigOptions = serviceProvider.GetRequiredService<IOptions<DatabaseConfiguration>>();
296 var databaseConfig = databaseConfigOptions.Value ??
throw new InvalidOperationException(
"DatabaseConfiguration missing!");
297 configureAction(builder, databaseConfig);
299 services.AddScoped<
IDatabaseContext>(x => x.GetRequiredService<TContext>());
308 AddTypedContext<MySqlDatabaseContext>();
311 AddTypedContext<SqlServerDatabaseContext>();
314 AddTypedContext<SqliteDatabaseContext>();
317 AddTypedContext<PostgresSqlDatabaseContext>();
320 throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
"Invalid {0}: {1}!", nameof(
DatabaseType), dbType));
332 services.AddSingleton<IPasswordHasher<Models.User>, PasswordHasher<Models.User>>();
337 AddWatchdog<WindowsWatchdogFactory>(services, postSetupServices);
351 AddWatchdog<PosixWatchdogFactory>(services, postSetupServices);
361 services.AddSingleton(x =>
new Lazy<IProcessExecutor>(() => x.GetRequiredService<
IProcessExecutor>(),
true));
368 var openDreamRepositoryDirectory = ioManager.
ConcatPath(
369 Environment.GetFolderPath(
370 Environment.SpecialFolder.LocalApplicationData,
371 Environment.SpecialFolderOption.DoNotVerify),
373 "OpenDreamRepository");
374 services.AddSingleton(
376 .GetRequiredService<IRepositoryManagerFactory>()
377 .CreateRepositoryManager(
380 openDreamRepositoryDirectory),
383 services.AddSingleton(
384 serviceProvider =>
new Dictionary<EngineType, IEngineInstaller>
389 .ToFrozenDictionary());
415 services.AddChatProviderFactory();
427 services.AddFileDownloader();
428 services.AddGitHub();
457 IApplicationBuilder applicationBuilder,
462 IOptions<ControlPanelConfiguration> controlPanelConfigurationOptions,
463 IOptions<GeneralConfiguration> generalConfigurationOptions,
464 IOptions<SwarmConfiguration> swarmConfigurationOptions,
465 ILogger<Application> logger)
467 ArgumentNullException.ThrowIfNull(applicationBuilder);
468 ArgumentNullException.ThrowIfNull(serverControl);
472 ArgumentNullException.ThrowIfNull(serverPortProvider);
473 ArgumentNullException.ThrowIfNull(assemblyInformationProvider);
475 var controlPanelConfiguration = controlPanelConfigurationOptions?.Value ??
throw new ArgumentNullException(nameof(controlPanelConfigurationOptions));
476 var generalConfiguration = generalConfigurationOptions?.Value ??
throw new ArgumentNullException(nameof(generalConfigurationOptions));
477 var swarmConfiguration = swarmConfigurationOptions?.Value ??
throw new ArgumentNullException(nameof(swarmConfigurationOptions));
479 ArgumentNullException.ThrowIfNull(logger);
486 applicationBuilder.UseAdditionalRequestLoggingContext(swarmConfiguration);
489 applicationBuilder.UseServerErrorHandling();
492 applicationBuilder.UseServerBranding(assemblyInformationProvider);
495 applicationBuilder.UseDisabledNginxProxyBuffering();
498 applicationBuilder.UseCancelledRequestSuppression();
502 (instanceManager, cancellationToken) => instanceManager.
Ready.WaitAsync(cancellationToken));
504 if (generalConfiguration.HostApiDocumentation)
506 applicationBuilder.UseSwagger(options =>
508 options.RouteTemplate = Routes.ApiRoot +
"doc/{documentName}.{json|yaml}";
510 applicationBuilder.UseSwaggerUI(options =>
513 options.SwaggerEndpoint(
Routes.
ApiRoot + $
"doc/{SwaggerConfiguration.DocumentName}.json",
"TGS API");
515 logger.LogTrace(
"Swagger API generation enabled");
519 if (controlPanelConfiguration.Enable)
521 logger.LogInformation(
"Web control panel enabled.");
522 applicationBuilder.UseFileServer(
new FileServerOptions
525 EnableDefaultFiles =
true,
526 EnableDirectoryBrowsing =
false,
531 logger.LogDebug(
"Web control panel was not included in TGS build!");
533 logger.LogTrace(
"Web control panel disabled!");
537 applicationBuilder.UseRouting();
540 Action<CorsPolicyBuilder>? corsBuilder =
null;
541 if (controlPanelConfiguration.AllowAnyOrigin)
543 logger.LogTrace(
"Access-Control-Allow-Origin: *");
544 corsBuilder = builder => builder.SetIsOriginAllowed(_ =>
true);
546 else if (controlPanelConfiguration.AllowedOrigins?.Count > 0)
548 logger.LogTrace(
"Access-Control-Allow-Origin: {allowedOrigins}", String.Join(
',', controlPanelConfiguration.AllowedOrigins));
549 corsBuilder = builder => builder.WithOrigins([.. controlPanelConfiguration.AllowedOrigins]);
552 var originalBuilder = corsBuilder;
553 corsBuilder = builder =>
559 .SetPreflightMaxAge(TimeSpan.FromDays(1));
560 originalBuilder?.Invoke(builder);
562 applicationBuilder.UseCors(corsBuilder);
565 applicationBuilder.UseApiCompatibility();
568 applicationBuilder.UseAuthentication();
571 applicationBuilder.UseAuthorization();
574 applicationBuilder.UseDbConflictHandling();
577 applicationBuilder.UseEndpoints(endpoints =>
584 options.Transports = HttpTransportType.ServerSentEvents;
585 options.CloseOnAuthenticationExpiration =
true;
587 .RequireAuthorization()
588 .RequireCors(corsBuilder);
591 endpoints.MapControllers();
598 if (controlPanelConfiguration.Enable)
601 logger.LogDebug(
"Starting hosting on port {httpApiPort}...", serverPortProvider.
HttpApiPort);
614 services.AddHttpContextAccessor();
624 services.AddScoped(provider => (provider
625 .GetRequiredService<IHttpContextAccessor>()
626 .HttpContext ??
throw new InvalidOperationException($
"Unable to resolve {nameof(IAuthenticationContext)} due to no HttpContext being available!"))
628 .GetRequiredService<AuthenticationContextFactory>()
629 .CurrentAuthenticationContext);
633 .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
634 .AddJwtBearer(jwtBearerOptions =>
639 jwtBearerOptions.MapInboundClaims =
false;
640 jwtBearerOptions.Events =
new JwtBearerEvents
642 OnMessageReceived = context =>
644 if (String.IsNullOrWhiteSpace(context.Token))
646 var accessToken = context.Request.Query[
"access_token"];
647 var path = context.HttpContext.Request.Path;
649 if (!String.IsNullOrWhiteSpace(accessToken) &&
650 path.StartsWithSegments(
Routes.
HubsRoot, StringComparison.OrdinalIgnoreCase))
652 context.Token = accessToken;
656 return Task.CompletedTask;
Routes to a server actions.
const string HubsRoot
The root route of all hubs.
const string ApiRoot
The root of API methods.
const string JobsHub
The root route of all hubs.
Base implementation of IEngineInstaller for EngineType.Byond.
Implementation of IEngineInstaller that forwards calls to different IEngineInstaller based on their a...
Implementation of IEngineInstaller for EngineType.OpenDream.
IEngineInstaller for Posix systems.
IEngineInstaller for windows systems.
Implementation of OpenDreamInstaller for Windows systems.
No-op implementation of IEventConsumer.
Constants used for communication with the DMAPI.
static readonly Version InteropVersion
The DMAPI InteropVersion being used.
Configuration options for the web control panel.
DatabaseType DatabaseType
The Configuration.DatabaseType to create.
LogLevel MicrosoftLogLevel
The minimum Microsoft.Extensions.Logging.LogLevel to display in logs for Microsoft library sources.
string GetFullLogDirectory(IIOManager ioManager, IAssemblyInformationProvider assemblyInformationProvider, IPlatformIdentifier platformIdentifier)
Gets the evaluated log Directory.
LogLevel LogLevel
The minimum Microsoft.Extensions.Logging.LogLevel to display in logs.
bool Disable
If file logging is disabled.
General configuration options.
static readonly Version CurrentConfigVersion
The current ConfigVersion.
bool HostApiDocumentation
If the swagger documentation and UI should be made avaiable.
uint RestartTimeoutMinutes
The timeout minutes for restarting the server.
bool UsingSystemD
If the server is running under SystemD.
Configuration options for the game sessions.
Configuration for the server swarm system.
Configuration for the automatic update system.
Controller for the web control panel.
const string ControlPanelRoute
Route to the ControlPanelController.
IActionResultExecutor<TResult> for LimitedStreamResults.
Sets up dependency injection.
override void ConfigureHostedService(IServiceCollection services)
Configures the IHostedService.
static void AddWatchdog< TSystemWatchdogFactory >(IServiceCollection services, IPostSetupServices postSetupServices)
Adds the IWatchdogFactory implementation.
void ConfigureServices(IServiceCollection services, IAssemblyInformationProvider assemblyInformationProvider, IIOManager ioManager, IPostSetupServices postSetupServices)
Configure the Application's services .
static IServerFactory CreateDefaultServerFactory()
Create the default IServerFactory.
void ConfigureAuthenticationPipeline(IServiceCollection services)
Configure the services for the authentication pipeline.
ITokenFactory? tokenFactory
The ITokenFactory for the Application.
void Configure(IApplicationBuilder applicationBuilder, IServerControl serverControl, ITokenFactory tokenFactory, IServerPortProvider serverPortProvider, IAssemblyInformationProvider assemblyInformationProvider, IOptions< ControlPanelConfiguration > controlPanelConfigurationOptions, IOptions< GeneralConfiguration > generalConfigurationOptions, IOptions< SwarmConfiguration > swarmConfigurationOptions, ILogger< Application > logger)
Configure the Application.
Application(IConfiguration configuration, IWebHostEnvironment hostingEnvironment)
Initializes a new instance of the Application class.
readonly IWebHostEnvironment hostingEnvironment
The IWebHostEnvironment for the Application.
Reads from the command pipe opened by the host watchdog.
Backend abstract implementation of IDatabaseContext.
JsonConverter and IYamlTypeConverter for serializing global::System.Versions in semver format.
IIOManager that resolves paths to Environment.CurrentDirectory.
IFilesystemLinkFactory for POSIX systems.
IPostWriteHandler for POSIX systems.
An IIOManager that resolve relative paths from another IIOManager to a subdirectory of that.
IFilesystemLinkFactory for windows systems.
IPostWriteHandler for Windows systems.
Handles mapping groups for the JobsHub.
A SignalR Hub for pushing job updates.
Attribute for bringing in the master versions list from MSBuild that aren't embedded into assemblies ...
string RawWebpanelVersion
The Version string of the control panel version built.
static MasterVersionsAttribute Instance
Return the Assembly's instance of the MasterVersionsAttribute.
A IClaimsTransformation that maps Claims using an IAuthenticationContext.
An IHubFilter that denies method calls and connections if the IAuthenticationContext is not valid for...
ISystemIdentityFactory for posix systems.
ISystemIdentityFactory for windows systems. Uses long running tasks due to potential networked domain...
Implementation of IServerFactory.
DI root for configuring a SetupWizard.
IConfiguration Configuration
The IConfiguration for the SetupApplication.
Helps keep servers connected to the same database in sync by coordinating updates.
Implements the SystemD notify service protocol.
Implementation of the file transfer service.
Helpers for manipulating the Serilog.Context.LogContext.
static string Template
Common template used for adding our custom log context to serilog.
Implements various filters for Swashbuckle.
const string DocumentationSiteRouteExtension
The path to the hosted documentation site.
static void Configure(SwaggerGenOptions swaggerGenOptions, string assemblyDocumentationPath, string apiDocumentationPath)
Configure the swagger settings.
SignalR client methods for receiving JobResponses.
For creating IChatManagers.
Factory for creating IRemoteDeploymentManagers.
For downloading and installing game engines for a given system.
Factory for creating IInstances.
Task Ready
Task that completes when the IInstanceManager finishes initializing.
Handler for BridgeParameters.
Factory for creating IGitRemoteFeatures.
For low level interactions with a LibGit2Sharp.IRepository.
Factory for creating LibGit2Sharp.IRepositorys.
Factory for creating IRepositoryManagers.
Factory for ITopicClients.
Represents a service that may take an updated Host assembly and run it, stopping the current assembly...
Provides access to the server's HttpApiPort.
ushort HttpApiPort
The port the server listens on.
Initiates server self updates.
Factory for scoping usage of IDatabaseContexts. Meant for use by Components.
For initially setting up a database.
For creating filesystem symbolic links.
Interface for using filesystems.
string ConcatPath(params string[] paths)
Combines an array of strings into a path.
string GetDirectoryName(string path)
Gets the directory portion of a given path .
string GetFileNameWithoutExtension(string path)
Gets the file name portion of a path with.
Handles changing file modes/permissions after writing.
For accessing the disk in a synchronous manner.
Manages the runtime of Jobs.
The service that manages everything to do with jobs.
Allows manually triggering jobs hub updates.
For creating and accessing authentication contexts.
Contains various cryptographic functions.
For caching ISystemIdentitys.
Receives notifications about permissions updates.
Factory for ISystemIdentitys.
For creating TokenResponses.
TokenValidationParameters ValidationParameters
The TokenValidationParameters for the ITokenFactory.
Contains IOAuthValidators.
Set of objects needed to configure an Core.Application.
ElasticsearchConfiguration ElasticsearchConfiguration
The Configuration.ElasticsearchConfiguration.
InternalConfiguration InternalConfiguration
The Configuration.InternalConfiguration.
GeneralConfiguration GeneralConfiguration
The Configuration.GeneralConfiguration.
DatabaseConfiguration DatabaseConfiguration
The Configuration.DatabaseConfiguration.
IPlatformIdentifier PlatformIdentifier
The IPlatformIdentifier.
FileLoggingConfiguration FileLoggingConfiguration
The Configuration.FileLoggingConfiguration.
Swarm service operations for the Controllers.SwarmController.
Start and stop controllers for a swarm service.
Used for swarm operations. Functions may be no-op based on configuration.
On Windows, DreamDaemon will show an unskippable prompt when using /world/proc/OpenPort()....
Abstraction for suspending and resuming processes.
Reads and writes to Streams associated with FileTicketResponses.
Service for temporarily storing files to be downloaded or uploaded.
Gets unassigned ports for use by TGS.
EngineType
The type of engine the codebase is using.
DatabaseType
Type of database to user.