{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Author:       Angus Robertson, Magenta Systems Ltd
Description:  ICS File Server, FTP and WebDAV server.
Creation:     Oct 2026
Updated:      Oct 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.

Sep 11, 2024 V9.3 - Baseline


 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

 unit IcsFileServerSrv;

interface

uses
  Windows, Messages, SysUtils, Classes, Dialogs, System.UITypes,
  DDSvcUtils,
  DDWindows,
  DDSvcMgr,
  OverbyteIcsUtils;  // for IcsSimpleLogging

type
  TIcsFileServerControl = class(TDDService)
    procedure DDServiceCreate(Sender: TObject);
    procedure DDServiceDestroy(Sender: TObject);
    procedure DDServiceExecute(Sender: TDDService);
    procedure DDServicePause(Sender: TDDService; var Paused: Boolean);
    procedure DDServiceShutdown(Sender: TDDService);
    procedure DDServiceStart(Sender: TDDService; var Started: Boolean);
    procedure DDServiceContinue(Sender: TDDService; var Continued: Boolean);
    procedure DDServiceAfterInstall(Sender: TDDService);
    procedure DDServiceAfterUninstall(Sender: TDDService);
    procedure DDServiceBeforeInstall(Sender: TDDService);
    procedure DDServiceRunException(Sender: TObject; E: Exception; var LogDefaultErrMsg, CanAbort: Boolean);
    procedure DDServiceStop(Sender: TDDService; var Stopped: Boolean);
  private
    { Private declarations }
  public
    function GetServiceController: TServiceController; override;
    function GetServiceControllerEx: TServiceControllerEx; override;
    function GetConsoleCtrlHandler: TServiceConsoleCtrlHandler; override;
    procedure LogFile (const S: string);
    procedure StopService;
    procedure CrashService;
    procedure GetStatus;
  end;

const
  GServiceIdent = 'WysYgstE2A';

var
  IcsFileServerControl: TIcsFileServerControl;
  GInstalling: Boolean = False;

implementation

{$R *.DFM}

uses
    IcsFileServerMain;

{///////////////////////////////////////////////////////////////////////////}
procedure ServiceController(CtrlCode: DWORD); stdcall;
begin
    IcsFileServerControl.Controller(CtrlCode);
end;

function TIcsFileServerControl.GetServiceController: TServiceController;
begin
    Result := ServiceController;
end;

function ServiceControllerEx(CtrlCode, EventType: DWORD; EventData, Context: Pointer): DWORD; stdcall;
begin
    Result := IcsFileServerControl.ControllerEx(CtrlCode, EventType, EventData, Context);
end;

function TIcsFileServerControl.GetServiceControllerEx: TServiceControllerEx;
begin
    Result := ServiceControllerEx;
end;

function ServiceConsoleCtrlHandler(Ctrl: DWord): Bool; stdcall;
begin
    Result := IcsFileServerControl.ConsoleCtrlHandler(Ctrl);
end;

procedure TIcsFileServerControl.DDServiceAfterInstall(Sender: TDDService);
var
    I: Integer;
    S: string;
begin
    S := ParamStr(0);
    I := Pos (' /', S);
    if I > 1 then
        S := Copy (S, 1, I - 1);  // strip arguments
    RegisterEventLogSource(Sender.ServiceName, S);
end;

procedure TIcsFileServerControl.DDServiceAfterUninstall(Sender: TDDService);
begin
    UnRegisterEventLogSource(Sender.ServiceName);
end;

procedure TIcsFileServerControl.DDServiceBeforeInstall(Sender: TDDService);
begin
    ImagePath := ImagePath + ' /' + GServiceIdent;
    IcsSimpleLogging (SimpLogName, 'Service Install - ' + ImagePath) ;
end;

procedure TIcsFileServerControl.DDServiceContinue(Sender: TDDService; var Continued: Boolean);
begin
//
end;

procedure TIcsFileServerControl.DDServiceCreate(Sender: TObject);
var
    S: string;
begin
    IcsSimpleLogging (SimpLogName, 'Service Create') ;
    if GInstalling then begin     // windows service
        S := 'Program Needs Administrator Rights to Install as Service';
        IcsSimpleLogging (SimpLogName, S) ;
        if NOT IcsIsProgAdmin then begin
            MessageDlg(S, mtError, [mbAbort], 0);
            ExitProcess(0);
            Exit;
        end;
    end;
end;

procedure TIcsFileServerControl.DDServiceDestroy(Sender: TObject);
begin
   IcsSimpleLogging (SimpLogName, 'Exception DDServiceDestroy');
end;

procedure TIcsFileServerControl.DDServiceExecute(Sender: TDDService);
begin
    IcsSimpleLogging (SimpLogName, 'Service Execute') ;
    LogFile ('Server Monitor Service Execute') ;
    GetStatus;
    while not Terminated do begin
        Sender.ServiceThread.ProcessRequests (true);  // !! must be true else gobbles CPU
    end;
    IcsSimpleLogging (SimpLogName, 'Service Stopped Execute') ;
end;

procedure TIcsFileServerControl.DDServicePause(Sender: TDDService; var Paused: Boolean);
begin
//
end;

procedure TIcsFileServerControl.DDServiceRunException(Sender: TObject; E: Exception; var LogDefaultErrMsg, CanAbort: Boolean);
begin
    LogFile ('Service Run Exception - ' + E.Message) ;
    CanAbort := true ;
end;

procedure TIcsFileServerControl.DDServiceShutdown(Sender: TDDService);
begin
//
end;

procedure TIcsFileServerControl.DDServiceStart(Sender: TDDService; var Started: Boolean);
begin
    IcsSimpleLogging (SimpLogName, 'Service Start') ;
    GetStatus;
    Started := True;
end;

procedure TIcsFileServerControl.DDServiceStop(Sender: TDDService; var Stopped: Boolean);
begin
    IcsSimpleLogging (SimpLogName, 'Service Stop') ;
    try
        GetStatus;
        if ServerMain <> nil then begin
            LogFile ('Service Stop Event from Windows, Closing Down') ;
            ServerMain.TimerMain.Enabled := false ;
            if NOT ClosingFlag then begin
                ClosingFlag := true ;
                LogFile('Stopping Server Monitor') ;
                ServerMain.MonitorStop;
            end;
        // warning, sets Applicaton.Terminated so lots of functions exit
            PostMessage(ServerMain.Handle, WM_ClOSE, 0, 0);
        end;
    except
    end;
    Stopped := True;
end;

function TIcsFileServerControl.GetConsoleCtrlHandler: TServiceConsoleCtrlHandler;
begin
    Result := ServiceConsoleCtrlHandler;
end;

procedure TIcsFileServerControl.LogFile (const S: string);
begin
    if Assigned (ServerMain) then
        ServerMain.AddLogLine (S) ;
end;

procedure TIcsFileServerControl.StopService;
begin
    GetStatus;
    IcsSimpleLogging (SimpLogName, 'Local Service Stop Request') ;
    LogFile ('Local Service Stop Request') ;
    Stop;
    GetStatus;
end;

procedure TIcsFileServerControl.CrashService;
begin
    GetStatus;
    IcsSimpleLogging (SimpLogName, 'Local Service Crash Request') ;
    ServiceThread.Terminate;
    IcsSimpleLogging (SimpLogName, 'Local Service Crash Thread ExitProcess') ;
    ExitProcess(0);
end;

const
  ServStatus: array [Low(TCurrentStatus)..High(TCurrentStatus)] of String =
      ('Stopped', 'Start Pending', 'Stop Pending', 'Running', 'Continue Pending', 'Pause Pending', 'Paused');

procedure TIcsFileServerControl.GetStatus;
begin
    ReportStatus;
    LogFile ('Service Status: ' + ServStatus[Status]) ;
end;


{///////////////////////////////////////////////////////////////////////////}

end.
