program l4_check;
{$mode objfpc}{$H+}
uses SysUtils, Classes, StrUtils
  {$IFDEF WINDOWS}, Windows{$ENDIF};
const Version='0.3.9';
{$I buildinfo.inc}
type
  TConn = record
    Proto, PID, Name, SrcIP, DstIP, State, Key: string;
    SrcPort, DstPort: Word;
    FirstSeen: TDateTime;
  end;
  PConn = ^TConn;
var
  Previous, Current: TStringList;
  IntervalMS: Integer=500;
  ProtoFilter, PortFilter, ProcessFilter, PIDFilter, IPFilter, NetFilter,
  ExcludePort, ExcludeProcess, FormatName, TimestampName, EventFilter: string;
  AllowFile: string;
  AllowRules: TStringList;
  AllTargets, OnceOnly, Summary: Boolean;
  StatsSeconds: Integer;
  Started, LastStats: TDateTime;
  TotalNew, TotalClosed, TotalState: QWord;
  ProcessStats: TStringList;

function HasToken(const CSV, Token: string): Boolean;
var s: string;
begin
  s:=','+LowerCase(StringReplace(CSV,' ','',[rfReplaceAll]))+',';
  Result:=Pos(','+LowerCase(Token)+',',s)>0;
end;
function IsDigits(const s: string): Boolean;
var i: Integer;
begin
 Result:=s<>'';
 for i:=1 to Length(s) do if not (s[i] in ['0'..'9']) then Exit(False);
end;
function IPv4Number(const s: string; out n: LongWord): Boolean;
var a: TStringList; i,v: Integer;
begin
 Result:=False; n:=0; a:=TStringList.Create;
 try
  a.Delimiter:='.'; a.StrictDelimiter:=True; a.DelimitedText:=s;
  if a.Count<>4 then Exit;
  for i:=0 to 3 do begin
   if not TryStrToInt(a[i],v) or (v<0) or (v>255) then Exit;
   n:=(n shl 8) or LongWord(v);
  end;
  Result:=True;
 finally a.Free end;
end;
function CIDRMatch(const IP, Network: string): Boolean;
var p, bits: Integer; a,b,mask: LongWord; net: string;
begin
 Result:=False; p:=Pos('/',Network);
 if p=0 then Exit(SameText(IP,Network));
 net:=Copy(Network,1,p-1);
 if not TryStrToInt(Copy(Network,p+1,MaxInt),bits) or (bits<0) or (bits>32) then Exit;
 if not IPv4Number(IP,a) or not IPv4Number(net,b) then Exit;
 if bits=0 then mask:=0 else mask:=LongWord($FFFFFFFF) shl (32-bits);
 Result:=(a and mask)=(b and mask);
end;
function PublicIP(const IP: string): Boolean;
var n: LongWord; a,b,c: Byte; s: string;
begin
 if Pos(':',IP)>0 then begin
  s:=LowerCase(IP);
  Result:=(s<>'::') and (s<>'::1') and (Pos('fe',s)<>1) and
    (Pos('fc',s)<>1) and (Pos('fd',s)<>1) and (Pos('ff',s)<>1) and
    (Pos('2001:db8:',s)<>1) and (Pos('2001:0db8:',s)<>1);
  Exit;
 end;
 if not IPv4Number(IP,n) then Exit(False);
 a:=n shr 24; b:=(n shr 16) and 255; c:=(n shr 8) and 255;
 Result:=not ((a=0) or (a=10) or (a=127) or (a>=224) or
  ((a=100) and (b>=64) and (b<=127)) or (a=169) and (b=254) or
  (a=172) and (b>=16) and (b<=31) or (a=192) and (b=168) or
  (a=192) and (b=0) and (c=0) or (a=192) and (b=0) and (c=2) or
  (a=192) and (b=88) and (c=99) or (a=198) and (b in [18,19]) or
  (a=198) and (b=51) and (c=100) or (a=203) and (b=0) and (c=113));
