Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

Bounded DNS lookups: safe DLL and package shutdown

================================================================================
 BOUNDED DNS LOOKUPS: SAFE DLL AND RUNTIME-PACKAGE SHUTDOWN
 StreamSec Security Library for Embarcadero Delphi
================================================================================

Updated: 2026-10-19
API: stSocket.ShutdownHostLookups(aWithinMs: Cardinal): Boolean
Related release note: CHANGES.txt, entry 37.

This guide applies to LookupHostWithin and to the system-resolver path used by
tHttpClient with RequestTimeout or DeadlineTick set and DnsServers empty.
A request can time out or be cancelled while its native resolver worker keeps
running. Before unloading the module containing that worker's stSocket unit,
the host must finish the sequence below.

The native-thread shutdown barrier is supported on Windows and Linux. Other
POSIX targets retain detached workers and return False after admitting any
bounded lookup; the retry examples below cannot make those modules unloadable.

--------------------------------------------------------------------------------
1. WHAT THE RESULT MEANS
--------------------------------------------------------------------------------

ShutdownHostLookups closes admission permanently for this loaded stSocket unit
instance. It asks waiting LookupHostWithin callers to stop waiting and spends
up to aWithinMs milliseconds waiting for native worker termination, including
RTL and thread-local cleanup.

  True   All bounded DNS workers have terminated and been reaped. The DNS
         condition for unloading is satisfied. Host callers and other module
         activity must also have finished before unloading.

  False  Keep the module loaded, with its references and shutdown entry point
         intact, and retry later. Keep custom resolver code modules, context
         and other worker-accessed resources alive too. Native resolution
         cannot be forcibly interrupted; there is no guaranteed time by which
         a later retry will succeed.

  0 ms   Closes admission and polls without waiting for native thread exit.
         True still does not prove that host API callers have returned.

Every call, including one returning False, leaves admission closed. Later
bounded lookups return hlrStopped; the HTTP deadline path reports that the
lookup service has been shut down. Neither ResetCancel nor creating a new
HTTP client reopens it. Concurrent shutdown calls are allowed, but the host
must serialize ownership of the eventual unload.

HostLookupsRunning = 0 is only a diagnostic. It does not close admission and
is not a substitute for a successful ShutdownHostLookups call.

--------------------------------------------------------------------------------
2. HOST SEQUENCE
--------------------------------------------------------------------------------

Run this sequence in ordinary HOST control flow, outside library initialization,
unit finalization, DllMain and resolver callbacks. The module must not unload
itself from inside its shutdown export and then try to return to the host.

  1. Mark the module as retiring. Stop dispatching new requests and prevent
     new API entries, scheduled work and queued callbacks from entering it.
     Coordinate every consumer of a shared lookup-owning package.

  2. Request cancellation of active HTTP operations, keeping each client alive
     until its caller has returned. Call the correct shutdown entry point with
     0 ms to close lookup admission immediately. Record its result, but continue
     the remaining host cleanup even if this first poll returns True.

  3. Join all host-owned request/API caller threads and finish or revoke queued
     callbacks while the module remains loaded. These joins need their own host
     timeout policy: aWithinMs budgets DNS worker shutdown only. If callers
     have not returned, defer unloading. Do not hold locks a caller or resolver
     needs while waiting for it.

  4. Retry ShutdownHostLookups with short waits or zero-budget polls. On False,
     retain the module and resolver resources and return to the host loop.
     Retry the shutdown barrier, not the HTTP request. New requests remain
     disabled throughout this phase.

  5. After True AND after all host callers have returned, release remaining
     objects/interfaces implemented by the module and custom resolver context
     while their code is still loaded. Finish other module-owned work too;
     this API joins bounded DNS workers only, not arbitrary HTTP, TLS, socket
     or plugin threads. Cleanup must not start new module work.

  6. From the host, release the module with FreeLibrary, UnloadPackage or
     dlclose as appropriate. After successful release, clear cached exported
     function pointers and the host's module handle. Resolve fresh addresses
     when loading a new instance.

