{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Author:       Angus Robertson, Magenta Systems Ltd
Description:  ICS File Server, FTP and WebDAV server.
Creation:     Oct 2026
Updated:      Nov 2026
Version:      V9.8
EMail:        francois.piette@overbyte.be  http://www.overbyte.be
Support:      https://en.delphipraxis.net/forum/37-ics-internet-component-suite/
Legal issues: Copyright (C) 2026 by Angus Robertson, Magenta Systems Ltd,
              Croydon, England. delphi@magsys.co.uk, https://www.magsys.co.uk/delphi/

              This software is provided 'as-is', without any express or
              implied warranty.  In no event will the author be held liable
              for any  damages arising from the use of this software.

              Permission is granted to anyone to use this software for any
              purpose, including commercial applications, and to alter it
              and redistribute it freely, subject to the following
              restrictions:

              1. The origin of this software must not be misrepresented,
                 you must not claim that you wrote the original software.
                 If you use this software in a product, an acknowledgment
                 in the product documentation would be appreciated but is
                 not required.

              2. Altered source versions must be plainly marked as such, and
                 must not be misrepresented as being the original software.

              3. This notice may not be removed or altered from any source
                 distribution.

              4. You must register this software by sending a picture postcard
                 to the author. Use a nice stamp and mention your name, street
                 address, EMail address and any comment you like to say.




DD Service Application Framework Requirement
--------------------------------------------
DDService is an enhanced Windows NT service application framework for Delphi and C++
Builder based on the original VCL service framework. In addition to it also encapsulates
new Windows NT service APIs introduced since Windows 2000. Original author was the late
Arno Garrels of Duodata in Berlin. Now being maintained by Magenta Systems Ltd.

https://www.magsys.co.uk/delphi/ddservice.asp

DDService must be installed before opening this sample.  Once the sample is built, it
may be installed as a Windows service from an elevated command line prompt with the
command IcsAppMon.exe /install. But this sample is written so it may also be run as
a GUI for debugging.




20 Nov 2026 V9.8 - Baseline
                   New sample combining the OverbyteIcsSslMultiFtpServ and
                     OverbyteIcsSslMultiWebServ samples, adding proper account support
                     for both using encoded passwords, and virtual directory support.
                     The web server only supports WebDAV requests not normal pages,
                     as an alternate to FTP.



Warning - this sample is only tested on recent Unicode compilers, it will
not build on older compilers without changes.

Insalling note:
The main WebDAV and FTP server configuration is in IcsFileServer-Hosts.config file, a
default file is included in the \ics\demoms-delphi-extra directory, and is copied to
ICS all users working directory, usually c:\ProgramData\ICS. Note this directory is
different to other ICS samples because it is common to all users instead of one user,
which is necessary because Windows services often run on the system account.  This
config file will need to be edited for IP addresses, SSL certificates, etc, although
some defaults may work.  Specifically Host4 has certificate ordering settings but
is disabled and will need new valid hosts, IP addresss and files names before it
will do anything useful.

Once this demo has been run once, any changes to the default INI file from new versions
(ie auto certificate ordering) will need to copied manually into the working file.

See OverbyteIcsWSocketS.pas for documentation on TSslWSocketServer whose
properties are exposed by TSslHttpAppSrv and TSslFtpServer, and for IcsHosts which
allows the web server to support multiple Hosts on multiple IP addresses and ports
with SSL support, including automatic SSL certificate ordering.

The server also uses a second IcsFileServer-Accounts.config file for accounts
authorised to access the WebDAV and FTP servers and their permissions, this is
in the same directory as the sample. This sample application uses the same file
for all IcsHosts which is opened after a remote client connects, but you can
use a different file for each host.

Sample entry from IcsFileServer-Accounts.config, one section for each login.
Note some values are specific to WebDAV or FTP protocols.

[00virtualdirs]
TotDirs=1
VDir1=d:\ftptest\logfiles
PDir1=d:\weblogs
;VDir2=d:\ceyedxfer\webcam
;PDir2=c:\magdelp\webcam

[webdav]
PwType=pwencaes256
Password=HRWnMAQepx/RbDYXN9yxOD4G+/YLqSZePh3EZVfA3wY=
ForceSsl=True
HomeDir=c:\webdavfiles\
OtpMethod=none
ReadOnly=true

[ftptest02]
PwType=pwencaes256
ForceSsl=falsMe
Password=IJmJHo6H65/GYhe2BnIExzlNJyqHbYWuwu/7qKhLzZk=
HomeDir=d:\ftptest
OtpMethod=otp-md5
ForceHomeDir=true
HidePhysicalPath=true
ReadOnly=false
VirtualDirs=false


 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

unit IcsFileServerMain;

{$I ..\Source\Include\OverbyteIcsDefs.inc}

{$B-}                                 { Enable partial boolean evaluation   }
{$T-}                                 { Untyped pointers                    }
{$X+}                                 { Enable extended syntax              }
{$H+}                                 { Use long strings                    }
{$J+}                                 { Allow typed constant to be modified }

{$WARN UNSAFE_TYPE off}
{$WARN UNSAFE_CAST off}
{$WARN UNSAFE_CODE off}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, WinApi.WinSvc, System.IniFiles,
  System.TypInfo, System.Types,
  OverbyteIcsUtils,
  OverbyteIcsTicks64,
//  OverbyteIcsIpStreamLog,
  OverbyteIcsSslHttpOAuth,
  OverbyteIcsMailQueue,
  OverbyteIcsTypes,
  OverbyteIcsSslUtils,
  OverbyteIcsSslBase,
  OverbyteIcsWndControl,
  OverbyteIcsWSocket,
  OverbyteIcsWSocketS,
  OverbyteIcsHttpSrv,
  OverbyteIcsHttpAppServer,
  OverbyteIcsSslX509Certs,
  OverbyteIcsAppMonCli,
  OverbyteIcsWinUtils,
  OverbyteIcsHtmlUtils,
  OverbyteIcsWebSocketcli,
{$IFDEF USE_IcsGeoTools}
  IcsGeoUtils,              { Delphi 11 and later only }
{$ENDIF USE_IcsGeoTools}
  OverbyteIcsWebSocketSrv,
  OverbyteIcsBlacklist,
  OverbyteIcsFtpSrv,
  OverbyteIcsFtpSrvT,
  OverbyteIcsMD5,
  OverbyteIcsOneTimePw,
  OverbyteIcsDnsQuery,
  OverbyteIcsSslJose;


const
    ProgTitle = 'IcsFileServer';
    SrvCopyRight : String = 'IcsFileServer'  + IcsVerLitCopyright;
    ProgVersion = ProgTitle + ' - ' + IcsVerLitRelDate;
    AppTitle = ProgTitle;
    SimpLogName = '"' + ProgTitle + '"yyyymmdd".log"' ;
    NameLogsPath = 'logs\' ;
    NameIniConfig = ProgTitle + '-Hosts.config' ;
    NameIniAccounts = ProgTitle + '-Accounts.config' ;
    EncodeKeyFileSrv = 61234 ;   // SMPT passwords
    IcsEncKeyAES = 'Jy6%$fDa,Jhs8i+ja7liw';   // encryption key to decode AES encoded passwords, MailQueue and Accounts
    WM_FM_STARTUP = WM_USER + 804 ;
    RestartDelaySecs = 30;   // seconds before attempting internal service restart
    FailedAttemptsMax = 5;   // max restart attempts before stopping this service so it restarts

  { account INI file layout }
    KeyPwType               = 'PwType' ;
    KeyPassword             = 'Password';
    KeyHomeDir              = 'HomeDir';
    KeyOtpMethod            = 'OtpMethod';
    KeyForceHomeDir         = 'ForceHomeDir';
    KeyHidePhysicalPath     = 'HidePhysicalPath';
    KeyReadOnly             = 'ReadOnly';
    KeyForceSsl             = 'ForceSsl';
    KeyVirtualDirs          = 'VirtualDirs';

type
  TMyHttpConnection = class(THttpWSSrvConn)    { client connection, where we add special stuff }
  public
    CStartTick        : Int64;  // used for logging requests
    CLastRead         : Int64;
    CLastWrite        : Int64;
    CPeerHostName     : string;
    AccountPwType     : TIcsPwType;
    AccountVirtDir    : Boolean;
    constructor Create(AOwner: TComponent); override;
    destructor  Destroy; override;
    procedure BgExceptionEvent (Sender : TObject; E : Exception; var CanClose : Boolean);
  end ;

  TUrlHandlerWSServerStatus = class(TUrlHandler)    { WebSocket page handler }
  public
      procedure Execute; override;
  end;

  { We use our own client class to hold our thread and other local stuff }
  TGetProcessingThread = class; { Forward declaration }
  TMyFtpClient = class(TFtpCtrlSocket)
  private
      FWorkerThread    : TGetProcessingThread;
      ReportSslCert    : Boolean;
  end;

  TGetProcessingThread = class(TThread)
  protected
    Server : TFtpServer;
    Client : TMyFtpClient;
  public
      procedure Execute; override;
  end;

type
  TServerMain = class(TForm)
    Panel1: TPanel;
    LogWin: TMemo;
    IcsMailQueue: TIcsMailQueue;
    IcsRestEmail: TIcsRestEmail;
    doClose: TButton;
    SslHttpAppSrv: TSslHttpAppSrv;
    TimerMain: TTimer;
    SslX509Certs: TSslX509Certs;
    IcsDomainNameCache1: TIcsDomainNameCache;
    IcsAppMonCli: TIcsAppMonCli;
    SslFtpServer: TSslFtpServer;
    procedure IcsMailQueueOATokenEvent(ServNr: Integer; var Token, TokAccount: string; var TokExpireDT: TDateTime);
    procedure IcsMailQueueLogEvent(LogLevel: TMailLogLevel; const Info: string);
    procedure FormCreate(Sender: TObject);
    procedure IcsRestEmailEmailNewToken(Sender: TObject);
    procedure IcsRestEmailEmailProg(Sender: TObject; LogOption: TLogOption; const Msg: string);
    procedure doCloseClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure TimerMainTimer(Sender: TObject);
    procedure SslHttpAppSrvAuthGetPassword(Sender, Client: TObject; var Password: string);
    procedure SslHttpAppSrvAuthGetType(Sender, Client: TObject);
    procedure SslHttpAppSrvAuthResult(Sender, Client: TObject; Success: Boolean);
    procedure SslHttpAppSrvBeforeProcessRequest(Sender, Client: TObject);
    procedure SslHttpAppSrvBgException(Sender: TObject; E: Exception; var CanClose: Boolean);
    procedure SslHttpAppSrvClientConnect(Sender, Client: TObject; Error: Word);
    procedure SslHttpAppSrvDisplay(Sender: TObject; const Msg: string);
    procedure SslHttpAppSrvProcDocument(Sender, Client: TObject; var Flags: THttpGetFlag);
    procedure SslHttpAppSrvHttpRequestDone(Sender, Client: TObject);
    procedure IcsAppMonSrvChangeEvent(Sender: TObject);
    procedure SslX509CertsCertProg(Sender: TObject; LogOption: TLogOption; const Msg: string);
    procedure LogWinChange(Sender: TObject);
    procedure SslHttpAppSrvOptionsDocument(Sender, Client: TObject; var Flags: THttpGetFlag);
    procedure SslHttpAppSrvHttpAcceptFilter(Sender, Client: TObject; var SessIpInfo: TIcsSessIpInfo; var Allowed: Boolean);
    procedure SslX509CertsGeoEvent(Sender: TObject; const IpStr: string; var Geo: string);
    procedure IcsAppLog(Sender: TObject; const Msg: string);
    procedure IcsDomainNameCache1DNUpdateEvent(Sender: TObject; ItemNr: Integer);
    procedure IcsAppMonCliWakeEvent(Sender: TObject);
    procedure IcsDomainNameCache1GeoEvent(Sender: TObject; const IpStr: string; var Geo: string);
    procedure SslFtpServer1ValidateRnFr(Sender: TObject; Client: TFtpCtrlSocket; var FilePath: TFtpString; var Allowed: Boolean);
    procedure SslFtpServer1AlterDirectory(Sender: TObject; Client: TFtpCtrlSocket; var Directory: TFtpString; Detailed: Boolean);
    procedure SslFtpServer1AnswerToClient(Sender: TObject; Client: TFtpCtrlSocket; var Answer: TFtpString);
    procedure SslFtpServer1Authenticate(Sender: TObject; Client: TFtpCtrlSocket; UserName, Password: TFtpString; var Authenticated: Boolean);
    procedure SslFtpServer1BgException(Sender: TObject; E: Exception; var CanClose: Boolean);
    procedure SslFtpServer1BuildDirectory(Sender: TObject; Client: TFtpCtrlSocket; var Directory: TFtpString; Detailed: Boolean);
    procedure SslFtpServer1BuildFilePath(Sender: TObject; Client: TFtpCtrlSocket; const Directory, FileName: string; var NewFileName: string);
    procedure SslFtpServer1ChangeDirectory(Sender: TObject; Client: TFtpCtrlSocket; Directory: TFtpString; var Allowed: Boolean);
    procedure SslFtpServer1ClientCommand(Sender: TObject; Client: TFtpCtrlSocket; var Keyword, Params, Answer: TFtpString);
    procedure SslFtpServer1ClientConnect(Sender: TObject; Client: TFtpCtrlSocket; AError: Word);
    procedure SslFtpServer1ClientDisconnect(Sender: TObject; Client: TFtpCtrlSocket; AError: Word);
    procedure SslFtpServer1Display(Sender: TObject; Client: TFtpCtrlSocket; Msg: TFtpString);
    procedure SslFtpServer1GetProcessing(Sender: TObject; Client: TFtpCtrlSocket; var DelayedSend: Boolean);
    procedure SslFtpServer1MakeDirectory(Sender: TObject; Client: TFtpCtrlSocket; Directory: TFtpString; var Allowed: Boolean);
    procedure SslFtpServer1OtpGetPassword(Sender: TObject; Client: TFtpCtrlSocket; UserName: TFtpString; var UserPassword: string);
    procedure SslFtpServer1OtpMethod(Sender: TObject; Client: TFtpCtrlSocket; UserName: TFtpString; var OtpMethod: TOtpMethod);
    procedure SslFtpServer1Rein(Sender: TObject; Client: TFtpCtrlSocket; var Allowed: Boolean);
    procedure SslFtpServer1RetrDataSent(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
    procedure SslFtpServer1RetrSessionClosed(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
    procedure SslFtpServer1RetrSessionConnected(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
    procedure SslFtpServer1SslHandshakeDone(Sender: TObject; ErrCode: Word; PeerCert: TX509Base; var Disconnect: Boolean);
    procedure SslFtpServer1SslServerName(Sender: TObject; var Ctx: TSslContext; var ErrCode: TTlsExtError);
    procedure SslFtpServer1SslVerifyPeer(Sender: TObject; var Ok: Integer; Cert: TX509Base);
    procedure SslFtpServer1StorSessionConnected(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
    procedure SslFtpServer1ValidateDele(Sender: TObject; Client: TFtpCtrlSocket; var FilePath: TFtpString; var Allowed: Boolean);
    procedure SslFtpServer1ValidatePut(Sender: TObject; Client: TFtpCtrlSocket; var FilePath: TFtpString; var Allowed: Boolean);
    procedure SslFtpServer1Host(Sender: TObject; Client: TFtpCtrlSocket; Host: TFtpString; var Allowed: Boolean);
    procedure WorkerThreadTerminated(Sender : TObject);
    procedure SslFtpServerAddVirtFiles(Sender: TObject; Client: TFtpCtrlSocket; var LocFiles: TIcsFileRecs; var LocFileList: TList;
      var TotalFiles: Integer; ProgressCallback: TMD5Progress);

  public
    procedure ApplicationEventsException(Sender: TObject; E: Exception);
    procedure AddLogLine (S1: string);
    procedure CloseLogFile;
    procedure FlushLogFile(OldFName: Boolean = False);
    procedure OpenLogFiles;
    procedure GetGenSettings ;
    procedure SendEmailEvent(Sender: TObject; const Subject, Body: string; Fatal: Boolean);
    procedure StartQueueMail;
    procedure StopQueueMail;
    procedure WMFMSTARTUP (var Msg : TMessage); message WM_FM_STARTUP;
    procedure MonitorStop;
    procedure ClientBgException(Sender: TObject; E: Exception; var CanClose : Boolean);
    procedure ClientWSLogEvent(Sender: TObject; const Msg: string);                                       { websockets }
    procedure ClientWSHandshakeEvent(Client: THttpWSSrvConn; var OK: Boolean; var WelcomeMsg: String);    { websockets }
    procedure ClientWSFrameRcvdEvent(Client: THttpWSSrvConn; const APacket: String; var AFrame: TWebSocketReceivedFrame);  { websockets }
    procedure ClientWSFrameSentEvent(Client: THttpWSSrvConn; var AFrame: TWebSocketOutgoingFrame);         { websockets }
    procedure ClientWSDisconnectedEvent(Sender: TObject);                                                  { websockets }
    procedure ClientWSReadyEvent(Client: THttpWSSrvConn);                                                  { websockets }
    procedure ClientWSPingTimerEvent(Client: THttpWSSrvConn);                                              { websockets }
    procedure ReportHosts;
    procedure CountryNameEvent(Sender: TObject; const ISOA2: string; var CountryName: String);
    procedure LoadAllLists;
    function UnEscapeStr (const Buffer: string): string ;
  end;

var
    ServerMain: TServerMain;
    GStartedByScm: Boolean = False;
    ServiceStartedByScm: string ;
    DiagLogBuffer: TIcsBuffLogStream ;     // temporary buffer for log
    DirApplication: String;
    ClosingFlag: Boolean;
    curDT: TDateTime;
    LogDate: TDateTime;
    LogOpenFlag: Boolean;
    OldRefrToken: String;
    SrvActiveTick: Int64;
    SrvRestarts: integer;
    SrvCompName: String;
    ServerInfo: String;
    ServerWSHost: String;
    ServerRegStatus: String;
    LastMemWarn: TIcsMemWarn;
    MemoryTrigger: Int64;
    HourlyTrigger: Int64;
    MemoryInfo: String;
    MemoryLoad: string;

// INI stuff for email and logging, more loaded by IcsLoadTAppMonSrvFromIni and web server versions
    FileLoggingsDir: string ;
    AdminEmailFrom: string ;
    AdminEmailTo: string ;
    AdminEmailStart: boolean ;

{$IFDEF USE_IcsGeoTools}
    IcsGeoTools: TIcsGeoTools;
{$ENDIF USE_IcsGeoTools}

    AttemptsBlackList: TIcsBlackList ; { restrict access by IP addresses }
    HackBlackList: TIcsBlackList ;     { detected hackers }
    IcsFilterList: TIcsFilterList;
    IcsWhiteList: TIcsIpAddrList;
    ChallengeTestingActive: Boolean;
    ListsDir: String;
    HostsIniFile: TMemIniFile;
    HostsIniConfig: String;
    AccountsIniFile: TMemIniFile;
    AccountsIniConfig: String;
    AccountsNames: TStringList;
    CertCheckTrigger: Int64;
    HouseKeepingTrg: int64;
    LastErrorEmail: String;
    FOtpSequence: integer;
    FOtpSeed: String;
    FAccountPath: String;
    TotVirDir: integer ;
    ListVDirs: TStringDynArray;
    ListPDirs: TStringDynArray;

implementation

{$R *.dfm}
{$R ICSMedia.res}    { geo stuff }

Uses IcsFileServerSrv;  // DDService


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TServerMain.UnEscapeStr (const Buffer: string): string ;
var
    I, TxLen: integer ;
    Ch: Char ;
    curDT: TDateTime;

    procedure BuildTxString (Ch2: Char) ;
    begin
        inc (TxLen) ;
        if Length (result) <= TxLen then SetLength (result, TxLen * 2) ;
        result [TxLen] := Ch2 ;
    end ;

    procedure BuildTxString2 (S2: string) ;
    begin
        if Length (result) <= (TxLen + Length (S2)) then
                                SetLength (result, TxLen + Length (S2) + 2) ;
        Move (S2 [1], result [TxLen + 1], (Length (S2) * SizeOf(Char)));   { V8.70 unicode fix }
        inc (TxLen, Length (S2)) ;
    end ;

begin
    result := '' ;
    if Length (Buffer) = 0 then exit ;
    curDT := Now ;
    SetLength (result, Length (Buffer) * 2) ;
    TxLen := 0 ;
    I := 1 ;
    while I <= Length (Buffer) do
    begin
        Ch := Buffer [I] ;
        inc (I) ;
        if Ch <> '\' then
            BuildTxString (Ch)
        else
        begin
            if I > Length (Buffer) then break ;
            Ch := Buffer [I] ;  // escape, get next character
            inc (I) ;
            if Ch = 'n' then
            begin
                BuildTxString (IcsCR) ;
                BuildTxString (IcsLF) ;
            end
            else if Ch = 'c' then
                BuildTxString (IcsCR)
            else if Ch = 'l' then
                BuildTxString (IcsLF)
            else if Ch = '\' then
                BuildTxString ('\')
            else if (Ch = 'd') then
            begin
                BuildTxString2 (DatetoStr (curDT) + Icsspace + TimeToStr (curDT)) ;
            end
            else if (Ch = 'o') then
            begin
                BuildTxString2 (FormatDateTime (ISODateTimeMask, curDT)) ;
            end
            else if (Ch = 't') then
            begin
                BuildTxString2 (TimeToStr (curDT)) ;
            end
            else if (Ch = 'p') then
            begin
                BuildTxString2 (SrvCompName) ;
            end
       (*     else if (Ch = 'i') then    { V8.70 }
            begin
                BuildTxString2 (FormatIpAddrPort (FormatIpAddr (Server.Addr), Server.Port)) ;
            end     *)
            else if (Ch = 'h') then    { V8.70 }
            begin
                BuildTxString2 (SslFtpServer.IcsHosts[0].HostNames[0]) ;
            end
            else if (Ch = 'v') then   { V8.70 }
            begin
                BuildTxString2 (SrvCopyRight) ;
            end
            else if (Ch = 's') then
            begin
                BuildTxString2 (OverbyteIcsFtpSrv.CopyRight) ;
            end
            else
            begin
                BuildTxString ('\') ;  // unknown escape, send both chars
                BuildTxString (Ch) ;
            end ;
        end ;
    end ;
    SetLength (result, TxLen) ;
end ;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.FormCreate(Sender: TObject);
begin
{$WARNINGS OFF}
    ReportMemoryLeaksOnShutdown := (DebugHook <> 0);     { V8.69 }
{$WARNINGS ON}
    Caption := ProgVersion ;
//    Application.OnMessage := TriggerMessageEvent ;
    Application.OnException := ApplicationEventsException ;
    if NOT IcsCheckUniqueInstance then begin
        IcsSimpleLogging (SimpLogName, 'ICS File Server is Already Running') ;
        Application.Terminate ;
        exit ;
    end ;
    SrvActiveTick := IcsGetTickCount64;
    AccountsNames := TStringList.Create;
    HouseKeepingTrg := IcsGetTrgSecs64 (300);
    CertCheckTrigger := Trigger64Disabled;
    PostMessage (Handle, WM_FM_STARTUP, 0, 0) ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
    if ClosingFlag then
        Exit ;
    ClosingFlag := true ;
    try
        TimerMain.Enabled := false ;
        if Assigned (DiagLogBuffer) then
            AddLogLine ('FormClose, Stopping Server Monitor') ;
        MonitorStop;
    except
        IcsSimpleLogging (SimpLogName, 'Exception FormClose') ;
    end ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.FormDestroy(Sender: TObject);
begin
    try
        if NOT ClosingFlag then begin
            ClosingFlag := true ;
            AddLogLine ('FormDestroy, Stopping Server Monitor') ;
            MonitorStop;
        end;
        FreeAndNil (AccountsNames);
        FreeAndNil (HostsIniFile) ;
        FreeAndNil (AccountsIniFile) ;
        CloseLogFile ;
        FreeAndNil (DiagLogBuffer) ;
    except
        IcsSimpleLogging (SimpLogName, 'Exception FormDestroy');
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.AddLogLine (S1: string);
var
    res: integer ;
begin
    curDT := Now ;
//    if ClosingFlag then
//        Exit;
    try
        S1 := TimeToStr (curDT) + IcsSpace + S1 ;
        if (NOT GStartedByScm) and (LogWin <> Nil) then
           LogWin.Lines.Add(S1);

   // file logging
        res := 0;
        try
            if Assigned (DiagLogBuffer) then
                res := DiagLogBuffer.WriteLine (S1) ;
        except
            res := -1 ;
        end ;
        if (res = -1) and Assigned (DiagLogBuffer) then
            DiagLogBuffer.WriteLine (S1) ;  // one retry before exception
    except
        IcsSimpleLogging (SimpLogName, 'Error Writing Log - ' + IcsGetExceptMess (ExceptObject)) ;
   end ;
end ;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.FlushLogFile(OldFName: Boolean = False) ;
begin
    try
        if Assigned (DiagLogBuffer) then
        begin
        //    if NOT FileInUse (DiagLogBuffer.FullName) then
                DiagLogBuffer.FlushFile(OldFName)
          //  else
         //       AddLogLine ('Skipped Flushing Diag Log, In-Use') ;
        end ;
    except
        IcsSimpleLogging (SimpLogName, 'Error Flushing Logs - ' + IcsGetExceptMess (ExceptObject)) ;
    end ;
end ;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.CloseLogFile ;
begin
    try
        if Assigned (DiagLogBuffer) then
        begin
            DiagLogBuffer.FlushFile ;
            DiagLogBuffer.Free ;
            DiagLogBuffer := Nil ;
        end ;
    except
        IcsSimpleLogging (SimpLogName, 'Aborting - Error Closing Diag Log') ;
    end ;
    LogOpenFlag := false ;
end ;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.doCloseClick(Sender: TObject);
begin
    Close;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.OpenLogFiles ;
var
    diagfname, S: string;
begin
    curDT := Now ;
    CloseLogFile ;

    diagfname := IcsDQUOTE + FileLoggingsDir + '\' + ProgTitle + '-"yyyymmdd".log"' ;
    S := '"' + ProgVersion + IcsCRLF +
         'Log File Created: "dd mmm yyyy hh:mm:ss"' + IcsCRLF +
         'Computer: ' + IcsGetCompName + '"' + IcsCRLF ;
    try
        DiagLogBuffer := TIcsBuffLogStream.Create (Self, diagfname, S) ;
        DiagLogBuffer.FlushFile ;
        LogOpenFlag := true ;
    except
        IcsSimpleLogging (SimpLogName, 'Aborting - Error Opening Log - ' + IcsGetExceptMess (ExceptObject)) ;
    end ;
end ;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.GetGenSettings ;
var
    section: string ;
begin
    if NOT FileExists (HostsIniConfig) then begin
      IcsSimpleLogging (SimpLogName, 'Hosts INI File Not Found - ' + HostsIniConfig);
      exit ;
    end;
    if NOT FileExists (AccountsIniConfig) then begin
      IcsSimpleLogging (SimpLogName, 'Accounts INI File Not Found - ' + AccountsIniConfig);
      exit ;
    end;
    FreeAndNil (HostsIniFile) ;
    FreeAndNil (AccountsIniFile) ;
    try
        HostsIniFile := TMemIniFile.Create (HostsIniConfig) ;
        section := 'General' ;
        with HostsIniFile do begin
            FileLoggingsDir := ReadString (section, 'FileLoggingsDir', 'c:\weblogs\' + ProgTitle + '\') ;
            AdminEmailTo := ReadString (section, 'AdminEmailTo', '') ;     // full email address
            AdminEmailFrom := ReadString (section, 'AdminEmailFrom', '') ; // @domain only, computer name added to front
            AdminEmailStart := IcsCheckTrueFalse (ReadString (section, 'AdminEmailStart', 'False')) ;
            SslX509Certs.ProxyURL := HostsIniFile.ReadString (section, 'X509ProxyURL', '') ;
        end ;
    except
        IcsSimpleLogging (SimpLogName, 'Aborting - Failed to open INI File - ' + IcsGetExceptMess (ExceptObject)) ;
    end ;
end ;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SendEmailEvent(Sender: TObject; const Subject, Body: string; Fatal: Boolean);
var
    sTempFrom: string ;
    id: integer ;
begin
    if Fatal then begin
        if NOT IcsMailQueue.Active then exit;   // July 2024 only once
        AddLogLine ('Stopping Mail Queue After Fatal Error') ;
        IcsMailQueue.Active := False;
        exit;
    end
    else begin
        if NOT IcsMailQueue.Active then
            StartQueueMail ;  // restart if not running
        if NOT IcsMailQueue.Active then
        begin
             AddLogLine ('Error Starting Mail Queue') ;
        end ;
    end;

    try
        with IcsMailQueue.QuHtmlSmtp do begin
            sTempFrom := AppTitle + '_' + IcsGetCompName ;
            sTempFrom := '"' + sTempFrom + '" <' + sTempFrom + AdminEmailFrom + '>' ;
            EmailFiles.Clear ;
            RcptName.clear;
            Allow8bitChars := true ;
            ContentType := smtpPlainText ;
            WrapMessageText := false ;
            WrapMsgMaxLineLen := 76 ;
            PlainText.Clear ;
            PlainText.Text := IcsAppMonTitle + ' on ' + IcsGetCompName + IcsCRLF + IcsCRLF + Body ;
            AddLogLine ('Queuing Email Form to ' + AdminEmailTo + ' from ' + sTempFrom) ;
            RcptName.Clear ;
            RcptName.Add (AdminEmailTo) ;
            FromName := sTempFrom ;
            HdrCc := '' ;
            HdrTo := AdminEmailTo ;
            HdrFrom := sTempFrom ;
            HdrReplyTo := sTempFrom ;
            if Subject = '' then
                HdrSubject := IcsAppMonTitle
            else
                HdrSubject := IcsAppMonTitle + ' - ' + Subject;
            XMailer := '' ;
            id := IcsMailQueue.QueueMail ;
            if id > 0 then
            begin
       // done OK
                AddLogLine ('Email Form Queued OK') ;
            end
            else
            begin
                AddLogLine ('Failed to Queue Email Form: ' + ErrorMessage) ;
            end ;
        end ;
    except
        AddLogLine ('Failed to Queue Email Form: ' + IcsGetExceptMess (ExceptObject)) ;
    end;
    FlushLogFile;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsRestEmailEmailNewToken(Sender: TObject);
var
    info: String;
begin
// we should save refresh token since only get it after a login window
    if (IcsRestEmail.RefrToken <> '') and (IcsRestEmail.RefrToken <> OldRefrToken) then begin
        info := 'New OAuth2 Refresh Token for Account: ' + IcsRestEmail.NewAccEmail +
                ', Should be Saved in Config File' + IcsCRLF +
                'RefrToken=' + IcsRestEmail.RefrToken;
        AddLogLine(info);
        if (AdminEmailTo <> '') then
            SendEmailEvent (Self, 'Refresh Token', 'IcsMailQueue New OAuth2 Refresh Token.' + IcsCRLF + IcsCRLF + info, False);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsRestEmailEmailProg(Sender: TObject; LogOption: TLogOption; const Msg: string);
begin
    AddLogLine (Msg) ;
end;


procedure TServerMain.LogWinChange(Sender: TObject);
begin

end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.StartQueueMail;
var
    S, PW: string ;
    I: integer ;
begin
    try
        if NOT IcsMailQueue.Active then
        begin
            IcsLoadMailQuFromIni(HostsIniFile, IcsMailQueue, 'MailQueue');
            if (IcsMailQueue.MailQuDir = '') or (NOT ForceDirectories (IcsMailQueue.MailQuDir)) then
            begin
                AddLogLine ('!! Failed to Start Mail Queue, No Directory') ;
                exit ;
            end;
            IcsLoadRestEmailFromIni(HostsIniFile, IcsRestEmail, 'RestEmail');
            OldRefrToken := IcsRestEmail.RefrToken;
            IcsMailQueue.PwEncKey := IcsEncKeyAES;
        end;
        if IcsMailQueue.MailServers.Count = 0 then
        begin
            AddLogLine ('!! Failed to Start Mail Queue, No Mail Servers') ;
            exit ;
        end;

        if (AdminEmailFrom = '') or (AdminEmailTo = '') then begin   { V9.6 }
            AddLogLine ('Can not start Mail Queue with EmailTo and EmailFrom addresses') ;
            Exit;
        end;

        S := '';
        for I := 0 to IcsMailQueue.MailServers.Count - 1 do
        begin
        //    PW := IcsMailQueue.MailServers[I].Password;
        //    IcsMailQueue.MailServers[I].Password := IcsStrBXDecryptEx (PW, EncodeKeyFileSrv) ;
            S := S + IcsMailQueue.MailServers[I].Host + ', ';
            S := S + 'Decode: ' + PW + ' > ' + IcsMailQueue.MailServers[I].Password + ', ';     // TEMP DIAG !!!!
        end;
        IcsMailQueue.Debug := False;
        IcsMailQueue.QuStartDelay := 0; // no delay sending email
        IcsMailQueue.Active := true ;
        if IcsMailQueue.Active then
        begin
             AddLogLine ('Started Mail Queue OK, Servers: ' + S) ;
        end;
    except
         AddLogLine ('!! Failed to Start Mail Queue - ' +  IcsGetExceptMess (ExceptObject)) ;
    end;
 end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.StopQueueMail;
begin
    if IcsMailQueue.Active then
    begin
        if (IcsMailQueue.MailImmItems > 0) then
            AddLogLine ('Waiting up to 10 seconds to send Queued Mail Items') ;
        IcsMailQueue.WaitSendandStop (10) ;
    end ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsMailQueueLogEvent(LogLevel: TMailLogLevel; const Info: string);
begin
    if LogLevel <= MLogLevelInfo then
        AddLogLine (Info) ;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// called by Blacklist to get country names from ISOA2
procedure TServerMain.CountryNameEvent(Sender: TObject; const ISOA2: string; var CountryName: String);
begin
{$IFDEF USE_IcsGeoTools}     { V9.5 }
    CountryName := IcsGeoTools.FindCountry(ISOA2);
{$ELSE}
    CountryName := '';
{$ENDIF USE_IcsGeoTools}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsAppLog(Sender: TObject; const Msg: string);
begin
    AddLogLine (Msg) ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsDomainNameCache1DNUpdateEvent(Sender: TObject; ItemNr: Integer);
begin
//
end;


{* * * * * * * *1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsDomainNameCache1GeoEvent(Sender: TObject; const IpStr: string; var Geo: string);
{$IFDEF USE_IcsGeoTools}     { V9.5 }
var
    ISO2A, CountryName, AsnName: string;
    AsnNum: Int64;
{$ENDIF USE_IcsGeoTools}
begin
{$IFDEF USE_IcsGeoTools}     { V9.5 }
    ISO2A := IcsGeoTools.FindISOA2Code(IPStr);
    CountryName := IcsGeoTools.FindCountry(ISO2A);
    AsnName := IcsGeoTools.FindASNCode(IpStr, AsnNum);
    Geo := ISO2A;
    if CountryName <> '' then
        Geo := CountryName;
    if AsnName <> '' then
        Geo := Geo + ', ' + AsnName;
{$ELSE}
    Geo := '';
{$ENDIF USE_IcsGeoTools}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.LoadAllLists;
var
    I, K: Integer;
    dirv, dirp: String;
begin
    IcsFilterList.FileName := DirApplication + '\hackfilterlist.txt';  // hackers bad paths and IP addresses
    IcsFilterList.LoadList;
    IcsWhiteList.FileName := DirApplication + '\whiteiplist.txt';  // address we don't want to block
    IcsWhiteList.LoadList;

 // load user accounts
    FreeAndNil (AccountsIniFile) ;
    try
        AccountsIniFile := TMemIniFile.Create (AccountsIniConfig) ;
        AccountsIniFile.ReadSections(AccountsNames);
        AddLogLine('Number of account names: ' + IntToStr(AccountsNames.Count));

      // read virtual directories, if configured
        TotVirDir := 0 ;
        K := AccountsIniFile.ReadInteger ('00virtualdirs', 'TotDirs', 0);
        SetLength (ListVDirs, K + 1) ;
        SetLength (ListPDirs, K + 1) ;
        if K > 0 then begin
            for I := 1 to K do begin
                dirv := AccountsIniFile.ReadString ('00virtualdirs', 'VDir' + IntToStr (I), '') ;
                dirp := LowerCase (AccountsIniFile.ReadString('00virtualdirs', 'PDir' + IntToStr (I), '')) ;
                if (dirv <> '') and (dirp <> '') then begin
                    if NOT IcsDirExists (dirp) then
                        AddLogLine('Virtual Directory Target Path Not Found - ' + dirp)
                    else begin
                        ListPDirs [TotVirDir] := dirv;
                        ListVDirs [TotVirDir] := dirp;
                        inc (TotVirDir) ;
                    end;
                end;
            end ;
            AddLogLine('Total Virtual Directories Configured: ' + IntToStr (TotVirDir));
        end;
    except
        AddLogLine('!! Failed to load accounts: ' + AccountsIniConfig);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsMailQueueOATokenEvent(ServNr: Integer; var Token, TokAccount: string; var TokExpireDT: TDateTime);
begin
    AddLogLine('Starting to get OAuth2 Bearer Token');
    if NOT IcsRestEmail.GetNewToken(False) then   // no interaction, waits for browser window to be completed
        AddLogLine('Failed to get OAuth2 Bearer Token')
    else begin
        Token := IcsRestEmail.AccToken;
        TokExpireDT := IcsRestEmail.AccExpireDT;
        TokAccount := IcsRestEmail.NewAccEmail;
      // note, AccToken has a short life, few hours, no need to save it in INI file, it can be refreshed
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ApplicationEventsException(Sender: TObject; E: Exception);
var
    S: string ;
begin
    S := '!!! Application Exception Event - ' + IcsGetExceptMess (E) ;
    if LogOpenFlag then
    begin
        AddLogLine (S) ;
        FlushLogFile;
    end
    else
        IcsSimpleLogging (SimpLogName, S) ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ReportHosts;
var
    S: string ;
    J: integer ;
    autoorder: string ;
begin
    autoorder := 'Disabled';
    AddLogLine (IcsCRLF + 'Total WebDAV server hosts ' + IntToStr(SslHttpAppSrv.IcsHosts.Count)) ;
    if SslHttpAppSrv.IcsHosts.Count > 0 then begin
        for J := 0 to SslHttpAppSrv.IcsHosts.Count - 1 do begin
            with SslHttpAppSrv.IcsHosts[J] do begin
                if CertValRes > chainOK then begin
                    AddLogLine ('Server: ' + DisplayName + IcsCRLF +
                                'SSL Certificate chain: ' + IcsCRLF +
                                CertInfo + IcsCRLF + CertErrs) ;
                end;
                if CertValRes = chainFail then begin
                    AddLogLine ('Server SSL Certificate Errors') ;
                end;
                S := 'Source #' + IntToStr(J) + ' - ' + HostTag + ': ' + Descr + IcsCRLF +
                     'Host: ' + HostNames [0] + ', Bindings: ' + BindInfo + IcsCRLF;
                if BindSslPort <> 0 then begin
                    if SslHttpAppSrv.SslCertAutoOrder then begin
                        autoorder := SupplierProtoLits[CertSupplierProto];
                        if CertSupplierProto > SuppProtoNone then
                            autoorder := autoorder + ',  Challenge: ' + ChallengeTypeLits[CertChallenge] + ', Database: ' + CertDirWork;
                    end;
                    S := S + 'SSL Certificate Auto Order: ' + autoorder + IcsCRLF;
                    S := S + 'SSL Security Level ' + SslSrvSecurityNames[SslSrvSecurity] + IcsCRLF;
                    S := S + CertErrs + icsCRLF +
                             CertInfo + icsCRLF;
                end
                else
                    S := S + 'No SSL' + IcsCRLF;
                if WellKnownPath <> '' then
                    S := S + 'Well-Known path root: ' + WellKnownPath + IcsCRLF;
                AddLogLine (S) ;
            end;
        end;
    end;
    AddLogLine (IcsCRLF + 'Total FTP server hosts '  + IntToStr(SslFtpServer.IcsHosts.Count)) ;
    if SslFtpServer.IcsHosts.Count > 0 then begin
        for J := 0 to SslFtpServer.IcsHosts.Count - 1 do begin
            with SslFtpServer.IcsHosts[J] do begin
                if CertValRes > chainOK then begin
                    AddLogLine ('Server: ' + DisplayName + IcsCRLF +
                                'SSL Certificate chain: ' + IcsCRLF +
                                CertInfo + IcsCRLF + CertErrs) ;
                end;
                if CertValRes = chainFail then begin
                    AddLogLine ('Server SSL Certificate Errors') ;
                end;
                S := 'Source #' + IntToStr(J) + ' - ' + HostTag + ': ' + Descr + IcsCRLF +
                     'Host: ' + HostNames [0] + ', Bindings: ' + BindInfo + IcsCRLF;
                if BindSslPort <> 0 then begin
                    if SslHttpAppSrv.SslCertAutoOrder then begin
                        autoorder := SupplierProtoLits[CertSupplierProto];
                        if CertSupplierProto > SuppProtoNone then
                            autoorder := autoorder + ',  Challenge: ' + ChallengeTypeLits[CertChallenge] + ', Database: ' + CertDirWork;
                    end;
                    S := S + 'SSL Certificate Auto Order: ' + autoorder + IcsCRLF;
                    S := S + 'SSL Security Level ' + SslSrvSecurityNames[SslSrvSecurity] + IcsCRLF;
                    S := S + CertErrs + icsCRLF +
                             CertInfo + icsCRLF;
                end
                else
                    S := S + 'No SSL' + IcsCRLF;
                if WellKnownPath <> '' then S := S + 'Well-Known path root: ' + WellKnownPath + IcsCRLF;
                AddLogLine (S) ;
            end;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.WMFMSTARTUP (var Msg : TMessage);
var
    S, Errs: String;
    I: Integer;
begin
    try
        DirApplication := ExtractFileDir (Lowercase (ParamStr(0)));
        HostsIniConfig := DirApplication + '\' + NameIniConfig ;        // main config file
        AccountsIniConfig := DirApplication + '\' + NameIniAccounts ;   // accounts config file
        IcsSimpleLogging (SimpLogName, 'Config File: ' + HostsIniConfig) ;
        GetGenSettings ;
        if FileLoggingsDir = '' then begin
            IcsSimpleLogging (SimpLogName, 'Fatal Error, No Config File') ;
            Application.Terminate;
            Exit;
        end;
        IcsSimpleLogging (SimpLogName, 'Logs Path: ' + FileLoggingsDir) ;
        ListsDir := IncludeTrailingBackslash(FileLoggingsDir) + 'datafiles\';
        IcsForceDirsEx(ListsDir);

    // logging and OpenSSL for mail
        OpenLogFiles;
        AddLogLine ('');
        AddLogLine (ProgVersion);
        AddLogLine ('OS: ' + TOSVersion.ToString);
        AddLogLine ('Compiler: ' + IcsBuiltWithEx) ;
        AddLogLine('SSL/TLS ' + IcsReportOpenSSLVer(True));
        AddLogLine('Config File: ' + HostsIniConfig) ;
        AddLogLine('Logs Path: ' + FileLoggingsDir) ;
        S := 'Initialising';
        AddLogLine(S) ;
 //       IcsAppMonSrvEmailEvent(Self, S, IcsAppMonTitle + ' ' + S, False);
 //       AddLogLine('LogPackets=' + BoolToStr(IcsAppMonSrv.LogPackets, True));   // TEMP !!!!

        FlushLogFile(True);

    // server information for web page and websocket
        ServerInfo := ProgVersion  + sTagBR +
        'Server Started Time: ' + IcsDateTimeToAStr (Now) + sTagBR +
        'Windows Boot Time: ' + IcsDateTimeToAStr (IcsLastBootDT) + sTagBR +
        'Server Computer: ' + SrvCompName + sTagBR +
        'Server OS: ' + TOSVersion.ToString + sTagBR +
        'Compiler: ' + IcsBuiltWithEx + sTagBR +
        'OpenSSL Version: ' + IcsReportOpenSSLVer(False) + sTagBR +
        'Config File: ' + HostsIniConfig + sTagBR +
        'Logs Path: ' + FileLoggingsDir + sTagBR;

    // open firewall and add rule
        try
            if IcsIsProgAdmin then begin
                AddLogLine (Trim(IcsFireWallRulesEnum('')));  // list settings
                S := IcsFireWallRulesAdd(ProgTitle, 'ICS', ProgTitle, ParamStr(0), FirewallBoth);
                AddLogLine ('Windows Firewall Rule: ' + S);
            end;
        except
            AddLogLine ('Failed to Access Firewall - ' + IcsGetExceptMess (ExceptObject)) ;
        end;

    // Application Monitor component
        IcsAppMonCli.AppTitle := ProgTitle;
        IcsAppMonCli.AppGeneral := ProgTitle + ', ' + IcsVerLitRelDate + ', ' + IcsBuiltWithEx + ', ' + IcsReportOpenSSLVer(False);
        if GStartedByScm then
            IcsAppMonCli.ServiceName := IcsFileServerControl.ServiceName
        else
            IcsAppMonCli.ServiceName := ServiceNone;
        IcsAppMonCli.LANWide := False;  // only listen for IcsAppMon on this computer
        IcsAppMonCli.AppHandle := Self.Handle;
        IcsAppMonCli.AppMonMode := AMModeNonStop;
        IcsAppMonCli.LogPackets := True;
 //       IcsAppMonCli.Start (AppTitle + ' Monitoring Starting');     // !!! TEMP suppressed during development

       // V8.60 load hackers filters and blacklists
       // V8.60 load hackers filters and blacklists
        if NOT Assigned (AttemptsBlacklist) then
            AttemptsBlacklist := TIcsBlackList.Create(self);
        AttemptsBlacklist.SaveAscii := true ;
        AttemptsBlacklist.ListName := 'Attempts' ;
        AttemptsBlacklist.onBlackLogEvent := IcsAppLog;           { V9.5 }
        AttemptsBlackList.OnCountryNameEvent := CountryNameEvent; { V9.5 }
        AttemptsBlacklist.BlockAfterMins := 1440;
        AttemptsBlacklist.BlockAttempts := 1000;
        AttemptsBlacklist.BlockForMins := 720;
        AttemptsBlacklist.BlackFile := ListsDir + 'AttemptsBlacklist.lst' ;
        if NOT Assigned (HackBlackList) then
            HackBlackList := TIcsBlackList.Create(self);
        HackBlackList.ListName := 'Hackers' ;
        HackBlackList.onBlackLogEvent := IcsAppLog;            { V9.5 }
        HackBlackList.OnCountryNameEvent := CountryNameEvent;  { V9.5 }
        HackBlackList.BlockAfterMins := 1;
        HackBlackList.BlockAttempts := 1;
        HackBlackList.BlockForMins := 1440;
        HackBlackList.BlackFile := ListsDir + 'HackBlacklist.lst' ;

        // MMDB Reader geo component, new list components
{$IFDEF USE_IcsGeoTools}     { V9.5 }
      IcsGeoTools := TIcsGeoTools.Create(Self);
      IcsGeoTools.OnAppLog := IcsAppLog;
      IcsGeoTools.UseResources := False;
      if FileExists(IcsGeoTools.DBCountryFile) then begin
          IcsGeoTools.LoadDBCountry;
          IcsGeoTools.LoadDBASN;
          IcsGeoTools.LoadIcsCountries;
      end
      else
           AddLogLine('GEO Database File Not Found: ' + IcsGeoTools.DBCountryFile);
{$ENDIF USE_IcsGeoTools}

        IcsFilterList := TIcsFilterList.Create(self);
        IcsWhiteList := TIcsIpAddrList.Create(Self);
        IcsFilterList.OnAppLog := IcsAppLog;
        IcsWhiteList.OnAppLog := IcsAppLog;
        LoadAllLists;  // filter lists, accounts
        ChallengeTestingActive := False;

    except
        S :='Failed to Initialise Server: ' + IcsGetExceptMess (ExceptObject) ;
        IcsSimpleLogging (SimpLogName, S) ;
        AddLogLine(S) ;
        Exit;
    end;

  // start WebDAV server, if configured
    try
        IcsLoadTHttpAppSrvFromIni(HostsIniFile, SslHttpAppSrv, 'WebDAVServer');
        IcsLoadIcsHostsFromIni(HostsIniFile, SslHttpAppSrv.IcsHosts, 'WD-Host');
        if SslHttpAppSrv.IcsHosts.Count = 0 then begin
            AddLogLine('No WebDAV Server Hosts Configured, WebDAV Server Disabled');
        end
        else begin
            AddLogLine('Number of WebDAV Hosts Configured: ' + IntToStr(SslHttpAppSrv.IcsHosts.Count));

       // validate hosts and keep site certificate information
            try
                S := SslHttpAppSrv.ValidateHosts(False, True); // don't stop on first error, no exceptions
                if S <> '' then begin
                    AddLogLine('WebDAV Server Validation Errors:' + icsCRLF + S);
                end;
                ReportHosts;
                AddLogLine('WebDAV Required Listen Bindings:' + icsCRLF + SslHttpAppSrv.ListenStates);
            except
                on E:Exception do begin
                    AddLogLine('WebDAV Host Validation Failed, Server Stopped - ' + E.Message);
                    Exit;
                end;
            end;

        // setup some web server defauls, most were done in IcsLoadTHttpAppSrvFromIni
            SslHttpAppSrv.TemplateDir := DirApplication;
            SslHttpAppSrv.DocDir := DirApplication;
            for I := 0 to SslHttpAppSrv.IcsHosts.Count -1  do begin
                SslHttpAppSrv.IcsHosts [I].WebTemplDir := DirApplication;
                SslHttpAppSrv.IcsHosts [I].WebDocDir := DirApplication;
            end;
            SslHttpAppSrv.DefaultDoc := '';   //  WebServStatusPage;
            SslHttpAppSrv.ServerHeader := DefServerHeader;  // get latest version
            SslHttpAppSrv.ClientClass := TMyHttpConnection;  // only needed if we have our own class or Websockets
            SslHttpAppSrv.SocketErrs := wsErrFriendly ;
            SslHttpAppSrv.ExclusiveAddr := true ;
            if SslHttpAppSrv.SessionTimeout < 30 then
                SslHttpAppSrv.SessionTimeout := 300;  // sanity check
            SslHttpAppSrv.WSDebugOptions := DefWSDebugServer + [wsdlogHdr];       // TEMP HTTP headers

         {  WebDAV support, and some newer commands, could be INI file  }
  // !!! not sure we need this, set in event and conmfig file
            SslHttpAppSrv.Options := SslHttpAppSrv.Options + [hoAllowOptions, hoAllowPut, hoAllowDelete, hoAllowTrace,
                                                            hoAllowPatch, hoAllowPropFind, hoAllowMkCol, hoAllowCopy,
                                                            hoAllowMove, hoAllowPropPatch, hoAllowLock, hoAllowUnlock,
                                                            hoAllowQuery];

          // note that AllowedPaths and Handlers must match a HostTag for each Host in INI file

          // application web server, only allow access to folders where static documents are.
            SslHttpAppSrv.AddGetAllowedPath('/', afBeginBy, 'APPMON');

          // Add dynamic webpage application page handlers, create pages from a template and dynamic content
            SslHttpAppSrv.AddGetHandler(WebServStatusPage, TUrlHandlerWSServerStatus, hgWillSendMySelf, 'APPMON');

          // start as many hosts as possible
            S := SslHttpAppSrv.Start (True) ;
            if S <> '' then
                AddLogLine('Status Web Server Error - ' + S);
            if NOT SslHttpAppSrv.ListenAllOK then
                S := 'Status Web Server Failed to Start, '
            else
               S := 'Status Web Server Started OK, ';
            S := S + 'WebDAV Listen Bindings:' + IcsCRLF + SslHttpAppSrv.ListenStates;
            AddLogLine(S);
            ServerInfo := ServerInfo + 'WebDAV Listen Bindings:' + sTagBR +
                                       IcsWebReplaceCRLF(SslHttpAppSrv.ListenStates) + sTagBR + sTagBR;
        end;
    except
        S :='Failed to Start WebDAV Server: ' + IcsGetExceptMess (ExceptObject) ;
        IcsSimpleLogging (SimpLogName, S) ;
        AddLogLine(S) ;
    end;

// start FTP server, if configured
    try
        IcsLoadFtpServerFromIni(HostsIniFile, SSlFtpServer, 'FtpServer');

      // read the server hosts from INI file and check SSL files exist
        IcsLoadIcsHostsFromIni(HostsIniFile, SslFtpServer.IcsHosts, 'FtpHost', SslFtpServer.ServSocket);
        if SslFtpServer.IcsHosts.Count <= 0 then begin
            AddLogLine('Can Not Start FTP Server - No Server Hosts Configured') ;
        end
        else begin
            AddLogLine('Number of FTP Hosts Configured: ' + IntToStr(SslFtpServer.IcsHosts.Count));

        // validate hosts and keep site certificiate information
            Errs := SslFtpServer.ValidateHosts(False, True); // don't stop on first error, no exceptions
            if Errs <> '' then begin
                AddLogLine('Server Validation Errors:' + icsCRLF + Errs);
                if AdminEmailTo <> '' then
                    SendEmailEvent(Self, 'ICS File Server, FTP Validation Errors', Errs, False);
            end;
            ReportHosts;
            AddLogLine('Required Listen Bindings:' + icsCRLF + SslFtpServer.ListenStates);

      // setup some FTP server defauls, most were done in IcsLoadTFtpAppSrvFromIni
           S := '';
            SslFtpServer.ClientClass := TMyFtpClient;
            SslFtpServer.SocketErrs := wsErrFriendly ;
            SslFtpServer.ExclusiveAddr := true ;
            if SslFtpServer.TimeoutSecsIdle < 30 then
                SslFtpServer.TimeoutSecsIdle := 30;  // sanity check
            if Pos ('\n', SslFtpServer.Banner) > 0 then
                SslFtpServer.Banner := UnEscapeStr (SslFtpServer.Banner);
            if SslFtpServer.Banner = '' then
                SslFtpServer.Banner := '220 ICS FTP Server';
            AddLogLine('Server options: ' + IcsSetToStr (TypeInfo (TFtpsOption), SslFtpServer.Options, 4)) ;
            SslFtpServer.WSDebugOptions := [wsdlogConnWS, wsdlogListen, wsdlogAccept, wsdlogInfo, wsdlogSsl, wsdlogHdr,
                                                                                     wsdlogCerts, wsdlogErrs, wsdlogDns];
            SslFtpServer.Start ;
            if NOT SslFtpServer.ListenAllOK then
                S := 'Failed to Start, '
            else
                 S := 'Started OK, ';
            S := S + 'FTP Server Listen Bindings:' + IcsCRLF + SslFtpServer.ListenStates;
            AddLogLine(S);
            ServerInfo := ServerInfo + 'FTP Server Listen Bindings:' + sTagBR +
                                       IcsWebReplaceCRLF(SslHttpAppSrv.ListenStates) + sTagBR + sTagBR;
            if (AdminEmailTo <> '') then
                SendEmailEvent(Self, 'ICS File Server, FTP Started', 'ICS FTP Server' + IcsCRLF + IcsCRLF + S + IcsCRLF, False);
            DiagLogBuffer.FlushFile(True);
        end;
    except
        on E:Exception do begin
        S :='Failed to Start FTP Server: ' + IcsGetExceptMess (ExceptObject) ;
        IcsSimpleLogging (SimpLogName, S) ;
        AddLogLine(S) ;
        end;
    end;

  //triggers, log and test memory
    MemoryTrigger := Trigger64Immediate;
    HourlyTrigger := Trigger64Immediate;
    CertCheckTrigger := IcsGetTrgSecs64 (15) ;
    ServerRegStatus := '(Pending server status updates and counters)';
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.MonitorStop;
var
    S: String;
    I: Integer;

    procedure Waiting(secs: integer);
    var
        Trg: Int64;
    begin
        Trg := IcsGetTrgSecs64 (secs) ;
        while True do begin
            Application.ProcessMessages ;
            if Application.Terminated then
                break ;
            if IcsTestTrgTick64 (Trg) then
                break ;
        end;
    end;

begin
    try

        // close WebDAV clients
         if SslHttpAppSrv.IcsHosts.Count > 0 then begin
              if SslHttpAppSrv.ClientCount > 0 then begin
                  AddLogLine ('Closing Websockets');
                  for I := SslHttpAppSrv.ClientCount - 1 downto 0 do begin
                      with (SslHttpAppSrv.Client[I] as THttpWSSrvConn) do begin
                          if (State = wsConnected) and WSClient and (NOT WSClosing) then
                              WSClose(wscrNormalClosure, 'Server Closing');
                      end;
                  end;
              end;
              AddLogLine ('Stopping WebDAV Server');
              FlushLogFile;
              SslHttpAppSrv.Stop;
          end;

       // stop FTP server
        if SslFtpServer.IcsHosts.Count > 0 then begin
              AddLogLine ('Stopping FTP Server');
              SslFtpServer.Stop;
        end;

        if (AdminEmailTo <> '') then
            SendEmailEvent(Self, 'ICS File Stopped', 'ICS File Server Stopped' + IcsCRLF, False);

        { report Blacklisted remotes }
          S := '' ;
          if Assigned (AttemptsBlackList) then
              S := S + AttemptsBlackList.ListName + ' Report:' + IcsCRLF +
                               AttemptsBlackList.ReportBlackList (true) + IcsCRLF ;
          if Assigned (HackBlackList) then
              S := S + HackBlackList.ListName + ' Report:' + IcsCRLF +
                               HackBlackList.ReportBlackList (true) + IcsCRLF ;
          AddLogLine(S);

        { save blacklists to files }
          if Assigned (HackBlackList) then
            HackBlackList.FlushToFiles;
          if Assigned (AttemptsBlackList) then AttemptsBlackList.FlushToFiles;

          if (AdminEmailTo <> '') then begin { tell someone }
              IcsMailQueue.QuStartDelay := 0; // V9.3 no delay sending last email
              SendEmailEvent (Self, 'ICS DD Web Service Stopped', 'ICS DD Web Service Stopped' + IcsCRLF, False);
          end;
          AddLogLine('Server stopped');
          DiagLogBuffer.FlushFile(True);

          AddLogLine ('Stopping Mail Queue');
          FlushLogFile;
          StopQueueMail;

          S :='Stopped Servers and Mail Queue OK';
          IcsSimpleLogging (SimpLogName, S) ;
          AddLogLine(S) ;
          FlushLogFile;
    except
        S :='Exception Stopping Monitoring: ' + IcsGetExceptMess (ExceptObject) ;
        IcsSimpleLogging (SimpLogName, S) ;
        AddLogLine(S) ;
        FlushLogFile;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.TimerMainTimer(Sender: TObject);
var
    S1: string;
    IcsMemWarn: TIcsMemWarn; { V9.5 }
    NewFlag: Boolean;
begin
    TimerMain.Enabled := False;
    try

     // Application Monitor component, only if server is running, should do more checks
     // pending only one server ??
     //   if SslHttpAppSrv.ListenAny and SslFtpServer.ListenAny then
     //       IcsAppMonCli.Awake('', '');

      // check SSL certificates every 20 minutes, may order expired certs
        if IcsTestTrgTick64 (CertCheckTrigger) then begin
            CertCheckTrigger := IcsGetTrgMins64 (20) ;
            try
              // don't stop on first error, no exceptions
                    AddLogLine('Regular Server Recheck for New SSL Certificates Starting');
                    if Assigned(DiagLogBuffer) then         { V9.8 sanity test }
                        DiagLogBuffer.FlushFile(True);
                    NewFlag := SslHttpAppSrv.RecheckSslCerts(S1, False, True);
                    if NewFlag or (S1 <> '') then  begin
                        if NewFlag then
                            AddLogLine('Server Recheck Loaded New SSL Certificate(s)');
                        AddLogLine('Server Recheck SSL Certificate Errors:' + icsCRLF + S1);
                        if (S1 <> '') and (LastErrorEmail <> S1) then
                             SendEmailEvent (Self, 'ICS File Server Recheck SSL Certificate Errors', S1, False);
                        LastErrorEmail := S1 ;
                        ReportHosts;    // report everything again
                        AddLogLine('Listen Bindings:' + icsCRLF + SslHttpAppSrv.ListenStates);
                    end
                    else
                        AddLogLine('Server Recheck SSL Certificate Nothing New');
                LoadAllLists;  //update filters
            except
                on E:Exception do begin
                   AddLogLine('Server Recheck SSL Certificate Failed - ' + E.Message);
                end;
            end;
        end;

      // rotate logs at midnight, recheck SSL certificates, log configuration again
        if LogDate <> Trunc(Date) then begin
            LogDate := Trunc(Date);
            AddLogLine('Nightly Server Recheck Starting');
            ReportHosts;    // report everything again
            AddLogLine('Listen Bindings:' + icsCRLF + SslHttpAppSrv.ListenStates);
            CertCheckTrigger := Trigger64Immediate;
           if Assigned(DiagLogBuffer) then
                DiagLogBuffer.FlushFile(True);
        end;

    // memory checking - once a minute
        if IcsTestTrgTick64 (MemoryTrigger) then begin
            MemoryTrigger := IcsGetTrgSecs64(60);                   // reported via Json
            IcsMemWarn := IcsMemWarning(MemoryLoad, 85, 85, 95);   // can customise warning levels
            if IcsMemWarn > MemWarnNone then begin
                S1 := '!!! Memory Warning: ' + IcsCRLF + MemoryInfo;
                AddLogLine (S1);
                if LastMemWarn <> IcsMemWarn then begin
                    LastMemWarn := IcsMemWarn;
                    if IcsMemWarn >= MemWarnCritical then
                        SendEmailEvent(Self, 'Critical Memory Warning', IcsAppMonTitle + ' ' + S1, False)
                    else
                        SendEmailEvent(Self, 'Low Memory Warning', IcsAppMonTitle + ' ' + S1, False);
                end;
            end
            else begin
                if LastMemWarn > MemWarnNone then
                    LastMemWarn := MemWarnNone;
            end;
        end;

    // V9.5 hourly memory logging
        if IcsTestTrgTick64 (HourlyTrigger) then begin
            HourlyTrigger := IcsGetTrgMins64(60);
            AddLogLine (MemoryInfo);
        LoadAllLists;
        end;

    finally
        TimerMain.Enabled := True;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TMyHttpConnection.Create(AOwner: TComponent);
begin
    inherited Create(AOwner);
    OnBgException := BgExceptionEvent ;
    CPeerHostName := '' ;
    OnWSLogEvent := ServerMain.ClientWSLogEvent;
    OnWSHandshake := ServerMain.ClientWSHandshakeEvent;
    OnWSFrameRcvd := ServerMain.ClientWSFrameRcvdEvent;
    OnWSFrameSent := ServerMain.ClientWSFrameSentEvent;
    OnWSDisconnected := ServerMain.ClientWSDisconnectedEvent;
    OnWSReady := ServerMain.ClientWSReadyEvent;
    OnWSPingTimer := ServerMain.ClientWSPingTimerEvent;
    // DebugBody decodes all frames, DebugHdr only main info , DebugConn only connections oe DebugNone
    DebugLevel := DebugConn;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMyHttpConnection.BgExceptionEvent(Sender : TObject; E : Exception; var CanClose : Boolean);
begin
     ServerMain.AddLogLine('Client Error - ' + IcsGetExceptMess (E)) ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ We need to override parent class destructor  }
destructor TMyHttpConnection.Destroy;
begin
    inherited Destroy;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// called before returning pages that require authenication, so we can check AuthUserName and find it's password }
procedure TServerMain.SslHttpAppSrvAuthGetPassword(Sender, Client: TObject; var Password: string);
var
    ClientCnx  : TMyHttpConnection;
    UName, EncPW: String;
begin
    Password := '';
    ClientCnx := TMyHttpConnection(Client);
    UName := ClientCnx.AuthUserName;
    AddLogLine('AuthGetPassword for "' + ClientCnx.Path + '" AuthType is "' + AuthTypesToString(ClientCnx.AuthTypes) + '"' +
                                                                                                    ' for Username: ' + UName);
    if AccountsNames.IndexOf(ClientCnx.AuthUserName) < 0 then begin
        AddLogLine('Login failed, no account for: ' + UName);
        Exit;
    end;

// find and decode account pssword }
    ClientCnx.AccountPwType := TIcsPwType(GetEnumValue(TypeInfo (TIcsPwType), IcsTrim(AccountsIniFile.ReadString(UName, KeyPwType, 'pwnone'))));
    ClientCnx.AccountVirtDir := IcsCheckTrueFalse (AccountsIniFile.ReadString (UName, KeyVirtualDirs, 'False'));
    EncPw := AccountsIniFile.ReadString(UName, KeyPassword, '');  // keep password to check later
    Password := IcsPasswordGet(ClientCnx.AccountPwType, UName, EncPw, IcsEncKeyAES) ;
    AddLogLine('Auth Get Password for: ' + UName + ' > ' + Password);   // !!! TEMP DIAG
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// called before any pages, so they can be protected by authenication
procedure TServerMain.SslHttpAppSrvAuthGetType(Sender, Client: TObject);
var
    ClientCnx  : TMyHttpConnection;
begin
    ClientCnx := TMyHttpConnection(Client);
    ClientCnx.AuthTypes  := [];

// only need to valid WebDAV login once in session
    if ClientCnx.WebDAVAcc >= webdavRead then begin
        Exit;
    end;

// only status  page escapes authenticatiom
    if CompareText(ClientCnx.Path, WebServStatusPage) = 0 then begin
       Exit;
    end;

     { special WebDAV session start page for shared servers, only needed if server has unauthenticated normal pages  }
//    if CompareText(ClientCnx.Path, '/WebDAV') = 0 then begin
//        ClientCnx.AuthTypes  := [atBasic, atDigest, atDigestSha2];
//        ClientCnx.AuthRealm := 'WebDAV';
//    end;

 { all requests are authenticated }
    ClientCnx.AuthTypes  := [atBasic, atDigest, atDigestSha2];
    ClientCnx.AuthRealm := 'WebDAV';
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// called autentication finished, so we can log the result, if we care
procedure TServerMain.SslHttpAppSrvAuthResult(Sender, Client: TObject; Success: Boolean);
var
    ClientCnx  : TMyHttpConnection;
    S: String;
const
    SuccessStr : array [Boolean] of String = ('failed', 'OK');
begin
    ClientCnx := TMyHttpConnection(Client);
    if Success and (AccountsNames.IndexOf(ClientCnx.AuthUserName) >= 0) then begin
         ClientCnx.WebDAVRootDir := AccountsIniFile.ReadString(ClientCnx.AuthUserName, KeyHomeDir, 'c:\temp');
         if IcsDirExists(ClientCnx.WebDAVRootDir ) then begin
            if NOT IcsCheckTrueFalse(AccountsIniFile.ReadString(ClientCnx.AuthUserName, KeyReadOnly, 'True')) then begin
                ClientCnx.WebDAVAcc := webdavWrite ;
                S := 'Read/Write';
            end
            else begin
                ClientCnx.WebDAVAcc := webdavRead;
                S := 'Read Only';
            end;
            AddLogLine('Root WebDAV Directory: ' + ClientCnx.WebDAVRootDir + ', Access: ' + S);
            S := ' for WebDAV ' + ClientCnx.WebDAVRootDir;
            ClientCnx.KeepAlive := True;
            ClientCnx.Options := ClientCnx.Options + [hoAllowPropFind, hoAllowMkCol, hoAllowCopy, hoAllowMove,
                                                            hoAllowPropPatch, hoAllowLock, hoAllowUnlock];
         end
         else
            AddLogLine('WebDAV Directory Not Found: ' + ClientCnx.WebDAVRootDir + ', Command Not Allowed');
    end;
    AddLogLine('Authentication result ' + SuccessStr[Success] + ' with type ' + HttpAuthTypeNames[ClientCnx.AuthGetMethod] +
                                                                                     ', Username: ' + ClientCnx.AuthUserName);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// called before authentication and specific methods are processed }
procedure TServerMain.SslHttpAppSrvBeforeProcessRequest(Sender, Client: TObject);
var
    ClientCnx: TMyHttpConnection;
    I: integer ;
    Protocol, S: String;
begin
    ClientCnx := TMyHttpConnection(Client) ;
    Protocol := ClientCnx.RequestProtocol + '://';
    ClientCnx.CStartTick := IcsGetTickCount64;
    ClientCnx.CLastWrite := ClientCnx.WriteCount ;

{ log request and heders }
    S := '[' + FormatDateTime('HH:NN:SS', Now) + ' ' + IntToStr(ClientCnx.CliId) + IcsSpace + ClientCnx.PeerAddr + '] ' +
                                                   ClientCnx.HostTag + ' ' +  ClientCnx.Method + ' ' + ClientCnx.Path;
    if ClientCnx.Params <> '' then
        S := S + '?' + ClientCnx.Params;
    AddLogLine(S);

  // check for absolute URL, strip off protocol and host
    if Pos (Protocol, ClientCnx.Path) = 1 then begin
        for I := (Length (Protocol) + 1) to Length (ClientCnx.Path) do begin
            if ClientCnx.Path [I] = '/' then begin
                AddLogLine('Found and Trimmed Absolute URL: ' + ClientCnx.Path);
                ClientCnx.Path := Copy (ClientCnx.Path, I, 999) ;
                Break ;
            end;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// something horrible has happened, it may be terminal and have crashed the server
procedure TServerMain.SslHttpAppSrvBgException(Sender: TObject; E: Exception; var CanClose: Boolean);
begin
    AddLogLine('Exception processing page - ' +  E.ClassName + ': ' + E.Message);
    CanClose := FALSE;  // Let the server continue to accept connections
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// something horrible has happened, it may be terminal and have crashed the server
procedure TServerMain.ClientBgException(Sender: TObject; E: Exception; var CanClose : Boolean);
begin
    AddLogLine('Exception processing page - ' + E.ClassName + ': ' + E.Message);
    CanClose := TRUE;  // Shutdown client
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslHttpAppSrvClientConnect(Sender, Client: TObject; Error: Word);
var
    ClientCnx : TMyHttpConnection;
begin
    ClientCnx := Client as TMyHttpConnection;
    ClientCnx.WSessionCookie := 'OverbyteIcsWebAppServer' + SslHttpAppSrv.Port;
    ClientCnx.OnBgException := ClientBgException;

 { log something at start }
    AddLogLine('New Web Server Remote Client: ' + ClientCnx.CPeerAddr);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslHttpAppSrvDisplay(Sender: TObject; const Msg: string);
begin
    AddLogLine(Msg);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslHttpAppSrvHttpAcceptFilter(Sender, Client: TObject; var SessIpInfo: TIcsSessIpInfo; var Allowed: Boolean);
var
    ClientCnx : TMyHttpConnection;
{$IFDEF USE_IcsGeoTools}     { V9.5 }
    IcsCountry: TIcsCountry;
{$ENDIF USE_IcsGeoTools}
    LogISO: String;
    AsnInfo: String;
    Geo: String;
begin
    ClientCnx := Client as TMyHttpConnection;
    LogISO := '';
    AsnInfo := '';
    Geo := '';

 { V9.5 SessIpInfo record has remote and local IPs and ports as binary and strings }
    with SessIpInfo do begin

{$IFDEF USE_IcsGeoTools}     { V9.5 }
{ V9.5 lookup country from IP Address, check if connections allowed }
        ISOA2 := IcsGeoTools.FindISOA2Code(RemoteAddr);
        IcsCountry := IcsGeoTools.FindNameRec(ISOA2);
        CountryName := IcsCountry.Country;
        RegionName := IcsGeoTools.FindRegion(IcsCountry.SubRegion);
        LogISO := ' ISO=' + ISOA2 + IcsSpace + CountryName + ', Region ' + RegionName;
        AsnName := IcsGeoTools.FindASNCode(RemoteAddr, AsnNum);
        if AsnNum > 0 then
            AsnInfo := AsnName + ' (' + IntToStr(AsnNum) + ')';
        Geo := CountryName;
        if AsnName <> '' then
            Geo := Geo + ', ' + AsnName;

     { V9.5 see if blocking regions or specific countries }
     { beware Let's Encrypt and Google Trust Service certificate ordering checks domains from multiple countries,
       so we whitelist remote connections for the few seconds that challenges are checked }
       if (IcsCountry.Region in [IcsRegionAsia, IcsRegionAfrica]) or
                (IcsCountry.SubRegion in [IcsRegionEastEurope]) or
                (IcsCountry.SubRegion = IcsRegionLatinAmerica) then begin    // range max 256, Latin=419
            if (NOT IcsWhiteList.CheckIpAddr(RemoteAddr, True)) and (NOT ChallengeTestingActive) then begin    { V9.5 }
                HackBlackList.AddBlackListSoc (SocRemoteAddr, 9999, ISOA2, AsnInfo);
                AddLogLine('Region Blocked, Connection Refused: ' + RemoteAddr + LogISO) ;
                Allowed := False;
                Exit;
            end;
            AddLogLine('Region Blocked, But IP Address Whitelisted: ' + RemoteAddr + LogISO) ;
        end;

   // V9.5, check ASN ISP
        if IcsFilterList.TestFilters ('asn', AsnInfo) then begin
            if (NOT IcsWhiteList.CheckIpAddr(RemoteAddr, True)) and (NOT ChallengeTestingActive) then begin    { V9.5 }
                HackBlackList.AddBlackListSoc (SocRemoteAddr, 9999, ISOA2, AsnInfo);
                AddLogLine('ASN/ISP Blocked, Connection Refused - ' + AsnInfo + ': ' + RemoteAddr);
                Allowed := False;
                Exit;
            end;
            AddLogLine('ASN/ISP Blocked, But IP Address Whitelisted: ' + AsnInfo + ': ' + RemoteAddr) ;
        end;

{$ENDIF USE_IcsGeoTools}

     { V8.71 reverse DNS for remote host using new DNS cache component }
     { may find remote IP in cache, if not returns IP and starts a DNS lookup calling event when done }
        ClientCnx.CPeerHostName := IcsDomainNameCache1.LookupIPOne(RemoteAddr, 1, sfAny, IcsDomainNameCache1DNUpdateEvent, Geo);
        RemoteRDNS := ClientCnx.CPeerHostName;  { SessIpInfo.RemoteRDNS replaces CPeerHostName, but kept backward compatit }

     { V8.64 log something at start }
        AddLogLine(FormatDateTime('HH:NN:SS', Now) + ' New Remote Client: ' + RemoteAddr + LogISO + ' ' + AsnInfo + ', Server: ' +
                                  IcsFmtIpv6AddrPort(LocalAddr, LocalPort));  { V8.71 added time, V9.5 added ISO, ASN and server }

    { V8.71 check blacklist before starting SSL negotiation }
        if IcsFilterList.TestFilters('remaddr', RemoteAddr, True) or IcsFilterList.TestFilters('remhost', RemoteRDNS) or
                                                       HackBlackList.CheckBlackListSoc(SocRemoteAddr) then begin
            if NOT IcsWhiteList.CheckIpAddr(RemoteAddr, True) then begin
                HackBlackList.AddBlackListSoc(SocRemoteAddr, 9999, ISOA2, AsnInfo);
                AddLogLine('Hacker Aleady Blacklisted, Connection Refused: ' + RemoteAddr) ;
                Allowed := False;   // tell server not to accept connection, it does not need to be closed
            end;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslHttpAppSrvHttpRequestDone(Sender, Client: TObject);
var
    ClientCnx  : TMyHttpConnection;
begin
    ClientCnx := TMyHttpConnection(Client);
    AddLogLine('Web Server Request Completed, ' + IntToStr(ClientCnx.CliId) + IcsSpace +
                                                        ClientCnx.GetPeerAddr + ', Status ' + IntToStr(ClientCnx.AnswerStatus));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslHttpAppSrvOptionsDocument(Sender, Client: TObject; var Flags: THttpGetFlag);
var
    ClientCnx  : TMyHttpConnection;
begin
    { path may be the resource for which OPTIONS should be checked }
    if Flags = hg401 then
        Exit;
    ClientCnx := TMyHttpConnection(Client);
    if CompareText(ClientCnx.Path, '/WebDAV') = 0 then begin          { special WebDAV session start page }
        if (ClientCnx.AuthTypes <> []) and (ClientCnx.WebDAVAcc = webdavNone) then
            Flags := hg401;     // force authentication
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// This event handler is shared by Get/Post/Put/Head to handle all requests, you can have separate handlers
procedure TServerMain.SslHttpAppSrvProcDocument(Sender, Client: TObject; var Flags: THttpGetFlag);
var
    ClientCnx : TMyHttpConnection;
begin
    ClientCnx := Client as TMyHttpConnection;

 // ignore page requests and simply return our status page
    ClientCnx.Path := WebServStatusPage;   // ignore page requested and return our status page only

end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslX509CertsCertProg(Sender: TObject; LogOption: TLogOption; const Msg: string);
begin
   AddLogLine(Msg);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslX509CertsGeoEvent(Sender: TObject; const IpStr: string; var Geo: string);
var
    ISO2A, CountryName, AsnName: string;
    AsnNum: Int64;
begin
{$IFDEF USE_IcsGeoTools}    { V9.7 }
    ISO2A := IcsGeoTools.FindISOA2Code(IPStr);
    CountryName := IcsGeoTools.FindCountry(ISO2A);
    AsnName := IcsGeoTools.FindASNCode(IpStr, AsnNum);
{$ENDIF USE_IcsGeoTools}
    Geo := ISO2A;
    if CountryName <> '' then
        Geo := CountryName;
    if AsnName <> '' then
        Geo := Geo + ', ' + AsnName;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ClientWSLogEvent(Sender: TObject; const Msg: string);
begin
    AddLogLine(Msg);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ClientWSHandshakeEvent(Client: THttpWSSrvConn; var OK: Boolean; var WelcomeMsg: String);
var
    S: String;
begin
    OK := False;
    if (CompareText(Client.WSReqPage, WebSocStatusWeb) = 0) or (CompareText(Client.WSReqPage, WebSocStatusJson) = 0) then begin
        OK := True;
        Client.WSPingSecs := 30;     // used for server push
        Client.WSPingEnabled := True;
    end;
     if OK then
        S := ' Accepted'
    else
        S := ' Rejected';
    AddLogLine('WebSocket ' + IntToStr(Client.CliId) + IcsSpace + Client.CPeerAddr + ': Request for ' + Client.WSReqPage + S);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
 // called once when the websocket is ready for traffic
procedure TServerMain.ClientWSReadyEvent(Client: THttpWSSrvConn);
begin
    AddLogLine('Websocket ' + IntToStr(Client.CliId) + IcsSpace + Client.PeerAddr + ': Ready for ' + Client.WSReqPage);
    if (CompareText(Client.WSReqPage, WebSocStatusWeb) = 0) then begin
        Client.WSSendText(Nil, '==1' + ServerInfo + '<BR><BR>' + IcsCRLF);
        Client.WSSendText(Nil, '==3' + IcsWebReplaceCRLF(MemoryInfo));     { V9.5 }
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// called evry 30 seconds to sending topical content
procedure TServerMain.ClientWSPingTimerEvent(Client: THttpWSSrvConn);
begin
    if (CompareText(Client.WSReqPage, WebSocStatusWeb) = 0) then begin
        Client.WSSendText(Nil, '==2' + ServerRegStatus);
        Client.WSSendText(Nil, '==3' + IcsWebReplaceCRLF(MemoryInfo));     { V9.5 }
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.IcsAppMonCliWakeEvent(Sender: TObject);
begin
//xx
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// for any appmonsrv changes, resend any websocket content immediately
procedure TServerMain.IcsAppMonSrvChangeEvent(Sender: TObject);
var
    I: Integer;
begin
    if SslHttpAppSrv.ClientCount = 0 then
        Exit;
  // loop around all remote clients
    for I := 0 to SslHttpAppSrv.ClientCount - 1 do begin
        with (SslHttpAppSrv.Client[I] as THttpWSSrvConn) do begin
            if (State = wsConnected) and WSClient then
                ClientWSPingTimerEvent((SslHttpAppSrv.Client[I] as THttpWSSrvConn));
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ClientWSFrameRcvdEvent(Client: THttpWSSrvConn; const APacket: String; var AFrame: TWebSocketReceivedFrame);
begin
    if AFrame = Nil then
        Exit;
    if AFrame.Kind = wsfkPong then
    Exit;
    AddLogLine('Websocket ' + IntToStr(Client.CliId) + IcsSpace + Client.PeerAddr + ': ' + Client.WSReqPage + ' ' +
                                         GetWSFrameKind(AFrame.Kind) + ' received, length: ' + IntToStr(AFrame.DataBytes));
    case AFrame.Kind of
        wsfkClose: begin
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ClientWSFrameSentEvent(Client: THttpWSSrvConn; var AFrame: TWebSocketOutgoingFrame);
begin
    if AFrame = Nil then
        Exit;
    if AFrame.Kind = wsfkPing then
        Exit;
    AddLogLine('Websocket ' + IntToStr(Client.CliId) + IcsSpace + Client.PeerAddr + ': ' +
                                            Client.WSReqPage + ' ' + GetWSFrameKind(AFrame.Kind) + ' sent');
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.ClientWSDisconnectedEvent(Sender: TObject);
var
    Client: THttpWSSrvConn;
begin
    Client := Sender as THttpWSSrvConn;
    AddLogLine('Websocket ' + IntToStr(Client.CliId) + IcsSpace + Client.PeerAddr +
                            ': ' + Client.WSReqPage + ' Closing, Total Frames ' + IntToStr(Client.WSFrameCounter));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// create the ServerStatus.htm web page from a template adding ws:// url and titles
procedure TUrlHandlerWSServerStatus.Execute;
begin
    if Client.SslEnable then                                                                   // host name
        ServerWSHost := 'wss://' + Client.SslServerName + ':' +  Client.CServerPort
    else
        ServerWSHost := 'ws://' + IcsFmtIpv6AddrPort(Client.CServerAddr, Client.CServerPort);  // numeric IP
    ServerWSHost := ServerWSHost + WebSocStatusWeb;
    AnswerPage('', NO_CACHE, WebServStatusPage, nil,
             ['PageFile', WebSocStatusWeb, 'PageTitle', IcsAppMonTitle + ' - ' + SrvCompName, 'WSHost', ServerWSHost ]);
    Finish;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1AlterDirectory(Sender: TObject; Client: TFtpCtrlSocket; var Directory: TFtpString; Detailed: Boolean);
var
    Buf : String;
begin
    if UpperCase(Client.Directory) <> 'C:\' then
        Exit;
    { Add our 'virtual' directory to the list }
    if Detailed then begin
        { We need to format directory lines according to the Unix standard }
        Buf :=
        'drwxrwxrwx   1 ftp      ftp            0 Apr 30 19:00 VIRTUAL' + #13#10;
        Client.DataStream.Write(Buf[1], Length(Buf));
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1AnswerToClient(Sender: TObject; Client: TFtpCtrlSocket; var Answer: TFtpString);
begin
    AddLogLine('> ' + Client.GetPeerAddr + ' ' + Answer)
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1BgException(Sender: TObject; E: Exception; var CanClose: Boolean);
begin
    AddLogLine('! Server BgException: ' + IcsGetExceptMess(E));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1BuildDirectory(Sender: TObject; Client: TFtpCtrlSocket; var Directory: TFtpString; Detailed: Boolean);
begin
//
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1BuildFilePath(Sender: TObject; Client: TFtpCtrlSocket; const Directory, FileName: string; var NewFileName: string);
var
    I: integer ;
begin
{ called from all FTP commands involving a file name, to allow virtual directoriesto be supported if NewFileName returned non blank
 if FileName is blank, means a directory is being validated, it might already be the translated virtual path }
    if (TotVirDir = 0) or (NOT Client.AccountVirtDir) then
        Exit ;
    if FileName <> '' then
        AddLogLine (Client.SessIdInfo + 'Build File Path, Directory: ' + Directory + ', Filename: ' + FileName);

 // translate virtual to phyiscal directory
    for I := 0 to TotVirDir - 1 do begin
        if (FileName <> '?') then begin // ? is used in FormatResponsePath to get original path
            if Pos(ListVDirs [I], Directory) = 1 then begin
                NewFileName := ListPDirs [I] + Copy (Directory, Length (ListVDirs [I]) + 1, 999) + FileName ;
                AddLogLine (Client.SessIdInfo + 'Changed to Virtual Path: ' + NewFileName) ;
                Exit
            end;
        end
        else begin
            if (Pos(ListPDirs [I], Directory) = 1) then begin
                NewFileName := ListVDirs [I] + Copy (Directory, Length (ListPDirs [I]) + 1, 999) ;
                AddLogLine (Client.SessIdInfo + 'Validated OK Virtual Path: ' + NewFileName) ;
                Exit ;
            end;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ChangeDirectory(Sender: TObject; Client: TFtpCtrlSocket; Directory: TFtpString; var Allowed: Boolean);
begin
    { It the right place to check if a user has access to a given directory }
    { The example below disable C:\ access to non root user.                }
    if (UpperCase(Client.UserName) <> 'ROOT') and
       (UpperCase(Client.Directory) = 'C:\') then
       Allowed := FALSE;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ClientCommand(Sender: TObject;  Client: TFtpCtrlSocket; var Keyword, Params, Answer: TFtpString);
var
    S: string ;
begin
    S := String(StringToUtf8(Params));
    if Keyword = 'PASS' then S := '####' ;
    AddLogLine('< ' + Client.GetPeerAddr + ' ' + Keyword + ' ' + S);
    if Keyword = 'QUIT' then
        DiagLogBuffer.FlushFile(True);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ClientConnect(Sender: TObject; Client: TFtpCtrlSocket; AError: Word);
begin
    AddLogLine('! ' + Client.GetPeerAddr + ' connected');
  { get INI file for default accounts, may be changed if HOST command used }
//    Client.AccountIniName := FtpServerForm.FAccountPath + 'ftpaccounts-default.ini';
    Client.AccountReadOnly := true;
    Client.AccountPassword := '';
    DiagLogBuffer.FlushFile(True);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ClientDisconnect(Sender: TObject; Client: TFtpCtrlSocket; AError: Word);
begin
    AddLogLine('! ' + Client.GetPeerAddr + ' disconnected');
    DiagLogBuffer.FlushFile(True);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1Display(Sender: TObject; Client: TFtpCtrlSocket; Msg: TFtpString);
begin
 // warning, Client may be nil for server messages
    AddLogLine(Msg);        { V96 }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1GetProcessing(Sender: TObject; Client: TFtpCtrlSocket; var DelayedSend: Boolean);
var
    MyServer : TFtpServer;
    MyClient : TMyFtpClient;
begin
    MyServer := Sender as TFtpServer;
    MyClient := Client as TMyFtpClient;
    { If client request a *.ZZZ file, then start a thread to do some      }
    { processing (here the thread just sleep 10 sec to show other clients }
    { are not blocked.                                                    }
    if UpperCase(ExtractFileExt(MyClient.FileName)) = '.ZZZ' then begin
        MyClient.FWorkerThread := TGetProcessingThread.Create(TRUE);
        MyClient.FWorkerThread.Server          := MyServer;
        MyClient.FWorkerThread.Client          := MyClient;
        MyClient.FWorkerThread.FreeOnTerminate := TRUE;
        MyClient.FWorkerThread.OnTerminate     := WorkerThreadTerminated;
    {$IF CompilerVersion >= 21}
        MyClient.FWorkerThread.Start;
    {$ELSE}
        MyClient.FWorkerThread.Resume;
    {$IFEND}
        { Ask server component to not start sending immediately           }
        { We will ask to start sending from WorkerThreadTerminated event  }
        DelayedSend := TRUE;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.WorkerThreadTerminated(Sender : TObject);
var
    MyThread : TGetProcessingThread;
    Answer   : TFtpString;
begin
    MyThread := Sender as TGetProcessingThread;
    MyThread.Server.DoStartSendData(MyThread.Client, Answer);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TGetProcessingThread.Execute;
begin
    Sleep(10000);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1Host(Sender: TObject; Client: TFtpCtrlSocket; Host: TFtpString; var Allowed: Boolean);
//var
//    fname: string ;
begin
{ HOST might be ftp.domain.com or [123.123.123.123]   }
{    fname := FAccountPath + 'ftpaccounts-' + Lowercase (Host) + '.ini';
    if NOT FileExists (fname) then begin
        AddLogLine('! Could not find Accounts File: ' + fname);
        Allowed := false;
        exit;
    end;
    Client.AccountIniName := fname;   }
    Allowed := true;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1MakeDirectory(Sender: TObject; Client: TFtpCtrlSocket; Directory: TFtpString; var Allowed: Boolean);
begin
    Allowed := NOT Client.AccountReadOnly;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1OtpMethod(Sender: TObject; Client: TFtpCtrlSocket; UserName: TFtpString; var OtpMethod: TOtpMethod);
var
    S: string;
begin
    OtpMethod := OtpKeyNone;
    Client.AccountPassword := '';
    if AccountsNames.IndexOf(UserName) < 0 then begin
        AddLogLine('Login failed, no account for: ' + UserName);
        Exit;
    end;

 { look up user account to find One Time Password method, root directory, etc }
    Client.AccountPwType := TIcsPwType(GetEnumValue(TypeInfo (TIcsPwType), IcsTrim(AccountsIniFile.ReadString(UserName, KeyPwType, 'pwnone'))));
    Client.AccountPassword := AccountsIniFile.ReadString(UserName, KeyPassword, '');  // keep password to check later
    S := AccountsIniFile.ReadString(UserName, KeyOtpMethod, 'none');
    Client.AccountReadOnly := IcsCheckTrueFalse(AccountsIniFile.ReadString(UserName, KeyReadOnly, 'True'));
    Client.AccountVirtDir := IcsCheckTrueFalse (AccountsIniFile.ReadString (UserName, KeyVirtualDirs, 'False'));
    Client.HomeDir := AccountsIniFile.ReadString(UserName, KeyHomeDir, 'c:\temp');
    Client.Directory := Client.HomeDir;
    if IcsCheckTrueFalse(AccountsIniFile.ReadString(UserName, KeyForceHomeDir, 'True')) then
        Client.Options := Client.Options + [ftpCdUpHome];
    if IcsCheckTrueFalse(AccountsIniFile.ReadString(UserName, KeyHidePhysicalPath, 'True')) then
        Client.Options := Client.Options + [ftpHidePhysicalPath];
    if IcsCheckTrueFalse(AccountsIniFile.ReadString(UserName,  KeyForceSsl, 'False')) then begin
        if NOT Client.SslEnable then
          Client.AccountPassword := '';  // if SSL not enabled fail password
    end;
    if Client.AccountPwType = pwNone then  // user not found, fail
          Client.AccountPassword := '';
    if Client.AccountPwType in [pwwindows, pwencsha256] then  // OTP not available
        S := '';

    { sequence and seed }
    OtpMethod := OtpGetMethod (S);
    Client.OtpSequence := FOtpSequence;
    Client.OtpSeed := FOtpSeed;

  { this could be user account information, SQL id or something }
    Client.SessIdInfo := Client.GetPeerAddr + '=' + UserName;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1OtpGetPassword(Sender: TObject; Client: TFtpCtrlSocket; UserName: TFtpString; var UserPassword: string);
begin
//    UserPassword := Client.AccountPassword;   // expected password will used to create OTP
    UserPassword := IcsPasswordGet(Client.AccountPwType, UserName, Client.AccountPassword, IcsEncKeyAES) ;
    AddLogLine('! ' + Client.SessIdInfo + ' OTP Get Password for: ' + UserName + ' > ' + UserPassword);   // !!! TEMP DIAG
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1Authenticate(Sender: TObject; Client: TFtpCtrlSocket; UserName, Password: TFtpString; var Authenticated: Boolean);
var
    accountok: boolean;
begin
  // One Time Passwords - keep sequence and seed for next login attempt
    accountok := false ;
    if Client.OtpMethod > OtpKeyNone then begin
        if not Authenticated then begin
            AddLogLine('! ' + Client.SessIdInfo + ' One Time Password failed authentication');
            Exit;
        end;
        accountok := true ;
        AddLogLine('! ' + Client.SessIdInfo + ' One Time Password authenticated OK');
        FOtpSequence := Client.OtpSequence;
        FOtpSeed := Client.OtpSeed;
    end
    else begin
        if (Client.AccountPwType <> pwwindows) then begin

        // check clear, encrypted or hash digest passwors
            if (Client.UserName = UserName) then begin
            // check password
                if IcsPasswordCheck(Client.AccountPwType, UserName, Password, Client.AccountPassword, IcsEncKeyAES) then begin
                    AddLogLine (Client.SessIdInfo + 'Authenticated OK - Account: ' + UserName) ;
                    accountok := true ;
                end
                else begin
                    AddLogLine (Client.SessIdInfo + 'Failed Authentication, Invalid Password - ' + Password);
                end
            end
            else begin
                AddLogLine (Client.SessIdInfo + 'Failed Authentication, Account Not Found');
            end;
        end
        else begin
          // windows authentication, if the client is already logged in log her off
            if Client.WinLoginAccToken <> 0 then begin
                CloseHandle(Client.WinLoginAccToken); // logoff
                Client.WinLoginAccToken := 0;
            end;
            { We call LogonUser API (see the PSDK) to get an access token }
            { that we can use to impersonate the user, see event handlers }
            { OnEnterSecurityContext and OnLeaveSecurityContext.          }
            accountok := LogonUserW (PWideChar(UserName), nil, PWideChar(Password), LOGON32_LOGON_NETWORK,
                                                                            LOGON32_PROVIDER_DEFAULT, Client.WinLoginAccToken);
            if accountok then
                AddLogLine (Client.SessIdInfo + UserName + ' Authenticated and Logged on locally to Windows')
            else
                AddLogLine (Client.SessIdInfo + UserName + ' Failed Windows Authentication');
        end;
    end;
    if accountok then begin
        Authenticated := true ;
        AddLogLine (Client.SessIdInfo + 'Logon OK') ;
        AddLogLine (Client.SessIdInfo + 'Home Directory: ' + Client.Directory) ;
    end
    else begin
        Authenticated := false ;
        AddLogLine (Client.SessIdInfo + 'Logon Failed') ;
        if HackBlackList.FailedBlackList (Client.SessIpInfo.RemoteAddr, 99) then begin
            AddLogLine (Client.SessIdInfo + 'Client Blacklisted Connection from ' + Client.SessIpInfo.RemoteAddr) ;
        end ;
    end ;
    DiagLogBuffer.FlushFile(True);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1Rein(Sender: TObject; Client: TFtpCtrlSocket; var Allowed: Boolean);
begin
    Allowed := true;
    AddLogLine('! Reinitialise client accepted');
    Client.SessIdInfo := Client.GetPeerAddr + '=(Not Logged On)';
    AddLogLine('! ' + Client.SessIdInfo + ' connected');
//    Client.AccountIniName := FtpServerForm.FAccountPath + 'ftpaccounts-default.ini';
    Client.AccountReadOnly := true;
    Client.AccountPassword := '';
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1RetrDataSent(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
begin
    if Error <> 0 then
        AddLogLine('! ' + Client.GetPeerAddr + ' Data sent. Error #' + IntToStr(Error));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1RetrSessionClosed(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
begin
    if Error <> 0 then
        AddLogLine('! ' + Client.GetPeerAddr + ' Data session closed. Error #' + IntToStr(Error));
    if Client.UserData = 1 then begin
        { We created a stream for a virtual file or dir. Delete the TStream }
        if Assigned(Client.DataStream) then begin
            { There is no reason why we should not come here, but who knows ? }
            Client.DataStream.Destroy;
            Client.DataStream := nil;
        end;
        Client.UserData   := 0;     { Reset the flag }
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1RetrSessionConnected(Sender: TObject; Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
begin
    if Error <> 0 then
        AddLogLine('! ' + Client.GetPeerAddr +  ' Data session connected. Error #' + IntToStr(Error));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1SslHandshakeDone(Sender: TObject; ErrCode: Word; PeerCert: TX509Base; var Disconnect: Boolean);
var
    Sock: TWSocket;
    Str: String;
    Client: TFtpCtrlSocket;
begin
    if Sender is TFtpCtrlSocket then begin
        Sock := TWSocket(Sender as TFtpCtrlSocket);
        Client := Sender as TFtpCtrlSocket ;
        Str := 'Ctrl Socket: ';
    end
    else begin
        Sock := (Sender as TWSocket);
        Client := Sock.Owner as TFtpCtrlSocket;
        Str := 'Data Socket: ';
    end;
    AddLogLine('SSL Client Hello from ' + Client.CPeerAddr + IcsCRLF + Trim(WSocketGetCliHelloStr(Client.CliHelloData))) ;
    if ErrCode = 0 then begin
        AddLogLine(Client.SessIdInfo + ' ' + Str + Sock.SslHandshakeRespMsg);
        AddLogLine('SSL Handshake done, IcsHost #' + IntToStr(Client.IcsHostIdx) + ' - ' + Client.HostTag);
    end
    else
        AddLogLine(Client.SessIdInfo + 'SSL Handshake Failed - ' + Str + Sock.SslHandshakeRespMsg);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1SslServerName(Sender: TObject; var Ctx: TSslContext; var ErrCode: TTlsExtError);
begin
    ErrCode := teeOk;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1SslVerifyPeer(Sender: TObject; var Ok: Integer; Cert: TX509Base);
var
    Client: TMyFtpClient;
begin
    if Sender is TMyFtpClient then
        Client := Sender as TMyFtpClient
    else
        Client := (Sender as TWSocket).Owner as TMyFtpClient;

// if client sending us an SSL certificate, does not often happen!!!!
// only report certificate once per session
    if Client.ReportSslCert then
    begin
        OK := 1 ;
        exit ;
    end ;
    Client.ReportSslCert := true ;
    AddLogLine(Client.SessIdInfo + 'Received SSL certificate' + IcsCRLF +
        'Subject: ' + Cert.SubjectOneLine + IcsCRLF +
        'Common Name: ' + Cert.SubjectCName + IcsCRLF +
        'Issuer: '  + Cert.IssuerOneLine);
//  if PostConnectionCheck(HostOrIp)  // check match for server IP
    if OK <> 1 then
    begin
        AddLogLine(Client.SessIdInfo + 'SSL Certificate Error: ' + Cert.VerifyErrMsg + ' (but error ignored)') ;
        OK := 1 ; //In this example we accept any client.
    end ;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1StorSessionConnected(Sender: TObject;  Client: TFtpCtrlSocket; Data: TWSocket; AError: Word);
begin
    if Error <> 0 then
        AddLogLine('! ' + Client.GetPeerAddr + ' Data session closed. Error #' + IntToStr(Error));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ValidateDele(Sender: TObject; Client: TFtpCtrlSocket; var FilePath: TFtpString; var Allowed: Boolean);
begin
    Allowed := NOT Client.AccountReadOnly;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ValidatePut(Sender: TObject; Client: TFtpCtrlSocket; var FilePath: TFtpString; var Allowed: Boolean);
begin
    Allowed := NOT Client.AccountReadOnly;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TServerMain.SslFtpServer1ValidateRnFr(Sender: TObject; Client: TFtpCtrlSocket; var FilePath: TFtpString; var Allowed: Boolean);
begin
    Allowed := NOT Client.AccountReadOnly;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// event from BuildDirList adds virtual files
procedure TServerMain.SslFtpServerAddVirtFiles(Sender: TObject; Client: TFtpCtrlSocket; var LocFiles: TIcsFileRecs;
                                                      var LocFileList: TList; var TotalFiles: Integer; ProgressCallback: TMD5Progress);
var
    LocDir, LocPartName, VDirName: String;
    flag: boolean;
    I, Loop, SResult, OldTot : integer ;
    SearchRec: TIcsSearchRecW ;
begin
    { check if need to index any virtual directories, only at root level }
    if (TotVirDir = 0) then
        Exit ;
    LocDir := ExtractFilePath (Client.DirListPath); // initial path to index
    if (LowerCase(Client.HomeDir) <> LowerCase(LocDir)) then
        Exit ;

    { process each virtual directory in turn }
    for Loop := 0 to Pred (TotVirDir) do begin
        LocDir := IncludeTrailingPathDelimiter (ListPDirs [Loop]) ;   { get physical directory }
        LocPartName := '*.*';
        VDirName := IcsExtractLastDir (ListVDirs [Loop]);       { get virtual directory name }
   { list all sub-directories, then add virtual directory }
        if Client.DirListSubDir then begin
            OldTot := TotalFiles ;
            flag := IcsBuildDirList (LocDir, LocPartName, Client.DirListSubDir, Client.DirListHidden,
                                                                       0, 0, TotalFiles, LocFiles, Client, ProgressCallback);
            if not flag then begin
                TotalFiles := -1;
                exit;
            end;
            if TotalFiles > OldTot then begin
                for I := OldTot to Pred (TotalFiles) do begin
                    with LocFiles[I] do
                        FrSubDirs := '\' + VDirName + FrSubDirs ; // add virtual directory
                end;
            end;
        end
     { just add virtual directories, but need SearchRec }
        else begin
            SResult := FindFirst(LocDir + LocPartName, faDirectory, SearchRec);
            if SResult = 0 then begin
                SearchRec.Name := VDirName ; { replace '.' with directory }
                inc(TotalFiles);
                if Length(LocFiles) <= TotalFiles then
                    SetLength(LocFiles, TotalFiles * 2);
                LocFiles[pred(TotalFiles)].FrSearchRec := SearchRec;
            end;
            FindClose(SearchRec);
        end;
    end;

    { rebbuild list and sort it }
    LocFileList.Clear ;
    if TotalFiles <= 0 then
        Exit ;
    SetLength(LocFiles, TotalFiles);
    LocFileList.Capacity := TotalFiles ;
    for I := 0 to Pred (TotalFiles) do
        LocFileList.Add (@LocFiles [I]);
    LocFileList.Sort (IcsCompareDirNext);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

end.