end;
function IPMatches(const IP, Rules: string): Boolean;
var a: TStringList; i: Integer;
begin
 Result:=False; if Rules='' then Exit;
 a:=TStringList.Create;
 try
  a.Delimiter:=','; a.StrictDelimiter:=True; a.DelimitedText:=Rules;
  for i:=0 to a.Count-1 do if CIDRMatch(IP,Trim(a[i])) then Exit(True);
 finally a.Free end;
end;
function Allowed(const C: TConn): Boolean;
var i: Integer;
begin
 Result:=False;
 if (C.DstPort=0) or ((not AllTargets) and (not PublicIP(C.DstIP))) then Exit;
 if (ProtoFilter<>'') and not HasToken(ProtoFilter,C.Proto) then Exit;
 if (PortFilter<>'') and not HasToken(PortFilter,IntToStr(C.DstPort)) then Exit;
 if (PIDFilter<>'') and (C.PID<>PIDFilter) then Exit;
 if (ProcessFilter<>'') and (Pos(LowerCase(ProcessFilter),LowerCase(C.Name))=0) then Exit;
 if (IPFilter<>'') and not IPMatches(C.DstIP,IPFilter) then Exit;
 if (NetFilter<>'') and not IPMatches(C.DstIP,NetFilter) then Exit;
 if HasToken(ExcludePort,IntToStr(C.DstPort)) then Exit;
 if (ExcludeProcess<>'') and (Pos(LowerCase(ExcludeProcess),LowerCase(C.Name))>0) then Exit;
 for i:=0 to AllowRules.Count-1 do if IPMatches(C.DstIP,Trim(AllowRules[i])) then Exit;
 Result:=True;
end;
function JsonQuote(const S: string): string;
var i: Integer; ch: Char;
begin
 Result:='"';
 for i:=1 to Length(S) do begin
  ch:=S[i];
  case ch of
   '"': Result:=Result+'\"';
   '\': Result:=Result+'\\';
   #10: Result:=Result+'\n';
   #13: Result:=Result+'\r';
   #9: Result:=Result+'\t';
  else if Ord(ch)<32 then Result:=Result+'?' else Result:=Result+ch end;
 end;
 Result:=Result+'"';
end;
function Stamp: string;
begin
 if TimestampName='iso8601' then Result:=FormatDateTime('yyyy"-"mm"-"dd"T"hh":"nn":"ss.zzz',Now)
 else Result:=FormatDateTime('hh:nn:ss.zzz',Now);
end;
procedure OutputEvent(const Event: string; const C: TConn; Age: Integer);
var ts: string;
begin
 if not HasToken(EventFilter,Event) then Exit;
 ts:=Stamp;
 if FormatName='jsonl' then
  WriteLn('{"time":',JsonQuote(ts),',"event":',JsonQuote(Event),',"proto":',JsonQuote(C.Proto),
   ',"pid":',JsonQuote(C.PID),',"process":',JsonQuote(C.Name),',"src_ip":',JsonQuote(C.SrcIP),
   ',"src_port":',C.SrcPort,',"dst_ip":',JsonQuote(C.DstIP),',"dst_port":',C.DstPort,
   ',"state":',JsonQuote(C.State),',"age_seconds":',Age,'}')
 else if FormatName='csv' then
  WriteLn('"',ts,'","',Event,'","',C.Proto,'","',C.PID,'","',StringReplace(C.Name,'"','""',[rfReplaceAll]),
   '","',C.SrcIP,'",',C.SrcPort,',"',C.DstIP,'",',C.DstPort,',"',C.State,'",',Age)
 else
  WriteLn(ts,' ',Event:6,' ',C.Proto:3,' ',C.PID:8,' ',C.Name:20,' ',
   C.SrcPort:5,' ',C.DstIP:39,' ',C.DstPort:5,' ',C.State:12,' ',Age:6);
 Flush(Output);
