-
Notifications
You must be signed in to change notification settings - Fork 345
/
Program.cs
287 lines (227 loc) · 10.2 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
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using CommandLiners;
using CommandLiners.Options;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mono.Options;
using Rnwood.Smtp4dev.Controllers;
using Rnwood.Smtp4dev.DbModel;
using Rnwood.Smtp4dev.Server;
using Rnwood.Smtp4dev.Server.Settings;
using Rnwood.Smtp4dev.Service;
using Serilog;
namespace Rnwood.Smtp4dev
{
public class Program
{
public static bool IsService { get; private set; }
private static ILogger _log;
public static async Task Main(string[] args)
{
try
{
var host = await StartApp(args, false, null);
if (host == null)
{
Environment.Exit(1);
}
else
{
await host.WaitForShutdownAsync();
}
Log.Information("Exiting");
}
catch (CommandLineOptionsException ex)
{
if (ex.IsHelpRequest)
{
Log.Information(ex.Message);
}
else
{
Log.Fatal(ex.Message);
}
}
catch (Exception ex)
{
Log.Fatal(ex, "A unhandled exception occurred.");
}
finally
{
Log.CloseAndFlush();
}
}
public static async Task<IHost> StartApp(IEnumerable<string> args, bool isDesktopApp, Action<CommandLineOptions> fixedOptions)
{
SetupStaticLogger(args);
_log = Log.ForContext<Program>();
string version = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
_log.Information("smtp4dev version {version}", version);
_log.Information("https://github.com/rnwood/smtp4dev");
_log.Information(".NET Core runtime version: {netcoreruntime}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
if (!Debugger.IsAttached && args.Contains("--service"))
IsService = true;
MapOptions<CommandLineOptions> commandLineOptions = CommandLineParser.TryParseCommandLine(args, isDesktopApp);
CommandLineOptions cmdLineOptions = new CommandLineOptions();
new ConfigurationBuilder().AddCommandLineOptions(commandLineOptions).Build().Bind(cmdLineOptions);
fixedOptions?.Invoke(cmdLineOptions);
if (!string.IsNullOrEmpty(cmdLineOptions.InstallPath))
{
Directory.SetCurrentDirectory(cmdLineOptions.InstallPath);
}
_log.Information("Install location: {installpath}", Directory.GetCurrentDirectory());
var host = BuildWebHost(args.Where(arg => arg != "--service").ToArray(), cmdLineOptions, commandLineOptions);
await host.StartAsync();
var addressesFeature = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>();
var urls = addressesFeature.Addresses;
foreach (var url in urls)
{
_log.Information("Now listening on: {url}", url);
}
return host;
}
private static string GetContentRoot()
{
string installLocation = AppContext.BaseDirectory;
if (Directory.Exists(Path.Join(installLocation, "wwwroot")))
{
return installLocation;
}
string cwd = Directory.GetCurrentDirectory();
if (Directory.Exists(Path.Join(cwd, "wwwroot")))
{
return cwd;
}
throw new ApplicationException($"Unable to find wwwroot in either '{installLocation}' or the CWD '{cwd}'");
}
private static IHost BuildWebHost(string[] args, CommandLineOptions cmdLineOptions, MapOptions<CommandLineOptions> commandLineOptions)
{
var contentRoot = GetContentRoot();
var dataDir = GetOrCreateDataDir(cmdLineOptions);
_log.Information("DataDir: {dataDir}", dataDir);
Directory.SetCurrentDirectory(dataDir);
IHostBuilder builder = Host.CreateDefaultBuilder(args)
.UseSerilog()
.UseContentRoot(contentRoot)
.ConfigureAppConfiguration(
(hostingContext, configBuilder) =>
{
var env = hostingContext.HostingEnvironment;
var cb = configBuilder
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_log.Information("Default settings file: {file}", Path.Join(env.ContentRootPath, "appsettings.json"));
if (!cmdLineOptions.NoUserSettings)
{
cb = cb.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
cb = cb.AddJsonFile(Path.Join(dataDir, "appsettings.json"), optional: true, reloadOnChange: true);
_log.Information("User settings file: {file}", Path.Join(dataDir, "appsettings.json"));
}
cb.AddEnvironmentVariables()
.AddCommandLineOptions(commandLineOptions);
var config = cb
.Build();
hostingContext.HostingEnvironment.EnvironmentName = config["Environment"];
if (cmdLineOptions.DebugSettings)
{
Console.WriteLine(JsonSerializer.Serialize(new SettingsDebugInfo
{
CmdLineArgs = Environment.GetCommandLineArgs(),
CmdLineOptions = cmdLineOptions,
ServerOptions = config.GetSection("ServerOptions").Get<ServerOptions>(),
RelayOption = config.GetSection("RelayOptions").Get<RelayOptions>(),
DesktopOptions = config.GetSection("DesktopOptions").Get<DesktopOptions>()
}, SettingsDebugInfoSerializationContext.Default.SettingsDebugInfo));
}
});
builder.ConfigureWebHostDefaults(c =>
{
c.UseStartup<Startup>();
c.UseShutdownTimeout(TimeSpan.FromSeconds(10));
c.ConfigureServices((webBuilderContext, services) =>
{
ServerOptions serverOptions = webBuilderContext.Configuration.GetSection("ServerOptions").Get<ServerOptions>();
if (!string.IsNullOrEmpty(serverOptions.Urls))
{
c.UseUrls(serverOptions.Urls.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(u => u.Trim()).ToArray());
}
services.AddSingleton(cmdLineOptions);
services.AddHostedService(sp => (Smtp4devServer)sp.GetRequiredService<ISmtp4devServer>());
services.AddHostedService(sp => sp.GetRequiredService<ImapServer>());
});
});
builder.UseWindowsService(s => s.ServiceName = "smtp4dev");
return builder.Build();
}
private static string GetOrCreateDataDir(CommandLineOptions cmdLineOptions)
{
var dataDir = DirectoryHelper.GetDataDir(cmdLineOptions);
if (!Directory.Exists(dataDir))
{
Directory.CreateDirectory(dataDir);
}
return dataDir;
}
public static void SetupStaticLogger(IEnumerable<string> args)
{
try
{
IConfigurationRoot configuration =
new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logConfigBuilder = new LoggerConfiguration()
.ReadFrom.Configuration(configuration);
if (args.Any(a => a.Equals("--service", StringComparison.OrdinalIgnoreCase)))
{
logConfigBuilder.WriteTo.EventLog("smtp4dev");
}
Log.Logger = logConfigBuilder
.CreateLogger();
}
catch
{
//Ensure output goes somewhere if there's a config error.
var logConfigBuilder = new LoggerConfiguration();
if (args.Any(a => a.Equals("--service", StringComparison.OrdinalIgnoreCase)))
{
logConfigBuilder.WriteTo.EventLog("smtp4dev");
}else
{
logConfigBuilder.WriteTo.Console();
}
Log.Logger = logConfigBuilder.CreateLogger();
throw;
}
}
}
internal class SettingsDebugInfo
{
public string[] CmdLineArgs { get; set; }
public CommandLineOptions CmdLineOptions { get; set; }
public ServerOptions ServerOptions { get; set; }
public RelayOptions RelayOption { get; set; }
public DesktopOptions DesktopOptions { get; set; }
}
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(SettingsDebugInfo))]
internal partial class SettingsDebugInfoSerializationContext : JsonSerializerContext {
}
}