Certificates expire, and on the public web they are renewed every few months. tCertificateReloader watches a PFX file and, when a new one is published there, hands it to the running server. Connections already open keep the certificate they started with; new ones get the new certificate. Nothing is restarted.
The reloader only reads files. Whatever renews the certificate - an ACME client, a script, an administrator - writes the new PFX in its place.
uses System.SysUtils, StreamSec.Mobile.CertificateReload, // tCertificateReloader TaskHttpsServer; // the server of "Serve HTTPS from a PFX file"
The server is the one from Serve HTTPS from a PFX file, which reads its PFX once at start and keeps those bytes as PfxContent.
function StartReloader(aServer: tTaskHttpsServer; const aPfxFile, aPassword, aHostName: string; aLog: tCertificateReloadLogEvent): tCertificateReloader; begin { After the server is active. } Result := tCertificateReloader.Create; try { First, so that every report - including one about the seed below - is seen. While the reloader runs, it is called on the reloader's thread. } Result.LogCallback := aLog; Result.AddTarget(aServer.Server); { The names the server answers to. A new certificate that does not cover one of them is still applied, with a warning in the log. } Result.HostNames.Add(aHostName); { The file to follow, and the content the server was started from: an unchanged file is then not applied again, and the first real replacement retires the certificate being served. } Result.AddFile(aPfxFile, aPassword, nil, aServer.PfxContent); Result.Start; except Result.Free; raise; end; end;
Before a new file is applied it is checked: it must open with the password, hold one private key that matches its certificate, have a chain that validates, and be usable for TLS server authentication. A file that fails is rejected and reported through LogCallback, and the server goes on with the certificate it had. So a half-written or wrong file never takes the server down.
A certificate that passes but does not cover every name in HostNames is applied, and a warning names the missing ones: watch the log for it.
Write the new PFX to a temporary file beside the real one and then replace the real one with it, in one step. A file written in place can be read while half written; the reloader rejects it, but it takes until the next check to see the finished file.
procedure StopServing(aServer: tTaskHttpsServer; aReloader: tCertificateReloader); begin { The reloader stops before the server it applies to. } aReloader.Stop; aReloader.Free; aServer.Stop; end;
One reloader can serve several targets and follow several files: every target receives every accepted file. Use this when one certificate is presented by several listeners - HTTPS and the mail protocols, say - or when a server has both an RSA and an ECDSA certificate. The certificate reload notes describe both.
TsmAsyncTLSServer · StreamSec.Mobile.CertificateReload