end;
procedure AddConnection(var C: TConn);
var p: PConn;
begin
 if not Allowed(C) then Exit;
 C.Key:=C.Proto+'|'+C.PID+'|'+C.SrcIP+'|'+IntToStr(C.SrcPort)+'|'+C.DstIP+'|'+IntToStr(C.DstPort);
 if Current.IndexOf(C.Key)>=0 then Exit;
 New(p); p^:=C; p^.FirstSeen:=Now;
 Current.AddObject(C.Key,TObject(p));
end;
procedure FreeEntries(L: TStringList);
var i: Integer;
begin
 for i:=0 to L.Count-1 do Dispose(PConn(L.Objects[i]));
 L.Clear;
end;
procedure CountProcess(const C: TConn);
var k: string; i: Integer;
begin
 k:=C.Name+' ('+C.PID+')'; i:=ProcessStats.IndexOfName(k);
 if i<0 then ProcessStats.Add(k+'=1')
 else ProcessStats.ValueFromIndex[i]:=IntToStr(StrToIntDef(ProcessStats.ValueFromIndex[i],0)+1);
end;
procedure Reconcile;
var i,j: Integer; a,b: PConn; age: Integer;
begin
 for i:=0 to Current.Count-1 do begin
  a:=PConn(Current.Objects[i]); j:=Previous.IndexOf(Current[i]);
  if j<0 then begin
   Inc(TotalNew); CountProcess(a^); OutputEvent('new',a^,0);
  end else begin
   b:=PConn(Previous.Objects[j]); a^.FirstSeen:=b^.FirstSeen;
   age:=Trunc((Now-a^.FirstSeen)*86400);
   if a^.State<>b^.State then begin Inc(TotalState); OutputEvent('state',a^,age) end;
  end;
 end;
 for i:=0 to Previous.Count-1 do if Current.IndexOf(Previous[i])<0 then begin
  b:=PConn(Previous.Objects[i]); Inc(TotalClosed);
  age:=Trunc((Now-b^.FirstSeen)*86400); OutputEvent('closed',b^,age);
 end;
end;
procedure PrintStats;
var i: Integer; s: string;
begin
 s:='STATS uptime='+IntToStr(Trunc((Now-Started)*86400))+'s new='+IntToStr(TotalNew)+
  ' closed='+IntToStr(TotalClosed)+' state='+IntToStr(TotalState)+' active='+IntToStr(Previous.Count);
 if FormatName='jsonl' then
  WriteLn('{"type":"stats","time":',JsonQuote(Stamp),',"new":',TotalNew,
   ',"closed":',TotalClosed,',"state":',TotalState,',"active":',Previous.Count,'}')
 else if FormatName='csv' then WriteLn('# ',s)
 else begin
  WriteLn(s); WriteLn('TOP PROCESSES (observed NEW sockets):');
  for i:=0 to ProcessStats.Count-1 do WriteLn('  ',ProcessStats.Names[i],': ',ProcessStats.ValueFromIndex[i]);
 end;
 Flush(Output);
end;
{$IFDEF LINUX}
function c_readlink(path:PChar; buf:PChar; size:SizeUInt):SizeInt; cdecl; external 'c' name 'readlink';
function LinkTarget(const Path: string): string;
var b: array[0..4095] of Char; n: SizeInt;
begin
 n:=c_readlink(PChar(Path),@b[0],SizeOf(b)-1);
 if n<0 then Exit(''); b[n]:=#0; Result:=StrPas(@b[0]);
end;
function ReadLine(const Path: string): string;
var f: TextFile;
begin
 Result:=''; AssignFile(f,Path); {$I-} Reset(f); {$I+}
 if IOResult<>0 then Exit;
 try if not EOF(f) then ReadLn(f,Result) finally CloseFile(f) end;
