This repository has been archived by the owner on Aug 5, 2019. It is now read-only.
/
NowinAcme.cs
83 lines (75 loc) · 2.83 KB
/
NowinAcme.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Oocx.ACME.Common;
namespace NowinAcme
{
public static class NowinAcme
{
class LoggerProxy: ILog
{
readonly IAcmeConfiguration _cfg;
public LoggerProxy(IAcmeConfiguration cfg)
{
_cfg = cfg;
}
public void Verbose(string message, params object[] args)
{
_cfg.LogVerbose(message,args);
}
public void Info(string message, params object[] args)
{
_cfg.LogInfo(message, args);
}
public void Warning(string message, params object[] args)
{
_cfg.LogWarning(message, args);
}
public void Error(string message, params object[] args)
{
_cfg.LogError(message, args);
}
}
// This must run on server port 80 - Let's encrypt does not allow anything else
public static Func<IDictionary<string, object>, Task> Use(Func<IDictionary<string, object>, Task> next, IAcmeConfiguration cfg)
{
string challengePath = null;
byte[] challengeContent = null;
Log.Level = LogLevel.Verbose;
Log.Current = new LoggerProxy(cfg);
Func<Task, Task> updateWorker = null;
updateWorker=async task =>
{
var utcNow = DateTime.UtcNow;
var lastUpdate = cfg.LastUpdate;
if (utcNow - lastUpdate > TimeSpan.FromDays(30))
{
await new AcmeProcess(cfg.Email, cfg.Domain, cfg.UpdateCertificate, (path, content) =>
{
Log.Info($"SET {path} = {content}");
challengePath = path;
challengeContent = content;
}).StartAsync();
}
#pragma warning disable 4014
// This cannot be awaited because it has to run once in a while without holding any resources.
// ReSharper disable once AssignNullToNotNullAttribute
Task.Delay(TimeSpan.FromMinutes(15)).ContinueWith(updateWorker);
#pragma warning restore 4014
};
Task.Delay(1).ContinueWith(updateWorker);
return env =>
{
var path = (string)env["owin.RequestPath"];
if (path == challengePath)
{
var respBody = (Stream)env["owin.ResponseBody"];
respBody.Write(challengeContent, 0, challengeContent.Length);
return Task.CompletedTask;
}
return next(env);
};
}
}
}