Do not put the unload call in a finally block that also runs after a timeout
or shutdown error. Library/package finalization is too late to start this
protocol. Ordinary executable finalization's bounded drain is not a DLL or
package unload protocol.

--------------------------------------------------------------------------------
3. CALL THE INSTANCE THAT OWNS THE LOOKUPS
--------------------------------------------------------------------------------

If the EXE and a DLL each statically link stSocket, each has a separate registry.
Calling the EXE's ShutdownHostLookups does not stop the DLL's workers. Export a
thin wrapper from the DLL and invoke that export while holding the DLL loaded.

The same approach works for a dynamically loaded runtime package: include the
wrapper unit in the package's contains list, using the SAME package-provided
stSocket instance as the code issuing the lookups. The example export below is
integration code supplied by the host/plugin author, not an existing StreamSec
export. Its scalar cdecl interface avoids passing Delphi strings or Boolean
values across a DLL boundary with different runtime/memory-manager settings.

  unit HostLookupControl;

  interface

  function PluginShutdownHostLookups(aWithinMs: Cardinal): Integer; cdecl;

  implementation

  uses stSocket;

  function PluginShutdownHostLookups(aWithinMs: Cardinal): Integer; cdecl;
  begin
    try
      Result := Ord(stSocket.ShutdownHostLookups(aWithinMs));
    except
      Result := -1;  { keep exceptions inside the module }
    end;
  end;

  exports
    PluginShutdownHostLookups name 'PluginShutdownHostLookups';

  end.

Include this unit in the DLL's uses clause or the package's contains clause.
The host's matching declaration is:

  type
    tPluginLookupShutdown = function(aWithinMs: Cardinal): Integer; cdecl;

The wrapper returns exactly 1 for success, 0 for pending shutdown, and -1 for
an unexpected exception. Only 1 allows the DNS phase to complete; an error
also means retain the module. A production integration can add error reporting
without allowing managed exceptions to cross this boundary.

For a shared StreamSec runtime package, shutdown affects ALL consumers of its
stSocket unit, not just one HTTP client or plugin. A wrapper in a separate
control package can call that same instance through its requires dependency.
Retain the owning package and callback dependencies until shutdown succeeds.
Reloading only a dependent DLL/control package does not reset the shared pool:
admission reopens only after the module owning stSocket is actually unloaded
and loaded again. Dropping one reference while another consumer still holds
the owning module is not a restart.

--------------------------------------------------------------------------------
4. WINDOWS DLL HOST: POLL, RETAIN ON TIMEOUT, RETRY
--------------------------------------------------------------------------------

Host code uses Windows and SysUtils. Keep the handle returned by LoadLibrary
and resolve the integration export while that handle is held:

  var
    lModule: HMODULE;
    lStop: tPluginLookupShutdown;
    lRetryEnabled: Boolean;

  { After lModule := LoadLibrary(...), and checking lModule <> 0: }
  lRetryEnabled := False;  { initialize before enabling retirement callbacks }
  @lStop := GetProcAddress(lModule, 'PluginShutdownHostLookups');
  if not Assigned(lStop) then
    raise Exception.Create('Shutdown export missing; module retained');

At retirement, perform steps 1-3 above, including the initial lStop(0) poll and
the host caller joins. Then make one bounded attempt per host control-loop or
timer invocation. Set the host-owned lRetryEnabled flag to True only after
caller joins are complete. The following is a host procedure body;
ReleasePluginState is an application hook implementing step 5, not a StreamSec
API. Lifecycle/timer invocations are serialized by the host:

  if not lRetryEnabled then
    Exit;
  case lStop(100) of
    0: Exit;  { keep lModule, lStop and resolver resources; retry later }
    1: ;      { DNS workers finished; host callers already joined }
  else
    lRetryEnabled := False;
    raise Exception.Create('Lookup shutdown failed; module retained');
  end;

  lRetryEnabled := False;  { no later timer tick may repeat cleanup/unload }
  ReleasePluginState;
  if not FreeLibrary(lModule) then
    RaiseLastOSError;
  lStop := nil;
  lModule := 0;