end;
procedure BuildOwners(Owners, Names: TStringList);
var sr,fd: TSearchRec; base,link,inode: string; i: Integer;
begin
 if FindFirst('/proc/*',faDirectory,sr)<>0 then Exit;
 try repeat
  if not IsDigits(sr.Name) then Continue;
  base:='/proc/'+sr.Name+'/fd/';
  if FindFirst(base+'*',faAnyFile,fd)<>0 then Continue;
  try repeat
   link:=LinkTarget(base+fd.Name);
   if (Copy(link,1,8)<>'socket:[') or (Length(link)<10) then Continue;
   inode:=Copy(link,9,Length(link)-9);
   if Owners.IndexOfName(inode)<0 then Owners.Add(inode+'='+sr.Name);
  until FindNext(fd)<>0;
  finally FindClose(fd) end;
  i:=Names.IndexOfName(sr.Name);
  if i<0 then Names.Add(sr.Name+'='+ReadLine('/proc/'+sr.Name+'/comm'));
 until FindNext(sr)<>0;
 finally FindClose(sr) end;
end;
function HexIPv4(const H: string): string;
var n: QWord;
begin
 Result:=''; if (Length(H)<>8) or not TryStrToQWord('$'+H,n) then Exit;
 Result:=IntToStr(n and 255)+'.'+IntToStr((n shr 8) and 255)+'.'+
  IntToStr((n shr 16) and 255)+'.'+IntToStr((n shr 24) and 255);
end;
function HexIPv6(const H: string): string;
var i,j: Integer; w: string;
begin
 Result:=''; if Length(H)<>32 then Exit;
 for i:=0 to 7 do begin
  j:=(i div 2)*8+(1-(i mod 2))*4+1;
  w:=Copy(H,j,4);
  if i>0 then Result:=Result+':';
  Result:=Result+LowerCase(Copy(w,3,2)+Copy(w,1,2));
 end;
end;
function HexPort(const H: string): Word;
var n: QWord;
begin
 Result:=0; if TryStrToQWord('$'+H,n) and (n<=65535) then Result:=n;
end;
function TcpState(const H: string): string;
begin
 if H='01' then Result:='ESTABLISHED' else if H='02' then Result:='SYN_SENT'
 else if H='03' then Result:='SYN_RECV' else if H='04' then Result:='FIN_WAIT1'
 else if H='05' then Result:='FIN_WAIT2' else if H='06' then Result:='TIME_WAIT'
 else if H='07' then Result:='CLOSE' else if H='08' then Result:='CLOSE_WAIT'
 else if H='09' then Result:='LAST_ACK' else if H='0A' then Result:='LISTEN'
 else if H='0B' then Result:='CLOSING' else Result:=H;
end;
procedure ScanProc(const Path,Proto: string; V6: Boolean; Owners,Names: TStringList);
var f: TextFile; line,src,dst,pid,procname: string; fields: TStringList;
    c: TConn; i: Integer;
begin
 AssignFile(f,Path); {$I-} Reset(f); {$I+}
 if IOResult<>0 then Exit;
 fields:=TStringList.Create;
 try
  if not EOF(f) then ReadLn(f,line);
  while not EOF(f) do begin
   ReadLn(f,line); fields.Clear;
   ExtractStrings([' ',#9],[],PChar(Trim(line)),fields);
   if fields.Count<10 then Continue;
   src:=fields[1]; dst:=fields[2];
   if (Pos(':',src)=0) or (Pos(':',dst)=0) then Continue;
   c.Proto:=Proto;
   if V6 then begin
    c.SrcIP:=HexIPv6(Copy(src,1,Pos(':',src)-1));
    c.DstIP:=HexIPv6(Copy(dst,1,Pos(':',dst)-1));
   end else begin
    c.SrcIP:=HexIPv4(Copy(src,1,Pos(':',src)-1));
    c.DstIP:=HexIPv4(Copy(dst,1,Pos(':',dst)-1));
   end;
   c.SrcPort:=HexPort(Copy(src,Pos(':',src)+1,MaxInt));
   c.DstPort:=HexPort(Copy(dst,Pos(':',dst)+1,MaxInt));
   if Proto='TCP' then c.State:=TcpState(fields[3]) else c.State:=fields[3];
   i:=Owners.IndexOfName(fields[9]); pid:='unknown';
   if i>=0 then pid:=Owners.ValueFromIndex[i];
   procname:='unknown'; i:=Names.IndexOfName(pid);
   if i>=0 then if Names.ValueFromIndex[i]<>'' then procname:=Names.ValueFromIndex[i];
   c.PID:=pid; c.Name:=procname;
   AddConnection(c);
  end;
 finally fields.Free; CloseFile(f) end;
end;
procedure Scan;
var owners,names: TStringList;
begin
 owners:=TStringList.Create; names:=TStringList.Create;
 try
  BuildOwners(owners,names);
  ScanProc('/proc/net/tcp','TCP',False,owners,names);
  ScanProc('/proc/net/udp','UDP',False,owners,names);
  ScanProc('/proc/net/tcp6','TCP',True,owners,names);
  ScanProc('/proc/net/udp6','UDP',True,owners,names);
 finally owners.Free; names.Free end;
end;
{$ENDIF}
{$IFDEF WINDOWS}
type
 TDWORD=LongWord;
 TMibTcpRowOwnerPid=packed record
  State,LocalAddr,LocalPort,RemoteAddr,RemotePort,OwningPid:TDWORD;
 end;
const AF_INET_=2; TCP_TABLE_OWNER_PID_ALL=5;
function GetExtendedTcpTable(pTable:Pointer; var Size:TDWORD; Order:LongBool;
 Family,TableClass,Reserved:TDWORD):TDWORD; stdcall; external 'iphlpapi.dll';
function QueryFullProcessImageNameA(hProcess:THandle; Flags:DWORD; Name:PAnsiChar;
 var Size:DWORD):BOOL; stdcall; external 'kernel32.dll' name 'QueryFullProcessImageNameA';
function ProcName(PID:TDWORD):string;
var h:THandle; buf:array[0..1023] of AnsiChar; n:DWORD;
begin
 Result:='unknown'; h:=OpenProcess($1000,False,PID);
 if h=0 then Exit;
 try
  n:=SizeOf(buf);
  if QueryFullProcessImageNameA(h,0,@buf[0],n) then Result:=ExtractFileName(Copy(string(buf),1,n));
 finally CloseHandle(h) end;
end;
function WinIP(N:TDWORD):string;
begin
 Result:=IntToStr(N and 255)+'.'+IntToStr((N shr 8) and 255)+'.'+
  IntToStr((N shr 16) and 255)+'.'+IntToStr((N shr 24) and 255);
end;
function WinPort(N:TDWORD):Word;
begin Result:=((N and $ff) shl 8) or ((N shr 8) and $ff) end;
function WinState(N:TDWORD):string;
begin
 case N of
 2:Result:='LISTEN'; 3:Result:='SYN_SENT'; 4:Result:='SYN_RECV';
 5:Result:='ESTABLISHED'; 6:Result:='FIN_WAIT1'; 7:Result:='FIN_WAIT2';
 8:Result:='CLOSE_WAIT'; 9:Result:='CLOSING'; 10:Result:='LAST_ACK';
 11:Result:='TIME_WAIT'; 12:Result:='CLOSE'; else Result:=IntToStr(N) end;
end;
procedure Scan;
var size,err,count,i:TDWORD; buf:Pointer; row:^TMibTcpRowOwnerPid; c:TConn;
begin
 size:=0; GetExtendedTcpTable(nil,size,False,AF_INET_,TCP_TABLE_OWNER_PID_ALL,0);
 if size<4 then Exit;
 GetMem(buf,size);
 try
  err:=GetExtendedTcpTable(buf,size,False,AF_INET_,TCP_TABLE_OWNER_PID_ALL,0);
  if err<>0 then Exit;
  count:=PDWORD(buf)^;
  if count=0 then Exit;
  for i:=0 to count-1 do begin
   row:=Pointer(PtrUInt(buf)+4+PtrUInt(i)*SizeOf(TMibTcpRowOwnerPid));
   c.Proto:='TCP'; c.PID:=IntToStr(row^.OwningPid);
   c.Name:=ProcName(row^.OwningPid);
   c.SrcIP:=WinIP(row^.LocalAddr); c.SrcPort:=WinPort(row^.LocalPort);
   c.DstIP:=WinIP(row^.RemoteAddr); c.DstPort:=WinPort(row^.RemotePort);
   c.State:=WinState(row^.State); AddConnection(c);
  end;
 finally FreeMem(buf) end;
end;
{$ENDIF}
procedure Help;
begin
 WriteLn('l4-check ',Version,' | https://ipsonic.com | ipsonic@mailbox.org');
 WriteLn('Unprivileged TCP/UDP socket polling (no root/admin required)');
 WriteLn;
 WriteLn('Usage: l4-check [OPTIONS]');
 WriteLn;
 WriteLn('Polling and scope:');
 WriteLn('  --interval MS             Poll interval in milliseconds (default: 500; min: 1)');
 WriteLn('  --once                    Scan once and exit');
 WriteLn('  --ipv6                    IPv6 option (Linux already scans IPv6)');
 WriteLn('  --all                     Include private and reserved destinations');
 WriteLn;
 WriteLn('Filters:');
 WriteLn('  --proto tcp,udp           Select protocols');
 WriteLn('  --pid PID                 Match a process ID');
 WriteLn('  --process NAME            Match process name (substring)');
 WriteLn('  --dst-ip IP[,IP/CIDR]     Match destination addresses / IPv4 CIDRs');
 WriteLn('  --dst-net IP/CIDR         Match an IPv4 destination network');
 WriteLn('  --dst-port 443,8443       Match destination ports');
 WriteLn('  --exclude-port PORTS      Exclude destination ports (comma-separated)');
 WriteLn('  --exclude-process NAME    Exclude process name (substring)');
 WriteLn('  --allowlist FILE          Suppress destinations listed as IP / IPv4 CIDR');
 WriteLn;
 WriteLn('Events and output:');
 WriteLn('  --events new,closed,state Select events (default: new)');
 WriteLn('  --format text|jsonl|csv   Output format (default: text)');
 WriteLn('  --timestamp time|iso8601  Timestamp format (default: time)');
 WriteLn('  --stats SECONDS           Periodic statistics (0 disables)');
 WriteLn('  --summary                 Print final summary with --once');
 WriteLn;
 WriteLn('Other:');
 WriteLn('  -h, --help                Show this help and exit');
 WriteLn('  --version                 Print version, source fingerprint and target');
 WriteLn;
 WriteLn('Examples:');
 WriteLn('  l4-check --interval 100');
 WriteLn('  l4-check --once --format jsonl --timestamp iso8601');
 WriteLn('  l4-check --process firefox --dst-port 443 --events new,closed');
 WriteLn('  l4-check --all --exclude-port 53 --stats 10');
 WriteLn;
 WriteLn('Notes: polling may miss short-lived connections; PID/name can be unknown.');
end;
procedure Fail(const MessageText: string);
begin WriteLn(StdErr,'l4-check: ',MessageText); Halt(2) end;
procedure ParseArgs;
var i,n: Integer; k,v: string;
begin
 FormatName:='text'; TimestampName:='time'; EventFilter:='new';
 i:=1;
 while i<=ParamCount do begin
  k:=ParamStr(i);
  if (k='--help') or (k='-h') then begin Help; Halt(0) end;
  if k='--version' then begin
   WriteLn('l4-check ',Version,' | Source: ',SourceFingerprint,' | Target: ',BuildTarget,' | https://ipsonic.com | ipsonic@mailbox.org');
   Halt(0)
  end;
  if k='--all' then AllTargets:=True
  else if k='--once' then OnceOnly:=True
  else if k='--summary' then Summary:=True
  else if k='--ipv6' then begin end
  else begin
   if not HasToken('--interval,--proto,--dst-port,--process,--pid,--dst-ip,--dst-net,--exclude-port,--exclude-process,--allowlist,--format,--timestamp,--events,--stats',k) then Fail('unknown option '+k+' (see --help)');
   if i>=ParamCount then Fail('missing value for '+k+' (see --help)');
   Inc(i); v:=ParamStr(i);
   if k='--interval' then begin
    if not TryStrToInt(v,n) or (n<1) then Fail('invalid interval'); IntervalMS:=n;
   end else if k='--proto' then ProtoFilter:=v
   else if k='--dst-port' then PortFilter:=v
   else if k='--process' then ProcessFilter:=v
   else if k='--pid' then PIDFilter:=v
   else if k='--dst-ip' then IPFilter:=v
   else if k='--dst-net' then NetFilter:=v
   else if k='--exclude-port' then ExcludePort:=v
   else if k='--exclude-process' then ExcludeProcess:=v
   else if k='--allowlist' then AllowFile:=v
   else if k='--format' then FormatName:=LowerCase(v)
   else if k='--timestamp' then TimestampName:=LowerCase(v)
   else if k='--events' then EventFilter:=LowerCase(v)
   else if k='--stats' then begin
    if not TryStrToInt(v,n) or (n<0) then Fail('invalid stats interval'); StatsSeconds:=n;
   end else Fail('unknown option '+k);
  end;
  Inc(i);
 end;
 if not HasToken('text,jsonl,csv',FormatName) then Fail('invalid format');
 if not HasToken('time,iso8601',TimestampName) then Fail('invalid timestamp');
 if (EventFilter='') then Fail('empty events');
end;
var tmp: TStringList; cycleStart: TDateTime; elapsed: Int64;
begin
 ParseArgs;
 Previous:=TStringList.Create; Current:=TStringList.Create;
 ProcessStats:=TStringList.Create; AllowRules:=TStringList.Create;
 try
  Previous.Sorted:=True; Current.Sorted:=True;
  Previous.Duplicates:=dupIgnore; Current.Duplicates:=dupIgnore;
  if AllowFile<>'' then begin
   try AllowRules.LoadFromFile(AllowFile) except on E:Exception do Fail('allowlist: '+E.Message) end;
  end;
  Started:=Now; LastStats:=Started;
  if FormatName='text' then begin
   WriteLn('L4-CHECK ',Version,' | source=',SourceFingerprint,' | https://ipsonic.com | polling=',IntervalMS,'ms');
   WriteLn('TIME         EVENT PROTO      PID PROCESS              SPORT DST-IP                                   DPORT STATE           AGE');
  end else if FormatName='csv' then
   WriteLn('time,event,proto,pid,process,src_ip,src_port,dst_ip,dst_port,state,age_seconds');
  repeat
   cycleStart:=Now; FreeEntries(Current); Scan; Reconcile;
   tmp:=Previous; Previous:=Current; Current:=tmp;
   if (StatsSeconds>0) and ((Now-LastStats)*86400>=StatsSeconds) then begin
    PrintStats; LastStats:=Now;
   end;
   if OnceOnly then Break;
   elapsed:=Round((Now-cycleStart)*86400000);
   if elapsed<IntervalMS then Sleep(IntervalMS-elapsed);
  until False;
  if Summary then PrintStats;
 finally
  FreeEntries(Previous); FreeEntries(Current);
  Previous.Free; Current.Free; ProcessStats.Free; AllowRules.Free;
 end;
end.