An early timeout leaves lRetryEnabled True and does not release any module
reference. On a later invocation, call the SAME lStop again. Once shutdown
succeeds, retries are disabled BEFORE object cleanup and unloading. If either
cleanup or FreeLibrary fails, keep that flag False and handle the unload error
separately; do not repeat already completed cleanup or resume module work.
Use lStop(0) for polling from a host loop that must not wait for DNS workers.

--------------------------------------------------------------------------------
5. WINDOWS RUNTIME-PACKAGE HOST
--------------------------------------------------------------------------------

A Windows host that dynamically loads a package uses SysUtils.LoadPackage,
then GetProcAddress on its returned handle to obtain the same wrapper export.
After the identical retirement, caller joins and successful shutdown poll,
its host-side tail is:

  lRetryEnabled := False;  { same host guard as in section 4 }
  ReleasePluginState;  { release package-defined objects/interfaces first }
  UnloadPackage(lModule);
  lStop := nil;
  lModule := 0;

Use UnloadPackage, not FreeLibrary, for a package loaded with LoadPackage.
UnloadPackage runs package finalizers before releasing the OS module. Keeping
an extra OS reference does not protect worker data from those finalizers.
If cleanup or UnloadPackage raises, leave retirement retries disabled and
handle that as an unload error. Package finalizers may already have run:
do not retry its shutdown export, repeat object cleanup or resume package use.

These examples assume explicit ownership of a dynamically loaded package.
Do not manually UnloadPackage a package imported by the host at load time or
still used by another consumer. Coordinate those consumers and their objects
before releasing the owning package. If a control package requires the lookup
owner, retain that dependency throughout shutdown and obey the shared-instance
rules in section 3.

Linux64 hosts use the equivalent loader, guarded unload and monotonic retry
examples in sections 7 and 8. The shared-instance rules in section 3 apply to
both platforms.

--------------------------------------------------------------------------------
6. OPTIONAL BOUNDED RETRY WINDOW (WINDOWS HOST)
--------------------------------------------------------------------------------

This helper uses Windows.GetTickCount64 as a monotonic clock. It spends at most
the remaining retry budget in each shutdown call, in slices of up to 100 ms.
Use it on a host control thread that can wait. Host caller joins and object
cleanup have separate budgets and are not included here.

  function WaitForPluginDns(aStop: tPluginLookupShutdown;
                            aTotalMs: Cardinal): Boolean;
  var
    lStart, lSpent: UInt64;
    lWait: Cardinal;
    lStatus: Integer;
  begin
    lStart := Windows.GetTickCount64;
    repeat
      lSpent := Windows.GetTickCount64 - lStart;
      if lSpent >= aTotalMs then
        lWait := 0
      else if aTotalMs - lSpent > 100 then
        lWait := 100
      else
        lWait := Cardinal(aTotalMs - lSpent);
      lStatus := aStop(lWait);
      if lStatus = 1 then begin
        Result := True;
        Exit;
      end;
      if lStatus <> 0 then
        raise Exception.Create('Lookup shutdown failed; module retained');
      if Windows.GetTickCount64 - lStart >= aTotalMs then begin
        Result := False;
        Exit;
      end;
    until False;
  end;

For example, after closing admission and joining the host callers:

  if not WaitForPluginDns(lStop, 5000) then
    Exit;  { keep the retired module and its resources; schedule a retry }
  lRetryEnabled := False;  { disable future retirement callbacks first }
  { True: perform step 5, then the appropriate host-side unload. }

If that five-second window expires, a later host invocation can use
WaitForPluginDns(lStop, 2000) or a single lStop(0) poll. Admission remains closed
between attempts. The module stays loaded until success; an overall application
deadline never authorizes forcibly terminating workers or unloading under them.

--------------------------------------------------------------------------------
7. LINUX64 HOST: SHARED LIBRARY OR RUNTIME PACKAGE
--------------------------------------------------------------------------------

These are Delphi 13 Linux64 host examples. Reuse tPluginLookupShutdown and the
unchanged HostLookupControl adapter from section 3. The host uses
System.SysUtils, System.Classes and Posix.Dlfcn. It does not statically link
its own stSocket merely to call shutdown; lStop reaches the loaded instance.

Keep module handles pointer-sized. Initialize lModule to 0, lStop to nil and
lRetryEnabled to False before the first load. Only the host's serialized
lifecycle controller accesses this state:

  var
    lModule: NativeUInt;
    lStop: tPluginLookupShutdown;
    lRetryEnabled: Boolean;
    lIsPackage: Boolean;

Copy loader error text before another loader call can replace it:

  function DlErrorText: string;
  var
    lError: MarshaledAString;
  begin
    lError := dlerror;
    if lError = nil then
      Result := 'no loader error text available'
    else
      Result := UTF8ToString(lError);
  end;

Resolve the scalar shutdown export from the same held module. Clear any old
dlerror first; dlsym returning a pointer alone does not report its error state.
On failure, the caller retains the module and leaves retries disabled:

  function ResolveLinuxShutdown(aModule: NativeUInt): tPluginLookupShutdown;
  var
    lSymbol: Pointer;
    lError: MarshaledAString;
    lMessage: string;
  begin
    dlerror;
    lSymbol := dlsym(aModule, 'PluginShutdownHostLookups');
    lError := dlerror;
    if lError <> nil then begin
      lMessage := UTF8ToString(lError);
      raise Exception.Create('Shutdown export lookup failed; module retained: '
                             + lMessage);
    end;
    if lSymbol = nil then
      raise Exception.Create('Shutdown export is nil; module retained');
    Result := tPluginLookupShutdown(lSymbol);
  end;

This loader accepts a full path and either a plain shared library (aAsPackage
= False) or a Delphi runtime package (True). Keep the UTF8String path variable
alive through dlopen; LoadPackage accepts the Delphi string directly:

  procedure OpenLinuxPlugin(const aPath: string; aAsPackage: Boolean);
  var
    lPath8: UTF8String;
  begin
    if lModule <> 0 then
      raise Exception.Create('Previous module is still held');
    lRetryEnabled := False;
    lStop := nil;
    lIsPackage := aAsPackage;
    if lIsPackage then
      lModule := LoadPackage(aPath)
    else begin
      lPath8 := UTF8String(aPath);
      dlerror;
      lModule := dlopen(PAnsiChar(lPath8), RTLD_NOW or RTLD_LOCAL);
      if lModule = 0 then
        raise Exception.Create('dlopen failed: ' + DlErrorText);
      InvalidateModuleCache;
    end;
    lStop := ResolveLinuxShutdown(lModule);
  end;

Do not overwrite a retained handle by calling OpenLinuxPlugin again after a
shutdown timeout or export-resolution error. Inspect/report loader errors in
the host while keeping any successfully loaded module held. A zero dlopen
result means no new reference was acquired. For raw dlopen/dlclose, Delphi's
InvalidateModuleCache is required after successful module changes; otherwise
reused addresses/handles can leave stale RTL module metadata. LoadPackage and
UnloadPackage maintain that cache themselves.

At retirement, follow steps 1-3 in section 2. After disabling new work, call
lStop(0) to close lookup admission. Separately cancel active operations and
join host API callers using the host's own budget. Treat wrapper errors as
a retained-module error.
Only after callers are joined set lRetryEnabled := True. It remains True on a
pending shutdown and becomes False before any object cleanup or unload.

The following host procedure makes one shutdown attempt per host loop/timer
invocation. ReleasePluginState is the application hook from section 4: release
module-defined objects/interfaces and resolver state only after DNS completion,
and do not start new work. All invocations are serialized by the host:

  procedure RetireLinuxPlugin;
  begin
    if not lRetryEnabled then
      Exit;
    case lStop(100) of
      0: Exit;  { retain module, export, context and callback dependencies }
      1: ;
    else
      lRetryEnabled := False;
      raise Exception.Create('Lookup shutdown failed; module retained');
    end;

    lRetryEnabled := False;  { no later invocation may repeat cleanup/unload }
    ReleasePluginState;
    if lIsPackage then
      UnloadPackage(lModule)
    else begin
      dlerror;
      if dlclose(lModule) <> 0 then
        raise Exception.Create('dlclose failed; unload retries disabled: '
                               + DlErrorText);
    end;
    lStop := nil;
    lModule := 0;
    if not lIsPackage then
      InvalidateModuleCache;
  end;

For a nonblocking DNS poll, change lStop(100) to lStop(0). A 0/pending result
keeps lRetryEnabled True and returns without releasing resources; schedule a
later invocation of this same host procedure. A 1/complete result permits
cleanup only because host caller joins already finished. The routine always
disables further invocations before cleanup or finalizers can run.

Use dlclose only for the dlopen path, and UnloadPackage for LoadPackage. If
cleanup, dlclose or UnloadPackage fails, leave retries disabled and handle the
unload error separately. Finalizers may already have run: do not repeat object
cleanup, call the shutdown export again, or resume module use. Do not move
either unload operation into a finally block around shutdown.

A successful dlclose releases this host's reference; another reference may
keep the owning module mapped. For both shared libraries and packages, a fresh
admission state requires actual unloading and reloading of the stSocket owner.
Releasing only a dependent package or one of several references is insufficient.

--------------------------------------------------------------------------------
8. LINUX64 HOST: BOUNDED RETRY WINDOW WITH A MONOTONIC CLOCK
--------------------------------------------------------------------------------

System.Classes.TThread.GetTickCount64 uses CLOCK_MONOTONIC on Delphi 13 Linux64.
This equivalent of the Windows helper does not depend on wall-clock time or
link another stSocket instance into the host. Each shutdown call receives only
the remaining window, capped at 100 ms. Caller joins and cleanup retain their
separate host budgets. A zero total window performs one nonblocking poll:

  function WaitForLinuxPluginDns(aStop: tPluginLookupShutdown;
                                 aTotalMs: Cardinal): Boolean;
  var
    lStart, lSpent: UInt64;
    lWait: Cardinal;
    lStatus: Integer;
  begin
    lStart := TThread.GetTickCount64;
    repeat
      lSpent := TThread.GetTickCount64 - lStart;
      if lSpent >= aTotalMs then
        lWait := 0
      else if aTotalMs - lSpent > 100 then
        lWait := 100
      else
        lWait := Cardinal(aTotalMs - lSpent);
      lStatus := aStop(lWait);
      if lStatus = 1 then begin
        Result := True;
        Exit;
      end;
      if lStatus <> 0 then
        raise Exception.Create('Lookup shutdown failed; module retained');
      if TThread.GetTickCount64 - lStart >= aTotalMs then begin
        Result := False;
        Exit;
      end;
    until False;
  end;

For example, on a host control thread that may wait, after closing admission
and joining callers (lRetryEnabled = True):

  if not lRetryEnabled then
    Exit;
  try
    if not WaitForLinuxPluginDns(lStop, 5000) then
      Exit;  { keep the retired module/resources; retry from a later event }
  except
    lRetryEnabled := False;
    raise;  { retained-module error, not permission to unload }
  end;
  RetireLinuxPlugin;  { idempotent ready poll, guarded cleanup, correct unload }

If the five-second window expires, keep the same lModule, lStop, resolver data
and dependency references. A later event can use a two-second window by calling
WaitForLinuxPluginDns(lStop, 2000), or poll with aTotalMs = 0. After True,
RetireLinuxPlugin confirms readiness and performs cleanup/unload exactly once.
Shutdown is still permanent between attempts; neither retrying nor a new
HTTP client reopens admission. The timeout never authorizes unloading under
a worker or forcibly terminating it.