{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Author:       François PIETTE
Description:  THttpServer implement the HTTP server protocol, that is a
              web server kernel.
              Reference: RFC2616 (HTTP protocol) and RFC2617 (Authentication).
              You must implement sucurity yourself, specially, check the URL or
              document path for valid values in your application. Be sure to
              check for '..\', '.\', drive designation and UNC.
              Do the check in OnGetDocument and similar event handlers.
Creation:     Oct 10, 1999
Version:      V10.0
EMail:        francois.piette@overbyte.be  http://www.overbyte.be
Support:      https://en.delphipraxis.net/forum/37-ics-internet-component-suite/
Legal issues: Copyright (C) 1999-2026 by François PIETTE
              Rue de Grady 24, 4053 Embourg, Belgium.

              SSL implementation includes code written by Arno Garrels,
              Berlin, Germany

              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.


History:
If not otherwise noted, changes are by Francois Piette
Nov 12, 1999 Beta 3 Added Linger properties
Apr 23, 2000 Beta 4 Added Delphi 1 compatibility
             Made everything public in THttpConnection because BCB has problems
             when deriving a component from Delphi and protected functions.
Oct 29, 2000 Beta 5 Added Client[] property and IsClient() method.
Nov 11, 2000 Beta 6 Added code from Sven <schmidts@cdesign.de> to set
             Last-Modified header line. Need some more changes !
Nov 12, 2000 Beta 7 Finished Last-Modified implementation.
             Corrected TriggerServerStopped.
Jun 18, 2001 V1.01 Check if still connected before sending any data.
Jul 31, 2001 V1.02 Handle URL encoded document file (for example when there is
             a space in the file name). Bug reported by Stian Grønland
             <joepezt@berzerk.net>.
             Better handling of non existant documents or documents with invalid
             file name.
Jan 13, 2002 V1.03 Changed SetPort() to SetPortValue() to avoid a conflict with
             BCB6 which has a macro to replace SetPort with SetPortA !
Apr 15, 2002 V1.04 In SendDocument, avoid calling Send(nil, 0) when a document
             has to be sent. Bug and fix by Adam Laforge <goodge@goodge.ca>.
Jul 06, 2002 V1.05 Thomas Smyth <smythtp@netscape.net> fixed
             ExtractURLEncodedValue which had problem with names beginning with
             same sequence of chars.
Oct 12, 2002 V1.06 Added THttpConnection.PostedDataReceived to be called from
             OnPostedData event handler when application has received all data
             from client.
             Added read/only property SrcVersion with component source version
Jan 05, 2003 V1.07 Fixed isxdigit
Feb 11, 2003 V1.08 Enhanced HTTP1.1 handling (persitant connexions)
Aug 28, 2003 V1.09 Stanislav Korotky <editor@tbsoft.ru> added the
             OnHttpRequestDone event and related stuff.
Oct 25, 2003 V1.10 Added a space before 'GMT' in Lats-Modified header line.
Oct 31, 2003 V1.11 Changed ProcessRequest so that empty FPath doesn't cause
             any problem.
Dec 17, 2003 V1.12 Added THttpConnection.FServer field
Jan 03, 2004 V1.13 Added directory list feature, Options property, utility
             functions TextToHtmlText, TranslateChar, UnixPathToDosPath,
             DosPathToUnixPath, IsDirectory, UrlDecode, AbsolutisePath.
             Removed useless units in the uses clause.
             Added hoAllowDirList and hoAllowOutsideRoot options.
             Added '.' in non encoded chars in UrlEncode
             Added hg403 flag and Answer403 response.
Jan 12, 2004 V1.14 "David A. G." <davidag@arnet.com.ar> added
                - Basic authorization support (Authorization header line)
                - Icon support "image/x-icon"
                - Property MaxClients
                - Simple WAP documents support
             Ivan Turcan <iturcan@drake-it.com>Added is Content-Range support
             by Http 1.1 specs. Still buggy ! Need to check end of range.
Jan 15, 2004 V1.15 Ivan Turcan code fixed.
             Conditional compilation with "UseInt64ForHttpRange" symbol to
             allow using 64 bit integer for HTTP ranges
Jan 16, 2004 V1.16 SendStream reset FDocstream position to start of stream.
             Added SendHeader method to make things more clear.
             David A.G. Fixed a bug related to sending last stream chunk.
Jan 17, 2004 V1.18 David A. G. <davidag@arnet.com.ar> implemented multi-host
             feature. That is added properties RequestHostName and
             RequestHostPort as well as event OnBeforeProcessRequest. From this
             event you can check RequestHostName and change DocDir and
             DefaultDoc appropriately.
             Added a CRLF at the end of the line generated by MakeCookie.
Jan 26, 2004 V1.19 Reordered uses for FPC compatibility.
             Added RequestCookies with the cookies included in the request.
Mar 27, 2004 V1.20 Added THttpConnection.AnswerPage method.
Apr 09, 2004 V1.21 Added method AnswerStream.
             Renamed Answer() to AnswerString() to make it similar to
             AnswerPage and AnswerStream.
May 11, 2004 V1.22 Added text/css check in DocumentToContentType
May 15, 2004 V1.23 Jack (jlist@softhome.net) added better support for HTTP/1.0
             persitant connection
May 30, 2004 V1.24 Enhanced byte-ranges support. Thanks to Andreas Hofmann
             <andreas.hofmann@docware.de> for his code which has been optimized
             and revised to work with older Delphi versions.
Jun 06, 2004 V1.25 Andreas Hofmann fixed a memory leak in the byte-ranges code
             implemented in V1.24. He also replaced THttpPartStreamRecord by an
             object THttpPartStream.
Jun 20, 2004 V1.26 THttpRangeList.Clear is not virtual in D3. (A. Garrels)
Jul 18, 2004 V1.27 David A. G. <davidag@arnet.com.ar> revised keep-alive
             handling. See SendDocument and ConnectionDataSent.
Aug 30, 2004 V1.28 Added support function RemoveHtmlSpecialChars which replace
             characters used as delimiter in HTML by their equivalent code:
             '<',    '>',    '&',     '''',    '"' are replaced by
             '&lt;', '&gt;', '&amp;', '&#39;', '&quot;'
             Added THttpSrv.SetDocDir (setter function for DocDir property) so
             that FDocDir is never terminated by a '\'.
             Changed THttpConnection.ProcessRequest to convert FPath to DOS
             type path.
Sep 12, 2004 V1.29 Made WSocketServer runtime property available.
Jan 08, 2005 V1.30 In TextToHtmlText, replace multiple spaces by a single space
             followed by the required number of non-breaking-spaces (&nbsp;)
             Replace TAB by a non-breaking-space.
             Added methods HtmlPageProducerToString and HtmlPageProducerToStream
             which ease the generation of dynamic pages from several templates.
Jan 14, 2005 V1.31 Added function HtmlPageProducerSetTagPrefix which allows
             to change the delimiter used in the various HtmlPageProducer
             functions. You can now change the '#' to something line 'ics:'
             which is better for XHTML validation tools provided you have a
             namespace defining the '<ics:somename>' tags. By default the
             delimiter is still '#' and no change is needed in the existing
             code. The HtmlPageProducer functions also accept a better form
             of the ending TABLE_ROWS delimiter (for XHTML compatibility). You
             can now use "</ics:TABLE_ROWS>" ("ics:" being whatever you selected
             with HtmlPageProducerSetTagPrefix and begin '#' by default).
Mar 07, 2005 V1.32 Added Answer501 method and use it to reply to unimplemented
             methods as suggested by M. Terrisse mterrisse@index-education.fr
Mar 13, 2005 V1.33 Changed define symbol for stream supporting 64 bits seek.
             Now use STREAM64 symbol. See ICSDEFS.INC where it is defined.
Apr 16, 2005 V1.34 Bjornar Nielsen:  Improved handling of Keepalive and
             persistent connections. Added KeepAlive property. Improved
             handling of pipelined requests.
May 15, 2005 V1.35 Added option wsoNoReceiveLoop in THttpConnection.Create.
             This fix message queue overflow when server is on a slow computer
             with a fast network.
May 22, 2005 V1.36 Fixed THttpConnection.AnswerStream to send Connection header
             line correctly (did't worked with HTTP 1.0). Big thansk to Bruno
             Sonnino <sonnino@netmogi.com.br> who found a reproductible case
             for this bug.
May 29, 2005 V1.37 Made a few more function virtual.
Dec 30, 2005 V1.38 A.Garrels added IcsLogger
Jan 16, 2005 V1.39 Fastream Technologies (www.fastream.com) coders SubZero
             (G. I. Ates) and PeterS (Peter Nikolow), Luke (Boris Evstatiev)
             implemented HTTP/1.1 digest authentication
Mar 04, 2006 V1.5 Lots of bugs fixed in DigestAuth code from Fastream.
             Implemented basic authentication as well.
             Renamed FBasicRealm to FAuthRealm to be universal.
Sep 04, 2006 V1.6 A. Garrels added NTLM authentication. Development of this
             feature has been sponsored by Fastream Technologies
             (www.fastream.com) and donated to ICS, thanks.
             **If you compile NTLM with BCB personality define SECURITY_WIN32
             in the project options**.
Jan 08, 2006 V1.61 Added AuthTypesToString function
Aug 10, 2007 V1.62 AG - New property SndBlkSize specifies the size of data
             chunks put into the send buffer in THttpConnection.
Mar 24, 2008 V6.01 Bumped version number to 6.01
             Francois Piette made some changes to prepare code for Unicode.
Apr 15, 2008 V6.02 A. Garrels added StreamWriteStrA() StreamWriteLnA()
             both replace WriteStream, WriteLnStream and WriteLnToStream.
             Got digest authentication working by type-changes from String to
             AnsiString. All authentication methods do work now, briefly tested.
Apr 20, 2008 Removed functions PutStringInSendBufferA() SendStrA() again.
             Now uses OverbyteIcsLibrary.pas, Sysutils.pas removed from the
             uses clause.
Apr 22, 2008 V6.03 AGarrels Removed checks for faVolumeID
Apr 30, 2008 V6.04 A. Garrels - Function names adjusted according to changes in
             OverbyteIcsLibrary.pas
May 15, 2008 V6.05 A. Garrels added function StreamReadStrA.
             Some type changes from String to AnsiString of published properties.
Jul 13, 2008 V6.06 Revised socket names used for debugging purpose.
Aug 11, 2008 V6.07 A. Garrels - Type AnsiString rolled back to String.
Sep 21, 2008 V6.08 A. Garrels removed a DELPHI4 conditional (CBuilder compat.)
Sep 28, 2008 V6.09 A. Garrels modified UrlEncode(), UrlDecode() and
             ExtractURLEncodedValue() to support UTF-8 encoding. Moved IsDigit,
             IsXDigit, XDigit, htoi2 and htoin to OverbyteIcsUtils.
             Fixed an AV in TextToHtmlText() with characters above #255.
Oct 10, 2008 V6.10 A. Garrels fixed TextToHtmlText() to work in all locales.
Oct 28, 2008 V7.11 A.Garrels - Replaced symbol UseInt64ForHttpRange by STREAM64.
             Fixed responses and  an infinite loop when a byte-range-set was
             unsatisfiable. Added a fix for content ranges with files > 2GB as
             suggested by Lars Gehre <lars@dvbviewer.com>.
Dec 03, 2008 V7.12 A.Garrels - Added Keep-Alive timeout and a maximum number
             of allowed requests during a persistent connection. Set property
             KeepAliveTimeSec to zero in order disable this feature entirely,
             otherwise persistent connections are dropped either after an idle
             time of value KeepAliveTimeSec or if the maximum number of requests
             (property MaxRequestKeepAlive) is reached. Multiple calls to
             CloseDelayed replaced by a graceful shutdown procedure to ensure
             all data is sent before the socket handle is closed. It's achieved
             by calling procedure PrepareGraceFullShutDown before data is actually
             sent, when ConnectionDataSent triggers ShutDown(1) is called and
             in case a client won't close the connection is dropped after 5
             seconds. New header Keep-Alive is sent if a client explcitely
             requests Connection: Keep-Alive.
Dec 05, 2008 V7.13 A.Garrels make use of function IcsCalcTickDiff in
             OverbyteIcsUtils.pas.
Dec 06, 2008 V7.14 A.Garrels - Avoid reentrance in procedure HeartBeatOnTimer.
             AnswerStream did not send the (optional) Keep-Alive header.
Jan 03, 2009 V7.15 A.Garrels - Fixed a bug with conditional define
             NO_AUTHENTICATION_SUPPORT introduced in V7.12.
             Fixed a infinite loop with digest authentication when user
             credential was wrong, caused by improper handling of a stale
             nonce. Improved nonce generation and added a new property
             AuthDigestNonceLifeTimeMin.
Jan 11, 2009 V7.16 A.Garrels - Removed some digest authentication code to new
             unit OverbyteIcsDigestAuth. OnAuthResult is no longer triggered
             with FALSE when the nonce is just stale. Changed string type of
             FAuthDigestBody to AnsiString. New directive NO_DIGEST_AUTH
             can be used to exclude the digest code from being compiled.
             ** Typo corrected, property AuthDigetUri is now AuthDigestUri **
             Added THttpConnection.AnswerStringEx() which works as AnswerString()
             however takes a CodePage argument in D2009 and better.
Jan 12, 2009 V7.17 A. Garrels fixed a bug with NTLM authentication in func.
             Answer401.
Apr 13, 2009 V7.18 Added overloaded ExtractURLEncodedValue with string arg.
Apr 17, 2009 V7.18 A. Garrels added a CodePage argument to functions
             ExtractURLEncodedValue(), UrlEncode() and UrlDecode.
             Changed type of local var TotalBytes in BuildDirList() from
             Cardinal to Int64 to avoid integer overruns.
Jun 12, 2009 V7.19 Angus made AuthBasicCheckPassword virtual
             Added AnswerStatus numeric property for web logging purposes
             Added OnBeforeAnswer event triggered once the answer is prepared
                but before it is sent from ProcessRequest
             Added OnAfterAnswer triggered after the answer is sent from
                ConnectionDataSent so time taken to send reply can be logged
             Ensure ConnectionDataSent is always called even for non-stream replies
Jun 15, 2009 V7.20 RTT and Angus added content encoding using zlib
               compression if Options hoContentEncoding set, and content
               type is text/* and content size is between SizeCompressMin and
               SizeCompressMax. New event HttpContentEncode called so application
               can encode content itself if needed or read a cached file,
               HttpContEncoded afterwards to save cached file or report compression
             Added XML and PNG MIME types
             Removed UseInt64ForHttpRange/Stream64 define, always use Int64
Jul 3, 2009  V7.21 Angus commonised content encoding with CheckContentEncoding
             and DoContentEncoding which are virtual to allow replacement
Aug 12, 2009 V7.22 Bjørnar Nielsen found a bug with conditional define NO_ADV_MT.
Oct 03, 2009 V7.23 Arno - Initialize client's counter in WSocketServerClientCreate
             otherwise the client might be disconnected before a single byte is
             sent/received. Happened rather frequently with SSL which led to SSL
             handshake errors.
Nov 29, 2009 7.24 Bjørnar Nielsen found a bug UrlDecode.
Feb 05, 2010 7.25 FPiette made StreamReadStrA, StreamWriteA and VarrecToString
             public.
             Added overloaded HtmlPageProducer to support template located
             in resource and in stream in adding to the existing file template.
Feb 08, 2010 V7.26 F. Piette fixed a bug introduced in 7.25 with ResType
                   (Need to be PChar instead of PAnsiChar).
                   TRL fixed HtmlPageProducerFromMemory which added an extra
                   empty line and passed the wrong length to HandleTableRow.
Aug 07, 2010 V7.27 Bjørnar Nielsen suggested to add an overloaded UrlDecode()
                   that takes a RawByteString URL.
Aug 08, 2010 V7.28 F. Piette: Published OnBgException from underlaying socket.
Sep 10, 2010 V7.29 RTT: Added OnUnknownRequestMethod event, triggered when
                   an unimplemented request method is being processed. Added
                   CustomHeaders variable to the SendDocument procedure, to
                   enable the possibility to send a custom header item(s) with
                   the document. Added PersistentHeader property to define
                   Header items that should be included in any response header.
Nov 06, 2010 V7.30 A. Garrels - Fixed posted data handling in case of posted
                   data is not accepted. Without this fix both posted data
                   and a valid new request could be received on the same line.
                   This also fixes NTLM authentication with POST requests.
                   RequestContentLength field type change to Int64.
Nov 08, 2010 V7.31 Arno improved final exception handling, more details
                   in OverbyteIcsWndControl.pas (V1.14 comments).
Jan 25, 2011 V7.32 FPiette fixed HtmlPageProducerToString for an unicode issue.
                   Thanks to Busai Péter for his help.
Jan 27, 2011 V7.33 Arno fixed a Unicode issue in VarRecToString, found by Péter
                   Busai. Methods THttpConnection.AnswerPage,
                   THttpConnection.HtmlPageProducerXy and helper functions take
                   optional code page parameter (D2009+ only).
Feb 4,  2011 V7.34 Angus added bandwidth throttling using TCustomThrottledWSocket
                   Set BandwidthLimit property to maximum bytes server wide, for
                   specific clients set BandwidthLimit in a client connect event
                   (requires BUILTIN_THROTTLE to be defined in project options or
                   enabled OverbyteIcsDefs.inc)
Feb 17, 2011 V7.35 FPiette fixed ExtractURLEncodedValue which returned a nul
                   byte when last character was a '%'. Now return a '%'.
Jun 15, 2011 V7.36 Arno removed the check for empty password string in
                   THttpConnection.AuthDigestCheckPassword.
Jun 18, 2011 V7.37 aguser removed one compiler hint.
Jul 01, 2011 V7.38 Lars Gehre found that HEAD could cause an infinite loop.
Jul 09, 2011 V7.39 Lars Gehre fixed an issue with conditional define
                   "NO_AUTHENTICATION_SUPPORT".
Oct 18, 2011 V7.40 Angus GET performance improvements, use TBufferedFileStream,
                   SndBlkSize default is 8192 and dynamically increased to new
                   property MaxBlkSize if stream is larger than SndBlkSize.
                   SocketSndBufSize also increased to SndBlkSize.
Oct 22, 2011 V7.41 Angus added OnHttpMimeContentType to allow custom ContentTypes
                   to be supported for unusual file extensions
Jan 20, 2012 V7.42 RTT - Apply fix of V1.05 to GetCookieValue().
Feb 04, 2012 V7.43 Tobias Rapp added method AnswerStreamAcceptRange which is
                   similar to AnswerStream however doesn't ignore requested
                   content range. Use this method only for OK responses.
Feb 07, 2012 V7.44 Arno - The HEAD method *MUST NOT* return a message-body in
                   the response. Do not skip compression on HEAD requests, we
                   need to send the correct size. Method SendDocument
                   simplified and added two overloads. AnswerStreamAcceptRange
                   got an overload too.
Feb 08, 2012 V7.45 Arno - If we receive an unknown method/request we have to
                   close the connection, otherwise we may receive junk data we
                   cannot handle properly.
Feb 15, 2012 V7.46 Angus - attach TMimeTypesList component to provide more MIME
                   content types read from registry, a file or strings, the
                   existing DocumentToContentType function is used as a default
Feb 18, 2012 V7.47 Arno - Attachment of MimeTypesList corrected.
Feb 29, 2012 V7.48 Arno - Use IcsRandomInt
Mar 26, 2012 V7.49 Angus - MakeCookie has optional domain parameter
Mar 31, 2012 V7.50 Arno - Made TextToHtmlText work with WideString in Ansi Delphi
Apr 27, 2012 V7.51 Arno - Fixed and deprecated FileDate() use
                   OverbyteIcsUtils.IcsFileUtcModified() instead.
May 2012 - V8.00 - Arno added FireMonkey cross platform support with POSIX/MacOS
                   also IPv6 support, include files now in sub-directory
                   New SocketFamily property (sfAny, sfAnyIPv4, sfAnyIPv6, sfIPv4, sfIPv6)
                   New MultiListenSockets property to add extra listening sockets,
                     each with Addr/Port/SocketFamily/SslEnable properties
                     in events check MultiListenIndex, -1 is main socket, >=0 is
                     index into MultiListenSockets[] for socket raising event
Jul 11, 2012 V8.01 Angus - added new THttpConnectionState of hcSendData for GET/HEAD so
                   we don't start a new request if extra blank lines sent after header
Jul 23, 2012 V8.02 Angus - added TCustomSslHttpServer to allow descendents (TSslHttpAppSrv)
                   added SslEnable property so SSL can be disabled, defaults to TRUE
Aug 21, 2012 V8.03 Tobias Rapp fixed a problem in THttpRangeStream with partial GET
                      requests returning less than requested
Jun 08, 2013 V8.04 FPiette fixed missing FAnswerStatus in AnswerStream
Jul 11 2013 V8.05 Angus - Tobias Rapp found that client requests timed out after 10 seconds
                     inactivity due to KeepAliveTimeSec which is far to fast.
                   So added KeepAliveTimeXferSec default to 300 seconds which is effective
                      during transfers, with KeepAliveTimeSec being used between requests.
                   Ignore blank line separating pipelined requests
Oct 13 2013 V8.06 Arno - POST did not work, a bug introduced in V8.05.
Feb 10 2014 V8.07 Angus - compress application/json and javascript content
Jul 17 2014 V8.08 Angus - added HTTP/1.1 methods OPTIONS, PUT, DELETE, TRACE, PATCH
                  and CONNECT, all need to be optionally enabled
                  OPTIONS and TRACE are handled by this component
                  PUT and POST need to be handled similarly to POST with an upload
                  DELETE is handled similarly to GET
                  CONNECT is really for Proxy Servers and ignored here for now
                  added ServerHeader property optionally sent if hoSendServerHdr
                  added RequestMethod property for client of THttpMethod
                  added RequestUpgrade property for client, websoocket is protocol should be changed
Mar 23 2015 V8.09 Angus onSslServerName event added
Jan 25 2016 V8.10 Angus added ReqTarget property for client, which is similar to Path but may
                    contain an absolute-form path starting with http://host
                  Convert Path absolute-form to origin-form per RFC7230 section 5.3.2
                    (a future version of HTTP may require absolute-form)
Feb 23 2016 V8.11 Angus get If-Modified-Since request header to RequestIfModSince
                  SendDocument does not return unchanged files but 304
                  Added Option hoIgnoreIfModSince to ignore date
                  Added Answer304
                  Moved RFC1123_Date to Utils
                  renamed TBufferedFileStream to TIcsBufferedFileStream
Apr 25 2016 V8.12 Angus added RequestStartTick to allow timing of request processing
                  Moved TextToHtmlText and RemoveHtmlSpecialChars to
                    OverbyteIcsFormDataDecoder to share with others units
Nov 04 2016 V8.37 Added ExclusiveAddr property to stop other applications listening on same socket
                  Added extended exception information, set SocketErrs = wsErrFriendly for
                      some more friendly messages (without error numbers)
                  MakeCookie has new Secure property that sets secure cookies
Apr 11 2017 V8.45 Added multiple SSL host support using SNI or Host header.
                  There is a new IcsHosts property which allows multiple hosts
                    to be specified, each with one or two IP addresses and
                    non-SSL and SSL port bindings, SSL certificates and private
                    key, SSL context and security level.
                  If IcsHosts is specified, TSslWSocketServer ignores existing
                   bindings and SSLContext, and creates new bindings and
                   initialises an SSL context for each host checking and reporting
                   all certificates.
                  For HttpSrv, IcsHostCollection includes four new properties,
                   WebDocDir, WebTemplDir, WebDefDoc and WebLogDir, which set
                   the client DocDir, TemplateDir and DefaultDoc according to
                   the request Host, so the server supports multiple web sites.
                  Note IcsHosts is only in the SSL server TSslHttpServer
                   but may be used for HTTP or HTTPS connections.
May 24 2017 V8.48 ValidateHosts has more options
                  Host: header checking higher priority than binding
                  Added ListenAllOK, ListenStates, RecheckSslCerts
Jul 5 2017  V8.49 Added .well-known directory support.  If WellKnownPath is
                     specified as a path, any access to /.well-known/xx is
                     handled locally either in the OnWellKnownDir Event or
                     by returning a file from WellKnownPath instead of DocDir.
                     This is primarily for Let's Encrypt challenges.
                   Start is now a function that optionally opens all possible
                      sockets ignoring errors, which are returned as a string.
                      This is primarily when using MultiListenrs where one
                      failing no longer stops all of them.
                   Moved DocumentToContentType to OverbyteIcsFormDataDecoder to share
                   Fixed bug locating HostTag from Host must check port as well.
                   Added RequestProtocol either http or https, useful to build links
Aug 10, 2017 V8.50 Fixed bug setting WebRedirectStat
                   Fixed bug that first IcsHost could not be SSL
                   Internal FSslEnable now FHttpSslEnable to ease confusion
Jul 6, 2018  V8.56 Added OnSslAlpnSelect called after OnSslServerName for HTTP/2
Oct 5, 2018 V8.57  Added SslCliCertMethod to allow server to request a client
                       SSL certificate from the browser, NOTE you should check it
                       the OnSslHandshakeDone event and close the connection if
                       invalid, beware this usually causes the browser to request
                       a certificate which can be obtrusive.
                   Allow SSL certificates to be ordered and installed automatically
                       by RecheckSslCerts if SslCertAutoOrder=True and so specified in
                       IcsHosts, if a TSslX509Certs component is attached and a
                       certificate supplier account has been created (by the
                       OverbyteIcsX509CertsTst sample application).
Oct 19, 2018 V8.58 Increased ListenBacklog property default to 15 to handle
                      higher server loads before rejecting new connections.
                   Some documentation on IcsHosts and main components.
Dec 04, 2018 V8.59 Added AUTO_X509_CERTS define set in OverbyteIcsDefs.inc which
                      can be disabled to remove a lot of units if automatic SSL/TLS
                      ordering is not required, saves up to 1 meg of code.
Feb 20, 2019 V8.60 Added WebLogIdx to THttpConnection for web logging.
                   Fixed bug Close did not close multi-listener sockets.
Mar 29, 2019 V8.61 OAS : Add InBound value for TNtlmAuthSession creation
                   because server NTLM auth is inbound and Client is outbound
Aug 7, 2019  V8.62 Builds without USE_SSL
Mar 11, 2020 V8.64 Added support for International Domain Names for Applications (IDNA),
                     i.e. using accents and unicode characters in domain names.
                   Host: header contains A-Label (Punycode ASCII) name, convert
                     to Unicode to compare Hosts.
Dec 09, 2020 V8.65 Support /.well-known/ from other proxies with absolute URL.
                   Renamed Ics.Posix.Messages.pas to Ics.Posix.PXMessages.pas.
Mar 11, 2021 V8.66 Added onBeforeCtxInit event which if set is called once before
                     each IcsHosts SslContext is initialised to allow the context
                     parameters to be adjusted for special ciphers or protocols.
May 24, 2021 V8.67 Added optional LastModified param to AnswerStream, AnswerPage,
                      and AnswerString to avoid needing custom header line.
                   Replaced Stream.Seek with Stream.Position.
Dec 29, 2021 V8.68 Support If-Range, If-Match and If-None-Match request headers
                     for conditional pages using Etag or last modified date, send
                     304 not modified for matches.  Helps with caching.
                   Add ETag header to responses in AnswerStream and AnswerPage when
                     we can create one from a file modification date and size (base64
                     CRC32), or if the EntityTag property is specified in the
                     onGetDocument event before using hgSendDoc or hgSendStream perhaps
                     a CRC32 of the entire content from a cache.
                   304 not modified response includes more recommended headers.
                   Add Date: header to AnswerStream and AnswerPage.
                   DELPHI24_UP to COMPILER24_UP for C++.
                   WARNING - applications that add Date: or Etag: to CustomHeaders
                     or to an AnswerStream should remove them since they are added
                     automatically.
May 18, 2022 V8.69 Added OCSP (Online Certificate Status Protocol) support using the TOcspHttp
                     component to confirm server SSL/TLS certificates are legitimate and not
                     revoked for security reasons (which (Let's Encrypt did with two days
                     notice on 28 Jan 2022).  The certificate OSCP response is also stapled
                     to the initial SSL/TLS HELO handshake and sent to the client to avoid
                     it needing to lookup OCSP using HTTP itself. OCSP responses are cached
                     and saved to a file for reloading later, but are refreshed every time
                     the certificate is validated, at least once a day. The server property
                     OcspSrvStapling=True enables OCSP checks and stapling only with
                     AUTO_X509_CERTS define since it adds extra HTTP client code. A revoked
                     certificate will be auto ordered.
                   Don't set FWSocketServer.Name when creating component, not needed.
                   Convert FLastModified to UTC/GMT for headers.
                   Added new authentication type atDigestSha2 with a SHA256 hash instead of
                     MD5 with atDigest only supported with USE_SSL. Note: Mozilla Firefox
                     supports Digest SHA-256, Chrome and Edge do not.
                   Added new client connection OnHttpRespHdr event to allow response headers
                     to be logged, previously only request headers could be logged.  Cleaned
                     up AnswerStream functions so separate lines don't go into send buffer.
Oct 19, 2022 V8.70 Simplified ZLIB support to allow use of System.ZLib.
Jan 26, 2023 V8.71 Fixed a Win64 issue reading streams in THttpRangeStream.Read, thanks
                     to Jaroslav Kulísek.
                   Ensure inherited destroy called.
                   Generally free objects instead of destroying them.
                   Using Int64 ticks.
Aug 08, 2023 V9.0  Updated version to major release 9.
Feb 13, 2024 V9.1  Added OverbyteIcsSslBase which now includes TX509Base and TX509List.
                   ContentLength can now be larger than 2GB.
                   Added new property NoSSL that prevents use of HTTPS, must be set before
                     server is started.
                  TOcspHttp now in OverbyteIcsSslUtils rather than OverbyteIcsSslHttpRest to
                     ease linking.
                  ExtractURLEncodedValue now calls IcsExtractURLEncodedValue in OverbyteIcsUrl
                    to ease sharing (not actually used by server, only apps).
                  Renamed UrlEncode to SrvUrlEncode to avoid conflicts with other units,
                    pending replace them with common versions.
                  Moved AbsolutisePath to Utils as IcsAbsolutisePath.
                  Added property ListenAny returns true if any sockets are listening,
                    ie server is running.
May 09, 2024 V9.2 Fixed a bug where authenticated POST/PUT requests always returned a 404 error.
                  Added method AnswerRedirect for various redirection responses to a new URL.
                  When accessing the default document in a path without a trailing path
                    delimited /, redirect using 301 to the correct path with delimiter
                    instead of adding it locally and displaying the document which will
                    then incorrectly link to pages in a higher level directory. Using the
                    THttpOption hoAddMissPath redirects if the default document is missing
                    perhaps a template or virtual document.
                  Added AnswerBodyTB client response with TBytes binary, similar to AnswerString.
                  Check for request HTTP version got corrupted if there were spaces in the URL,
                    which are not allowed.
Sep 16, 2024 V9.3 Avoid repeated redirection for virtual default page /, was adding /// etc,
                     bug in V9.2.
                  Using OverbyteIcsTypes for consolidated types and constants, allowing
                     other import units to be removed.
                  Added NativeInt version of THttpRangeList.Items[] due to a Win64 TList
                     change in Delphi 12.
Oct 11, 2024 V9.4 Updated Base64 encoding functions to IcsBase64 functions.
Jul 25, 2025 V9.5 Allow built in HTTP error respones to be customised using new event
                    OnHttpCustomError which is called by the error handlers with the error,
                    path, and existing Body, that may be replaced or modified as required.
                    Called for errors 301, 302, 307, 308, 400, 401, 403, 404, 416, 501.
                  Added new hoContDispHdr Option and AttachmentTypes list of file extensions
                    that if matched causes the server to add an Content-Disposition: attachment
                    header with the filename, that should cause a browser to offer a 'Save As'
                    dialog to save a binary file, rather than trying to display it.  Note the
                    default list includes .pdf so Acrobat files are saved rather than displayed.
                  Added OCSP conditionals. Note properties OcspSrvStapling and OcspSrvHttp are
                    still published, but ignore without define  OpenSSL_OcspStaple.
                  Ignore DHParams without DEFINE OpenSSL_Deprecated, no longer needed for
                    modern cyphers.
                  The Get and Delete methods now accept uploaded body content similarly to POST/PUT.
                    The derived THttpAppSrv server has handlers for uploaded content, for
                    THttpSrv you need to write your own.
                  Added OnHttpAcceptFilter event called before TWSocketServer accepts an
                     incoming connection allowing filtering on the remote IP address so the
                     connection is refused without any more events being called.
Feb 21, 2026 V9.6 Fixed check for If-Modified-Since: header.
                  BuildETag no longer truncates the CRC calculation for the ETag value, so will
                    now be unique for similar time stamps, thanks to nouvakis for finding this.
                  Using new onDisplay event to display messages from TWSocketS, controlled
                    by TWSDebugOptions.  Note onDisplay was previously in THttpAppSrv.
                    Defaulted from IcsLoadTHttpAppSrvFromIni.
                  Added request and response header logging if wsdlogHdr specified in
                    FWSDebugOptions.
                  OCSP gone, mostly discontinued.  Revocation of server certificates is
                    now checked using ACME Renewal Information API used by Let's Encrypt
                    and Google Trust Services for free certificates.  DHParams gone.
                  Initial support for WebDAV verbs PROPFIND, MKCOL, COPY, MOVE, PROPPaATCH,
                    LOCK, UNLOCK, enabled by hoAllowXX options.  Call OnWebDAVDocument event
                    only PROPFIND handled by server so far.
                  Added client WebDAVAcc property to define WebDAV command permissions,
                    should be set during client authentication to webdavRead or webdavWrite
                    otherwise the relevant verbs will be inaccessible, and not in OPTIONS.
                  Added WebDAV request header properties, RequestDepth, RequestBrief,
                    RequestTranslate, RequestOverwrite, RequestDestination, RequestXML,
                    the last is body content received with WebDAV requests, usually XML.
                  ParseRequest now sets now sets FRequestMethod so other functions don't
                   need to check verb literals against FMethod.
May 16, 2026 V9.7 Builds without AUTO_X509_CERT.
Aug 28, 2026 V9.8 Commonise unit copyright literals, from Types.
                  HtmlPageProducer no longer generates an exception if resource does
                    not exist, usually bad name.
                  Added client DebugDisplay for logging.
                  Using wsdlogHdr, trying to log full file name or origin of pages sent by
                    the server, ie in SendDocument, HtmlPageProducer, AnswerPage,
                    AnswerString, AnswerBodyTB, etc.
                  If a template file can not be found, log it and return 404 rather than a
                    page with the missing file name - we now have logging!
                  Added support for new QUERY request verb, similar to GET but always has
                    content, which GET has supported since V9.5.  Set Option hoAllowQuery
                    to enable the new command. OnQueryDocument event is called where code
                    should handle the content uploaded.  The OPTIONS request will then
                    list QUERY as supported.


Jul 27, 2026 V10.0 Updated for DEFINE ICS_NewMessaging that implements new cross platform
                     message handler for Windows and Linux, planned for mobile platforms.

Pending WebDAB, WebDAVAcc property to handle PUT file here, and to disable all events for
GET file since WebDAV only wants real files, not virtual or processed templates, etc,
MKCOL to create directory, COPY/MOVE verbs, maybe PROPPATCH, not LOCK/UNLOCK.


Quick reference guide:
----------------------

See OverbyteIcsWSocketS.pas for documentation on TSslWSocketServer whose
properties are exposed by TSslHttpServer, TSslWSocketClient for properties
exposed by THttpConnection, 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.

TSslHttpAppSrv in OverbyteIcsHttpAppServer.pas descends from TSslHttpServer
and adds session support and template processing based on URLs, it is generally
preferred over TSslHttpServer.  It includes a function IcsLoadTHttpAppSrvFromIni
that will load all major server settings from an INI file, as documented in that
unit and the OverbyteIcsSslMultiWebServ sample application.


Authentication:
  To implement authentication in your website, you must install an event
  handler for OnAuthGetType. In this handler, you check for each
  Client.Path which need to be password protected. For each selected path, you
  have to set Client.AuthType to whatever authentication method you need (none,
  basic or digest). You could also set Client.AuthRealm to whatever realm you
  need. By default AuthType and AuthRealm are initialized from the corresponding
  values ate the server component level.
  The next thing to do is to implement an event handler for the
  OnAuthGetPassword event. This event is triggered whenever the component need
  to get a password to check with what the client sent. Usually, you'll get
  the password using Client.AuthUsername property which is the username
  provided by the client. You may also use the path and the realm to
  implement more complex passwrod system.
  Use the OnAuthResult event to log authentication success or failure.

 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF ICS_INCLUDE_MODE}
unit OverbyteIcsHttpSrv;
{$ENDIF}

{$B-}                 { Enable partial boolean evaluation   }
{$T-}                 { Untyped pointers                    }
{$X+}                 { Enable extended syntax              }
{$H+}                 { Use long strings                    }
{$J+}                 { Allow typed constant to be modified }
{$I Include\OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
  {$IFDEF NO_EXTENDED_RTTI}
    {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
  {$ENDIF}
{$ENDIF}
{$IFDEF COMPILER12_UP}
    { These are usefull for debugging !}
    {$WARN IMPLICIT_STRING_CAST       ON}
    {$WARN IMPLICIT_STRING_CAST_LOSS  ON}
    {$WARN EXPLICIT_STRING_CAST       OFF}
    {$WARN EXPLICIT_STRING_CAST_LOSS  OFF}
{$ENDIF}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY    OFF}
{$WARN SYMBOL_DEPRECATED OFF}

{$IFDEF BCB3_UP}
    {$ObjExportAll On}
{$ENDIF}

{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    {$DEFINE USE_NTLM_AUTH}
{$ELSE}
    {$UNDEF USE_NTLM_AUTH}
    {$DEFINE NO_DIGEST_AUTH}
{$ENDIF}
{$IFDEF POSIX}
    {$IFDEF USE_NTLM_AUTH}
        {$UNDEF USE_NTLM_AUTH}  {SSPI is Windows only}
    {$ENDIF}
{$ENDIF}

{ V9.3 Delphi 12 and later have NativeInt version of TList.Items }
{$IFDEF COMPILER29_UP}
    {$DEFINE TListNatInt}
{$ENDIF}


interface

uses
{$IFDEF MSWINDOWS}
    {$IFDEF RTL_NAMESPACES}Winapi.Messages{$ELSE}Messages{$ENDIF},
    {$IFDEF RTL_NAMESPACES}Winapi.Windows{$ELSE}Windows{$ENDIF},
{$ENDIF}
{$IFDEF POSIX}
    Posix.Time,
{$ENDIF}
    {$IFDEF RTL_NAMESPACES}System.Classes{$ELSE}Classes{$ENDIF},
    {$IFDEF RTL_NAMESPACES}System.SysUtils{$ELSE}SysUtils{$ENDIF},
    OverbyteIcsZlibHigh,     { V7.20 }
    OverbyteIcsStreams,   { V7.40 }
    OverbyteIcsMD5,
{$IFDEF FMX}
    Ics.Fmx.OverbyteIcsWndControl,
    Ics.Fmx.OverbyteIcsWSocket,
    Ics.Fmx.OverbyteIcsWSocketS,
    Ics.Fmx.OverbyteIcsSslBase,  { V9.1 TX509Base }
    Ics.Fmx.OverbyteIcsFileCopy,      { V9.7 }
{$ELSE}
    OverbyteIcsWndControl,
    OverbyteIcsWSocket,
    OverbyteIcsWSocketS,
    OverbyteIcsSslBase,    { V9.1 TX509Base }
    OverbyteIcsFileCopy,            { V9.7 }
{$ENDIF FMX}
{$IFDEF AUTO_X509_CERTS}  { V8.59 }
{$IFDEF FMX}
    Ics.Fmx.OverbyteIcsSslX509Certs,  { V8.57 }
{$ELSE}
    OverbyteIcsSslX509Certs,        { V8.57 }
{$ENDIF}
{$ENDIF} // AUTO_X509_CERTS

{$IFDEF USE_NTLM_AUTH}
    OverbyteIcsSspi,
    OverbyteIcsNtlmSsp,
    OverbyteIcsNtlmMsgs,
{$ENDIF}
{$IFNDEF NO_DIGEST_AUTH}
    OverbyteIcsDigestAuth,
{$ENDIF}
    OverbyteIcsWSockBuf,
    OverbyteIcsMimeUtils,
    OverbyteIcsTypes,
    OverbyteIcsUtils,
//    OverbyteIcsWinsock,
    OverbyteIcsFormDataDecoder,
    OverbyteIcsCRC,        { V8.68 }
    OverbyteIcsTicks64,    { V8.71 }
    OverbyteIcsHtmlUtils,  { V9.1 }
    OverbyteIcsUrl;        { V9.1 }

const
    THttpServerVersion = IcsVerLitNum;                      { V9.8 }
    CopyRight : String = ' THttpServer'  + IcsVerLitCopyright; { V9.8 }
    DefServerHeader : string = 'Server: ICS-HttpServer-' + IcsVerLitRel;   { V8.09. V9.8 }
    CompressMinSize = 5000;  { V7.20 only compress responses within a size range, these are defaults only }
    CompressMaxSize = 5000000;
    MinSndBlkSize = 8192 ;  { V7.40 }
    WellKnownDirStr = '/.well-known/';    { V8.49 }
    { see http://www.iana.org/assignments/well-known-uris/well-known-uris.xhtml }

type
    THttpServer          = class;
    THttpConnection      = class;
    THttpConnectionClass = class of THttpConnection;
    THttpDirEntry        = class;
    TStringIndex         = class;

    THttpGetFlag         = (hgSendDoc, hgSendStream, hgWillSendMySelf, hg404, hg403, hg401, hg400, hgAcceptData, hgSendDirList,  hg501);                           { V8.08 added hg501 }
    THttpSendType        = (httpSendHead, httpSendDoc);
 (* V9.6 moved to Types
  THttpMethod          = (httpMethodNone, httpMethodGet, httpMethodPost, httpMethodHead,
                           httpMethodOptions, httpMethodPut, httpMethodDelete, httpMethodTrace,
                           httpMethodPatch, httpMethodConnect,                   { V8.08 more methods }
                           httpMethodPropFind, httpMethodMkCol, httpMethodCopy,  { V9.6 following WebDAV }
                           httpMethodMove, httpMethodPropPatch, httpMethodLock,
                           httpMethodUnlock);  *)

    THttpGetEvent        = procedure (Sender    : TObject;
                                      Client    : TObject;
                                      var Flags : THttpGetFlag) of object;
    THttpGetConnEvent    = procedure (Sender    : TObject;
                                      var Flags : THttpGetFlag) of object;
    THttpConnectEvent    = procedure (Sender    : TObject;
                                      Client    : TObject;
                                      Error     : Word) of object;
    THttpPostedDataEvent = procedure (Sender    : TObject;
                                      Client    : TObject;
                                      Error     : Word) of object;
    THttpRequestDoneEvent= procedure (Sender    : TObject;
                                      Client    : TObject) of object;
    THttpBeforeProcessEvent= procedure (Sender  : TObject;   {DAVID}
                                        Client  : TObject) of object;
    THttpFilterDirEntry  = procedure (Sender    : TObject;
                                      Client    : TObject;
                                      DirEntry  : THttpDirEntry) of object;
    THttpGetRowDataEvent = procedure (Sender          : TObject;
                                      const TableName : String;
                                      Row             : Integer;
                                      TagData         : TStringIndex;
                                      var More        : Boolean;
                                      UserData        : TObject) of object;
    THttpBeforeAnswerEvent= procedure (Sender    : TObject;
                                       Client    : TObject) of object;   { V7.19 }
    THttpAfterAnswerEvent= procedure  (Sender    : TObject;
                                       Client    : TObject) of object;   { V7.19 }

    THttpContentEncodeEvent= procedure (Sender    : TObject;           { V7.20 }
                                        Client    : TObject;
                                        out ContentEncoding: string;
                                        var Handled: Boolean) of object;
    TContentEncodeEvent= procedure (Sender    : TObject;           { V7.20 }
                                    out ContentEncoding: string;
                                    var Handled: Boolean) of object;
    THttpContEncodedEvent= procedure (Sender    : TObject;                 { V7.20 }
                                      Client    : TObject) of object;
    THttpUnknownRequestMethodEvent= procedure (Sender : TObject;   { V7.29 }
                                               Client : TObject;
                                               var Handled : Boolean) of object;
    TUnknownRequestMethodEvent= procedure (Sender : TObject;       { V7.29 }
                                           var Handled : Boolean) of object;
    THttpMimeContentTypeEvent= procedure (Sender    : TObject;     { V7.41 }
                                          Client    : TObject;
                                          const FileName: string;
                                          var ContentType: string) of object;
    TMimeContentTypeEvent= procedure (Sender    : TObject;         { V7.41 }
                                      const FileName: string;
                                      var ContentType: string) of object;

    TWellKnownEvent= procedure (Sender          : TObject;         { V8.49 }
                                Client          : TObject;
                                const Path      : string;
                                var BodyStr     : string)of object;

    TWellKnownConnEvent= procedure (Sender          : TObject;     { V8.49 }
                                    const Path      : string;
                                    var BodyStr     : string)of object;

    THttpRespHdrEvent= procedure (Sender          : TObject;                 { V8.69 }
                                  Client          : TObject;
                                  const Header: string) of object;

    TRespHdrEvent= procedure (Sender    : TObject;                           { V8.69 }
                              const Header: string) of object;

    TCustomErrorBodyEvent= procedure (Sender      : TObject;                { V9.5 }
                                      ErrNr       : Integer;
                                      const Info  : String;
                                      var Body    : String)  of object;

    THttpCustomErrorEvent= procedure (Sender      : TObject;
                                      Client      : TObject;
                                      ErrNr       : Integer;
                                      const Info  : String;
                                      var Body    : String)  of object;      { V9.5 }

    THttpAcceptFilterEvent = procedure (Sender: TObject; Client: TObject; var SessIpInfo: TIcsSessIpInfo;
                                                                                       var Allowed: Boolean) of object;  { V9.5 }

    THttpWebDAVConnEvent = procedure (Sender: TObject; HttpMethod: THttpMethod; var Flags : THttpGetFlag) of object; { 9.6 }

    THttpWebDAVEvent = procedure (Sender: TObject; Client: TObject; HttpMethod: THttpMethod;
                                                                                     var Flags : THttpGetFlag) of object; { 9.6 }

    THttpConnectionState = (hcRequest, hcHeader, hcPostedData, hcSendData);   { V8.01 }
    THttpOption          = (hoAllowDirList, hoAllowOutsideRoot, hoContentEncoding, { V7.20 }
                            hoAllowOptions, hoAllowPut, hoAllowDelete, hoAllowTrace,
                            hoAllowPatch, hoAllowConnect, hoSendServerHdr,   { V8.08 allow new methods }
                            hoIgnoreIfModSince, hoAddMissPath, hoContDispHdr,     { V8.11, V9.2, V9.5 }
                            hoAllowPropFind, hoAllowMkCol, hoAllowCopy,  { V9.6 following WebDAV }
                            hoAllowMove, hoAllowPropPatch, hoAllowLock, hoAllowUnlock,
                            hoAllowQuery);                               { V9.8 }

    THttpOptions         = set of THttpOption;

    TWebDAVAcc           = (webdavNone, webdavRead, webdavWrite);          { V9.6 permissions for WebDAV requests }

    THttpRangeInt        = Int64;
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    TAuthenticationType     = (atNone, atBasic
                              {$IFNDEF NO_DIGEST_AUTH}, atDigest {$ENDIF}
                              {$IFDEF USE_NTLM_AUTH}, atNtlm {$ENDIF}
                              {$IFNDEF NO_DIGEST_AUTH}, atDigestSha2 {$ENDIF});    { V8.69 }
    TAuthenticationTypes    = set of TAuthenticationType;
    TAuthGetPasswordEvent   = procedure (Sender       : TObject;
                                         Client       : TObject;
                                         var Password : String) of object;
    TAuthResultEvent        = procedure (Sender    : TObject;
                                         Client    : TObject;
                                         Success   : Boolean) of object;
    TAuthGetTypeEvent       = procedure (Sender    : TObject;
                                         Client    : TObject) of object;
  {$IFDEF USE_NTLM_AUTH}
    TAuthNtlmBeforeValidate = procedure (Sender       : TObject;
                                         Client       : TObject;
                                         var Allow    : Boolean) of object;
  {$ENDIF}
{$ENDIF}

    {ANDREAS one byte-range}
    THttpRange = class( TObject)
    private
        FRangeTo   : THttpRangeInt;
        FRangeFrom : THttpRangeInt;
        procedure SetRangeFrom(const Value: THttpRangeInt);
        procedure SetRangeTo(const Value: THttpRangeInt);
    public
        constructor Create;
        procedure   Assign(Source: THttpRange);
        function    GetContentRangeString(CompleteDocSize : THttpRangeInt): String;
        property    RangeFrom : THttpRangeInt read FRangeFrom write SetRangeFrom;
        property    RangeTo   : THttpRangeInt read FRangeTo   write SetRangeTo;
    end;

    {ANDREAS list of byte-ranges}
    THttpRangeList = class(TList)
    private
{$IFDEF TListNatInt}
        function  GetItems(NIndex: NativeInt): THttpRange;                        { V9.3 Delphi 12.2 changed type }
        procedure SetItems(NIndex: NativeInt; const Value: THttpRange);
{$ELSE}
        function  GetItems(NIndex: Integer): THttpRange;
        procedure SetItems(NIndex: Integer; const Value: THttpRange);
{$ENDIF}
    public
        destructor Destroy; override;
        procedure  Clear; override;
        procedure Assign(Source: THttpRangeList);
        function  CreateRangeStream(SourceStream    : TStream;
                                    ContentString   : String;
                                    CompleteDocSize : THttpRangeInt;
                                    var SyntaxError : Boolean): TStream;
        function  Valid: Boolean;
        procedure InitFromString(AStr: String);
{$IFDEF TListNatInt}
        property  Items[NIndex: NativeInt]: THttpRange read  GetItems          { V9.3 Delphi 12.2 changed type }
                                                    write SetItems;
{$ELSE}
        property  Items[NIndex: Integer]: THttpRange read  GetItems
                                                    write SetItems;
{$ENDIF}
    end;

    THttpPartStream = class(TObject)
        Stream   : TStream;
        StartPos : THttpRangeInt;
        EndPos   : THttpRangeInt;
        Offset   : THttpRangeInt;
        Size     : THttpRangeInt;
    end;

    {ANDREAS virtual Stream for the byte-range content }
    THttpRangeStream = class(TStream)
    private
        FSourceStream : TStream;
        FPosition     : THttpRangeInt;
        FSize         : THttpRangeInt;
        FPartStreams  : TList;
        procedure ClearPartStreams;
        procedure CalculateOffsets;
        function  GetPartStreams(NIndex: Integer): THttpPartStream;
    public
        constructor Create;
        destructor  Destroy; override;
        procedure AddPartStream(Value     : TStream;
                                AStartPos : THttpRangeInt;
                                AEndPos   : THttpRangeInt);
        function InitRangeStream(SourceStream    : TStream;
                                 RangeList       : THttpRangeList;
                                 ContentString   : String;
                                 var SyntaxError : Boolean): Boolean;
        function Read(var Buffer; Count: Longint): Longint; override;
        function Write(const Buffer; Count: Longint): Longint; override;
        function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
        function PartStreamsCount: Integer;
        property PartStreams[NIndex : Integer] : THttpPartStream
                                                   read  GetPartStreams;
    end;

    { THttpConnection is used to handle client connections }
    TBaseHttpConnection = class(TSslWSocketClient);
    THttpConnection = class(TBaseHttpConnection)
    protected
        FHttpVerNum                   : Integer;                 { V1.6 }
        FSendType                     : THttpSendType;           { V7.44 }
        FPostRcvBuf                   : TBytes;                  { V9.6 was fixed 1K, now variable }
        FPostRcvLen                   : Integer;                 { V9.6 how much in FPostRcvBuf for WebDAV }
        FPostCounter                  : Int64;                   { V7.30 }{V7.39}
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    {$IFDEF USE_NTLM_AUTH}
        FAuthNtlmSession              : TNtlmAuthSession;
    {$ENDIF}
        FAuthInit                     : Boolean;                        { V1.6 }
        FAuthUserName                 : String;
        FAuthPassword                 : String;
    {$IFNDEF NO_DIGEST_AUTH}
        FAuthDigestRealm              : String;   { Received from client }
        FAuthDigestUri                : String;
        FAuthDigestNonce              : String;
        FAuthDigestQop                : String;
        FAuthDigestNc                 : String;
        FAuthDigestCnonce             : String;
        FAuthDigestResponse           : String;
        FAuthDigestOpaque             : String;
        FAuthDigestServerNonce        : String;
        FAuthDigestServerOpaque       : String;
        FAuthDigestAlg                : String;
        FAuthDigestStale              : Boolean;
        FAuthDigestBody               : AnsiString; // Entity-Body as specified in RFC 2617, section 3.2.2.4
        FAuthDigestNonceLifeTimeMin   : Cardinal;
        FAuthDigestNonceTimeStamp     : TDateTime;
        FAuthDigestOneTimeFlag        : Boolean;
    {$ENDIF}
        FAuthType                     : TAuthenticationType;
        FAuthTypes                    : TAuthenticationTypes;
        FAuthenticated                : Boolean;
        function  AuthGetMethod: TAuthenticationType;
        procedure AuthCheckAuthenticated; virtual;
    {$IFNDEF NO_DIGEST_AUTH}
        function  AuthDigestCheckPassword(const Password: String): Boolean;
        function  AuthDigestGetParams: Boolean;
    {$ENDIF}
        function  AuthBasicGetParams: Boolean;
        function  AuthBasicCheckPassword(const Password: String): Boolean; virtual;  { V7.19 }
{$IFDEF USE_NTLM_AUTH}
        procedure AuthNtlmSessionBeforeValidate(Sender: TObject; var Allow: Boolean);
{$ENDIF}
{$ENDIF}
    protected
        FRcvdLine              : String;
        FMethod                : String;
        FVersion               : String;
        FPath                  : String;
        FParams                : String;
        FRequestHeader         : TStringList;
        FState                 : THttpConnectionState;
        FDocDir                : String;
        FTemplateDir           : String;
        FDefaultDoc            : String;
        FDocument              : String;
        FDocStream             : TStream;
        FDocBuf                : PAnsiChar;
        FSndBlkSize            : Integer;       {AG 03/10/07}
        FLastModified          : TDateTime;
        FAnswerContentType     : String;
        FRequestContentLength  : Int64;         { V7.30 }
        FRequestHasContentLength : Boolean;     { V7.30 }
        FRequestContentType    : String;
        FRequestAccept         : String;
        FRequestReferer        : String;
        FRequestAcceptLanguage : String;
        FRequestAcceptEncoding : String;
        FRequestUserAgent      : String;
        FRequestAuth           : String;        {DAVID}
        FRequestCookies        : String;
        FRequestHost           : String;
        FRequestHostName       : String;        {DAVID}
        FRequestHostPort       : String;        {DAVID}
        FRequestConnection     : String;
        FAcceptPostedData      : Boolean;
        FServer                : THttpServer;
        FAuthRealm             : String;
        FOptions               : THttpOptions;
        FOutsideFlag           : Boolean;
        FKeepAlive             : Boolean;        {Bjornar}
        FKeepAliveRequested    : Boolean;
        FRequestRangeValues    : THttpRangeList; {ANDREAS}
        FDataSent              : THttpRangeInt; {TURCAN}
        FDocSize               : THttpRangeInt; {TURCAN}
        FMsg_WM_HTTP_DONE      : UINT;
        FKeepAliveTimeSec      : Cardinal;
        FKeepAliveTimeXferSec  : Cardinal;   { V8.05 }
        FMaxRequestsKeepAlive  : Integer;
        FShutDownFlag          : Boolean;
        FAnswerStatus          : Integer;  { V7.19 }
        FOnGetDocument         : THttpGetConnEvent;
        FOnHeadDocument        : THttpGetConnEvent;
        FOnPostDocument        : THttpGetConnEvent;
        FOnPostedData          : TDataAvailable;
        FOnHTTPRequestDone     : TNotifyEvent;
        FOnBeforeProcessRequest: TNotifyEvent;  {DAVID}
        FOnFilterDirEntry      : THttpFilterDirEntry;
        FOnGetRowData          : THttpGetRowDataEvent;
        FOnBeforeAnswer        : TNotifyEvent;   { V7.19 }
        FOnAfterAnswer         : TNotifyEvent;   { V7.19 }
        FOnContentEncode       : TContentEncodeEvent;  { V7.20 }
        FOnContEncoded         : TNotifyEvent;         { V7.20 }
        FOnUnknownRequestMethod: TUnknownRequestMethodEvent; { V2.29 }
        FOnMimeContentType     : TMimeContentTypeEvent;  { V7.41 }
        FRequestMethod         : THttpMethod;          { V8.08 }
        FRequestUpgrade        : string;               { V8.08 }
        FOnOptionsDocument     : THttpGetConnEvent;    { V8.08 }
        FOnPutDocument         : THttpGetConnEvent;    { V8.08 }
        FOnDeleteDocument      : THttpGetConnEvent;    { V8.08 }
        FOnTraceDocument       : THttpGetConnEvent;    { V8.08 }
        FOnPatchDocument       : THttpGetConnEvent;    { V8.08 }
        FOnConnectDocument     : THttpGetConnEvent;    { V8.08 }
        FReqTarget             : string;               { V8.10 }
        FRequestIfModSince     : TDateTime;            { V8.11 }
        FRequestStartTick      : Int64;                { V8.12 }  { V8.71 }
        FWebLogDir             : string;               { V8.45 }
        FWellKnownPath         : String;               { V8.49 }
        FWebRedirectURL        : string;               { V8.49 }
        FWebRedirectStat       : integer;              { V8.49 }
        FonWellKnownDir        : TWellKnownConnEvent;  { V8.49 }
        FRequestProtocol       : String;               { V8.49 }
        FWebLogIdx             : Integer;              { V8.60 }
        FRequestIfRange        : String;               { V8.68 }
        FRequestIfMatch        : String;               { V8.68 }
        FRequestIfNoneMatch    : String;               { V8.68 }
        FEntityTag             : String;               { V8.68 }
        FOnRespHdr             : TRespHdrEvent;        { V8.69 }
        FCustomErrorBody       : TCustomErrorBodyEvent; { V9.5 }
        FOnWebDAVConn          : THttpWebDAVConnEvent; { V9.6 }
        FWebDAVAcc             : TWebDAVAcc;           { V9.6 }
        FRequestDepth          : String;               { V9.6 WebDAV PROPFIND 0,1,infinity }
        FRequestBrief          : String;               { V9.6 WebDAV PROPFIND T/F fewer XML }
        FRequestTranslate      : String;               { V9.6 WebDAV T/F for GET source ASP/CGI script, V9.8 typo }
        FRequestOverwrite      : String;               { V9.6 WebDAV T/F COPY/MOVE }
        FRequestDestination    : String;               { V9.6 WebDAV destination URL for COPY/MOVE }
        FRequestXML            : String;               { V9.6 WebDAV request XML }
        FOnQueryDocument       : THttpGetConnEvent;    { V9.8 }
        procedure SetSndBlkSize(const Value: Integer);
        procedure ConnectionDataAvailable(Sender: TObject; Error : Word); virtual;
        procedure ConnectionDataSent(Sender : TObject; Error : WORD); virtual;
        procedure ParseRequest; virtual;
        procedure ProcessRequest; virtual;
        procedure ProcessGet; virtual;
        procedure ProcessHead; virtual;
        procedure ProcessPost; virtual;
        procedure ProcessOptions; virtual;     { V8.08 }
        procedure ProcessPut; virtual;         { V8.08 }
        procedure ProcessDelete; virtual;      { V8.08 }
        procedure ProcessTrace; virtual;       { V8.08 }
        procedure ProcessPatch; virtual;       { V8.08 }
        procedure ProcessConnect; virtual;     { V8.08 }
        procedure ProcessGetHeadDel; virtual;  { V8.08 }
        procedure ProcessPostPutPat; virtual;  { V8.08 }
        procedure ProcessWellKnownDir;         { V8.49 }
        procedure ProcessPropFind; virtual;    { V9.6 WebDAV }
        procedure ProcessMkCol; virtual;       { V9.6 WebDAV }
        procedure ProcessCopy; virtual;        { V9.6 WebDAV }
        procedure ProcessMove; virtual;        { V9.6 WebDAV }
        procedure ProcessPropPatch; virtual;   { V9.6 WebDAV }
        procedure ProcessLock; virtual;        { V9.6 WebDAV }
        procedure ProcessUnlock; virtual;      { V9.6 WebDAV }
        procedure ProcessWebDAV; virtual;      { V9.6 WebDAV }
        procedure ProcessQuery; virtual;       { V9.8 }
        procedure Answer416; virtual;
        procedure Answer404; virtual;
        procedure Answer304; virtual;   { V8.11 }
        procedure Answer403; virtual;
        procedure Answer401; virtual;
        procedure Answer400; virtual;   { V7.30 }
        procedure Answer501; virtual;
{$IFDEF ICS_NewMessaging}   { V10 }
        procedure WMHttpDone(const Value : TIcsSocketMsgRec); virtual;
{$ELSE}
        procedure WndProc(var MsgRec: TMessage); override;
        procedure WMHttpDone(var msg: TMessage); virtual;
        procedure AllocateMsgHandlers; override;
        procedure FreeMsgHandlers; override;
        function  MsgHandlersCount: Integer; override;
{$ENDIF ICS_NewMessaging} { V10 }
        procedure TriggerGetDocument(var Flags : THttpGetFlag); virtual;
        procedure TriggerHeadDocument(var Flags : THttpGetFlag); virtual;
        procedure TriggerPostDocument(var Flags : THttpGetFlag); virtual;
        procedure TriggerOptionsDocument(var Flags : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerPutDocument(var Flags : THttpGetFlag); virtual;        { V8.08 }
        procedure TriggerDeleteDocument(var Flags : THttpGetFlag); virtual;     { V8.08 }
        procedure TriggerTraceDocument(var Flags : THttpGetFlag); virtual;      { V8.08 }
        procedure TriggerPatchDocument(var Flags : THttpGetFlag); virtual;      { V8.08 }
        procedure TriggerConnectDocument(var Flags : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerQueryDocument(var Flags : THttpGetFlag); virtual;      { V9.8 }
        procedure TriggerHttpRequestDone; virtual;
        procedure TriggerBeforeProcessRequest; virtual; {DAVID}
        procedure TriggerFilterDirEntry(DirEntry: THttpDirEntry); virtual;
        procedure TriggerBeforeAnswer; virtual; { V7.19 }
        procedure TriggerAfterAnswer; virtual;  { V7.19 }
        procedure TriggerContentEncode (out ContentEncoding: string;
                                        var Handled: Boolean); virtual;  { V7.20 }
        procedure TriggerContEncoded; virtual;    { V7.20 }
        procedure TriggerUnknownRequestMethod(var Handled : Boolean); virtual; { V7.29 }
        procedure TriggerMimeContentType(const FileName: string; var ContentType: string); virtual; { V7.41 }
        procedure TriggerWellKnownDir(const Path: string; var BodyStr: string); virtual;   { V8.49 }
        procedure TriggerWebDAVEvent(HttpMethod: THttpMethod; var Flags: THttpGetFlag); virtual; { 9.6 }
        function  CheckContentEncoding(const ContType : String): Boolean; virtual; { V7.21 are we allowed to compress content }
        function  DoContentEncoding: String; virtual; { V7.21 compress content returning Content-Encoding header }
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
        procedure TriggerAuthGetPassword(var PasswdBuf : String); virtual;
        procedure TriggerAuthResult(Authenticated : Boolean);
        procedure TriggerAuthGetType;
{$ENDIF}
        procedure SendDirList(SendType : THttpSendType); virtual;
        function  BuildDirList: String; virtual;
        function  FormatDirEntry(F: THttpDirEntry): String; virtual;
        procedure TriggerGetRowData(const TableName : String;
                                    Row             : Integer;
                                    TagData         : TStringIndex;
                                    var More        : Boolean;
                                    UserData        : TObject); virtual;
        procedure BuildETag(ContentSize: Int64); virtual;                 { V8.68 }
        procedure SendPropFindDir(var Flags : THttpGetFlag);              { V9.6 }
    public
        constructor Create(AOwner: TComponent); override;
        destructor  Destroy; override;

{$IFDEF ICS_NewMessaging}   { V10 }
        procedure   IcsDispatchMessage(const Value : TIcsSocketMsgRec); override;
{$ENDIF ICS_NewMessaging}  { V10 }
        procedure   SendStream; virtual;
        procedure   SendDocument; overload; virtual;  { V7.44 }
        procedure   SendDocument(const CustomHeaders: String); overload; virtual; { V7.44 }
        procedure   SendDocument(SendType : THttpSendType); overload; virtual;
        procedure   SendDocument(SendType : THttpSendType; const CustomHeaders: String); overload; virtual; { V7.29 }
        procedure   SendHeader(Header : String); virtual;
        procedure   PostedDataReceived; virtual;
        procedure   PrepareGraceFullShutDown; virtual;
        function    Receive(Buffer : TWSocketData; BufferSize: Integer) : Integer; override; { V7.30 }
        function    GetKeepAliveHdrLines: String;
        { AnswerPage will take a HTML template and replace all tags in this
          template with data provided in the Tags argument.
          The tags in the template must have the form <#TagName>.
          The Tags argument must be an array of const having the form
          ['TAG1', 'VALUE1', 'TAG2', VALUE2', ....]
          Of course TAG1, TAG2,... and VALUE1, VALUE2,... can be replaced by
          appropriate variables.
          There is a pair of special tags in the template:
              <#TABLE_ROWS TABLENAME> and <#/TABLE_ROWS>
          When finding the first tag, AnswerPage search for the second one
          and repeatedly trigger the event OnGetRowData to get data for the
          other tags. The loop is controlled by the event handler "More"
          argument. This permit easy table insertion with a single table row
          defined in the template and repeated for each row.
          It is permiited to have <#TABLE_ROWS TABLENAME> and <#/TABLE_ROWS>
          pairs embedded to make tables inside tables.

          UserData argument is passed to the OnGetRowData as is. It is
          intended to pass any object to the event handler, for example the
          dataset which was used to query the data to populate the table.

          The Status argument is the HTTP answer status.
          Default value "200 OK" is used when Status is an empty string.

          The Header argument is used to build the HTTP header for the answer.
          You _must_ not add Content-Length nor Content-Type in the header
          because those two values are generated automatically by AnswerPage.
          You can use Header argument for cache control, cookies or anything
          else your application require.
        }
        procedure   AnswerPage(var   Flags    : THttpGetFlag;
                               const Status   : String;
                               const Header   : String;
                               const HtmlFile : String;  // Template file name
                               UserData       : TObject;
                               Tags           : array of const;
                           {$IFDEF COMPILER12_UP}
                               FileCodepage   : LongWord = CP_ACP;
                               DstCodepage    : LongWord = CP_ACP;
                           {$ENDIF}
                               LastModified    : TDateTime = 0); overload; virtual;             { V8.67  }
        procedure   AnswerPage(var   Flags    : THttpGetFlag;
                               const Status   : String;
                               const Header   : String;
                               const ResName  : String;    // Template resource name
                               const ResType  : PChar;     // Template resource type
                               UserData       : TObject;
                               Tags           : array of const;
                           {$IFDEF COMPILER12_UP}
                               ResCodepage    : LongWord = CP_ACP;
                               DstCodepage    : LongWord = CP_ACP;
                           {$ENDIF}
                               LastModified    : TDateTime = 0); overload; virtual;             { V8.67  }
        procedure   AnswerStream(var   Flags    : THttpGetFlag;
                                 const Status   : String;
                                 const ContType : String;
                                 const Header   : String;   { Do not use Content-Length }
                                 LastModified    : TDateTime = 0); virtual;           { V8.67  }
        procedure   AnswerStreamAcceptRange(
                                 var Flags      : THttpGetFlag;
                                 const ContType : String;
                                 LastModified   : TDateTime = 0); overload; virtual;  { V7.44 }
        procedure   AnswerStreamAcceptRange(
                                 var Flags      : THttpGetFlag;
                                 const ContType : String;
                                 const Header   : String;
                                 LastModified   : TDateTime = 0); overload; virtual;  { V7.43 }
        procedure   AnswerString(var   Flags    : THttpGetFlag;
                                 const Status   : String;
                                 const ContType : String;
                                 const Header   : String;
                                 const Body     : String;
                                 LastModified   : TDateTime = 0); virtual;             { V8.67  }
{$IFDEF COMPILER12_UP}
        procedure   AnswerStringEx(var Flags    : THttpGetFlag;
                                 const Status   : String;
                                 const ContType : String;
                                 const Header   : String;
                                 const Body     : String;
                                 BodyCodePage   : Integer = CP_ACP;
                                 LastModified   : TDateTime = 0); virtual;             { V8.67  }
{$ENDIF}
        procedure   AnswerRedirect(RespCode: Integer; const NewLocation: String; const ExtraHdrs: String = ''); virtual;  { V9.2 redirection responses }
        procedure   AnswerBodyTB(var Flags: THttpGetFlag; const Status, ContType, Header: String; const Body: TBytes;
                                                                                          LastModified: TDateTime = 0); virtual;  { V9.2  }

        { Mostly like AnswerPage but the result is given into a string.
          Designed to be used within a call to AnswerPage as one of the
          replacable tag value. This permit to build a page based on several
          templates. A main template given to AnswerPage and one or more
          templates given to HtmlPageProducerToString, resulting string begin
          used as tag value for the main template. Of course you can
          recursively use HtmlPageProducerToString to build complex pages. }
        function HtmlPageProducerToString(const HtmlFile: String;
                                          UserData: TObject;
                                          Tags: array of const
                                      {$IFDEF COMPILER12_UP};
                                          FileCodepage: LongWord = CP_ACP
                                      {$ENDIF}
                                          ): String; virtual;
        { Mostly like AnswerPage but the result is given into a stream }
        procedure HtmlPageProducerToStream(const HtmlFile: String;
                                           UserData: TObject;
                                           Tags: array of const;
                                           DestStream: TStream
                                       {$IFDEF COMPILER12_UP};
                                           FileCodepage: LongWord = CP_ACP;
                                           DstCodepage: LongWord = CP_ACP
                                       {$ENDIF}
                                           ); overload; virtual;
        procedure HtmlPageProducerToStream(const ResName : String;
                                           const ResType : PChar;
                                           UserData: TObject;
                                           Tags: array of const;
                                           DestStream: TStream
                                       {$IFDEF COMPILER12_UP};
                                           ResCodepage: LongWord = CP_ACP;
                                           DstCodepage: LongWord = CP_ACP
                                       {$ENDIF}
                                           ); overload; virtual;
        procedure DebugDisplay(const Msg: String);                                 { V9.8 for client logging }
        property SndBlkSize : Integer read FSndBlkSize write SetSndBlkSize;
        { Method contains GET/POST/HEAD as requested by client }
        property Method                    : String read  FMethod;
        { Version contains HTTP version from client request }
        property Version                   : String read  FVersion;
        { The whole header as received from client }
        property RequestHeader             : TStringList
                                                    read  FRequestHeader;
        { Stream used to send reply to client }
        property DocStream                 : TStream
                                                     read  FDocStream
                                                     write FDocStream;
        { Client is asking to keep connection alive }
        property KeepAlive             : Boolean     read  FKeepAlive  {Bjornar}
                                                     write FKeepAlive; {Bjornar}
        { All RequestXXX are header fields from request header }
        property RequestContentLength  : Int64       read  FRequestContentLength;{ V7.30 }
        property RequestContentType    : String      read  FRequestContentType;
        property RequestAccept         : String      read  FRequestAccept;
        property RequestReferer        : String      read  FRequestReferer;
        property RequestAcceptLanguage : String      read  FRequestAcceptLanguage;
        property RequestAcceptEncoding : String      read  FRequestAcceptEncoding;
        property RequestUserAgent      : String      read  FRequestUserAgent;
        property RequestAuth           : String      read  FRequestAuth; {DAVID}
        property RequestCookies        : String      read  FRequestCookies;
        property RequestHost           : String      read  FRequestHost;
        property RequestHostName       : String      read  FRequestHostName;    {DAVID}
        property RequestHostPort       : String      read  FRequestHostPort;    {DAVID}
        property RequestConnection     : String      read  FRequestConnection;
        property RequestRangeValues    : THttpRangeList
                                                     read  FRequestRangeValues; {ANDREAS}
        property KeepAliveTimeSec      : Cardinal    read  FKeepAliveTimeSec
                                                     write FKeepAliveTimeSec;
        property KeepAliveTimeXferSec  : Cardinal    read  FKeepAliveTimeXferSec
                                                     write FKeepAliveTimeXferSec;  { V8.05 }
        property MaxRequestsKeepAlive  : Integer     read  FMaxRequestsKeepAlive
                                                     write FMaxRequestsKeepAlive;
        property AnswerStatus          : Integer     read  FAnswerStatus;  { V7.19 }
        property RequestMethod         : THttpMethod read  FRequestMethod; { V8.08 }
        property RequestUpgrade        : String      read  FRequestUpgrade; { V8.08 }
        property RequestIfModSince     : TDateTime   read  FRequestIfModSince; { V8.11 }
        property RequestStartTick      : Int64       read  FRequestStartTick;  { V8.12 }   { V8.71 }
        property RequestProtocol       : String      read  FRequestProtocol;   { V8.49 }
        property RequestIfRange        : String      read  FRequestIfRange;    { V8.68 }
        property RequestIfMatch        : String      read  FRequestIfMatch;    { V8.68 }
        property RequestIfNoneMatch    : String      read  FRequestIfNoneMatch;{ V8.68 }
        property RequestDepth          : String      read  FRequestDepth;      { V9.6 WebDAV PROPFIND 0,1,infinity }
        property RequestBrief          : String      read  FRequestBrief;      { V9.6 WebDAV PROPFIND T/F fewer XML }
        property RequestTranslate      : String      read  FRequestTranslate;  { V9.6 WebDAV T/F for GET source ASP/CGI script, V9.8 typo  }
        property RequestOverwrite      : String      read  FRequestOverwrite;  { V9.6 WebDAV T/F COPY/MOVE }
        property RequestDestination    : String      read  FRequestDestination;  { V9.6 WebDAV destination URL for COPY/MOVE }
        property RequestXML            : String      read  FRequestXML;        { V9.6 WebDAV request XML }
    published
        { Where all documents are stored. Default to c:\wwwroot }
        property DocDir         : String            read  FDocDir
                                                    write FDocDir;
        { Where all template documents are stored. Default to c:\wwwroot\templates }
        property TemplateDir    : String            read  FTemplateDir
                                                    write FTemplateDir;
        { Default document name. Default to index.html }
        property DefaultDoc     : String            read  FDefaultDoc
                                                    write FDefaultDoc;
        { Complete document path and file name on local file system }
        property Document       : String            read  FDocument
                                                    write FDocument;
        { Origin-form Document path as requested by client }
        property Path           : String            read  FPath
                                                    write FPath;
        { Absolute-form path that may start with http://host as requested by client }
        property ReqTarget      : string            read FReqTarget     { V8.10 }
                                                    write FReqTarget;
        { Parameters in request (Question mark is separator) }
        property Params         : String            read  FParams
                                                    write FParams;
        { Selected HTTP server optional behaviour }
        property Options        : THttpOptions      read  FOptions
                                                    write FOptions;
        { Triggered when client sent GET request }
        property OnGetDocument  : THttpGetConnEvent read  FOnGetDocument
                                                    write FOnGetDocument;
        { Triggered when client sent HEAD request }
        property OnHeadDocument : THttpGetConnEvent read  FOnHeadDocument
                                                    write FOnHeadDocument;
        { Triggered when client sent POST request }
        property OnPostDocument : THttpGetConnEvent read  FOnPostDocument
                                                    write FOnPostDocument;
        { Triggered when client sent POST request and data is available }
        property OnPostedData   : TDataAvailable    read  FOnPostedData
                                                    write FOnPostedData;
        { Triggered when a HTTP-request is done; since a connection can
        be established as keep-alive, there could possibly be several request
        done }
        property OnHttpRequestDone : TNotifyEvent   read  FOnHttpRequestDone
                                                    write FOnHttpRequestDone;
        { Triggered when client sent OPTIONS request V8.08 }
        property OnOptionsDocument : THttpGetConnEvent read  FOnOptionsDocument
                                                       write FOnOptionsDocument;
        { Triggered when client sent PUT request V8.08 }
        property OnPutDocument : THttpGetConnEvent  read  FOnPutDocument
                                                    write FOnPutDocument;
        { Triggered when client sent DELETE request V8.08 }
        property OnDeleteDocument : THttpGetConnEvent read  FOnDeleteDocument
                                                      write FOnDeleteDocument;
        { Triggered when client sent TRACE request V8.08 }
        property OnTraceDocument : THttpGetConnEvent  read  FOnTraceDocument
                                                      write FOnTraceDocument;
        { Triggered when client sent PATCH request V8.08 }
        property OnPatchDocument : THttpGetConnEvent  read  FOnPatchDocument
                                                      write FOnPatchDocument;
        { Triggered when client sent CONNECT request V8.08 }
        property OnConnectDocument : THttpGetConnEvent  read  FOnConnectDocument
                                                        write FOnConnectDocument;

        { Triggered before we process the HTTP-request }
        property OnBeforeProcessRequest : TNotifyEvent    {DAVID}
                                                    read  FOnBeforeProcessRequest
                                                    write FOnBeforeProcessRequest;

        { Triggered when doing a directory listing, for each entry. You
          can set Visible to FALSE to hide the entry, or even change anything
          in the data to fake the entry }
        property OnFilterDirEntry  : THttpFilterDirEntry
                                                    read  FOnFilterDirEntry
                                                    write FOnFilterDirEntry;
        { Triggered from AnswerPage when building a table, for each row }
        property OnGetRowData      : THttpGetRowDataEvent
                                                    read  FOnGetRowData
                                                    write FOnGetRowData;
        { Triggered once the answer is prepared but before it is sent from ProcessRequest V7.19 }
         property OnBeforeAnswer : TNotifyEvent     read  FOnBeforeAnswer
                                                    write FOnBeforeAnswer;
        { Triggered after the answer is sent from ConnectionDataSent V7.19 }
         property OnAfterAnswer : TNotifyEvent      read  FOnAfterAnswer
                                                    write FOnAfterAnswer;
        { Triggered before answer stream is sent, so it's content may be encoded or
         retrieved from cache V7.20 }
        property OnContentEncode : TContentEncodeEvent
                                                    read  FOnContentEncode
                                                    write FOnContentEncode;
        { Triggered after answer stream is compressed, so the stream may be cached V7.20 }
        property OnContEncoded : TNotifyEvent       read  FOnContEncoded
                                                    write FOnContEncoded;
        { Triggered when about to process an unimplemented request method V2.29 }
        property OnUnknownRequestMethod   : TUnknownRequestMethodEvent
                                                    read  FOnUnknownRequestMethod
                                                    write FOnUnknownRequestMethod;
        { Triggered from SendDocument to allow MIME content type to be changed    V7.41 }
        property OnMimeContentType  : TMimeContentTypeEvent
                                                    read  FOnMimeContentType
                                                    write FOnMimeContentType;
        { Triggered after sending a header                                       V8.69 }
        property OnRespHdr : TRespHdrEvent          read  FOnRespHdr
                                                    write FOnRespHdr;
        { Triggered when sending an error message, allowing Body to be customised V9.5 }
        property OnCustomErrorBody: TCustomErrorBodyEvent
                                                    read  FCustomErrorBody
                                                    write FCustomErrorBody;

{$IFNDEF NO_AUTHENTICATION_SUPPORT}
        { AuthType contains the actual authentication method selected by client }
        property AuthType          : TAuthenticationType
                                                    read  FAuthType;
        { AuthTypes contains the list of authentication methods accepted }
        property AuthTypes         : TAuthenticationTypes
                                                    read  FAuthTypes
                                                    write FAuthTypes;
        property AuthUserName      : String         read  FAuthUserName
                                                    write FAuthUserName;
        property AuthPassword      : String         read  FAuthPassword
                                                    write FAuthPassword;
        property AuthRealm         : String         read  FAuthRealm
                                                    write FAuthRealm;
    {$IFNDEF NO_DIGEST_AUTH}
        property AuthDigestUri     : String         read  FAuthDigestUri
                                                    write FAuthDigestUri;
        property AuthDigestNonceLifeTimeMin  : Cardinal
                                                    read  FAuthDigestNonceLifeTimeMin
                                                    write FAuthDigestNonceLifeTimeMin;
    {$ENDIF}
    {$IFDEF USE_NTLM_AUTH}
        property AuthNtlmSession   : TNtlmAuthSession
                                                    read  FAuthNtlmSession;
    {$ENDIF}
        property WebLogDir         : string         read  FWebLogDir            { V8.45 }
                                                    write FWebLogDir;
        property WellKnownPath     : String         read  FWellKnownPath        { V8.49 }
                                                    write FWellKnownPath;
        property WebRedirectURL    : string         read  FWebRedirectURL       { V8.49 }
                                                    write FWebRedirectURL;
        property WebRedirectStat   : integer        read  FWebRedirectStat      { V8.49 }
                                                    write FWebRedirectStat;
        property onWellKnownDir    : TWellKnownConnEvent  read  FonWellKnownDir  { V8.49 }
                                                          write FonWellKnownDir;
        property WebLogIdx         : integer        read  FWebLogIdx      { V8.60 }
                                                    write FWebLogIdx;
        property OnWebDAVConn: THttpWebDAVConnEvent read  FOnWebDAVConn
                                                    write FOnWebDAVConn; { V9.6 }
        property WebDAVAcc         : TWebDAVAcc     read  FWebDAVAcc
                                                    write FWebDAVAcc;     { V9.6 }
        { Triggered when client sent QUERY request V9.8 }
        property OnQueryDocument : THttpGetConnEvent  read  FOnQueryDocument
                                                      write FOnQueryDocument;

{$ENDIF}
    end;

    { This is the HTTP server component handling all HTTP connection }
    { service. Most of the work is delegated to a TWSocketServer     }
    THttpServer = class(TIcsWndControl)
    protected
        { FWSocketServer will handle all client management work }
        FWSocketServer            : TWSocketServer;
        FPort                     : String;
        FAddr                     : String;
        FSocketFamily             : TSocketFamily;        { V8.00 }
        FMaxClients               : Integer;              {DAVID}
        FClientClass              : THttpConnectionClass;
        FDocDir                   : String;
        FTemplateDir              : String;
        FDefaultDoc               : String;
        FLingerOnOff              : TSocketLingerOnOff;
        FLingerTimeout            : Integer;        { In seconds, 0 = disabled }
        FOptions                  : THttpOptions;
        FOnServerStarted          : TNotifyEvent;
        FOnServerStopped          : TNotifyEvent;
        FOnClientConnect          : THttpConnectEvent;
        FOnClientDisconnect       : THttpConnectEvent;
        FOnGetDocument            : THttpGetEvent;
        FOnHeadDocument           : THttpGetEvent;
        FOnPostDocument           : THttpGetEvent;
        FOnPostedData             : THttpPostedDataEvent;
        FOnHttpRequestDone        : THttpRequestDoneEvent;
        FOnBeforeProcessRequest   : THttpBeforeProcessEvent;    {DAVID}
        FOnFilterDirEntry         : THttpFilterDirEntry;
        FListenBacklog            : Integer; {Bjørnar}
        FKeepAliveTimeSec         : Cardinal;
        FKeepAliveTimeXferSec     : Cardinal;  { V8.05 }
        FMaxRequestsKeepAlive     : Integer;
        FHeartBeat                : TIcsTimer;
        FHeartBeatBusy            : Boolean;
        FOnBeforeAnswer           : THttpBeforeAnswerEvent;  { V7.19 }
        FOnAfterAnswer            : THttpAfterAnswerEvent;   { V7.19 }
        FOnHttpContentEncode      : THttpContentEncodeEvent;  { V7.20 }
        FOnHttpContEncoded        : THttpContEncodedEvent;    { V7.20 }
        FOnHttpUnknownReqMethod   : THttpUnknownRequestMethodEvent; { V7.29 }
        FSizeCompressMin          : Integer;  { V7.20 }
        FSizeCompressMax          : Integer;  { V7.20 }
        FPersistentHeader         : String;   { V7.29 }
        FMaxBlkSize               : Integer;  { V7.40 }
        FOnHttpMimeContentType    : THttpMimeContentTypeEvent;  { V7.41 }
        FMimeTypesList            : TMimeTypesList;             { V7.46 }
        FServerHeader             : String;           { V8.08 }
        FOnOptionsDocument        : THttpGetEvent;    { V8.08 }
        FOnPutDocument            : THttpGetEvent;    { V8.08 }
        FOnDeleteDocument         : THttpGetEvent;    { V8.08 }
        FOnTraceDocument          : THttpGetEvent;    { V8.08 }
        FOnPatchDocument          : THttpGetEvent;    { V8.08 }
        FOnConnectDocument        : THttpGetEvent;    { V8.08 }
{$IFDEF BUILTIN_THROTTLE}
        FBandwidthLimit           : LongWord;   { angus V7.34 Bytes per second, null = disabled }
        FBandwidthSampling        : LongWord;   { angus V7.34 Msec sampling interval }
{$ENDIF}
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
        FAuthTypes                : TAuthenticationTypes;
        FAuthRealm                : String;
{$IFNDEF NO_DIGEST_AUTH}
        FAuthDigestServerSecret       : Int64;
        FAuthDigestNonceLifeTimeMin   : Cardinal;
        FAuthDigestMethod             : TAuthDigestMethod;
{$ENDIF}
        FOnAuthGetPassword        : TAuthGetPasswordEvent;
        FOnAuthResult             : TAuthResultEvent;
{$IFDEF USE_NTLM_AUTH}
        FOnAuthNtlmBeforeValidate : TAuthNtlmBeforeValidate;
{$ENDIF}
        FOnAuthGetType            : TAuthGetTypeEvent;
{$ENDIF}
        FSocketErrs               : TSocketErrs;   { V8.37 }
        FExclusiveAddr            : Boolean;       { V8.37 }
        FWellKnownPath            : String;        { V8.49 }
        FAttachmentTypes          : String;        { V9.5 attachment content types,  }
        FonWellKnownDir           : TWellKnownEvent;        { V8.49 }
        FOnHttpRespHdr            : THttpRespHdrEvent;      { V8.69 }
        FOnHttpCustomError        : THttpCustomErrorEvent;  { V9.5 }
        FOnHttpAcceptFilter       : THttpAcceptFilterEvent;  { V9.5 }
        FOnWebDAVDocument         : THttpWebDAVEvent;        { V9.6 }
        FOnDisplay                : TDebugDisplay;           { V9.6 }
        FWSDebugOptions           : TWSDebugOptions;         { V9.6 }
        FOnQueryDocument          : THttpGetEvent;           { V9.8 }
        function  GetMultiListenSockets: TWSocketMultiListenCollection;
        procedure SetMultiListenSockets(const Value: TWSocketMultiListenCollection);
        function  CreateServerSecret: Int64; virtual;
        procedure Notification(AComponent: TComponent; operation: TOperation); override;
        procedure CreateSocket; virtual;
        procedure WSocketServerClientConnect(Sender : TObject;
                                             Client : TWSocketClient;
                                             Error  : Word); virtual;
        procedure WSocketServerClientCreate(Sender : TObject;
                                            Client : TWSocketClient); virtual;
        procedure WSocketServerClientDisconnect(Sender : TObject;
                                                Client : TWSocketClient;
                                                Error  : Word);
        procedure WSocketServerSessionClosed(Sender : TObject;
                                             Error  : Word);
        procedure WSocketServerChangeState(Sender : TObject;
                                           OldState, NewState : TSocketState);
        procedure WSocketServerCliAcceptFilter(Sender: TObject; Client: TWSocketClient; var SessIpInfo: TIcsSessIpInfo;
                                                                                                    var Allowed: Boolean); { V9.5 }
        procedure TriggerDisplay(Sender: TObject; const Msg: string);            { V9.6 }
        procedure SetOnBgException(const Value: TIcsBgExceptionEvent); override; { V7.31 }
        procedure TriggerServerStarted; virtual;
        procedure TriggerServerStopped; virtual;
        procedure TriggerClientConnect(Client : TObject; Error  : Word); virtual;
        procedure TriggerClientDisconnect(Client : TObject; Error : Word); virtual;
        procedure TriggerGetDocument(Sender     : TObject;
                                     var Flags  : THttpGetFlag); virtual;
        procedure TriggerHeadDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;
        procedure TriggerPostDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;
        procedure TriggerOptionsDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerPutDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerDeleteDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerTraceDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerPatchDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerConnectDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V8.08 }
        procedure TriggerQueryDocument(Sender     : TObject;
                                      var Flags  : THttpGetFlag); virtual;    { V9.8 }
        procedure TriggerPostedData(Sender     : TObject;
                                    Error      : WORD); virtual;
        procedure TriggerHttpRequestDone(Client : TObject); virtual;
        procedure TriggerBeforeProcessRequest(Client : TObject); virtual; {DAVID}
        procedure TriggerFilterDirEntry(Sender   : TObject;
                                        Client   : TObject;
                                        DirEntry : THttpDirEntry); virtual;
        procedure TriggerBeforeAnswer(Client : TObject);  { V7.19 }
        procedure TriggerAfterAnswer(Client : TObject);   { V7.19 }
        procedure TriggerContentEncode(Client : TObject;  { V7.20 }
                                       out ContentEncoding: string;
                                       var Handled: Boolean);
        procedure TriggerContEncoded(Client : TObject);   { V7.20 }
        procedure TriggerUnknownRequestMethod(Client : TObject; var Handled : Boolean); { V7.29 }
        procedure TriggerMimeContentType(Client : TObject; const FileName: string; var ContentType: string); virtual; { V7.41 }
        procedure TriggerWellKnownDir(Client : TObject; const Path: string; var BodyStr: string); virtual;   { V8.49 }
        procedure TriggerRespHdr(Client: TObject; const Header: string); virtual;  { V8.69 }
        procedure TriggerCustomError(Client: TObject; ErrNr: Integer; const Info: String; var Body: String); virtual;   { V9.5 }
        procedure TriggerCliAcceptFilter(Client: TWSocketClient; var SessIpInfo: TIcsSessIpInfo; var Allowed: Boolean); virtual; { V9.5 }
        procedure TriggerWebDAVEvent(Client: TObject; HttpMethod: THttpMethod; var Flags: THttpGetFlag); virtual; { 9.6 }
        procedure SetPortValue(const newValue : String);
        procedure SetAddr(const newValue : String);
        procedure SetDocDir(const Value: String);
        function  GetClientCount : Integer;
        function  GetClient(nIndex : Integer) : THttpConnection;
        function  GetSrcVersion: String;
        procedure HeartBeatOnTimer(Sender: TObject); virtual;
        procedure SetKeepAliveTimeSec(const Value: Cardinal);
        procedure SetKeepAliveTimeXferSec(const Value: Cardinal); { V8.05 }
        procedure SetMimeTypesList(const Value: TMimeTypesList); { V7.47 }
        procedure SetWellKnownPath(const Value: String);                  { V8.49 }
    public
        constructor Create(AOwner: TComponent); override;
        destructor  Destroy; override;
        function    Start(ReturnErrs: Boolean = false): String; virtual; { V8.49 made function }
        procedure   Stop; virtual;
        function    ListenAllOK: Boolean;                              { V8.48 }
        function    ListenAny: Boolean;                                { V9.1 }
        function    ListenStates: String;                              { V8.48 }
        { Check  if a given object is one of our clients }
        function    IsClient(SomeThing : TObject) : Boolean;
        { Runtime readonly property which gives number of connected clients }
        property    ClientCount : Integer        read  GetClientCount;
        { Client[] give direct access to anyone of our clients }
        property    Client[nIndex : Integer] : THttpConnection
                                                 read  GetClient;
        { Runtime property which tell the component class which has to be }
        { instanciated to handle client connection                        }
        property    ClientClass : THttpConnectionClass
                                                 read  FClientClass
                                                 write FClientClass;
        property    WSocketServer : TWSocketServer  read  FWSocketServer
                                                    write FWSocketServer;
    published
        property ListenBacklog  : Integer           read  FListenBacklog
                                                    write FListenBacklog; {Bjørnar}
        property MultiListenSockets : TWSocketMultiListenCollection                   { V8.00 }
                                                    read  GetMultiListenSockets
                                                    write SetMultiListenSockets;
        { Component source version }
        property SrcVersion    : String          read GetSrcVersion;
        { We will listen to that port. Default to 80 for http service }
        property Port          : String          read  FPort
                                                 write SetPortValue;
        { We will use that interface to listen. 0.0.0.0 means all     }
        { available interfaces                                        }
        property Addr          : String          read  FAddr
                                                 write SetAddr;
        property SocketFamily  : TSocketFamily   read  FSocketFamily                  { V8.00 }
                                                 write FSocketFamily;
        property MaxClients    : Integer         read  FMaxClients   {DAVID}
                                                 write FMaxClients;
        { Where all documents are stored. Default to c:\wwwroot }
        property DocDir        : String          read  FDocDir
                                                 write SetDocDir;
        { Where all template documents are stored. Default to c:\wwwroot\templates }
        property TemplateDir    : String            read  FTemplateDir
                                                    write FTemplateDir;
        { Default document name. Default to index.html }
        property DefaultDoc    : String          read  FDefaultDoc
                                                 write FDefaultDoc;
        property LingerOnOff   : TSocketLingerOnOff
                                                 read  FLingerOnOff
                                                 write FLingerOnOff;
        property LingerTimeout : Integer         read  FLingerTimeout
                                                 write FLingerTimeout;
        { Selected HTTP server optional behaviour }
        property Options        : THttpOptions   read  FOptions
                                                 write FOptions;
        property KeepAliveTimeSec : Cardinal     read  FKeepAliveTimeSec
                                                 write SetKeepAliveTimeSec;
        property KeepAliveTimeXferSec : Cardinal read  FKeepAliveTimeXferSec
                                                 write SetKeepAliveTimeXferSec;  { V8.05 }
        property MaxRequestsKeepAlive : Integer  read  FMaxRequestsKeepAlive
                                                 write FMaxRequestsKeepAlive;
        { Size between which textual responses should be compressed, too small is a
          waste of compression, too large blocks web server during zlib compression }
        property SizeCompressMin : integer       read  FSizeCompressMin
                                                 write FSizeCompressMin;
        property SizeCompressMax : integer       read  FSizeCompressMax
                                                 write FSizeCompressMax;
        {Header items to always included in any response header} { V7.29 }
        property PersistentHeader:string         read  FPersistentHeader
                                                 write FPersistentHeader;
        { maximum buffer block size to read/sent for large files }
        property MaxBlkSize : Integer            read FMaxBlkSize   { V7.40 }
                                                 write FMaxBlkSize ;
        { class providing MIME Content Types for documents }
        property MimeTypesList : TMimeTypesList  read  FMimeTypesList  { V7.46 }
                                                 write SetMimeTypesList; { V7.47 }
{$IFDEF BUILTIN_THROTTLE}
        { BandwidthLimit slows down speeds, bytes per second, null = disabled }
        property BandwidthLimit : LongWord       read  FBandwidthLimit
                                                 write FBandwidthLimit;     { angus V7.34 }
       { BandwidthSampling interval in msec }
        property BandwidthSampling : LongWord    read  FBandwidthSampling
                                                 write FBandwidthSampling;  { angus V7.34 }
{$ENDIF}
        { Server Header title }
        property ServerHeader : String           read FServerHeader
                                                 write FServerHeader;       { V8.08 }
        { OnServerStrated is triggered when server has started listening }
        property OnServerStarted    : TNotifyEvent
                                                 read  FOnServerStarted
                                                 write FOnServerStarted;
        { OnServerStopped is triggered when server has stopped listening }
        property OnServerStopped    : TNotifyEvent
                                                 read  FOnServerStopped
                                                 write FOnServerStopped;
        { OnClientConnect is triggered when a client has connected }
        property OnClientConnect    : THttpConnectEvent
                                                 read  FOnClientConnect
                                                 write FOnClientConnect;
        { OnClientDisconnect is triggered when a client is about to }
        { disconnect.                                               }
        property OnClientDisconnect : THttpConnectEvent
                                                 read  FOnClientDisconnect
                                                 write FOnClientDisconnect;
        { OnGetDocument is triggered when a client sent GET request    }
        { You can either do nothing and let server handle all work, or }
        { you can build a document on the fly or refuse access.        }
        property OnGetDocument      : THttpGetEvent
                                                 read  FOnGetDocument
                                                 write FOnGetDocument;
        { OnGetDocument is triggered when a client sent HEAD request   }
        { You can either do nothing and let server handle all work, or }
        { you can build a document header on the fly or refuse access. }
        property OnHeadDocument     : THttpGetEvent
                                                 read  FOnHeadDocument
                                                 write FOnHeadDocument;
        { OnGetDocument is triggered when a client sent POST request   }
        { You have to tell if you accept data or not. If you accept,   }
        { you'll get OnPostedData event with incomming data.           }
        property OnPostDocument     : THttpGetEvent
                                                 read  FOnPostDocument
                                                 write FOnPostDocument;
        { On PostedData is triggered when client post data and you     }
        { accepted it from OnPostDocument event.                       }
        { When you've got all data, you have to build a reply to be    }
        { sent to client.                                              }
        property OnPostedData       : THttpPostedDataEvent
                                                 read  FOnPostedData
                                                 write FOnPostedData;
        { Triggered when client sent OPTIONS request V8.08 }
        property OnOptionsDocument : THttpGetEvent
                                                 read  FOnOptionsDocument
                                                 write FOnOptionsDocument;
        { Triggered when client sent PUT request V8.08 }
        property OnPutDocument : THttpGetEvent
                                                 read  FOnPutDocument
                                                 write FOnPutDocument;
        { Triggered when client sent DELETE request V8.08 }
        property OnDeleteDocument : THttpGetEvent
                                                 read  FOnDeleteDocument
                                                 write FOnDeleteDocument;
        { Triggered when client sent TRACE request V8.08 }
        property OnTraceDocument : THttpGetEvent
                                                 read  FOnTraceDocument
                                                 write FOnTraceDocument;
        { Triggered when client sent PATCH request V8.08 }
        property OnPatchDocument : THttpGetEvent
                                                 read  FOnPatchDocument
                                                 write FOnPatchDocument;
        { Triggered when client sent CONNECT request V8.08 }
        property OnConnectDocument : THttpGetEvent
                                                 read  FOnConnectDocument
                                                 write FOnConnectDocument;
        { Triggered when client sent QUERY request V9.8 }
        property OnQueryDocument : THttpGetEvent
                                                 read  FOnQueryDocument
                                                 write FOnQueryDocument;
        property OnHttpRequestDone  : THttpRequestDoneEvent
                                                 read  FOnHttpRequestDone
                                                 write FOnHttpRequestDone;

        property OnBeforeProcessRequest : THttpBeforeProcessEvent  {DAVID}
                                                 read  FOnBeforeProcessRequest
                                                 write FOnBeforeProcessRequest;

        property OnFilterDirEntry   : THttpFilterDirEntry
                                                 read  FOnFilterDirEntry
                                                 write FOnFilterDirEntry;
        { Triggered once the answer is prepared but before it is sent V7.19 }
        property OnBeforeAnswer : THttpBeforeAnswerEvent
                                                 read  FOnBeforeAnswer
                                                 write FOnBeforeAnswer;
        { Triggered after the answer is sent V7.19 }
        property OnAfterAnswer : THttpAfterAnswerEvent
                                                 read  FOnAfterAnswer
                                                 write FOnAfterAnswer;
        property OnHttpContentEncode : THttpContentEncodeEvent      { V7.20 }
                                                 read FOnHttpContentEncode
                                                 write FOnHttpContentEncode;
        property OnHttpContEncoded : THttpContEncodedEvent      { V7.20 }
                                                 read FOnHttpContEncoded
                                                 write FOnHttpContEncoded;
        property OnUnknownRequestMethod : THttpUnknownRequestMethodEvent { V2.29 }
                                                 read FOnHttpUnknownReqMethod
                                                 write FOnHttpUnknownReqMethod;
        property OnHttpMimeContentType : THttpMimeContentTypeEvent         { V7.41 }
                                                 read FOnHttpMimeContentType
                                                 write FOnHttpMimeContentType;
        property OnHttpCustomError : THttpCustomErrorEvent                   { V9.5 }
                                                 read FOnHttpCustomError
                                                 write FOnHttpCustomError;
        property OnHttpAcceptFilter : THttpAcceptFilterEvent
                                                 read  FOnHttpAcceptFilter
                                                 write FOnHttpAcceptFilter;  { V9.5 }
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
        property OnAuthGetPassword  : TAuthGetPasswordEvent
                                                 read  FOnAuthGetPassword
                                                 write FOnAuthGetPassword;
        property OnAuthResult       : TAuthResultEvent
                                                 read  FOnAuthResult
                                                 write FOnAuthResult;
        property OnAuthGetType      : TAuthGetTypeEvent
                                                 read  FOnAuthGetType
                                                 write FOnAuthGetType;
    {$IFDEF USE_NTLM_AUTH}
         property OnAuthNtlmBeforeValidate  : TAuthNtlmBeforeValidate
                                                 read  FOnAuthNtlmBeforeValidate
                                                 write FOnAuthNtlmBeforeValidate;
    {$ENDIF}
        property AuthTypes         : TAuthenticationTypes
                                                 read  FAuthTypes
                                                 write FAuthTypes;
        property AuthRealm         : String      read  FAuthRealm
                                                 write FAuthRealm;
    {$IFNDEF NO_DIGEST_AUTH}
        property AuthDigestMethod  : TAuthDigestMethod
                                                 read  FAuthDigestMethod
                                                 write FAuthDigestMethod
                                                 default daAuth;
        property AuthDigestNonceLifeTimeMin  : Cardinal
                                                 read  FAuthDigestNonceLifeTimeMin
                                                 write FAuthDigestNonceLifeTimeMin default 1;
    {$ENDIF}
{$ENDIF}
        property OnBgException;  { F.Piette V7.27 }
        { wsErrFriendly gives more friendly error messages }
        property SocketErrs        : TSocketErrs read  FSocketErrs
                                                 write FSocketErrs;      { V8.37 }
        { stop other applications listening on our socket }
        property ExclusiveAddr     : Boolean     read  FExclusiveAddr
                                                 write FExclusiveAddr;   { V8.37 }
        { Where /.well-known/ documents are stored. Default is blank for ignore
          for Let'S Encrypt challenges and other special uses }
        property WellKnownPath     : String      read  FWellKnownPath
                                                 write SetWellKnownPath;      { V8.49 }
        property onWellKnownDir    : TWellKnownEvent  read  FonWellKnownDir
                                                      write FonWellKnownDir; { V8.49 }
        { after a response header sent, for logging }
        property OnHttpRespHdr     : THttpRespHdrEvent read  FOnHttpRespHdr
                                                       write FOnHttpRespHdr;   {  V8.69 }
        property AttachmentTypes   : String            read  FAttachmentTypes
                                                       write FAttachmentTypes;    { V9.5 attachment content types }
        property OnWebDAVDocument : THttpWebDAVEvent   read  FOnWebDAVDocument
                                                       write FOnWebDAVDocument; { V9.6 }
        property WSDebugOptions: TWSDebugOptions       read  FWSDebugOptions      {  V9.6 Debug Log Options for OnDebugDisplay event }
                                                       write FWSDebugOptions;
        property OnDisplay : TDebugDisplay             read  FOnDisplay
                                                       write FOnDisplay;         { V9.6 }

    end;

    THttpDirEntry = class
        Visible   : Boolean;    { TRUE if the entry is to be shown in list  }
        Name      : String;
        SizeLow   : Cardinal;
        SizeHigh  : Cardinal;
        Year      : Integer;
        Month     : Integer;
        Day       : Integer;
        Hour      : Integer;
        Min       : Integer;
        Sec       : Integer;
        VolumeID  : Boolean;
        Directory : Boolean;
        ReadOnly  : Boolean;
        SysFile   : Boolean;
        Hidden    : Boolean;   { File is hidden, not the same as Visible !  }
    end;

    TStringIndex = class(TObject)
    protected
        FList : TStringList;
    public
        constructor Create;
        destructor Destroy; override;
        procedure Add(const Key, Value : String);
        function  Find(const Key : String; var Value : String) : Boolean;
        function  Count : Integer;
        procedure Clear;
    end;

    TStringIndexObject = class(TObject)
    public
        Value : String;
        constructor Create(const Data : String);
    end;

    TTableRowDataGetter = procedure(const TableName : String;
                                    Row             : Integer;
                                    TagData         : TStringIndex;
                                    var More        : Boolean;
                                    UserData        : TObject);
    PTableRowDataGetter = ^TTableRowDataGetter;
    THttpSrvRowDataGetter = procedure(const TableName : String;
                                      Row             : Integer;
                                      TagData         : TStringIndex;
                                      var More        : Boolean;
                                      UserData        : TObject) of object;
    THttpSrvRowDataGetterUserData = class
    public
        Event    : THttpSrvRowDataGetter;
        UserData : TObject;
    end;

type
    TCustomSslHttpServer = class(THttpServer)  //  V8.02 Angus - was TSslHttpServer
    protected
        FHttpSslEnable                 : Boolean;  //  V8.02 Angus renamed V8.50
        FOnSslHandshakeDone            : TSslHandshakeDoneEvent;
        FOnSslVerifyPeer               : TSslVerifyPeerEvent;
        FOnSslSetSessionIDContext      : TSslSetSessionIDContext;
        FOnSslSvrNewSession            : TSslSvrNewSession;
        FOnSslSvrGetSession            : TSslSvrGetSession;
        FOnSslServerName               : TSslServerNameEvent;     // V8.09
        FOnSslAlpnSelect               : TSslAlpnSelect;          { V8.56 }
        FOnBeforeCtxInit               : TBeforeCtxInitEvent;     { V8.66 }
        procedure CreateSocket; override;
        procedure SetSslContext(Value: TSslContext);
        function  GetSslContext: TSslContext;
        procedure SetSslAcceptableHosts(Value : TStrings);
        function  GetSslAcceptableHosts: TStrings;
        procedure TransferSslVerifyPeer(Sender        : TObject;
                                        var Ok        : Integer;
                                        Cert          : TX509Base); virtual;
        procedure TransferSslHandshakeDone(Sender         : TObject;
                                           ErrCode        : Word;
                                           PeerCert       : TX509Base;
                                           var Disconnect : Boolean); virtual;
        procedure TransferSslSetSessionIDContext(Sender : TObject;
                                          var SessionIDContext : TSslSessionIdContext); virtual;
        procedure TransferSslSvrNewSession(Sender          : TObject;
                                        SslSession      : Pointer;
                                        SessId          : Pointer;
                                        Idlen           : Integer;
                                 var AddToInternalCache : Boolean); virtual;
        procedure TransferSslSvrGetSession(Sender          : TObject;
                                         var SslSession : Pointer;
                                         SessId         : Pointer;
                                         Idlen          : Integer;
                                         var IncRefCount: Boolean); virtual;
        procedure WSocketServerClientConnect(Sender  : TObject;
                                             Client  : TWSocketClient;
                                             ErrCode : Word); override;
        procedure WSocketServerClientCreate(Sender : TObject;
                                            Client : TWSocketClient); override;
        procedure TransferSslServerName(Sender: TObject;   // V8.09
                     var Ctx: TSslContext; var ErrCode: TTlsExtError); virtual;
        function  GetIcsHosts: TIcsHostCollection;                    { V8.45 }
        procedure SetIcsHosts(const Value: TIcsHostCollection);       { V8.45 }
        function  GetRootCA: String;                                  { V8.46 }
        procedure SetRootCA(const Value: String);                     { V8.46 }
        procedure TransferSslAlpnSelect(Sender: TObject;
          ProtoList: TStrings; var SelProto : String; var ErrCode: TTlsExtError);  { V8.56 }
        procedure TransferBeforeCtxInit(Sender: TObject; IcsHost: TIcsHost);    { V8.66 }
{$IFDEF AUTO_X509_CERTS}  { V8.59 }
        function  GetSslX509Certs: TSslX509Certs;                     { V8.57 }
        procedure SetSslX509Certs(const Value : TSslX509Certs);       { V8.57 }

{$ENDIF} // AUTO_X509_CERTS
        function  GetSslCliCertMethod: TSslCliCertMethod;             { V8.57 }
        procedure SetSslCliCertMethod(const Value : TSslCliCertMethod); { V8.57 }
        function  GetCertExpireDays: Integer;                         { V8.57 }
        procedure SetCertExpireDays(const Value : Integer);           { V8.57 }
        function  GetSslCertAutoOrder: Boolean;                       { V8.57 }
        procedure SetSslCertAutoOrder(const Value : Boolean);         { V8.57 }
        function  GetNoSSL: Boolean;                                  { V9.1 }
        procedure SetNoSSL(const Value : Boolean);                    { V9.1 }
    public
        constructor Create(AOwner : TComponent); override;
        destructor  Destroy; override;
        procedure   SetAcceptableHostsList(const SemiColonSeparatedList : String);
        function    ValidateHosts(Stop1stErr: Boolean=True;
                      NoExceptions: Boolean=False): String; virtual; { V8.48 }
        function    RecheckSslCerts(var CertsInfo: String;
                      Stop1stErr: Boolean=True; NoExceptions: Boolean=False): Boolean; { V8.48 }
//    published V8.02 Angus stop them being published in custom component
        property  SslEnable          : Boolean             read  FHttpSslEnable  //  V8.02 Angus, internal renamed V8.50
                                                           write FHttpSslEnable;
        property  SslContext         : TSslContext         read  GetSslContext
                                                           write SetSslContext;
        property  IcsHosts           : TIcsHostCollection  read  GetIcsHosts
                                                           write SetIcsHosts;    { V8.45 }
        property  RootCA             : String              read  GetRootCA
                                                           write SetRootCA;      { V8.45 }
        property  SslCliCertMethod   : TSslCliCertMethod   read  GetSslCliCertMethod
                                                           write SetSslCliCertMethod; { V8.57 }
        property  SslCertAutoOrder   : Boolean             read  GetSslCertAutoOrder
                                                           write SetSslCertAutoOrder; { V8.57 }
        property  CertExpireDays     : Integer             read  GetCertExpireDays
                                                           write SetCertExpireDays;   { V8.57 }
        property NoSSL               : Boolean             read  GetNoSSL
                                                           write SetNoSSL;            { V9.1 }
{$IFDEF AUTO_X509_CERTS}  { V8.59 }
        property  SslX509Certs       : TSslX509Certs       read  GetSslX509Certs
                                                           write SetSslX509Certs;     { V8.57 }
{$ENDIF} // AUTO_X509_CERTS
        property  OnSslVerifyPeer    : TSslVerifyPeerEvent read  FOnSslVerifyPeer
                                                           write FOnSslVerifyPeer;
        property  OnSslSetSessionIDContext : TSslSetSessionIDContext
                                                           read  FOnSslSetSessionIDContext
                                                           write FOnSslSetSessionIDContext;
        property  OnSslSvrNewSession : TSslSvrNewSession   read  FOnSslSvrNewSession
                                                           write FOnSslSvrNewSession;
        property  OnSslSvrGetSession : TSslSvrGetSession   read  FOnSslSvrGetSession
                                                           write FOnSslSvrGetSession;
        property  OnSslHandshakeDone : TSslHandshakeDoneEvent
                                                           read  FOnSslHandshakeDone
                                                           write FOnSslHandshakeDone;
        property  OnSslServerName    : TSslServerNameEvent
                                                           read  FOnSslServerName     // V8.09
                                                           write FOnSslServerName;
        property  OnSslAlpnSelect : TSslAlpnSelect         read  FOnSslAlpnSelect
                                                           write FOnSslAlpnSelect;     { V8.56 }
        property  OnBeforeCtxInit : TBeforeCtxInitEvent    read  FOnBeforeCtxInit
                                                           write FOnBeforeCtxInit;     { V8.66 }
    end;

    TSslHttpServer = class(TCustomSslHttpServer)     //  V8.02 Angus
    published
        property SslEnable;
        property SslContext;
        property IcsHosts;                      { V8.45 }
        property RootCA;                        { V8.45 }
        property SslCliCertMethod;              { V8.57 }
        property SslCertAutoOrder;              { V8.57 }
        property CertExpireDays;                { V8.57 }
{$IFDEF AUTO_X509_CERTS}  { V8.59 }
        property SslX509Certs;                  { V8.57 }
{$ENDIF} // AUTO_X509_CERTS
        property OnSslVerifyPeer;
        property OnSslSetSessionIDContext;
        property OnSslSvrNewSession;
        property OnSslSvrGetSession;
        property OnSslHandshakeDone;
        property OnSslServerName;
        property OnSslAlpnSelect;              { V8.56 }
    end;

{ Retrieve a single value by name out of an cookies string.                 }
{ V9.1 these functions now call Icsxx versions in OverbyteIcsUrl }
function GetCookieValue(
    const CookieString : String;    { Cookie string from header line        }
    const Name         : String;    { Cookie name to look for               }
    var Value          : String)    { Where to put variable value           }
    : Boolean;                      { Found or not found that's the question}
{ Retrieve a single value by name out of an URL encoded data stream.        }
function ExtractURLEncodedValue(
    Msg         : PChar;            { URL Encoded stream                    }
    Name        : String;           { Variable name to look for             }
    var Value   : String;           { Where to put variable value           }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Boolean; overload;
function ExtractURLEncodedValue(
    const Msg   : String;           { URL Encoded stream                     }
    Name        : String;           { Variable name to look for              }
    var Value   : String;           { Where to put variable value            }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Boolean; overload;
function ExtractURLEncodedParamList(
    Msg       : PChar;             { URL Encoded stream                     }
    Params    : TStrings;          { Where to put the list of parameters    }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Integer; overload;           { Number of parameters found             }
function ExtractURLEncodedParamList(
    const Msg : String;            { URL Encoded stream                     }
    Params    : TStrings;          { Where to put the list of parameters    }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Integer; overload;           { Number of parameters found             }

{ V9.1 renamed to avoid conflict with other units, but need to be removed !!! }
function SrvUrlEncode(const S : String; DstCodePage : LongWord = CP_UTF8) : String;
function SrvUrlDecode(const Url   : String;
                   SrcCodePage : LongWord = CP_ACP;
                   DetectUtf8  : Boolean = TRUE) : String;
{$IFDEF COMPILER12_UP}
                   overload;
function SrvUrlDecode(const Url   : RawByteString;
                   SrcCodePage : LongWord = CP_ACP;
                   DetectUtf8  : Boolean = TRUE) : UnicodeString; overload;
{$ENDIF}


function TranslateChar(const Str: String; FromChar, ToChar: Char): String;
function UnixPathToDosPath(const Path: String): String;
function DosPathToUnixPath(const Path: String): String;
function AdjustOSPathDelimiters(const Path: String): String;
function IsDirectory(const Path : String) : Boolean;
function AbsolutisePath(const Path : String) : String;
function MakeCookie(const Name, Value : String;
                    Expires           : TDateTime;
                    const Path        : String;
                    const Domain      : String = '';
                    const Secure      : Boolean = false) : String;   { V8.37 }
function HtmlPageProducer(const FromStream   : TStream;
                          Tags               : array of const;
                          RowDataGetter      : PTableRowDataGetter;
                          UserData           : TObject;
                          DestStream         : TStream
                      {$IFDEF COMPILER12_UP};
                          FromCodepage       : LongWord = CP_ACP;
                          DestCodePage       : LongWord = CP_ACP
                      {$ENDIF}
                          ) : Boolean; overload;
function HtmlPageProducer(const HtmlFileName : String;
                          Tags               : array of const;
                          RowDataGetter      : PTableRowDataGetter;
                          UserData           : TObject;
                          DestStream         : TStream
                      {$IFDEF COMPILER12_UP};
                          FileCodepage       : LongWord = CP_ACP;
                          DestCodePage       : LongWord = CP_ACP
                      {$ENDIF}
                          ) : Boolean; overload;
function HtmlPageProducer(const ResName      : String;
                          const ResType      : PChar;
                          Tags               : array of const;
                          RowDataGetter      : PTableRowDataGetter;
                          UserData           : TObject;
                          DestStream         : TStream
                      {$IFDEF COMPILER12_UP};
                          ResCodepage        : LongWord = CP_ACP;
                          DestCodePage       : LongWord = CP_ACP
                      {$ENDIF}
                          ) : Boolean; overload;
function HtmlPageProducerFromMemory(
    Buf                : PChar;
    BufLen             : Integer;
    TagData            : TStringIndex;
    RowDataGetter      : PTableRowDataGetter;
    UserData           : TObject;
    DestStream         : TStream
{$IFDEF COMPILER12_UP};
    DestCodePage       : LongWord = CP_ACP
{$ENDIF}
    ) : Boolean;
function HtmlPageProducerSetTagPrefix(const Value : String) : String;
//function RemoveHtmlSpecialChars(const S : String) : String;
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
function AuthTypesToString(Types : TAuthenticationTypes) : String;
{$ENDIF}
function StreamWriteStrA(AStrm : TStream; const AStr: String {$IFDEF COMPILER12_UP}; DstCodePage: LongWord = CP_ACP {$ENDIF}): Integer;
function StreamWriteLnA(AStrm : TStream; const AStr: String {$IFDEF COMPILER12_UP}; DstCodePage: LongWord = CP_ACP {$ENDIF}): Integer;
function StreamReadStrA(AStrm : TStream; ByteCnt: Integer {$IFDEF COMPILER12_UP}; SrcCodePage: LongWord = CP_ACP {$ENDIF}): String;
function StreamWriteA(AStream : TStream; Buf: PChar; CharCnt: Integer {$IFDEF COMPILER12_UP}; DstCodePage: LongWord = CP_ACP {$ENDIF}): Integer;
function VarRecToString(V : TVarRec) : String;

const
    HttpConnectionStateName : array [THttpConnectionState] of String =
         ('hcRequest', 'hcHeader', 'hcPostedData', 'hcSendData');

{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    HttpAuthTypeNames : array [TAuthenticationType] of String =
         ('None', 'Basic' {$IFNDEF NO_DIGEST_AUTH}, 'Digest-MD5' {$ENDIF}
          {$IFDEF USE_NTLM_AUTH}, 'NTLM' {$ENDIF}
          {$IFNDEF NO_DIGEST_AUTH}, 'Digest-Sha256' {$ENDIF});      { V8.69 }
{$ENDIF}

implementation

const
    GTagPrefix : String = '#';
    PathDelim = {$IFDEF MSWINDOWS} '\'; {$ELSE} '/'; {$ENDIF}

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StreamWriteStrA(AStrm : TStream; const AStr: String
{$IFDEF COMPILER12_UP};
    DstCodePage: LongWord = CP_ACP
{$ENDIF}
    ): Integer;
{$IFDEF COMPILER12_UP}
var
    S : AnsiString;
begin
    S := UnicodeToAnsi(AStr, DstCodePage);
    Result := AStrm.Write(Pointer(S)^, Length(S));
{$ELSE}
begin
    Result := AStrm.Write(Pointer(AStr)^, Length(AStr));
{$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StreamWriteLnA(AStrm : TStream; const AStr: String
{$IFDEF COMPILER12_UP};
    DstCodePage: LongWord = CP_ACP
{$ENDIF}
    ): Integer;
const
    AsciiLineBreak : array [0..1] of AnsiChar = (#13, #10);
begin
    if Length(AStr) > 0 then
        Result := StreamWriteStrA(AStrm, AStr
                              {$IFDEF COMPILER12_UP},
                                  DstCodePage
                              {$ENDIF}
                                  )
    else
        Result := 0;
    Result := Result + AStrm.Write(AsciiLineBreak, SizeOf(AsciiLineBreak));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StreamReadStrA(AStrm : TStream; ByteCnt: Integer
{$IFDEF COMPILER12_UP};
    SrcCodePage: LongWord = CP_ACP
{$ENDIF}
    ): String;
var
    Len : Integer;
{$IFNDEF COMPILER12_UP}
begin
    if ByteCnt > 0 then begin
        SetLength(Result, ByteCnt);
        Len := AStrm.Read(Pointer(Result)^, ByteCnt);
        if Len <> ByteCnt then
            SetLength(Result, Len);
    end
{$ELSE}
    Str : AnsiString;
begin
    if ByteCnt > 0 then begin
        SetLength(Str, ByteCnt);
        Len := AStrm.Read(Pointer(Str)^, ByteCnt);
        if Len <> ByteCnt then
            SetLength(Str, Len);
        Result := AnsiToUnicode(Str, SrcCodePage); // Cast to Unicode
    end
{$ENDIF}
    else
        Result := '';
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StreamWriteA(AStream : TStream; Buf: PChar; CharCnt: Integer
{$IFDEF COMPILER12_UP};
    DstCodePage: LongWord = CP_ACP
{$ENDIF}
    ): Integer;
begin
{$IFDEF COMPILER12_UP}
    Result := StreamWriteString(AStream, Buf, CharCnt, DstCodePage);
{$ELSE}
    Result := AStream.Write(Buf^, CharCnt);
{$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpServer.Create(AOwner: TComponent);
begin
    inherited Create(AOwner);
    CreateSocket;
{$IFDEF NO_ADV_MT}
//    FWSocketServer.Name := ClassName + '_SrvSocket' + IntToStr(WSocketGCount);      { V8.69 not used }
{$ELSE}
//    FWSocketServer.Name := ClassName + '_SrvSocket' + IntToStr(SafeWSocketGCount);
{$ENDIF}
    FClientClass    := THttpConnection;
    FOptions        := [];
    FAddr           := ICS_ANY_HOST_V4;
    FPort           := '80';
    FSocketFamily   := DefaultSocketFamily;        { V8.00 }
    FMaxClients     := 0;                {DAVID}
    FListenBacklog  := 15; {Bjørnar} { V8.57 was 5 }
    FDefaultDoc     := 'index.html';
    FDocDir         := 'c:\wwwroot';
    FTemplateDir    := 'c:\wwwroot\templates';
    FWellKnownPath  := '';                        { V8.49 blank means ignore }
    FLingerOnOff    := wsLingerNoSet;
    FLingerTimeout  := 0;
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    FAuthRealm                    := 'ics';
  {$IFNDEF NO_DIGEST_AUTH}
    FAuthDigestNonceLifeTimeMin   := 1;
  {$ENDIF}
    FAuthTypes                    := [];
{$ENDIF}
    FKeepAliveTimeSec     := 10;
    FKeepAliveTimeXferSec := 300;  { V8.05 }
    FMaxRequestsKeepAlive := 100;
    FHeartBeat            := TIcsTimer.Create(FWSocketServer);
    FHeartBeat.OnTimer    := HeartBeatOnTimer;
    FHeartBeat.Interval   := 5000; { It's slow, just used for timeout detection }
    FHeartBeat.Enabled    := TRUE;
    SizeCompressMin       := CompressMinSize;  { V7.20 only compress responses within a size range }
    SizeCompressMax       := CompressMaxSize;
    FMaxBlkSize           := MinSndBlkSize;    { V7.40 }
{$IFDEF BUILTIN_THROTTLE}
    FBandwidthLimit       := 0;       { angus V7.34 no bandwidth limit, yet, bytes per second }
    FBandwidthSampling    := 1000;    { angus V7.34 Msec sampling interval, less is not possible }
{$ENDIF}
    FServerHeader         := DefServerHeader;  { V8.08 }
    FExclusiveAddr        := True;    { 8.37 make our sockets exclusive  }
    FAttachmentTypes      := '.zip;.rar;.7z;.cab;.lzh;.gz;.iso;.exe;.dll;.pdf;'  { V9.5 attachment file extensions }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor THttpServer.Destroy;
begin
{ V8.71 Ensure inherited destroy called }
    try
        if Assigned(FWSocketServer) then
            FreeAndNil(FWSocketServer);
    finally
        inherited Destroy;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Called by destructor when child component is created or destroyed.        }
procedure THttpServer.Notification(
    AComponent : TComponent;
    Operation  : TOperation);
begin
    inherited Notification(AComponent, Operation);
    if Operation = opRemove then begin
        if AComponent = FWSocketServer then
            FWSocketServer := nil
        else if AComponent = FMimeTypesList then  { 7.47 }
            FMimeTypesList := nil;                { 7.47 }
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.CreateSocket;
begin
    FWSocketServer := TWSocketServer.Create(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpServer.CreateServerSecret: Int64;
begin
    { This is weak, however better than nothing }
    Result := Int64(IcsRandomInt(MaxInt)) or IcsRandomInt(MaxInt) shl 32;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Start the server. That is make FWSocketServer listening to the port.      }
{ V8.49 optionally return list of errors instead of exception on fail }
function THttpServer.Start(ReturnErrs: Boolean = false): String;
const
    BusyText = 'Server overloaded. Retry later.' + IcsCRLF;
begin
    Result := '';
    { Create a new FWSocketServer if needed }
    if not Assigned(FWSocketServer) then
        CreateSocket;
    { If already listening, then do nothing }
    if FWSocketServer.State = wsListening then
        Exit;
    { Pass all parameters to FWSocketServer and make it listen }
    FWSocketServer.ClientClass        := FClientClass;
    FWSocketServer.OnClientCreate     := WSocketServerClientCreate;
    FWSocketServer.OnClientConnect    := WSocketServerClientConnect;
    FWSocketServer.OnClientDisconnect := WSocketServerClientDisconnect;
    FWSocketServer.OnSessionClosed    := WSocketServerSessionClosed;
    FWSocketServer.OnChangeState      := WSocketServerChangeState;
    FWSocketServer.OnClientAcceptFilter := WSocketServerCliAcceptFilter;   { V9.5 }
    FWSocketServer.OnDebugDisplay     := TriggerDisplay;        { V9.6 }
    FWSocketServer.WSDebugOptions     := FWSDebugOptions;       { V9.6 }
    FWSocketServer.Banner             := '';
    FWSocketServer.Proto              := 'tcp';
    FWSocketServer.Port               := FPort;
    FWSocketServer.SocketFamily       := FSocketFamily;
    FWSocketServer.Addr               := FAddr;
    FWSocketServer.MaxClients         := FMaxClients;    {DAVID}
    FWSocketServer.ListenBacklog      := FListenBacklog; {Bjørnar}
    FWSocketServer.BannerTooBusy      :=
        'HTTP/1.0 503 Service Unavailable' + IcsCRLF +
        'Content-type: text/plain' + IcsCRLF +
        'Content-length: ' + IntToStr(Length(BusyText)) + IcsCRLF + IcsCRLF +
        BusyText;
{$IFDEF BUILTIN_THROTTLE}
    FWSocketServer.BandwidthLimit     := FBandwidthLimit;     { angus V7.34 slow down control connection }
    FWSocketServer.BandwidthSampling  := FBandwidthSampling;  { angus V7.34 }
{$ENDIF}
{$IFNDEF NO_DIGEST_AUTH}
    FAuthDigestServerSecret           := CreateServerSecret;
{$ENDIF}
{$IFDEF USE_SSL}
 { V8.45 if using IcsHosts, set default directories }
    if FWSocketServer is TSslWSocketServer then begin
      if TSslWSocketServer(FWSocketServer).IcsHosts.Count > 0 then begin
          with TSslWSocketServer(FWSocketServer).IcsHosts [0] do begin
              Self.FDocDir := WebDocDir;
              Self.FTemplateDir := WebTemplDir;
              Self.FDefaultDoc := WebDefDoc;
              Self.FWellKnownPath := WellKnownPath;   { V8.49 }
          end;
      end;
    end;
{$ENDIF}
    FWSocketServer.ExclusiveAddr      := FExclusiveAddr;     { V8.37 }
    FWSocketServer.SocketErrs         := FSocketErrs;        { V8.37 }
    if ReturnErrs then
        Result := FWSocketServer.MultiListenEx     { V8.49 no exception, opens as many as possible }
    else
        FWSocketServer.MultiListen;       { V8.00 listen on multiple sockets, if more than one configured }
{$IFNDEF NO_DEBUG_LOG}
    if CheckLogOptions(loProtSpecInfo) then                           { V1.38 }
        DebugLog(loProtSpecInfo, Name + ' started, errors: ' + Result);
{$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.Stop;
begin
    if not Assigned(FWSocketServer) then
        Exit;
    FWSocketServer.MultiClose;     { V8.60 close all hosts }
    { Disconnect all clients }
    FWSocketServer.DisconnectAll;
{$IFNDEF NO_DEBUG_LOG}
    if CheckLogOptions(loProtSpecInfo) then
        DebugLog(loProtSpecInfo, Name + ' stopped');                  { V1.38 }
{$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerDisplay(Sender: TObject; const Msg: String);   { V9.6 }
begin
    if Assigned(OnDisplay) then
        OnDisplay(Sender, Msg);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetPortValue(const newValue : String);
begin
    if newValue = FPort then
        Exit;
    FPort := newValue;
    { If server is already listening, then stop it and restart it with      }
    { new port. Do not disconnect already connected clients.                }
    if Assigned(FWSocketServer) and
       (FWSocketServer.State = wsListening) then begin
        FWSocketServer.MultiClose;     { V8.60 close all hosts }
        Start;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetAddr(const newValue : String);
begin
    if newValue = FAddr then
        Exit;
    FAddr := newValue;
    { If server is already listening, then stop it and restart it with      }
    { new Addr. Do not disconnect already connected clients.                }
    if Assigned(FWSocketServer) and
       (FWSocketServer.State = wsListening) then begin
        FWSocketServer.MultiClose;     { V8.60 close all hosts }
        Start;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetDocDir(const Value: String);
begin
    if (Value > '') and (Value[Length(Value)] = PathDelim) then
        FDocDir := IcsAbsolutisePath(Copy(Value, 1, Length(Value) - 1))
    else
        FDocDir := IcsAbsolutisePath(Value);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetWellKnownPath(const Value: String);    { V8.49 }
begin
    if (Value > '') and (Value[Length(Value)] = PathDelim) then
        FWellKnownPath := IcsAbsolutisePath(Copy(Value, 1, Length(Value) - 1))
    else
        FWellKnownPath := IcsAbsolutisePath(Value);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetMimeTypesList(const Value: TMimeTypesList);{ V7.47 }
begin
    if FMimeTypesList <> Value then begin
        if Assigned(FMimeTypesList) then
            FMimeTypesList.RemoveFreeNotification(Self);
        FMimeTypesList := Value;
        if Assigned(FMimeTypesList) then
            FMimeTypesList.FreeNotification(Self);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Get function for ClientCount property. Just return value from             }
{ FWSocketServer.                                                           }
function THttpServer.GetClientCount;
begin
    if not Assigned(FWSocketServer) then
        Result := 0
    else
        Result := FWSocketServer.ClientCount;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Get function for Client[] property. Just return value from                }
{ FWSocketServer.                                                           }
function THttpServer.GetClient(nIndex : Integer) : THttpConnection;
begin
    if not Assigned(FWSocketServer) then
        Result := nil
    else
        Result := THttpConnection(FWSocketServer.Client[nIndex]);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Check is an object is one of our clients. Just return value from          }
{ FWSocketServer.                                                           }
function THttpServer.IsClient(SomeThing : TObject) : Boolean;
begin
    if not Assigned(FWSocketServer) then
        Result := FALSE
    else
        Result := FWSocketServer.IsClient(SomeThing);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Min(A, B : THttpRangeInt) : THttpRangeInt;
begin
    if A < B then
        Result := A
    else
        Result := B;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SetSndBlkSize(const Value: Integer);
begin
    if Value <> FSndBlkSize then begin
        if Assigned(FDocBuf) then
            ReallocMem(FDocBuf, Value);
        FSndBlkSize := Value;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetKeepAliveTimeSec(const Value: Cardinal);
begin
    if Value > High(Cardinal) div 1000 then
        FKeepAliveTimeSec := High(Cardinal) div 1000
    else
        FKeepAliveTimeSec := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetKeepAliveTimeXferSec(const Value: Cardinal);  { V8.05 }
begin
    if Value > High(Cardinal) div 1000 then
        FKeepAliveTimeXferSec := High(Cardinal) div 1000
    else
        FKeepAliveTimeXferSec := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is triggered when state of server socket has changed.  }
{ We use it to trigger our OnServerStarted event.                           }
procedure THttpServer.WSocketServerChangeState(
    Sender : TObject;
    OldState, NewState : TSocketState);
begin
    if newState = wsListening then
        TriggerServerStarted;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.WSocketServerSessionClosed(
    Sender : TObject;
    Error  : Word);
begin
    TriggerServerStopped;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetOnBgException(const Value: TIcsBgExceptionEvent); { V7.31 }
begin
    if Assigned(FWSocketServer) then
        FWSocketServer.OnBgException := Value;
    inherited;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ A new client component has been created                                   }
procedure THttpServer.WSocketServerClientCreate(
    Sender : TObject;
    Client : TWSocketClient);
begin
    Client.LingerOnOff                         := FLingerOnOff;
    Client.LingerTimeout                       := FLingerTimeout;
    (Client as THttpConnection).Options        := FOptions;
    THttpConnection(Client).KeepAliveTimeSec     := FKeepAliveTimeSec;
    THttpConnection(Client).KeepAliveTimeXferSec := FKeepAliveTimeXferSec;  { V8.05 }
    Client.CreateCounter;
    Client.Counter.SetConnected;               { V7.23 }
    {$IFDEF USE_SSL}
    if not (Client.Owner is TSslWSocketServer) then
        (Client as THttpConnection).SslEnable := FALSE;
    {$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ A new client just connected. Setup things to handle his requests.         }
{ HTTP header is line oriented so we turn line mode on. We use LF as end of }
{ line character altough HTTP uses CR/LF pair as end of line, because many  }
{ Unix client do not respect standards and use single LF...                 }
{ HTTP is not interactive, so we turn line editing to false (faster).       }
procedure THttpServer.WSocketServerClientConnect(
    Sender : TObject;
    Client : TWSocketClient;
    Error  : Word);
begin
    THttpConnection(Client).FServer           := Self;
    THttpConnection(Client).LineMode          := TRUE;
    THttpConnection(Client).LineEdit          := FALSE;
    THttpConnection(Client).LineEnd           := IcsLF;  { V9.5 AnsiChar(#10);  }
    THttpConnection(Client).DocDir            := Self.DocDir;
    THttpConnection(Client).TemplateDir       := Self.TemplateDir;
    THttpConnection(Client).DefaultDoc        := Self.DefaultDoc;
    THttpConnection(Client).OnGetDocument     := TriggerGetDocument;
    THttpConnection(Client).OnHeadDocument    := TriggerHeadDocument;
    THttpConnection(Client).OnPostDocument    := TriggerPostDocument;
    THttpConnection(Client).OnOptionsDocument := TriggerOptionsDocument;  { V8.08 }
    THttpConnection(Client).OnPutDocument     := TriggerPutDocument;      { V8.08 }
    THttpConnection(Client).OnDeleteDocument  := TriggerDeleteDocument;   { V8.08 }
    THttpConnection(Client).OnTraceDocument   := TriggerTraceDocument;    { V8.08 }
    THttpConnection(Client).OnPatchDocument   := TriggerPatchDocument;    { V8.08 }
    THttpConnection(Client).OnConnectDocument := TriggerConnectDocument;  { V8.08 }
    THttpConnection(Client).OnPostedData      := TriggerPostedData;
    THttpConnection(Client).OnHttpRequestDone := TriggerHttpRequestDone;
    THttpConnection(Client).OnBeforeProcessRequest := TriggerBeforeProcessRequest; {DAVID}
    THttpConnection(Client).OnFilterDirEntry  := TriggerFilterDirEntry;
    THttpConnection(Client).MaxRequestsKeepAlive := Self.MaxRequestsKeepAlive;
    THttpConnection(Client).OnBeforeAnswer    := TriggerBeforeAnswer;  { V7.19 }
    THttpConnection(Client).OnAfterAnswer     := TriggerAfterAnswer;   { V7.19 }
    THttpConnection(Client).OnContentEncode   := TriggerContentEncode; { V7.20 }
    THttpConnection(Client).OnContEncoded     := TriggerContEncoded;   { V7.20 }
    THttpConnection(Client).OnUnknownRequestMethod  := TriggerUnknownRequestMethod; { V2.29 }
    THttpConnection(Client).OnMimeContentType := TriggerMimeContentType; { V7.41 }
    THttpConnection(Client).WellKnownPath     := Self.WellKnownPath;    { V8.49 }
    THttpConnection(Client).onWellKnownDir    := TriggerWellKnownDir;   { V8.49 }
    THttpConnection(Client).OnRespHdr         := TriggerRespHdr;        { V8.69 }
    THttpConnection(Client).OnCustomErrorBody := TriggerCustomError;    { V9.5 }
    THttpConnection(Client).OnWebDAVConn      := TriggerWebDAVEvent;    { V9.6 }
    THttpConnection(Client).OnQueryDocument   := TriggerQueryDocument;  { V9.8 }
    TriggerClientConnect(Client, Error);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ A client is about to disconnect.                                          }
procedure THttpServer.WSocketServerClientDisconnect(
    Sender : TObject;
    Client : TWSocketClient;
    Error  : Word);
begin
    TriggerClientDisconnect(Client, Error);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.5 A new client is about to be accepted.                                          }
procedure THttpServer.WSocketServerCliAcceptFilter(Sender: TObject; Client: TWSocketClient; var SessIpInfo: TIcsSessIpInfo;
                                                                                                    var Allowed: Boolean); { V9.5 }
begin
    TriggerCliAcceptFilter(Client, SessIpInfo, Allowed);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerServerStarted;
begin
    if Assigned(FOnServerStarted) then
        FOnServerStarted(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerServerStopped;
begin
    if Assigned(FOnServerStopped) then
        FOnServerStopped(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerClientConnect(
    Client : TObject;
    Error  : Word);
begin
    if Assigned(FOnClientConnect) then
        FOnClientConnect(Self, Client, Error);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerCliAcceptFilter(Client: TWSocketClient; var SessIpInfo: TIcsSessIpInfo; var Allowed: Boolean); { V9.5 }
begin
    if Assigned(FOnHttpAcceptFilter) then
        FOnHttpAcceptFilter(Self, Client, SessIpInfo, Allowed);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerClientDisconnect(
    Client : TObject;
    Error  : Word);
begin
    if Assigned(FOnClientDisconnect) then
        FOnClientDisconnect(Self, Client, Error);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerGetDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);
begin
    if Assigned(FOnGetDocument) then
        FOnGetDocument(Self, Sender, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerHeadDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);
begin
    if Assigned(FOnHeadDocument) then
        FOnHeadDocument(Self, Sender, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerPostedData(Sender     : TObject;
                                        Error      : WORD);
begin
    if Assigned(FOnPostedData) then
        FOnPostedData(Self, Sender, Error);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerPostDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);
begin
    if Assigned(FOnPostDocument) then
        FOnPostDocument(Self, Sender, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerOptionsDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnOptionsDocument) then
        FOnOptionsDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerPutDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);     { V8.08 }
begin
    if Assigned(FOnPutDocument) then
        FOnPutDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerDeleteDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnDeleteDocument) then
        FOnDeleteDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerTraceDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnTraceDocument) then
        FOnTraceDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerPatchDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnPatchDocument) then
        FOnPatchDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerConnectDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);    { V8.08 }
begin
    if Assigned(FOnConnectDocument) then
        FOnConnectDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerQueryDocument(
     Sender     : TObject;
     var Flags  : THttpGetFlag);     { V9.8 }
begin
    if Assigned(FOnQueryDocument) then
        FOnQueryDocument(Self, Sender, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerHTTPRequestDone(
    Client : TObject);
begin
    if Assigned(FOnHttpRequestDone) then
        FOnHttpRequestDone(Self, Client);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerBeforeProcessRequest(  {DAVID}
    Client : TObject);
begin
    if Assigned(FOnBeforeProcessRequest) then
        FOnBeforeProcessRequest(Self, Client);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerFilterDirEntry(
    Sender   : TObject;
    Client   : TObject;
    DirEntry : THttpDirEntry);
begin
    if Assigned(FOnFilterDirEntry) then
        FOnFilterDirEntry(Self, Client, DirEntry);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerBeforeAnswer
    (Client : TObject);  { V7.19 }
begin
    if Assigned(FOnBeforeAnswer) then
        FOnBeforeAnswer(Self, Client);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerAfterAnswer
    (Client : TObject);   { V7.19 }
begin
    if Assigned(FOnAfterAnswer) then
        FOnAfterAnswer(Self, Client);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerContentEncode
    (Client : TObject;
     out ContentEncoding: string;
     var Handled: Boolean);  { V7.20 }
begin
    if Assigned(FOnHttpContentEncode) then
        FOnHttpContentEncode(Self, Client, ContentEncoding, Handled);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerContEncoded
    (Client : TObject);  { V7.20 }
begin
    if Assigned(FOnHttpContEncoded) then
        FOnHttpContEncoded(Self, Client);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerUnknownRequestMethod(
    Client      : TObject;
    var Handled : Boolean);                                         { V7.29 }
begin
    if Assigned(FOnHttpUnknownReqMethod) then
        FOnHttpUnknownReqMethod(Self, Client, Handled);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerMimeContentType
    (Client : TObject;
     const FileName: string;
     var ContentType: string);                                     { V7.41 }
begin
    if Assigned(FOnHttpMimeContentType) then
        FOnHttpMimeContentType(Self, Client, FileName, ContentType);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerWellKnownDir
    (Client : TObject;
     const Path      : string;
     var BodyStr     : string);                                     { V8.49 }
begin
    if Assigned(FonWellKnownDir) then
        FonWellKnownDir(Self, Client, Path, BodyStr);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerRespHdr
    (Client : TObject;
     const Header    : string);                                     { V8.69 }
begin
    if Assigned(FonHttpRespHdr) then
        FOnHttpRespHdr(Self, Client, Header);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerWebDAVEvent(Client: TObject; HttpMethod: THttpMethod; var Flags: THttpGetFlag); { 9.6 }
begin
    if Assigned(FOnWebDAVDocument) then
        FOnWebDAVDocument(Self, Client, HttpMethod, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.TriggerCustomError(Client: TObject; ErrNr: Integer; const Info: String; var Body: String);    { V9.5 }
begin
    if Assigned(FonHttpCustomError) then
        FOnHttpCustomError(Self, Client, ErrNr, Info, Body);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.HeartBeatOnTimer(Sender: TObject);
var
    CurTicks : Int64;  { V8.71 }
    I        : Integer;
    Cli      : THttpConnection;
    Timeout  : Integer; { V8.71 }
begin
    if not FHeartBeatBusy then  { Avoid reentrance }
    try
        FHeartBeatBusy := TRUE;
        CurTicks := IcsGetTickCount64;
        for I := ClientCount - 1 downto 0 do begin
            Cli := Client[I];
            if (Cli.FState = hcRequest) then  { V8.05 }
                Timeout := Cli.KeepAliveTimeSec
            else
                Timeout := Cli.KeepAliveTimeXferSec;
           if (Timeout > 0) and  (IcsDiffSecs64(Cli.Counter.LastAliveTick, CurTicks) > Timeout) then  { V8.71 }
                FWSocketServer.Disconnect(Cli);
        end;
    finally
        FHeartBeatBusy := FALSE;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpServer.GetMultiListenSockets: TWSocketMultiListenCollection;    { V8.00 }
begin
    if Assigned(FWSocketServer) then
        Result := FWSocketServer.MultiListenSockets
    else
        Result := nil;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpServer.SetMultiListenSockets(                                 { V8.00 }
  const Value: TWSocketMultiListenCollection);
begin
    if Assigned(FWSocketServer) then
        FWSocketServer.MultiListenSockets := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpServer.ListenAllOK: Boolean;                              { V8.48 }
begin
    if Assigned(FWSocketServer) then
        Result := FWSocketServer.ListenAllOK
    else
        Result := False;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpServer.ListenAny: Boolean;                                 { V9.1 }
begin
    if Assigned(FWSocketServer) then
        Result := FWSocketServer.ListenAny
    else
        Result := False;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpServer.ListenStates: String;                              { V8.48 }
begin
    if Assigned(FWSocketServer) then
        Result := FWSocketServer.ListenStates
    else
        Result := '';
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpConnection.Create(AOwner : TComponent);
begin
    inherited Create(AOwner);
    LineMode              := TRUE;
    LineEdit              := FALSE;
    LineEnd               := AnsiChar(#10);
    FRequestHeader        := TStringList.Create;
    FRequestHeader.NameValueSeparator := ':'; { V7.29 }
    FState                := hcRequest;
    OnDataAvailable       := ConnectionDataAvailable;
    FRequestRangeValues   := THttpRangeList.Create; {ANDREAS}
    ComponentOptions      := [wsoNoReceiveLoop];    { FP 15/05/2005 }
    FSndBlkSize           := MinSndBlkSize;  { V7.40 was  BufSize; // default value = 1460  }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor THttpConnection.Destroy;
begin
{ V8.71 Ensure inherited destroy called }
    try
        if Assigned(FRequestHeader) then
            FreeAndNil(FRequestHeader);
        if Assigned(FDocStream) then
            FreeAndNil(FDocStream);
        if Assigned(FDocBuf) then begin
            FreeMem(FDocBuf, FSndBlkSize);
            FDocBuf := nil;
        end;
        if Assigned(FRequestRangeValues) then
            FreeAndNil(FRequestRangeValues);
{$IFDEF USE_NTLM_AUTH}
        FreeAndNil(FAuthNtlmSession);
{$ENDIF}
    finally
        inherited Destroy;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.DebugDisplay(const Msg: String);        { V9.8 for client logging }
begin
    FServer.TriggerDisplay(Self, Msg);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF ICS_NewMessaging}   { V10 }
procedure THttpConnection.IcsDispatchMessage(const Value: TIcsSocketMsgRec);
var
    HttpConn: THttpConnection;
begin
    if Assigned(Value.Instance) and (Value.Instance is THttpConnection) then begin
        HttpConn := THttpConnection(Value.Instance);
        try
            with Value do begin
                if Msg = WM_ICS_HTTPSRV_DONE then begin
                    if (wsdlogMsgs in FServer.FWSocketServer.WSDebugOptions) then begin
                        DebugDisplay('THttpCli:DispatchMessage: ' + IcsGetNewMsgLit(Value.Msg));
                    end;
                    HttpConn.WMHttpDone(Value);
                end
                else
                    FServer.FWSocketServer.IcsDispatchMessage(Value);
            end;
        except
            on E: Exception do
                HttpConn.HandleBackGroundException(E, 'THttpConnection:DispatchMessage: ' + IntToStr(Value.Msg));
        end;
    end
    else
        FServer.FWSocketServer.IcsDispatchMessage(Value);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.WMHttpDone(const Value: TIcsSocketMsgRec);
begin
     TriggerHttpRequestDone;
end;
{$ENDIF ICS_NewMessaging}   { V10 }


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF ICS_NewMessaging}  { V10 }
function THttpConnection.MsgHandlersCount : Integer;
begin
    Result := 1 + inherited MsgHandlersCount;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.AllocateMsgHandlers;
begin
    inherited AllocateMsgHandlers;
    FMsg_WM_HTTP_DONE := FWndHandler.AllocateMsgHandler(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.FreeMsgHandlers;
begin
    if Assigned(FWndHandler) then
        FWndHandler.UnregisterMessage(FMsg_WM_HTTP_DONE);
    inherited FreeMsgHandlers;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.WndProc(var MsgRec: TMessage);
begin
    with MsgRec do begin
        { We *MUST* handle all exception to avoid application shutdown }
            if Msg = FMsg_WM_HTTP_DONE then begin
                try
                    WMHttpDone(MsgRec)
                except
                    on E:Exception do
                        HandleBackGroundException(E);
                end;
            end
            else
                inherited WndProc(MsgRec);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.WMHttpDone(var msg: TMessage);
begin
    { Bjornar, If we are done with a request at the same time as the client }
    { posts data to us we will lose the posted data. If the headerlines of  }
    { a get request is split into 2 different packets and we are done with  }
    { a request between those packets, we will lose the initial request url }
    { and the already received headerlines. This comment makes sure sending }
    { data and receiving data is independent of each other                  }
    { FState := hcRequest;                                          Bjornar }
     TriggerHttpRequestDone;
end;
{$ENDIF N ICS_NewMessaging} { V10 }


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
{$IFNDEF NO_DIGEST_AUTH}
function THttpConnection.AuthDigestCheckPassword(const Password: String): Boolean;
var
    SessKey      : THashHex;
    MyResponse   : THashHex;
    HEntity      : THashHex;
    NonceLifeTime: Cardinal;
begin
{$IFNDEF USE_SSL}  { old version with MD5 only }
    AuthDigestCalcHA1(FAuthDigestAlg, AnsiString(FAuthUserName),
                      AnsiString(FAuthDigestRealm), AnsiString(Password),
                      AnsiString(FAuthDigestNonce), AnsiString(FAuthDigestCnonce),
                      SessKey);

    AuthDigestGetBodyHash(FAuthDigestBody, HEntity);
    AuthDigestCalcResponse(SessKey, AnsiString(FAuthDigestNonce),
                           AnsiString(FAuthDigestNc),
                           AnsiString(FAuthDigestCnonce),
                           AnsiString(FAuthDigestQop), AnsiString(FMethod),
                           AnsiString(FAuthDigestUri), HEntity, MyResponse);
{$ENDIF}

{$IFDEF USE_SSL}   { new version using OpenSSL functions }
    AuthDigestCalcHA1Ex(FindAlgoDigest(FAuthDigestAlg),
                      FAuthDigestAlg, AnsiString(FAuthUserName),
                      AnsiString(FAuthDigestRealm), AnsiString(Password),
                      AnsiString(FAuthDigestNonce), AnsiString(FAuthDigestCnonce),
                      SessKey);

    AuthDigestGetBodyHashEx(FindAlgoDigest(FAuthDigestAlg), FAuthDigestBody, HEntity);
    AuthDigestCalcResponseEx(FindAlgoDigest(FAuthDigestAlg),
                           SessKey, AnsiString(FAuthDigestNonce),
                           AnsiString(FAuthDigestNc),
                           AnsiString(FAuthDigestCnonce),
                           AnsiString(FAuthDigestQop), AnsiString(FMethod),
                           AnsiString(FAuthDigestUri), HEntity, MyResponse);
{$ENDIF}

    Result := IcsCompareText(AnsiString(FAuthDigestResponse), MyResponse) = 0;

    if Result then begin
        { Check whether we have to force a new nonce in which case we set    }
        { FAuthDigestStale to TRUE which avoids popping up a login dialog at }
        { the client side. }
        if FAuthDigestOneTimeFlag then
            NonceLifeTime := 2
            { Grant the user two minutes to be able to enter login manually  }
            { if FAuthDigestNonceLifeTimeMin equals zero = one-timer nonce. }
        else
            NonceLifeTime := FAuthDigestNonceLifeTimeMin;

        if (((FAuthDigestNonceTimeStamp * 1440) + NonceLifeTime) / 1440) < Now then
        begin
            { The nonce is stale, respond a 401 }
            FAuthDigestStale := TRUE;
            Result := FALSE;
        end;
     end;
end;
{$ENDIF}

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.AuthBasicCheckPassword(const Password: String): Boolean;
begin
    Result := (FAuthPassword = Password);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.AuthBasicGetParams: Boolean;
var
    Buf : String;
    I   : Integer;
begin
    { Must begin with 'basic ' }
    {Result := (LowerCase(Copy(FRequestAuth, 1, 6)) = 'basic ');
    if not Result then
        Exit;}

    Buf := String(IcsBase64Decode(Copy(FRequestAuth, 7, Length(FRequestAuth))));  { V9.4 }
    if Buf = '' then
        Result := FALSE
    else begin
        I := Pos(':', Buf);
        if I > 0 then begin
            FAuthUserName := Copy(Buf, 1, I - 1);
            FAuthPassword := Copy(Buf, I + 1, Length(Buf));
        end
        else begin
            FAuthUserName := Buf;
            FAuthPassword := '';
        end;
        Result := TRUE;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.AuthGetMethod: TAuthenticationType;
begin
    if Length(FRequestAuth) < 5 then
        Result := atNone
{$IFDEF USE_NTLM_AUTH}
    else if LowerCase(Copy(FRequestAuth, 1, 5)) = 'ntlm ' then
        Result := atNtlm
{$ENDIF}
{$IFNDEF NO_DIGEST_AUTH}
    else if LowerCase(Copy(FRequestAuth, 1, 7)) = 'digest ' then begin
        if (Pos('=sha-256', LowerCase(FRequestAuth)) > 0) then        { V8.69 algorithm=SHA-256 }
            Result := atDigestSha2
        else
            Result := atDigest      { algorithm=MD5, default }
    end
{$ENDIF}
    else if LowerCase(Copy(FRequestAuth, 1, 6)) = 'basic ' then
        Result := atBasic
    else
        Result := atNone;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF NO_DIGEST_AUTH}
function THttpConnection.AuthDigestGetParams: Boolean;
begin
    Result := AuthDigestGetRequest(FRequestAuth, FAuthDigestNonceTimeStamp,
                   FAuthUserName, FAuthDigestRealm, FAuthDigestQop,
                   FAuthDigestAlg, FAuthDigestNonce, FAuthDigestNc,
                   FAuthDigestUri, FAuthDigestCnonce, FAuthDigestOpaque,
                   FAuthDigestResponse);
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Set FAuthenticated accordingly to the authenticated state of the user.    }
procedure THttpConnection.AuthCheckAuthenticated;
var
    PasswdBuf : String;
begin
    FAuthTypes                    := FServer.AuthTypes;
    FAuthRealm                    := FServer.FAuthRealm;
{$IFNDEF NO_DIGEST_AUTH}
    FAuthDigestNonceLifeTimeMin   := FServer.FAuthDigestNonceLifeTimeMin;
{$ENDIF}
    TriggerAuthGetType;
    if (FAuthTypes = []) or (FAuthTypes = [atNone]) then begin
        FAuthenticated := TRUE;
        Exit;
    end;
    FAuthenticated := FALSE;
    FAuthType      := AuthGetMethod;

    if (AuthType = atNone) or (not(AuthType in FAuthTypes)) then begin
        FAuthInit := TRUE;
        Exit;
    end;
    FAuthInit  := FALSE;
    FAuthTypes := [AuthType];
    if AuthType = atBasic then begin
        FAuthenticated := AuthBasicGetParams;
        if FAuthenticated then begin
            PasswdBuf := #0;
            TriggerAuthGetPassword(PasswdBuf);
            FAuthenticated := AuthBasicCheckPassword(PasswdBuf);
            TriggerAuthResult(FAuthenticated);
        end;
    end
{$IFNDEF NO_DIGEST_AUTH}
    else if AuthType in [atDigest, atDigestSha2] then begin     { V8.69 added Sha2 }
        FAuthDigestBody := '';
        FAuthenticated := AuthDigestGetParams;
        if FAuthenticated then begin
            PasswdBuf := #0;
            TriggerAuthGetPassword(PasswdBuf);
            FAuthenticated := AuthDigestCheckPassword(PasswdBuf);
            { Even if the login was correct FAuthenticated may be FALSE here. }
            { This happens when the nonce is stale and a new nonce is forced. }
            { Note that this is a fix and change, previous versions did not   }
            { enter this IF-Block when the nonce was stale.                   }
            { Don't trigger AuthResult when the nonce is stale.               }
            if not FAuthDigestStale then
                TriggerAuthResult(FAuthenticated);
        end;
        FAuthDigestOneTimeFlag := FALSE;
    end
{$ENDIF}
{$IFDEF USE_NTLM_AUTH}
    else if AuthType = atNtlm then begin
        if not Assigned(FAuthNtlmSession) then begin
           FAuthNtlmSession := TNtlmAuthSession.Create (cuInBound) ;
           FAuthNtlmSession.OnBeforeValidate := AuthNtlmSessionBeforeValidate;
        end;
        FAuthenticated := FAuthNtlmSession.ProcessNtlmMsg(Copy(FRequestAuth, 6, Length(FRequestAuth)));
        if (FAuthNtlmSession.State in [lsDoneOk, lsDoneErr]) then begin
            TriggerAuthResult(FAuthenticated);
            if FAuthNtlmSession.State = lsDoneErr then
                FAuthNtlmSession.CleanUpLogonSession;
        end;
    end
{$ENDIF}
    else
        FAuthenticated := FALSE; { Should never occur ! }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF USE_NTLM_AUTH}
procedure THttpConnection.AuthNtlmSessionBeforeValidate(Sender: TObject; var Allow: Boolean);
begin
    if Assigned(FServer.FOnAuthNtlmBeforeValidate) then
        FServer.FOnAuthNtlmBeforeValidate(FServer, Self, Allow);
end;
{$ENDIF}

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerAuthGetPassword(
    var PasswdBuf : String);
begin
    if Assigned(FServer.FOnAuthGetPassword) then
        FServer.FOnAuthGetPassword(FServer, Self, PasswdBuf);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerAuthResult(Authenticated : Boolean);
begin
    if Assigned(FServer.FOnAuthResult) then
        FServer.FOnAuthResult(FServer, Self, Authenticated);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerAuthGetType;
begin
    if Assigned(FServer.FOnAuthGetType) then
        FServer.FOnAuthGetType(FServer, Self);
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.PrepareGraceFullShutDown;
begin
    FKeepAliveTimeSec := 5;
    FShutDownFlag     := TRUE;
    OnDataSent        := ConnectionDataSent;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This procedure is called each time data is available from a client.       }
{ We use FState variable to keep track of the where we are in the http      }
{ protocol: request command, header line or posted data.                    }
procedure THttpConnection.ConnectionDataAvailable(Sender: TObject; Error : Word);
var
    Len     : Integer;
    I, J    : Integer;
begin
    { If we are in data state, then the application has to receive data }
    if FState = hcPostedData then begin
        if FAcceptPostedData and Assigned(FOnPostedData) then
            FOnPostedData(Self, Error)
        else begin
            { Nobody wants data, we receive it and throw it away.   }
            { We call our overridden method Receive which will care }
            { about correct length and switch back to line mode.    }
            if Length(FPostRcvBuf) < MAX_BUFSIZE then      { V9.6 TBytes }
                SetLength(FPostRcvBuf, MAX_BUFSIZE);

         { V9.6 keep uploaded data for WebDAV requests, got it all process request }
         { !! pending, work with PUT for large files, this version only works with small uploads like DebDAV XML }
            FPostRcvLen := Receive(@FPostRcvBuf[0], MAX_BUFSIZE);  // local version that uses FPostCounter
            if FState = hcRequest then begin
                FRequestXML := IcsTBytesToString(FPostRcvBuf, FPostRcvLen, CP_UTF8);
                ProcessRequest;
            end;
        end;
        Exit;
    end;

    { We use line mode. We will receive complete lines using LineMode, turn off for POST body content }
    FRcvdLine := ReceiveStr;
    { Remove trailing CR/LF }
    Len := Length(FRcvdLine);
    if (Len > 0) and (FRcvdLine[Len] = #10) then begin
        Dec(Len);
        if (Len > 0) and (FRcvdLine[Len] = #13) then
            Dec(Len);
        SetLength(FRcvdLine, Len);
    end;
    if FState = hcSendData then begin  // V8.01 got more commands while sending data
        if FRcvdLine = '' then
            exit;   // ignore blank line
        FState := hcRequest;
    end;
    if FState = hcRequest then begin
        if FRcvdLine = '' then
            exit;   // ignore blank line separating pipelined requests { V8.05 }
        { We just start a new request. Initialize all header variables }
        FRequestContentType    := '';
        FRequestContentLength  := 0;
        FRequestContentType    := '';
        FRequestAccept         := '';
        FRequestReferer        := '';
        FRequestAcceptLanguage := '';
        FRequestAcceptEncoding := '';
        FRequestUserAgent      := '';
        FRequestAuth           := '';     {DAVID}
        FRequestCookies        := '';
        FRequestHost           := '';
        FRequestHostName       := '';     {DAVID}
        FRequestHostPort       := '';     {DAVID}
        FRequestConnection     := '';
        FRequestIfModSince     := 0;      { V8.11 }
        FRequestStartTick      := IcsGetTickCount64;  { V8.12 }  { V8.71 }
        FRequestIfRange        := '';               { V8.68 }
        FRequestIfMatch        := '';               { V8.68 }
        FRequestIfNoneMatch    := '';               { V8.68 }
        FEntityTag             := '';               { V8.68 }
        FPostRcvLen            := 0;                { V9.6 WebDAV }
        FRequestDepth          := '';               { V9.6 WebDAV }
        FRequestBrief          := '';               { V9.6 WebDAV }
        FRequestTranslate      := '';               { V9.6 WebDAV, V9.8 typo }
        FRequestOverwrite      := '';               { V9.6 WebDAV }
        FRequestDestination    := '';               { V9.6 WebDAV }
        FRequestXML            := '';               { V9.6 WebDAV }
        FPostCounter           := 0;                { V9.6 }
        FDataSent              := 0;      {TURCAN}
        FDocSize               := 0;      {TURCAN}
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
        FAuthPassword          := '';
        FAuthUserName          := '';
        FAuthTypes             := FServer.FAuthTypes;
        FAuthRealm             := FServer.FAuthRealm;
    {$IFNDEF NO_DIGEST_AUTH}
        FAuthDigestServerNonce := '';
        FAuthDigestStale       := FALSE;
        FAuthDigestNonceLifeTimeMin  := FServer.FAuthDigestNonceLifeTimeMin;
    {$ENDIF}
{$ENDIF}
        FRequestRangeValues.Clear;        {ANDREAS}
        FRequestHeader.Clear;
        FKeepAlive             := FALSE;  {Bjornar, default value. This is set to true when header indicates keep-alive.
                                           Use this value to decide when to shut down the socket}
        FKeepAliveRequested    := FALSE;
        FHttpVerNum            := 11;     { Assume HTTP 1.1 by default }{ V1.6 }
        if FKeepAliveTimeSec > 0 then
            Dec(FMaxRequestsKeepAlive);
        FAnswerStatus          := 0;      { V7.19 changed to 200, 404, etc whenever header status is set, used for logging }
        OnDataSent             := ConnectionDataSent;  { V7.19 always need an event after header is sent }
        { The line we just received is HTTP command, parse it  }
        ParseRequest;   { sets FReqTarget, FPath, FMethod, FParams, FHttpVerNum, FKeepAlive and FRequestMethod V9.6 }
        if (FRequestMethod = httpMethodHead) then        { V9.6 }
            FSendType := httpSendHead   { V7.44 }
        else                            { V7.44 }
            FSendType := httpSendDoc;   { V7.44 }
      { V8.49 keep protocol, useful for building URLs  }
{$IFDEF USE_SSL}
        if FSslEnable then     { V8.50 was SslEnable }
            FRequestProtocol := 'https'
        else
{$ENDIF}
            FRequestProtocol := 'http';
        { Next lines will be header lines }
        FState := hcHeader;
        FRequestHasContentLength := FALSE;

     { V9.6 new debug logging }
        if (wsdlogHdr in FServer.WSDebugOptions) then begin
            DebugDisplay('< ' + FRcvdLine);
        end;
        Exit;
    end;

    { We can comes here only in hcHeader state }
    if FRcvdLine = '' then begin
        { Last header line is an empty line. Then we enter data state }
        if FRequestContentLength > 0 then     { Only if we have data  } { V7.30 }
            FState := hcPostedData
        { With a GET method, we _never_ have any document        10/02/2004 }
   //     else if (FMethod <> 'POST') and (FMethod <> 'PUT') and (FMethod <> 'PATCH') then    {10/02/2004 Bjornar}
        else if NOT (FRequestMethod in [httpMethodPost, httpMethodPut, httpMethodPatch]) then   { V9.6 }
            FState := hcSendData;         // V8.01 was hcRequest;

     // pending WebDAV PUT, create file stream

     { V9.6 must get any XML data sent with request, before processing request }
        if (FState = hcPostedData) and (FRequestMethod in [httpMethodPropFind, httpMethodPropPatch, httpMethodMkCol,
                                                                                   httpMethodLock, httpMethodUnlock]) then begin
            LineMode := False;
            FPostCounter := FRequestContentLength;
            if Length(FPostRcvBuf) < MAX_BUFSIZE then      { V9.6 TBytes }
                SetLength(FPostRcvBuf, MAX_BUFSIZE);
            Exit;
        end;

        { We will process request before receiving data because application }
        { has to setup things to be able to receive posted data             }
        {Bjornar, should also be able to accept more requests after HEAD}
        ProcessRequest;
        Exit;
    end;

    { We comes here for normal header line. Extract some interesting variables }
    I := Pos(':', FRcvdLine);
    if I > 0 then begin
        try
            repeat
                Inc(I);
            until (I > Length(FRcvdLine)) or (FRcvdLine[I] <> ' ');
            if StrLIComp(@FRcvdLine[1], 'content-type:', 13) = 0 then
                FRequestContentType := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'content-length:', 15) = 0 then begin            {Bjornar}
                FRequestHasContentLength := TRUE; { V7.30 }
                try                                                                           {Bjornar}
                    FRequestContentLength := StrToInt64(Copy(FRcvdLine, I, Length(FRcvdLine))); { V9.1 allow Int64 }
                except                                                                        {Bjornar}
                    FRequestContentLength := -1;  { V7.30 }                                            {Bjornar}
                end;
            end                                                                               {Bjornar}
            else if StrLIComp(@FRcvdLine[1], 'Accept:', 7) = 0 then
                FRequestAccept:= Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'Referer:', 8) = 0 then
                FRequestReferer := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'Accept-Language:', 16) = 0 then
                FRequestAcceptLanguage := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'Accept-Encoding:', 16) = 0 then
                FRequestAcceptEncoding := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'User-Agent:', 11) = 0 then
                FRequestUserAgent := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'Authorization:', 14) = 0 then {DAVID}
                FRequestAuth := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'Cookie:', 7) = 0 then {DAVID}
                FRequestCookies := Copy(FRcvdLine, I, Length(FRcvdLine))
            else if StrLIComp(@FRcvdLine[1], 'Host:', 5) = 0 then begin
            { V8.64 need to separate host and port before punycoding }
                FRequestHost := IcsLowerCase(Copy(FRcvdLine, I, Length(FRcvdLine)));
                J := Pos(':', FRequestHost);
                if J > 0 then begin
                    FRequestHostName := IcsIDNAToUnicode(Copy(FRequestHost, 1, J - 1));  { V8.64 }
                    FRequestHostPort := Copy(FRequestHost, J + 1, 100);
                    FRequestHost := FRequestHostName + ':' + FRequestHostPort;           { V8.64 }
                end
                else begin
                    FRequestHostName := IcsIDNAToUnicode(FRequestHost);         { V8.64 }
                    FRequestHostPort := FServer.Port; { by default server port }
                    FRequestHost := FRequestHostName;                           { V8.64 }
                end;
            end
            else if StrLIComp(@FRcvdLine[1], 'Connection:', 11) = 0 then begin
                FRequestConnection := Copy(FRcvdLine, I, Length(FRcvdLine));
                FKeepAliveRequested := CompareText(FRequestConnection, 'keep-alive') = 0;
                if FHttpVerNum = 10 then
                    FKeepAlive := FKeepAliveRequested
                else if CompareText(FRequestConnection, 'close') = 0 then
                    FKeepAlive := FALSE;
            end
            {ANDREAS}
            else if StrLIComp(@FRcvdLine[1], 'Range:', 6) = 0 then begin
                { Init the Byte-range object }
                RequestRangeValues.InitFromString(Trim(Copy(FRcvdLine, I, Length(FRcvdLine))));
            end
            else if StrLIComp(@FRcvdLine[1], 'Upgrade:', 8) = 0 then begin   { V8.08 for websockets }
                FRequestUpgrade := Copy(FRcvdLine, I, Length(FRcvdLine));
            end
            else if StrLIComp(@FRcvdLine[1], 'If-Modified-Since:', 18) = 0 then begin   { V8.11 added, V9.6 fixed wrong length }
                FRequestIfModSince := RFC1123_StrToDate (Copy(FRcvdLine, I, Length(FRcvdLine)));
            end
            else if StrLIComp(@FRcvdLine[1], 'If-Range:', 9) = 0 then begin   { V8.68 conditional range request with Etag or LastModDate }
                FRequestIfRange := Copy(FRcvdLine, I, Length(FRcvdLine));
            end
            else if StrLIComp(@FRcvdLine[1], 'If-Match:', 9) = 0 then begin   { V8.68 conditional request with multiple Etags }
                FRequestIfMatch := Copy(FRcvdLine, I, Length(FRcvdLine));
            end
            else if StrLIComp(@FRcvdLine[1], 'If-None-Match:', 14) = 0 then begin   { V8.68 conditional request with multiple Etags }
                FRequestIfNoneMatch := Copy(FRcvdLine, I, Length(FRcvdLine));
            end
            else if StrLIComp(@FRcvdLine[1], 'Depth:', 6) = 0 then begin
                FRequestDepth  := Copy(FRcvdLine, I, Length(FRcvdLine));         { V9.6 WebDAV PROPFIND 0,1,infinity }
            end
            else if StrLIComp(@FRcvdLine[1], 'Brief:', 6) = 0 then begin
                FRequestBrief := Copy(FRcvdLine, I, Length(FRcvdLine));          { V9.6 WebDAV PROPFIND T/F fewer XML }
            end
            else if StrLIComp(@FRcvdLine[1], 'Translate:', 10) = 0 then begin
                FRequestTranslate := Copy(FRcvdLine, I, Length(FRcvdLine));     { V9.6 WebDAV T/F for GET source ASP/CGI script, V9.8 typo }
            end
            else if StrLIComp(@FRcvdLine[1], 'Overwrite:', 10) = 0 then begin
                FRequestOverwrite := Copy(FRcvdLine, I, Length(FRcvdLine));      { V9.6 WebDAV T/F COPY/MOVE }
            end
            else if StrLIComp(@FRcvdLine[1], 'Destination:', 13) = 0 then begin
                FRequestDestination := Copy(FRcvdLine, I, Length(FRcvdLine));    { V9.6 WebDAV destination URL for COPY/MOVE }
            end;
        except
            { Ignore any exception in parsing header line }
        end;
    end;
    FRequestHeader.Add(FRcvdLine);

 { V9.6 new debug logging }
    if (wsdlogHdr in FServer.WSDebugOptions) then begin
        DebugDisplay('< ' + FRcvdLine);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Request is in FRcvdLine property.                                         }
{ Split it into FMethod, FPath/FReqTarget, FVersion and parameters.         }
{ V9.6 now sets FRequestMethod so other functions don't check literals      }
procedure THttpConnection.ParseRequest;
var
    I, J, K : Integer;
    Method: THttpMethod;
begin
    I := 1;
    while (I <= Length(FRcvdLine)) and (FRcvdLine[I] <> ' ') do
        Inc(I);
    FMethod := UpperCase(Copy(FRcvdLine, 1, I - 1));
    Inc(I);
    while (I <= Length(FRcvdLine)) and (FRcvdLine[I] = ' ') do
        Inc(I);
    J := I;
    while (I <= Length(FRcvdLine)) and (FRcvdLine[I] <> ' ') do
        Inc(I);
    FPath := Copy(FRcvdLine, J, I - J);

  { V9.6 lookup request method verb from table }
    FRequestMethod := httpMethodNone;
    for Method := Low(THttpMethod) to High(THttpMethod) do begin
        if FMethod = HttpMethodVerbs[Method] then begin
            FRequestMethod := Method;
            Break;
        end;
    end;

  { V8.10 check if absolute-form path supplied, ie a complete URL, strip
      off protocol and host and port for backward compatility }
    FReqTarget := FPath;
    if Pos ('HTTP', Trim(UpperCase(FPath))) = 1 then begin
        J := 0;
        K := 1;
        while (K <= Length (FPath)) do begin
            if FPath[K] = '/' then inc (J);
            if J = 3 then begin
                FPath := Copy (FPath, K, 999);
                Break;
            end;
            Inc(K);
        end;
    end;

    { Find parameters }
    J := Pos('?', FPath);
    if J <= 0 then
        FParams := ''
    else begin
        FParams := Copy(FPath, J + 1, Length(FPath));
        FPath   := Copy(FPath, 1, J - 1);
    end;
    Inc(I);
    while (I <= Length(FRcvdLine)) and (FRcvdLine[I] = ' ') do
        Inc(I);
    J := I;
    while (I <= Length(FRcvdLine)) and (FRcvdLine[I] <> ' ') do
        Inc(I);
    FVersion := Trim(UpperCase(Copy(FRcvdLine, J, I - J)));

 { V9.2 check we really have version, there may have been a space in the URL }
    if (Pos ('HTTP/', FVersion) <> 1) then begin
        J := Length(FRcvdLine) - 4;
        while (J > 0) and (FRcvdLine[J] <> ' ') do
            Dec(J);
        FVersion := Trim(UpperCase(Copy(FRcvdLine, J, 999)));
        if (Pos ('HTTP/', FVersion) <> 1) then
            FVersion := '';
    end;
    if FVersion = '' then
        FVersion := 'HTTP/1.0';
    if FVersion = 'HTTP/1.0' then
        FHttpVerNum := 10;
    if FVersion = 'HTTP/2.0' then     { should not happen! }
        FHttpVerNum := 20;
    FKeepAlive := (FHttpVerNum = 11);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This method has to be called by main code when all posted data has been   }
{ received.                                                                 }
procedure THttpConnection.PostedDataReceived;
begin
    LineMode := TRUE;
    FState   := hcRequest; { Bjørnar. To let the server be able to handle   }
                           { more requests on same connection after a POST  }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ All data in TWSocket has been sent. Read next lock from stream and send.  }
{ When end of stream is reached, closed communication.                      }
procedure THttpConnection.ConnectionDataSent(Sender : TObject; Error : WORD);
var
    Count  : THttpRangeInt;
    ToSend : THttpRangeInt;
begin
    if FShutDownFlag then begin
        TriggerAfterAnswer;                   { V7.19 we can log how much data was sent from here }
        Shutdown(1);
        Exit;
    end;
    if not Assigned(FDocStream) then begin
        if (FState in [hcPostedData, hcSendData, hcRequest]) and (FPostCounter = 0) then    { V9.2 added hcReady for POST errors }
        begin
            TriggerAfterAnswer;               { V7.19 we can log how much data was sent from here }
            FState := hcRequest;              { ready for next pipelined requests } { V8.05 }
{$IFDEF ICS_NewMessaging}   { V10.0 }
            IcsPostMessage(Self, WM_ICS_HTTPSRV_DONE, 0, 0);
{$ELSE}
            PostMessage(Handle, FMsg_WM_HTTP_DONE, 0, 0);
{$ENDIF ICS_NewMessaging}   { V10.0 }
        end;
        if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
            DebugDisplay('! No stream sent');
        Exit;
        { No stream usually means just a header string has been sent         }
        { or an error response with body                                     }
        { or we are currently receiving posted data (and received a FD_WRITE }
        { message when internal send buffer was empty)                       }
    end;

    if FDocSize <= 0 then
        Send(nil, 0);                         {Force send buffer flush}

    if FDataSent >= FDocSize then begin       {DAVID}
        { End of file found }
        TriggerAfterAnswer;                   { V7.19 we can log how much data was sent from here }
        if Assigned(FDocStream) then begin    {DAVID}
            FDocStream.Free;                  {DAVID}
            FDocStream := nil;                {DAVID}
{$IFDEF USE_ZLIB}

{$ENDIF}
        end;                                  {DAVID}

    { V9.6 debug logging }
        if (wsdlogHdr in FServer.WSDebugOptions) then begin
            DebugDisplay('! Finished sending body, size: ' + IcsIntToKbyte(FDataSent));
        end;

        if FKeepAlive = FALSE then {Bjornar}
           Shutdown(1);            {Bjornar}

        { Bjornar. Because client might pipeline requests, FState should only be set to
          hcRequest in ConnectionDataAvailable after receiving empty line (when GET) and
          after all posted data is received (when POST).}
        if FState in [hcPostedData, hcSendData] then
            FState := hcRequest;                  { restored V8.05 }
{$IFDEF ICS_NewMessaging}   { V10.0 }
        IcsPostMessage(Self, WM_ICS_HTTPSRV_DONE, 0, 0);
{$ELSE}
        PostMessage(Handle, FMsg_WM_HTTP_DONE, 0, 0);
{$ENDIF ICS_NewMessaging}   { V10.0 }
        Exit;
    end;

    { We have at least one byte to read.    }
    { Never read more than specified range. }
    ToSend := FDocSize - FDataSent;
    if ToSend > FSndBlkSize then
        ToSend := FSndBlkSize;
    Count     := FDocStream.Read(FDocBuf^, ToSend);
    FDataSent := FDataSent + Count;      { Count data which is sent         }
    if State = wsConnected then          { Be sure to be still connected... }
        Send(FDocBuf, Count);            { before actually send any data.   }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure RowDataGetterProc(
    const TableName : String;
    Row             : Integer;
    TagData         : TStringIndex;
    var More        : Boolean;
    UserData        : TObject);
var
    UD : THttpSrvRowDataGetterUserData;
begin
    UD := UserData as THttpSrvRowDataGetterUserData;
    if Assigned(UD.Event) then
        UD.Event(TableName, Row, TagData, More, UD.UserData)
    else
        More := FALSE;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerGetRowData(
    const TableName : String;
    Row             : Integer;
    TagData         : TStringIndex;
    var More        : Boolean;
    UserData        : TObject);
begin
    if Assigned(FOnGetRowData) then
        FOnGetRowData(Self, TableName, Row, TagData, More, UserData);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.CheckContentEncoding(const ContType : String): boolean;  { V7.21 are we allowed to compress content }
begin
    Result := False;
    if NOT (hoContentEncoding in FServer.Options) then exit;  { V7.20 are we allowed to compress content }
    if (ContType = '') or
         (Pos ('text/', ContType) > 0) or
         (Pos ('application/json', ContType) > 0) or  { V8.07 }
         (Pos ('javascript', ContType) > 0) or        { V8.07 }
         (Pos ('xml', ContType) > 0) then begin    { only compress textual stuff }
       if (FDocStream.Size < FServer.SizeCompressMin) then exit;   { too small a waste of time }
       if (FDocStream.Size > FServer.SizeCompressMax) then exit;   { too large will block server and use a lot of memory }
       Result := True;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.DoContentEncoding: String; { V7.21 compress content returning Content-Encoding header }
var
  ContentEncoding: String;        { V7.20 }
  CompressionHandled: Boolean;    { V7.20 }
  ZDocStream: TMemoryStream;      { V7.20 }
  ZStreamType: TZStreamType;      { V7.20 }
begin
    Result := '';
    CompressionHandled := false;
    TriggerContentEncode(ContentEncoding, CompressionHandled);    { let application do it, or find cached file }
    if CompressionHandled then begin
        Result := 'Content-Encoding: ' + ContentEncoding + IcsCRLF;
        TriggerContEncoded;  { let application cache compressed file or report what we did }
    end
    else begin
        if Pos('deflate', FRequestAcceptEncoding) > 0 then begin
            Result := 'Content-Encoding: deflate' + IcsCRLF;
            ZStreamType := zsRaw;
        end
        else if Pos('gzip', FRequestAcceptEncoding) > 0 then begin
            Result := 'Content-Encoding: gzip' + IcsCRLF;
            ZStreamType := zSGZip;
        end
        else
            ZStreamType := zsZLib;
        if ZStreamType <> zsZLib then begin
            ZDocStream := TMemoryStream.Create;
            FDocStream.Position := 0; { V8.67 Seek (0, 0); { reset to start }
            ZlibCompressStreamEx(FDocStream, ZDocStream, clDefault, ZStreamType, true);
            FDocStream.free;
            FDocStream := ZDocStream;
            TriggerContEncoded;  { let application cache compressed file or report what we did }
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{V8.68 build Entity Tag CRC of time stamp and size, unless application provided
  something better like CRC of content }
procedure THttpConnection.BuildETag(ContentSize: Int64);        { V8.68 }
begin
    if FEntityTag <> '' then Exit;  // user generated it
    if (ContentSize <= 0) or (FLastModified = 0) then Exit;
    FEntityTag := IcsDQUOTE + IcsBase64UrlEncode(
       StrCRC32(RFC3339_DateToStr(FLastModified, False) + IntToStr(ContentSize))) + IcsDQUOTE;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.AnswerStream(
    var   Flags    : THttpGetFlag;
    const Status   : String;   { if empty, default to '200 OK'           }
    const ContType : String;   { if emtpy, default to text/html          }
    const Header   : String;   { Do not use Content-Length               }
    LastModified    : TDateTime = 0); { zero => no Last-Modified header  V8.67  }
var
    ContEncoderHdr  : String ;      { V7.21 }
    RespHeader      : String;       { V8.69 }
begin
    Flags := hgWillSendMySelf;
    ContEncoderHdr := '';
    FLastModified := LastModified;       { V8.67  }

 { V8.68 see if comparing old entity tag with latest version to skip download, we may
   have been given a comma list of etags }
    if not Assigned(FDocStream) then
        BuildETag(0)
    else
        BuildETag(FDocStream.Size);
    if (FRequestIfNoneMatch <> '') and (FEntityTag <> '') then begin
        if (Pos(FEntityTag, FRequestIfNoneMatch) > 0) then begin { etag found, skip }
            Answer304;
            Exit;
         end;
    end;
    if (FRequestIfMatch <> '') and (FEntityTag <> '') then begin
        if (Pos(FEntityTag, FRequestIfMatch) = 0) then begin   { no etag found, skip }
            Answer304;
            Exit;
         end;
    end;
  { see if document actually changed, within one second of time stamp, V8.68 RequestIfNoneMatch has precidence }
    if (NOT (hoIgnoreIfModSince in FOptions)) and (FLastModified > 0) and
             (FRequestIfModSince >= (FLastModified - (1 / SecsPerDay))) then begin
        Answer304;
        Exit;
    end;

  { V8.69 build string with response header instead of using lots of PutStringInSendBuffer }
    if Status = '' then begin
        RespHeader := FVersion + ' 200 OK' + IcsCRLF ;
        FAnswerStatus := 200;   { V7.19 }
    end
    else begin
        FAnswerStatus := StrToIntDef(Copy(Status, 1, 3), 0);      { V8.04 }
        RespHeader := FVersion + ' ' + Status + IcsCRLF;
    end;
    if FLastModified <> 0 then
        RespHeader := RespHeader + 'Last-Modified: ' + RFC1123_Date(IcsDateTimeToUTC (FLastModified)) + ' GMT' + IcsCRLF;   { V8.67, V8.69 UTC }
    if ContType = '' then
        RespHeader := RespHeader + 'Content-Type: text/html' + IcsCRLF
    else
        RespHeader := RespHeader + 'Content-Type: ' + ContType + IcsCRLF;
    RespHeader := RespHeader + GetKeepAliveHdrLines;

    if not Assigned(FDocStream) then begin
        RespHeader := RespHeader + 'Content-Length: 0' + IcsCRLF;
    end
    else begin
        if CheckContentEncoding(ContType) then           { V7.21 are we allowed to compress content }
               ContEncoderHdr := DoContentEncoding;      { V7.21 do it, returning new header }
        RespHeader := RespHeader + 'Content-Length: ' + IntToStr(FDocStream.Size) + IcsCRLF;
    end;

    RespHeader := RespHeader + 'Accept-Ranges: bytes' + IcsCRLF;                                    { V8.68 }
    RespHeader := RespHeader + 'Date: ' + RFC1123_Date(IcsDateTimeToUTC (Now)) + ' GMT' + IcsCRLF;  { V8.68 }
    if FEntityTag <> '' then
        RespHeader := RespHeader + 'ETag: ' + FEntityTag + IcsCRLF;                                 { V8.68 }
    if (hoSendServerHdr in FOptions) and (FServer.FServerHeader <> '') then
        RespHeader := RespHeader + FServer.FServerHeader + IcsCRLF;    { V8.08 }
    if Header <> '' then
        RespHeader := RespHeader + Header;
    if ContEncoderHdr <> '' then
        RespHeader := RespHeader + ContEncoderHdr;  { V7.21 }
 //   if FServer.PersistentHeader <> '' then              done by sendheader
 //     RespHeader := RespHeader + FServer.PersistentHeader;  { V7.29 }
    RespHeader := RespHeader + IcsCRLF;
    SendHeader(RespHeader);

    if FSendType = httpSendHead then begin   { V7.44 }
        FDataSent := 0;                      { V7.44 }
        FDocSize  := 0;                      { V7.44 }
        Send(nil, 0);                        { V7.44 }
    end
    else
        SendStream;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ANDREAS Byte-range-separator (use the same as IIS) }
const
    ByteRangeSeparator = '[lka9uw3et5vxybtp87ghq23dpu7djv84nhls9p]';


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ANDREAS Helperfunction to create the HTTP-Header }
function CreateHttpHeader(
    Version           : String;
    ProtoNumber       : Integer;
    AnswerContentType : String;
    RangeList         : THttpRangeList;
    DocSize           : THttpRangeInt;
    CompleteDocSize   : THttpRangeInt): String;
begin
    if ProtoNumber = 200 then
        Result := Version + ' 200 OK' + IcsCRLF +
                  'Content-Type: ' + AnswerContentType + IcsCRLF +
                  'Content-Length: ' + IntToStr(DocSize) + IcsCRLF +
                  'Accept-Ranges: bytes' + IcsCRLF
    {else if ProtoNumber = 416 then
        Result := Version + ' 416 Request range not satisfiable' + IcsCRLF}
    else if ProtoNumber = 206 then begin
        if RangeList.Count = 1 then begin
            Result := Version + ' 206 Partial Content' + IcsCRLF +
                      'Content-Type: ' + AnswerContentType + IcsCRLF +
                      'Content-Length: ' + IntToStr(DocSize) + IcsCRLF +
                      'Content-Range: bytes ' +
                      RangeList.Items[0].GetContentRangeString(CompleteDocSize) +
                      IcsCRLF;
        end
        else begin
            Result := Version + ' 206 Partial Content' + IcsCRLF +
                      'Content-Type: multipart/byteranges; boundary=' +
                      ByteRangeSeparator + IcsCRLF +
                      'Content-Length: ' + IntToStr(DocSize) + IcsCRLF;
        end;
    end
    else
        raise Exception.Create('Unexpected ProtoNumber in CreateHttpHeader');
    Result := Result + 'Date: ' + RFC1123_Date(IcsDateTimeToUTC (Now)) + ' GMT' + IcsCRLF;  { V8.68 }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Only use this method for OK responses                                     }
procedure THttpConnection.AnswerStreamAcceptRange(                  { V7.44 }
    var   Flags     : THttpGetFlag;
    const ContType  : String;      { if emtpy, defaults to text/html        }
    LastModified    : TDateTime = 0); { zero => no Last-Modified header     }
begin
    AnswerStreamAcceptRange(Flags, ContType, '', LastModified);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Only use this method for OK responses                                     }
procedure THttpConnection.AnswerStreamAcceptRange(                  { V7.43 }
    var   Flags     : THttpGetFlag;
    const ContType  : String;      { if emtpy, defaults to text/html        }
    const Header    : String;      { do not use Content-Length, Content-Range, Last-Modified }
    LastModified    : TDateTime = 0); { zero => no Last-Modified header     }
var
    NewDocStream    : TStream;
    ProtoNumber     : Integer;
    CompleteDocSize : THttpRangeInt;
    SyntaxError     : Boolean;
    ContEncoderHdr  : String;
//    ContStatusHdr   : String;
    DateStr         : String;       { V8.68 }
    RespHeader      : String;       { V8.69 }
begin
    Flags := hgWillSendMySelf;
    ProtoNumber := 200;
    ContEncoderHdr := '';
    if ContType <> '' then
        FAnswerContentType := ContType
    else
        FAnswerContentType := 'text/html';
    FLastModified := LastModified;
    if FLastModified <> 0 then
        DateStr := RFC1123_Date(IcsDateTimeToUTC (FLastModified)) + ' GMT';      { V8.68, V8.69 UTC }
    CompleteDocSize := FDocStream.Size;

 { V8.68 see if comparing old entity tag with latest version to skip download, we may
   have been given a comma list of etags }
    BuildETag(CompleteDocSize);

 { resuming a download with a range, check original has not changed other ignore range and return whole file }
    if RequestRangeValues.Valid and (FRequestIfRange <> '') and (FEntityTag <> '') then begin
        if NOT ((Pos(FEntityTag, FRequestIfRange) > 0) or (Pos(DateStr, FRequestIfRange) > 0)) then
             RequestRangeValues.Clear;
    end;
    if (FRequestIfNoneMatch <> '') and (FEntityTag <> '') then begin
        if (Pos(FEntityTag, FRequestIfNoneMatch) > 0) then begin { etag found, skip }
            Answer304;
            Exit;
         end;
    end;
    if (FRequestIfMatch <> '') and (FEntityTag <> '') then begin
        if (Pos(FEntityTag, FRequestIfMatch) = 0) then begin   { no etag found, skip }
            Answer304;
            Exit;
         end;
    end;
  { V8.11 see if document actually changed, within one second of time stamp, V8.68 RequestIfNoneMatch has precidence }
    if (NOT (hoIgnoreIfModSince in FOptions)) and (FLastModified <> 0) and (NOT RequestRangeValues.Valid) and        { V8.68  not for a range }
                                              (FRequestIfModSince >= (FLastModified - (1 / SecsPerDay))) then begin
        Answer304;
        Exit;
    end;

    {ANDREAS Create the virtual 'byte-range-doc-stream', if we are ask for ranges}
    if RequestRangeValues.Valid then begin
        { NewDocStream will now be the owner of FDocStream -> don't free FDocStream }
        NewDocStream := RequestRangeValues.CreateRangeStream(FDocStream, FAnswerContentType, CompleteDocSize, SyntaxError);
        if Assigned(NewDocStream) then begin
            FDocStream := NewDocStream;
            FDocStream.Position := 0;
            ProtoNumber := 206;
        end
        else begin
            if SyntaxError then
            { Ignore the content range header and send entire document in case }
            { of syntactically invalid byte-range-set                          }
                FDocStream.Position := 0
            else begin
            { Answer 416 Request range not satisfiable                      }
                FDocStream.Free;
                FDocStream := nil;
                if not FKeepAlive then
                    PrepareGraceFullShutDown;
                Answer416;
                Exit;
            end;
        end;
    end;

    FDataSent := 0;       { will be incremented after each send part of data }
    FDocSize := FDocStream.Size;
    OnDataSent := ConnectionDataSent;

    { V7.21 are we allowed to compress content }
    if CheckContentEncoding(FAnswerContentType) then begin
        ContEncoderHdr := DoContentEncoding;   { V7.21 do it, returning new header }
        FDocSize := FDocStream.Size;           { stream is now smaller, we hope }
    end;

    { Create Header }
  { V8.69 build string with response header instead of using lots of PutStringInSendBuffer }
    RespHeader := CreateHttpHeader(FVersion, ProtoNumber, FAnswerContentType, RequestRangeValues, FDocSize, CompleteDocSize);
    FAnswerStatus := ProtoNumber;   { V7.19 }

    if FLastModified <> 0 then
        RespHeader := RespHeader + 'Last-Modified: ' + DateStr;                 { V8.68 }
    if ContEncoderHdr <> '' then
        RespHeader := RespHeader + ContEncoderHdr;  { V7.21 }
    RespHeader := RespHeader + 'Date: ' + RFC1123_Date(IcsDateTimeToUTC (Now)) + ' GMT' + IcsCRLF;  { V8.68 }
    if FEntityTag <> '' then
        RespHeader := RespHeader + 'ETag: ' + FEntityTag + IcsCRLF;                { V8.68 }
    if (hoSendServerHdr in FOptions) and (FServer.FServerHeader <> '') then
        RespHeader := RespHeader + FServer.FServerHeader + IcsCRLF;    { V8.08 }
    if Header <> '' then
        RespHeader := RespHeader + Header;
    RespHeader := RespHeader + GetKeepAliveHdrLines;
    RespHeader := RespHeader + IcsCRLF;
    SendHeader(RespHeader);

    if FSendType = httpSendHead then begin   { V7.44 }
        FDocSize := 0;                       { V7.44 }
        Send(nil, 0);                        { V7.44 }
    end
    else
        SendStream;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.HtmlPageProducerToString(
    const HtmlFile : String;
    UserData       : TObject;
    Tags           : array of const
{$IFDEF COMPILER12_UP};
    FileCodepage   : LongWord = CP_ACP
{$ENDIF}
    ) : String;
var
    Stream : TMemoryStream;
const
    NulByte : Byte = 0;
begin
    Stream := TMemoryStream.Create;
    try
        HtmlPageProducerToStream(HtmlFile, UserData, Tags, Stream
                             {$IFDEF COMPILER12_UP},
                                 FileCodepage
                             {$ENDIF}
                                 );
{$IFDEf COMPILER12_UP}
        // For unicode char compiler (D2009 and up)
        // Add a nul byte at the end of string
        Stream.Write(NulByte, 1);
        Result := String(PAnsiChar(Stream.Memory));
{$ELSE}
        // For ansi char compiler
        SetLength(Result, Stream.Size);
        Stream.Position := 0; { V8.67 Seek(0, 0); }
        Stream.Read(Result[1], Stream.Size);
{$ENDIF}
    finally
        Stream.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.HtmlPageProducerToStream(
    const HtmlFile : String;
    UserData       : TObject;
    Tags           : array of const;
    DestStream     : TStream
{$IFDEF COMPILER12_UP};
    FileCodepage   : LongWord = CP_ACP;
    DstCodepage    : LongWord = CP_ACP
{$ENDIF}
    );
var
    UD : THttpSrvRowDataGetterUserData;
    FName: String;
begin
    UD := THttpSrvRowDataGetterUserData.Create;
    try
        UD.UserData := UserData;
        UD.Event    := Self.TriggerGetRowData;
        if FTemplateDir = '' then
            FName := HtmlFile
        else
            FName := IncludeTrailingPathDelimiter(FTemplateDir) + HtmlFile;
        if NOT FileExists(FName) then begin        { V9.8 check now so we can log failure }
            if (wsdlogErrs in FServer.WSDebugOptions) then
                   DebugDisplay('= HtmlPageProducer, File Not Found: ' + FName);
            Answer404;
            Exit;
        end;
        if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
               DebugDisplay('= HtmlPageProducer, File: ' + FName);
        HtmlPageProducer(FName, Tags, @RowDataGetterProc, UD, DestStream
                                              {$IFDEF COMPILER12_UP},FileCodepage, DstCodepage{$ENDIF} );
    finally
        UD.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.HtmlPageProducerToStream(
    const ResName : String;
    const ResType : PChar;
    UserData      : TObject;
    Tags          : array of const;
    DestStream    : TStream
{$IFDEF COMPILER12_UP};
    ResCodepage   : LongWord = CP_ACP;
    DstCodepage   : LongWord = CP_ACP
{$ENDIF}
    );
var
    UD : THttpSrvRowDataGetterUserData;
begin
    UD := THttpSrvRowDataGetterUserData.Create;
    try
        UD.UserData := UserData;
        UD.Event    := Self.TriggerGetRowData;
        if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
            DebugDisplay('= HtmlPageProducer, Resource: ' + ResName);
        HtmlPageProducer(ResName, ResType, Tags, @RowDataGetterProc, UD, DestStream
                     {$IFDEF COMPILER12_UP}, ResCodepage, DstCodepage {$ENDIF} );
    finally
        UD.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.AnswerPage(
    var   Flags    : THttpGetFlag;
    const Status   : String;   { if empty, default to '200 OK'              }
    const Header   : String;   { Do not use Content-Length nor Content-Type }
    const HtmlFile : String;
    UserData       : TObject;
    Tags           : array of const;
{$IFDEF COMPILER12_UP}
    FileCodepage   : LongWord = CP_ACP;
    DstCodepage    : LongWord = CP_ACP;
{$ENDIF}
    LastModified   : TDateTime = 0);                                    { V8.67  }
begin
    DocStream.Free;
    DocStream := TMemoryStream.Create;
    HtmlPageProducerToStream(HtmlFile, UserData, Tags, DocStream
                        {$IFDEF COMPILER12_UP},
                             FileCodepage, DstCodepage
                        {$ENDIF}
                             );
    AnswerStream(Flags, Status, 'text/html', Header, LastModified);   { V8.67  }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.AnswerPage(
    var   Flags    : THttpGetFlag;
    const Status   : String;
    const Header   : String;
    const ResName  : String;
    const ResType  : PChar;
    UserData       : TObject;
    Tags           : array of const;
{$IFDEF COMPILER12_UP}
    ResCodepage    : LongWord = CP_ACP;
    DstCodepage    : LongWord = CP_ACP;
{$ENDIF}
    LastModified   : TDateTime = 0);                                    { V8.67  }
begin
    DocStream.Free;
    DocStream := TMemoryStream.Create;
    HtmlPageProducerToStream(ResName, ResType, UserData, Tags, DocStream
                        {$IFDEF COMPILER12_UP},ResCodepage, DstCodepage{$ENDIF});
    AnswerStream(Flags, Status, 'text/html', Header, LastModified);   { V8.67  }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Build an answer and send it to the client.                                }
{ The header is automatically built but you can provide your own lines.     }
{ Add a CR/LF at the end of each of your header line but do not add an      }
{ empty line at the end of your header: it is added automatically.          }
procedure THttpConnection.AnswerString(
    var   Flags    : THttpGetFlag;
    const Status   : String;   { if empty, default to '200 OK'              }
    const ContType : String;   { if empty, default to 'text/html'           }
    const Header   : String;   { Do not use Content-Length nor Content-Type }
    const Body     : String;  { Could be empty. No default.                }
    LastModified   : TDateTime = 0);                                    { V8.67  }
begin
    if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
         DebugDisplay('= AnswerString, Length: ' + IntToStr(Length(Body)));
    DocStream.Free;
    DocStream := TStringStream.Create(Body);
    AnswerStream(Flags, Status, ContType, Header, LastModified);   { V8.67  }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF COMPILER12_UP}
procedure THttpConnection.AnswerStringEx(
    var   Flags    : THttpGetFlag;
    const Status   : String;   { if empty, default to '200 OK'              }
    const ContType : String;   { if empty, default to 'text/html'           }
    const Header   : String;   { Do not use Content-Length nor Content-Type }
    const Body     : String;   { Could be empty. No default.                }
    BodyCodePage   : Integer  = CP_ACP;
    LastModified   : TDateTime = 0);                                    { V8.67  }
begin
    if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
         DebugDisplay('= AnswerStringEx, Length: ' + IntToStr(Length(Body)));
    DocStream.Free;
    DocStream := TStringStream.Create(Body, BodyCodePage);
    AnswerStream(Flags, Status, ContType, Header, LastModified);   { V8.67  }
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.2 Answer request with Body as TBytes binary  }
procedure THttpConnection.AnswerBodyTB(var Flags: THttpGetFlag; const Status, ContType, Header: String; const Body: TBytes;
                                                                                          LastModified: TDateTime = 0);   { V9.2  }
begin
    if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
         DebugDisplay('= AnswerBodyTB, Length: ' + IntToStr(Length(Body)));
    DocStream.Free;
{$IFDEF COMPILER16_UP}
    DocStream := TBytesStream.Create(Body);
{$ELSE}
    DocStream := TMemoryStream.Create;
    if Length(Body) > 0 then
        DocStream.Write(Body[1], Length(Body));
{$ENDIF}
    AnswerStream(Flags, Status, ContType, Header, LastModified);   { V8.67  }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer416;
var
    Body : String;
begin
    Body := '<HTML><HEAD><TITLE>416 Requested range not satisfiable</TITLE></HEAD>' +
            '<BODY><H1>416 Requested range not satisfiable</H1><P></BODY></HTML>' + IcsCRLF;
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, 416, '', Body);
    SendHeader(FVersion + ' 416 Requested range not satisfiable' + IcsCRLF +
               'Content-Type: text/html' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               GetKeepAliveHdrLines +
               IcsCRLF);
    FAnswerStatus := 416;  { V7.19 }
    if FSendType = httpSendHead then  { V7.44 }
        Send(nil, 0)                  { V7.44 }
    else                              { V7.44 }
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer404;
var
    Body : String;
begin
    Body := '<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD>' +
            '<BODY><H1>404 Not Found</H1>The requested URL ' +  TextToHtmlText(FPath) +
            ' was not found on this server.<P></BODY></HTML>' + IcsCRLF;
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, 404, FPath, Body);
    SendHeader(FVersion + ' 404 Not Found' + IcsCRLF +
               'Content-Type: text/html' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               GetKeepAliveHdrLines +
               IcsCRLF);
    FAnswerStatus := 404;   { V7.19 }
    if FSendType = httpSendHead then  { V7.44 }
        Send(nil, 0)                  { V7.44 }
    else                              { V7.44 }
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer304;    { V8.11 }
var
    Hdr: String;
begin
    Hdr := FVersion + ' 304 Not Modified' + IcsCRLF +
          'Content-Length: 0' + IcsCRLF;
 { V8.68 should include Cache-Control, Content-Location, Date, ETag, Expires, and Vary }
    if FEntityTag <> '' then
        Hdr := Hdr + 'ETag: ' + FEntityTag + IcsCRLF;
    Hdr := Hdr + 'Accept-Ranges: bytes' + IcsCRLF +
                 'Date: ' + RFC1123_Date(IcsDateTimeToUTC (Now)) + ' GMT' + IcsCRLF +
                 GetKeepAliveHdrLines +
                 IcsCRLF;
    SendHeader(Hdr);
    FAnswerStatus := 304;
    Send(nil, 0)
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer400;
var
    Body : String;
begin
    Body := '<HTML><HEAD><TITLE>400 Bad Request</TITLE></HEAD>' +
            '<BODY><H1>400 Bad Request</H1>The request could ' +
            'not be understood by the server due to malformed '+
            'syntax.<P></BODY></HTML>' + IcsCRLF;
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, 400, '', Body);
    SendHeader(FVersion + ' 400 Bad Request' + IcsCRLF +
               'Content-Type: text/html' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               GetKeepAliveHdrLines +
               IcsCRLF);
    FAnswerStatus := 400;
    if FSendType = httpSendHead then  { V7.44 }
        Send(nil, 0)                  { V7.44 }
    else                              { V7.44 }
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.GetKeepAliveHdrLines: String;
begin
    if (FHttpVerNum = 11) then
    begin
        if not FKeepAlive then
            Result := 'Connection: Close' + IcsCRLF
        else if FKeepAliveRequested then
            Result := 'Connection: Keep-Alive' + IcsCRLF;
    end
    else if FKeepAlive then
        Result := 'Connection: Keep-Alive' + IcsCRLF;

    if FKeepAlive and FKeepAliveRequested and (FKeepAliveTimeSec > 0) then
        Result := Result + 'Keep-Alive: timeout=' + IntToStr(FKeepAliveTimeSec) + ', max=' + IntToStr(FMaxRequestsKeepAlive) + IcsCRLF;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer403;
var
    Body    : String;
begin
    Body := '<HTML><HEAD><TITLE>403 Forbidden</TITLE></HEAD>' +
            '<BODY><H1>403 Forbidden</H1>The requested URL ' + TextToHtmlText(FPath) +
            ' is Forbidden on this server.<P></BODY></HTML>' + IcsCRLF;
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, 403, FPath, Body);
    SendHeader(FVersion + ' 403 Forbidden' + IcsCRLF +
               'Content-Type: text/html' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               GetKeepAliveHdrLines +
               IcsCRLF);
    FAnswerStatus := 403;   { V7.19 }
    if FSendType = httpSendHead then  { V7.44 }
        Send(nil, 0)                  { V7.44 }
    else                              { V7.44 }
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer401;
var
    Body       : String;
    Header     : String;
begin
    Body := '<HTML><HEAD><TITLE>401 Access Denied</TITLE></HEAD>' +
            '<BODY><H1>401 Access Denied</H1>The requested URL ' + TextToHtmlText(FPath) +
            ' requires authorization.<P></BODY></HTML>' + IcsCRLF;
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, 401, FPath, Body);
    Header := FVersion + ' 401 Access Denied' + IcsCRLF;
    FAnswerStatus := 401;   { V7.19 }

{ we send one header for each of the authentication types we support,
  let the browser choose which, easiest last  }

{$IFNDEF NO_AUTHENTICATION_SUPPORT}
  {$IFDEF USE_NTLM_AUTH}
    if (atNtlm in FAuthTypes) then begin
        if Assigned(FAuthNtlmSession) and
            (FAuthNtlmSession.State = lsInAuth) then
            Header := Header +  Trim('WWW-Authenticate: NTLM ' + FAuthNtlmSession.NtlmMessage) + IcsCRLF
        else
            Header := Header + 'WWW-Authenticate: NTLM' + IcsCRLF;
    end;
  {$ENDIF}
  {$IFNDEF NO_DIGEST_AUTH}
    if (atDigestSha2 in FAuthTypes) then begin                             { V8.69 }
        FAuthDigestServerNonce  := '';
        FAuthDigestServerOpaque := '';
        Header := Header + 'WWW-Authenticate: Digest ' + AuthDigestGenerateChallenge(FServer.FAuthDigestMethod,
                   FServer.FAuthDigestServerSecret, FAuthRealm, '', FAuthDigestStale, FAuthDigestServerNonce,
                                                                   FAuthDigestServerOpaque, 'SHA-256') + IcsCRLF;  { V8.69 }
    end;
    if (atDigest in FAuthTypes) then begin
        FAuthDigestServerNonce  := '';
        FAuthDigestServerOpaque := '';
        Header := Header + 'WWW-Authenticate: Digest ' + AuthDigestGenerateChallenge(FServer.FAuthDigestMethod,
                   FServer.FAuthDigestServerSecret, FAuthRealm, '', FAuthDigestStale, FAuthDigestServerNonce,
                                                              FAuthDigestServerOpaque, 'MD5') + IcsCRLF;  { V8.69 }
    end;
  {$ENDIF}
    if (atBasic in FAuthTypes) then begin
        Header := Header + 'WWW-Authenticate: ' + 'Basic Realm="' + FAuthRealm + '"' + IcsCRLF;
    end;
{$ENDIF}
    Header := Header + 'Content-Type: text/html' + IcsCRLF +
                       'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF;
    Header := Header + GetKeepAliveHdrLines +
                       IcsCRLF; // Mark the end of header
    SendHeader(Header);
    if FSendType = httpSendHead then  { V7.44 }
        Send(nil, 0)                  { V7.44 }
    else                              { V7.44 }
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.Answer501;
var
    Body : String;
begin
    Body := '501 Unimplemented';
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, 501, FPath, Body);
    SendHeader(FVersion + ' 501 Unimplemented' + IcsCRLF +
               'Content-Type: text/plain' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               GetKeepAliveHdrLines +
               IcsCRLF);
    FAnswerStatus := 501;   { V7.19 }
    if FSendType = httpSendHead then  { V7.44 }
        Send(nil, 0)                  { V7.44 }
    else                              { V7.44 }
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.2 redirection responses, optional extra headers like cookies }
procedure THttpConnection.AnswerRedirect(RespCode: Integer; const NewLocation: String; const ExtraHdrs: String = '');
var
    Body, RespStatus: String;
begin
    case RespCode of
        301: RespStatus := '301 Moved Permanently';
        302: RespStatus := '302 Found';
        307: RespStatus := '307 Temporary Rediect';
        308: RespStatus := '308 Permanent Rediect';
    else
        RespStatus := IntToStr(RespCode) + ' Unknown';
    end;
    Body := '<HTML><HEAD><TITLE>' + RespStatus + '</TITLE></HEAD>' +
            '<BODY><H1>' + RespStatus + '</H1>' + IcsCRLF +
            'You should be redirected automatically !<BR>' + IcsCRLF +
            '<A HREF="' + TextToHtmlText(NewLocation) + '">Or Click Here</A><BR>' + IcsCRLF +
            '</BODY></HTML>' + IcsCRLF;
  { V9.5 allow Body to be customised }
    if Assigned(FCustomErrorBody) then
        FCustomErrorBody(Self, RespCode, NewLocation, Body);
    if (RespCode <> 302) or (Pos (FRequestProtocol, NewLocation) <> 1) then
        FKeepAlive := False ;  { close connection, might be different host or protocol }
    SendHeader(FVersion + ' ' + RespStatus + IcsCRLF +
               'Location: ' + NewLocation + IcsCRLF +
               'Content-Type: text/plain' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               ExtraHdrs +
               IcsCRLF);
    FAnswerStatus := RespCode;
    if FSendType = httpSendHead then    { redirection will fail for HEAD? }
        Send(nil, 0)
    else
        SendStr(Body);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ As its name implies...                                                    }
procedure THttpConnection.ProcessRequest;
var
    Handled : Boolean;
{$IFDEF USE_SSL}
    I, J, TotHosts, NewIdx, MLIndx: integer;
{$ENDIF}
    NewURL: String;
begin
//  FRequestMethod := httpMethodNone;   { V8.08 keep method as literal }   { V9.6 prevously set, don't corrupt it }
    if FKeepAlive and (FKeepAliveTimeSec > 0) then
        FKeepAlive := FMaxRequestsKeepAlive > 0;

  { V8.48 see if checking Host: against IcsHosts, should have already
    been done using SSL server name indication, or bind address/port,
    but Host: is the preferred choice }
{$IFDEF USE_SSL}
    if FServer.WSocketServer is TSslWSocketServer then begin
        TotHosts := TCustomSslHttpServer(FServer).IcsHosts.Count;
        MLIndx := FServer.WSocketServer.MultiListenIndex;
        if (TotHosts > 0) and (FRequestHostName <> '') then begin
            NewIdx := -1;
            for I := 0 to TotHosts - 1 do begin
                with TCustomSslHttpServer(FServer).IcsHosts [I] do begin
                    if ((BindIdxNone = MLIndx) or  { V8.49 check port as well } (BindIdx2None = MLIndx) or
                                          (BindIdxSsl = MLIndx) or (BindIdx2Ssl = MLIndx)) and (HostNameTot > 0) then begin
                        for J := 0 to HostNameTot - 1 do begin
                            if ((HostNames [J] = '*') or (HostNames [J] = FRequestHostName)) then begin
                                NewIdx := I;
                                break ;
                            end;
                        end;
                    end;
                end;
            end;
            if NewIdx >= 0 then begin
                Self.FIcsHostIdx := NewIdx;

             { V9.6 new debug logging }
                if (wsdlogAccept in FServer.WSDebugOptions) then begin
                    DebugDisplay('Server Host ' + IntToStr(NewIdx + 1) + ' - ' + TCustomSslHttpServer(FServer).IcsHosts [NewIdx].HostTag);
                end;
            end;

       { V8.45 change directories to host site, if found }
            if FIcsHostIdx >= 0 then begin
                with TCustomSslHttpServer(FServer).IcsHosts[FIcsHostIdx] do begin
                    Self.FDocDir := WebDocDir;
                    Self.FTemplateDir := WebTemplDir;
                    Self.FDefaultDoc := WebDefDoc;
                    Self.FHostTag := HostTag;
                    Self.FWebLogDir := WebLogDir;
                    Self.FWellKnownPath := WellKnownPath;      { V8.49 }
                    Self.FWebRedirectURL := WebRedirectURL;    { V8.49 }
                    Self.FWebRedirectStat := WebRedirectStat;  { V8.50 }
                    Self.FWebLogIdx := WebLogIdx;              { V8.60 }
                end;
            end;
        end;
    end;
{$ENDIF}

    TriggerBeforeProcessRequest;

  { check for well-known directory, which we treat outside the normal web root }
    if (FRequestMethod = httpMethodGet) and (FWellKnownPath <> '') then begin             { V9.6 }
        if Pos (WellKnownDirStr, IcsLowercase(FPath)) >= 1 then begin  { V8.65 allow for absolute Path }
            FDocument := FWellKnownPath + Copy(FPath, Length(WellKnownDirStr), 9999);
            ProcessWellKnownDir;
            FKeepAlive := False;
            CloseDelayed;
            Exit;
        end;
    end;

  { build document file name, removing any ../  }
    if FPath = '/' then
        FDocument := FDocDir
    else if (FPath <> '') and (FPath[1] = '/') then
        FDocument := IcsAbsolutisePath(FDocDir + SrvURLDecode(AdjustOSPathDelimiters(FPath)))
    else
        FDocument := IcsAbsolutisePath(FDocDir + PathDelim + SrvURLDecode(AdjustOSPathDelimiters(FPath)));

  { check path is within the base document directory, and not adjusted to c:\ or something dangerous }
    if Length(FDocument) < Length(FDocDir) then
        FOutsideFlag := True
    else if Length(FDocument) > Length(FDocDir) then
        FOutsideFlag := not SameFileName(Copy(FDocument, 1, Length(FDocDir) + 1), FDocDir + PathDelim)
    else
        FOutsideFlag := not SameFileName(FDocument + PathDelim, FDocDir + PathDelim);

  { Check for default document }
    if (Length(FDocument) > 0) and (FDocument[Length(FDocument)] = PathDelim) and (FileExists(FDocument + FDefaultDoc)) then
        FDocument := FDocument + FDefaultDoc

  { V9.2 no trailing path delim, 301 redirect with delimiter so browser knows it is needed to find default doc }
  { generally if page found, or with hoAddMissPath is page is virtual or template generated }
  { beware may be virtual page request to so real file, like demo.html for samples }
    else if IsDirectory(FDocument) and ((FileExists(FDocument + PathDelim + FDefaultDoc) or (hoAddMissPath in FOptions))) then begin
        if (Length(Path) = 0) or ((Length(Path) > 0) and (Path[Length(Path)] <> '/')) then begin  { V9.3 avoid repeated redirection, adding /// }
            NewURL := FRequestProtocol + '://' + FRequestHost + FPath + '/';
            if FParams <> '' then
                NewURL := NewURL + '?' + FParams;
            AnswerRedirect(301, NewURL);
            Exit;
        end;
        FDocument := FDocument + PathDelim + FDefaultDoc;
    end;

{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    AuthCheckAuthenticated;    { checks if path or command required authentication, set WebDAVAcc=webdavWrite for WebDAV }
{$ENDIF}

{ V9.6 simplifed }
    if FRequestMethod = httpMethodGet then
        ProcessGet
    else if FRequestMethod = httpMethodPost then
        ProcessPost
    else if FRequestMethod = httpMethodHead then
        ProcessHead
    else if (FRequestMethod = httpMethodOptions) and (hoAllowOptions in FOptions) then   { V8.08 }
        ProcessOptions
    else if (FRequestMethod = httpMethodPut) and (hoAllowPut in FOptions) then    { V8.08 }
        ProcessPut
    else if (FRequestMethod = httpMethodDelete) and (hoAllowDelete in FOptions) then  { V8.08 }
        ProcessDelete
    else if (FRequestMethod = httpMethodTrace) and (hoAllowTrace in FOptions) then    { V8.08 }
        ProcessTrace
    else if (FRequestMethod = httpMethodPatch) and (hoAllowPatch in FOptions) then    { V8.08 }
        ProcessPatch
    else if (FRequestMethod = httpMethodConnect) and (hoAllowConnect in FOptions) then   { V8.08 }
        ProcessConnect
    else if (FRequestMethod = httpMethodPropFind) and (hoAllowPropFind in FOptions) then  { V9.6 WebDAV }
        ProcessPropFind
    else if (FRequestMethod = httpMethodMkCol) and (hoAllowMkCol in FOptions) then        { V9.6 WebDAV }
        ProcessMkCol
    else if (FRequestMethod = httpMethodCopy) and (hoAllowCopy in FOptions) then          { V9.6 WebDAV }
        ProcessCopy
    else if (FRequestMethod = httpMethodMove) and (hoAllowMove in FOptions) then          { V9.6 WebDAV }
        ProcessMove
    else if (FRequestMethod = httpMethodPropPatch) and (hoAllowPropPatch in FOptions) then  { V9.6 WebDAV }
        ProcessPropPatch
    else if (FRequestMethod = httpMethodLock) and (hoAllowLock in FOptions) then          { V9.6 WebDAV }
        ProcessLock
    else if (FRequestMethod = httpMethodUnlock) and (hoAllowUnlock in FOptions) then      { V9.6 WebDAV }
         ProcessUnlock
    else if (FRequestMethod = httpMethodQuery) and (hoAllowQuery in FOptions) then       { V9.8 new Query verb }
         ProcessQuery
    else begin
        Handled := False;
        if (wsdlogErrs in FServer.WSDebugOptions) then begin
            DebugDisplay('! Unsupported verb: ' + FMethod);
        end;
        TriggerUnknownRequestMethod(Handled); { V7.29 }
        if NOT Handled then begin
            { If we receive an unknown method/request we have to   }
            { close the connection, otherwise we may receive junk  }
            { data we cannot handle properly.                V7.45 }
            FKeepAlive := False;    { V7.45 }
            Answer501;   { 07/03/2005 was Answer404 }
            CloseDelayed;           { V7.45 }
        end;
    end;
    TriggerBeforeAnswer;  { V7.19 }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.Receive(Buffer: TWSocketData; BufferSize: Integer): Integer;             { V7.30 }
begin
    if FState = hcPostedData then begin
        Result := inherited Receive(Buffer, Min(FPostCounter, BufferSize));
        if Result > 0 then
           Dec(FPostCounter, Result);
        if FPostCounter <= 0 then begin
           LineMode        := TRUE;
           FState          := hcRequest;
           FPostCounter    := 0;
        end;
    end
    else
        Result := inherited Receive(Buffer, BufferSize);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerGetDocument(var Flags : THttpGetFlag);
begin
    if Assigned(FOnGetDocument) then
        FOnGetDocument(Self, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerHeadDocument(var Flags : THttpGetFlag);
begin
    if Assigned(FOnHeadDocument) then
        FOnHeadDocument(Self, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerPostDocument(var Flags : THttpGetFlag);
begin
    if Assigned(FOnPostDocument) then
        FOnPostDocument(Self, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerOptionsDocument(var Flags : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnOptionsDocument) then
        FOnOptionsDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerPutDocument(var Flags : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnPutDocument) then
        FOnPutDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerDeleteDocument(var Flags : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnDeleteDocument) then
        FOnDeleteDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerTraceDocument(var Flags : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnTraceDocument) then
        FOnTraceDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerPatchDocument(var Flags : THttpGetFlag);      { V8.08 }
begin
    if Assigned(FOnPatchDocument) then
        FOnPatchDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerConnectDocument(var Flags : THttpGetFlag);    { V8.08 }
begin
    if Assigned(FOnConnectDocument) then
        FOnConnectDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerQueryDocument(var Flags : THttpGetFlag);      { V9.8 }
begin
    if Assigned(FOnQueryDocument) then
        FOnQueryDocument(Self, Flags);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerHttpRequestDone;
begin
    if Assigned(FOnHttpRequestDone) then
        FOnHttpRequestDone(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerBeforeProcessRequest;  {DAVID}
begin
    if Assigned(FOnBeforeProcessRequest) then
        FOnBeforeProcessRequest(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerBeforeAnswer;  { V7.19 }
begin
    if Assigned(FOnBeforeAnswer) then
        FOnBeforeAnswer(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerAfterAnswer;  { V7.19 }
begin
    if Assigned(FOnAfterAnswer) then
        FOnAfterAnswer(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerContentEncode
     (out ContentEncoding: string;
      var Handled: Boolean);  { V7.20 }
begin
    if Assigned(FOnContentEncode) then
        FOnContentEncode(Self, ContentEncoding, Handled);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerUnknownRequestMethod(var Handled : Boolean); { V2.29 }
begin
    Handled := FALSE;
    if Assigned(FOnUnknownRequestMethod) then
        FOnUnknownRequestMethod(Self, Handled);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerMimeContentType(const FileName: string; var ContentType: string); { V7.41 }
begin
    if Assigned(FOnMimeContentType) then
        FOnMimeContentType(Self, FileName, ContentType);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerContEncoded;  { V7.20 }
begin
    if Assigned(FOnContEncoded) then
        FOnContEncoded(Self);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerWellKnownDir(const Path: string; var BodyStr: string);   { V8.49 }
begin
    if Assigned(FOnWellKnownDir) then
        FOnWellKnownDir(Self, Path, BodyStr);
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerWebDAVEvent(HttpMethod: THttpMethod; var Flags: THttpGetFlag); { 9.6 }
begin
    if Assigned(FOnWebDAVConn) then
        FOnWebDAVConn(Self, HttpMethod, Flags);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ handle all methods that don't send any body content }
procedure THttpConnection.ProcessGetHeadDel; { V8.08 }
var
    Flags      : THttpGetFlag;
    TempStream : TFileStream;
    OK         : Boolean;
begin
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    if not FAuthenticated then
        Flags := hg401
    else
{$ENDIF}
    if FOutsideFlag and (not (hoAllowOutsideRoot in FOptions)) then
        Flags := hg403
    else if (hoAllowDirList in FOptions) and IsDirectory(FDocument) and NOT (FRequestMethod = httpMethodDelete) then
        Flags := hgSendDirList
    else
        Flags := hgSendDoc;

    if (FRequestMethod = httpMethodHead) then begin
        FSendType := httpSendHead;
        TriggerHeadDocument(Flags);
    end
    else if (FRequestMethod = httpMethodGet) then
        TriggerGetDocument(Flags)
    else if (FRequestMethod = httpMethodDelete) then
        TriggerDeleteDocument(Flags)
    else begin
        Answer501;
        Exit;
    end;

    case Flags of
    hg400:                             { V7.30 }
        begin
            if FKeepAlive = FALSE then
                PrepareGraceFullShutDown;
            Answer400;
        end;
    hg401:
        begin
            if FKeepAlive = FALSE then {Bjornar}
                PrepareGraceFullShutDown;
            Answer401;
        end;
    hg403:
        begin
            if FKeepAlive = FALSE then {Bjornar}
                PrepareGraceFullShutDown;
            Answer403;
        end;
    hg404:
        begin
            if FKeepAlive = FALSE then {Bjornar}
                PrepareGraceFullShutDown;
            Answer404;
        end;
    hgSendDoc:
        begin
            OK := FALSE;
            try
                if not FileExists(FDocument) then begin
                    { File not found }
                    if FKeepAlive = FALSE then {Bjornar}
                        PrepareGraceFullShutDown;
                    Answer404;
                end
                else begin
                    { see if we have access to file, but don't read it yet }
                    TempStream := TFileStream.Create(FDocument, fmOpenRead + fmShareDenyWrite);
                    TempStream.Free;   { V8.71 }
                    OK := TRUE;
                end;
            except
                if FKeepAlive = FALSE then {Bjornar}
                    PrepareGraceFullShutDown;
                Answer404;
            end;
            if OK then
                SendDocument(FSendType)
        end;
    hgSendStream:
        SendStream;
    hgSendDirList:
        SendDirList(FSendType);
    hgWillSendMySelf:
        { Nothing to do };
    else
        if FKeepAlive = FALSE then {Bjornar}
            CloseDelayed;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ handle well-known directory separately to main root }
procedure THttpConnection.ProcessWellKnownDir;  { V8.49 }
var
    BodyStr    : string;
    TempStream : TFileStream;
    OK         : Boolean;
    I          : Integer;
begin

  { V8.65 look for absolute URL sent by proxy }
    I := Pos('://', FPath);
    if (I = 4) or (I = 5) then begin
        FPath := Copy(FPath, I + 3, 99999);  // strip http://
        I := Pos('/', FPath);  // start of path
        if (I > 1) then
            FPath := Copy(FPath, I, 999999);  // strip host
    end;

  { application event may generate a body to send }
    BodyStr := '';
    if Assigned(onWellKnownDir) then begin
        TriggerWellKnownDir(FPath, BodyStr);
    end;

  { nothing returned, look for file }
    if BodyStr = '' then begin
        OK := FALSE;
        try
            if not FileExists(FDocument) then begin
                { File not found }
                PrepareGraceFullShutDown;
                Answer404;
            end
            else begin
                { see if we have access to file, but don't read it yet }
                TempStream := TFileStream.Create(FDocument, fmOpenRead + fmShareDenyWrite);
                TempStream.Free;   { V8.71 }
                OK := TRUE;
            end;
        except
            PrepareGraceFullShutDown;
            Answer404;
        end;
        if OK then begin
            SendDocument('');  // no custom headers
            Exit;
        end;
    end;

  { create page and send it }
    if BodyStr = '' then
        Answer404
    else begin
        SendHeader(FVersion + ' 200 OK' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(BodyStr)) + IcsCRLF +
               IcsCRLF);
        FAnswerStatus := 200;
        if FSendType = httpSendHead then
            Send(nil, 0)
        else
            SendStr(BodyStr);
    end;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.5 note now also handles GET and DELETE if they have content }
procedure THttpConnection.ProcessPostPutPat;  { V8.08 }
var
    Flags : THttpGetFlag;
begin
    { POST and no content-length received, we treat this as "bad request"     }
    { and don't pass it to the component user.                                }
    if (not FRequestHasContentLength) or (FRequestContentLength < 0) then begin
        { HTTP/1.0
          A valid Content-Length is required on all HTTP/1.0 POST requests.
          An HTTP/1.0 server should respond with a 400 (bad request) message
          if it cannot determine the length of the request message's content.

          HTTP/1.1
          The presence of a message-body in a request is signaled by the
          inclusion of a Content-Length or Transfer-Encoding header field in
          the request's message-headers.
          For compatibility with HTTP/1.0 applications, HTTP/1.1 requests
          containing a message-body MUST include a valid Content-Length header
          field unless the server is known to be HTTP/1.1 compliant. If a
          request contains a message-body and a Content-Length is not given,
          the server SHOULD respond with 400 (bad request) if it cannot
          determine the length of the message, or with 411 (length required)
          if it wishes to insist on receiving a valid Content-Length.
          Currently we act as a HTTP/1.0 server. }
        if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
            DebugDisplay('= No content for request that requires it, 400');

        FKeepAlive := FALSE;
        Answer400;
        { We close the connection non-gracefully otherwise we might receive
          data we cannot handle properly. }
        CloseDelayed;
        Exit;
    end;

{$IFNDEF NO_AUTHENTICATION_SUPPORT}
    if not FAuthenticated then
        Flags := hg401
    else
{$ENDIF}
    if FOutsideFlag and (not (hoAllowOutsideRoot in FOptions)) then
        Flags := hg403
    else
        Flags := hgSendDoc;          { V9.2 must try to send something, was hg404 }

    FAcceptPostedData := FALSE;
    if (FRequestMethod = httpMethodPost) then
        TriggerPostDocument(Flags)
    else if (FRequestMethod = httpMethodPut) then
        TriggerPutDocument(Flags)
    else if (FRequestMethod = httpMethodPatch) then
        TriggerPatchDocument(Flags)
    else if (FRequestMethod = httpMethodGet) then          { V9.5 handle GET and DELETE }
        TriggerGetDocument(Flags)
    else if (FRequestMethod = httpMethodDelete) then
        TriggerDeleteDocument(Flags)
    else if (FRequestMethod = httpMethodQuery) then       { V9.8 }
        TriggerQueryDocument(Flags);

    if (not FAcceptPostedData) and (FRequestContentLength > 0) then begin { V7.30 }
    { The component user doesn't handle posted data.               }
    { Turn LineMode off if RequestContentLength > 0, we'll turn it }
    { back on again in our overridden method Receive.              }
        if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
            DebugDisplay('= Waiting for content');
        LineMode     := FALSE;
        FPostCounter := FRequestContentLength;
    end
    else begin
        FPostCounter := 0;
        if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
            DebugDisplay('= Server does not have handler for content for this request');
    end;

    case Flags of
    hg400:
        begin
            FKeepAlive := FALSE;
            Answer400;
            CloseDelayed;
        end;                                                              {/V7.30 }
    hg401:
        begin
            if FKeepAlive = FALSE then {Bjornar}
                PrepareGraceFullShutDown;
            Answer401;
        end;
    hg403:
        begin
            if FKeepAlive = FALSE then {Bjornar}
                PrepareGraceFullShutDown;
            Answer403;
        end;
    hg404:
        begin
            if FKeepAlive = FALSE then {Bjornar}
                PrepareGraceFullShutDown;
            Answer404;
        end;
    hgAcceptData:
        FAcceptPostedData := TRUE;
    else
        if FKeepAlive = FALSE then {Bjornar}
            CloseDelayed;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessPost;
begin
    FRequestMethod := httpMethodPost;
    ProcessPostPutPat;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessHead;
begin
    FRequestMethod := httpMethodHead;
    ProcessGetHeadDel;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessGet;
begin
    FRequestMethod := httpMethodGet;
    if FRequestHasContentLength then   { V9.5 allow upload content }
        ProcessPostPutPat
    else
        ProcessGetHeadDel;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessQuery;          { V9.8 }
begin
    FRequestMethod := httpMethodQuery;
    if FRequestHasContentLength then   { V9.5 allow upload content }
        ProcessPostPutPat
    else
        ProcessGetHeadDel;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessOptions;      { V8.08 }
var
    Flags      : THttpGetFlag;
    Header     : string;
begin
//    FSendType := httpSendHead;  { don't want a body }
    Flags := hgSendDoc;
    TriggerOptionsDocument(Flags);
    case Flags of
    hg400:
        begin
            if FKeepAlive = FALSE then
                PrepareGraceFullShutDown;
            Answer400;
        end;
    hg501:     { not implemented }
        begin
            Answer501;
         //   CloseDelayed;
        end;
    hgSendDoc:   { note - ignore document argument and always returning server info }
        begin
        { Create Header }
            Header := FVersion + ' 200 OK' + IcsCRLF + 'Content-Length: 0' + IcsCRLF;
            if FServer.FServerHeader <> '' then
                Header := Header + FServer.FServerHeader + IcsCRLF;
            if (FWebDAVAcc >= webdavRead) then
                Header := Header + 'DAV: 1' + IcsCRLF;    { V9.6 may 1,2,3, not sure what commands/level }
            Header := Header + 'Allow: HEAD, GET, POST';
            if (hoAllowOptions in FOptions) then
                Header := Header + ', OPTIONS';
            if (hoAllowPut in FOptions) then
                Header := Header + ', PUT';
            if (hoAllowDelete in FOptions) then
                Header := Header + ', DELETE';
            if (hoAllowTrace in FOptions) then
                Header := Header + ', TRACE';
            if (hoAllowPatch in FOptions) then
                Header := Header + ', PATCH';
            if (hoAllowConnect in FOptions) then
                Header := Header + ', CONNECT';
            if (hoAllowQuery in FOptions) then
                Header := Header + ', QUERY';        { V9.8 }

         { V9.6 WebDAV verbs, only if authenticated already }
            if (FWebDAVAcc >= webdavRead) then begin
                if (hoAllowPropFind in FOptions) then
                    Header := Header + ', PROPFIND';
            end;
            if (FWebDAVAcc >= webdavWrite) then begin
                if (hoAllowMkCol in FOptions) then
                    Header := Header + ', MKCOL';
                if (hoAllowCopy in FOptions) then
                    Header := Header + ', COPY';
                if (hoAllowMove in FOptions) then
                    Header := Header + ', MOVE';
                if (hoAllowPropPatch in FOptions) then
                    Header := Header + ', PROPPATCH';
                if (hoAllowLock in FOptions) then
                    Header := Header + ', LOCK';
                 if (hoAllowUnLock in FOptions) then
                    Header := Header + ', UNLOCK';
            end;
            Header := Header + IcsCRLF;  // end of verbs list
            Header := Header + 'Date: ' + RFC1123_Date(IcsDateTimeToUTC (Now)) + ' GMT' + IcsCRLF;
            Header := Header + IcsCRLF;  { blank line end of header }
            FAnswerStatus := 200;
            SendHeader(Header);
            FDocSize := 0;
            Send(nil, 0);
        end;
    hgWillSendMySelf:
        { Nothing to do };
    else
        if FKeepAlive = FALSE then
            CloseDelayed;
    end;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessPut;      { V8.08 }
begin
    FRequestMethod := httpMethodPut;
    ProcessPostPutPat;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessDelete;      { V8.08 }
begin
    FRequestMethod := httpMethodDelete;
    if FRequestHasContentLength then   { V9.5 allow upload content }
        ProcessPostPutPat
    else
        ProcessGetHeadDel;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessTrace;      { V8.08 }
var
    Flags        : THttpGetFlag;
    Header, Body : string;
begin
    Flags := hgSendDoc;
    TriggerTraceDocument(Flags);
    case Flags of
    hg501:     { not implemented }
        begin
            Answer501;
            CloseDelayed;
        end;
    hgSendDoc:   { note - ignore document argument and always returning server info }
        begin
         { Body is all request lines, no HTML wrapper }
            Body := FMethod + ' ' + FPath;
            if (FParams <> '') then Body := Body + '?' + FParams;
            Body := Body + ' ' + FVersion + IcsCRLF +
             FRequestHeader.Text + IcsCRLF;
        { Create Header }
            Header := FVersion + ' 200 OK' + IcsCRLF +
               'Content-Type: message/http' + IcsCRLF +
               'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
               GetKeepAliveHdrLines + IcsCRLF;
            FAnswerStatus := 200;
            SendHeader(Header);
            SendStr(Body);
        end;
    hgWillSendMySelf:
        { Nothing to do };
    else
        if FKeepAlive = FALSE then
            CloseDelayed;
    end;

end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessPatch;      { V8.08 }
begin
    FRequestMethod := httpMethodPatch;
    ProcessPostPutPat;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ CONNECT is normally used by proxy servers, not web servers }
procedure THttpConnection.ProcessConnect;    { V8.08 }
var
    Flags      : THttpGetFlag;
begin
    Flags := hg501;
    TriggerConnectDocument(Flags);
    case Flags of
    hg501:     { not implemented }
        begin
            Answer501;
            CloseDelayed;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessPropFind;     { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodPropFind;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessMkCol;       { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodMkCol;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessCopy;       { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodCopy;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessMove;       { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodMove;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessPropPatch;    { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodPropPatch;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessLock;         { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodLock;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.ProcessUnlock;       { V9.6 WebDAV }
begin
    FRequestMethod := httpMethodPropFind;
    ProcessWebDAV;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection. ProcessWebDAV;      { V9.6 WebDAV }
var
    Flags: THttpGetFlag;
begin
    if (FRequestXML <> '') and  (wsdlogHdr in FServer.WSDebugOptions) then begin
        DebugDisplay('< ' + FRequestXML);
    end;
    if NOT FAuthenticated or (FWebDAVAcc = webdavNone) then
        Flags := hg401
    else begin
        Flags := hg400;

     { only if authenticated already, must do something and set Flags to hgWillSendMySelf }
        TriggerWebDAVEvent(FRequestMethod, Flags);

    { we can handle PROPFIND oureselves }
        if (FRequestMethod = httpMethodPropFind) and (Flags = hg400) then begin
            SendPropFindDir(Flags);
        end;
    end;

    case Flags of
    hg400:
        begin
            if FKeepAlive = FALSE then
                PrepareGraceFullShutDown;
            Answer400;
        end;
    hg401:
        begin
            if FKeepAlive = FALSE then
                PrepareGraceFullShutDown;
            Answer401;
        end;
    hg403:
        begin
            if FKeepAlive = FALSE then
                PrepareGraceFullShutDown;
            Answer403;
        end;
    hg404:
        begin
            if FKeepAlive = FALSE then
                PrepareGraceFullShutDown;
            Answer404;
        end;
    hgWillSendMySelf:
        { Nothing to do };
    else
        if FKeepAlive = FALSE then
            CloseDelayed;
    end;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ SendDocument will send FDocument file to remote client, build header and  }
{ sending data (if required)                                                }
procedure THttpConnection.SendDocument(SendType : THttpSendType);
begin
   FSendType := SendType; // overwrites the default value for this request
   SendDocument('');
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SendDocument(
    SendType            : THttpSendType;
    const CustomHeaders : String);
begin
    FSendType := SendType; // overwrites the default value for this request
    SendDocument(CustomHeaders);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SendDocument;
begin
    SendDocument('');
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SendDocument(const CustomHeaders : String);
var
    Header          : String;
    NewDocStream    : TStream;
    ProtoNumber     : Integer;
    CompleteDocSize : THttpRangeInt;
    SyntaxError     : Boolean;
    ContEncoderHdr  : String ;      { V7.20 }
    DateStr         : String;       { V8.68 }
    FileExt         : String;       { V9.5 }
begin
    ProtoNumber := 200;
    if (wsdlogHdr in FServer.WSDebugOptions) then      { V9.8 debug logging }
         DebugDisplay('= SendDocument, File: ' + FDocument);
    FLastModified := IcsFileUtcModified(FDocument);
    DateStr := '';
    if FLastModified <> 0 then
        DateStr := RFC1123_Date(IcsDateTimeToUTC (FLastModified)) + ' GMT';      { V8.68, V8.69 UTC }
    CompleteDocSize := IcsGetFileSize(FDocument);  { V8.68 get size before opening stream }
    if CompleteDocSize < 0 then begin              { V8.68 nothing to open }
        Answer404;
        Exit;
    end;

    if Assigned (FServer.MimeTypesList) then
        FAnswerContentType := FServer.MimeTypesList.TypeFromFile(FDocument)  { V7.46 }
    else
        FAnswerContentType := DocumentToContentType(FDocument);
    TriggerMimeContentType(FDocument, FAnswerContentType);  { V7.41 allow content type to be changed }

 { V8.68 see if comparing old entity tag with latest version to skip download, we may
   have been given a comma list of etags }
    BuildETag(CompleteDocSize);

 { resuming a download with a range, check original has not changed other ignore range and return whole file }
    if RequestRangeValues.Valid and (FRequestIfRange <> '') and (FEntityTag <> '') then begin
        if NOT ((Pos(FEntityTag, FRequestIfRange) > 0) or
                   (Pos(DateStr, FRequestIfRange) > 0)) then
                                         RequestRangeValues.Clear;
    end;
    if (FRequestIfNoneMatch <> '') and (FEntityTag <> '') then begin
        if (Pos(FEntityTag, FRequestIfNoneMatch) > 0) then begin { etag found, skip }
            Answer304;
            Exit;
         end;
    end;
    if (FRequestIfMatch <> '') and (FEntityTag <> '') then begin
        if (Pos(FEntityTag, FRequestIfMatch) = 0) then begin   { no etag found, skip }
            Answer304;
            Exit;
         end;
    end;
  { V8.11 see if document actually changed, within one second of time stamp, V8.68 RequestIfNoneMatch has precidence }
    if (NOT (hoIgnoreIfModSince in FOptions)) and (FLastModified <> 0) and
             (FRequestIfModSince >= (FLastModified - (1 / SecsPerDay))) then begin
        Answer304;
        Exit;
    end;

    FDocStream.Free;
    FDocStream := TIcsBufferedFileStream.Create(FDocument, fmOpenRead + fmShareDenyWrite, MAX_BUFSIZE); { V7.40 faster }

//    CompleteDocSize := FDocStream.Size;  { V8.68 got it earlier }
    {ANDREAS Create the virtual 'byte-range-doc-stream', if we are ask for ranges}
    if RequestRangeValues.Valid then begin
        { NewDocStream will now be the owner of FDocStream -> don't free FDocStream }
        NewDocStream := RequestRangeValues.CreateRangeStream(FDocStream,
                             FAnswerContentType, CompleteDocSize, SyntaxError);
        if Assigned(NewDocStream) then begin
            FDocStream := NewDocStream;
            FDocStream.Position := 0;
            ProtoNumber := 206;
        end
        else begin
            if SyntaxError then
            { Ignore the content range header and send entire document in case }
            { of syntactically invalid byte-range-set                          }
                FDocStream.Position := 0
            else begin
            { Answer 416 Request range not satisfiable                      }
                FDocStream.Free;
                FDocStream := nil;
                if not FKeepAlive then
                    PrepareGraceFullShutDown;
                Answer416;
                Exit;
            end;
        end;
    end;

    FDataSent := 0;       { will be incremented after each send part of data }
    FDocSize := FDocStream.Size;
    OnDataSent := ConnectionDataSent;
    ContEncoderHdr := '';  { V7.20 }

    { V7.44  Do not skip compression on HEAD requests, we need the correct size }

    { V7.21 are we allowed to compress content }
    if CheckContentEncoding(FAnswerContentType) then begin
        ContEncoderHdr := DoContentEncoding;   { V7.21 do it, returning new header }
        FDocSize := FDocStream.Size;           { stream is now smaller, we hope }
    end;

    { Create Header }
    {ANDREAS Create Header for the several protocols}
    Header := CreateHttpHeader(FVersion, ProtoNumber, FAnswerContentType,
                               RequestRangeValues, FDocSize, CompleteDocSize);
    FAnswerStatus := ProtoNumber;   { V7.19 }
    if DateStr <> '' then
        Header := Header +  'Last-Modified: ' + DateStr + IcsCRLF;
    if ContEncoderHdr <> '' then
        Header := Header + ContEncoderHdr;  { V7.20 }
    if FEntityTag <> '' then
        Header := Header + 'ETag: ' + FEntityTag + IcsCRLF;                  { V8.68 }
    if (hoSendServerHdr in FOptions) and (FServer.FServerHeader <> '') then
        Header := Header + FServer.FServerHeader + IcsCRLF;    { V8.08 }

 { V9.5 see if sending Content-Disposition: attachment; filename="myname.exe" header }
 { should cause browser to display 'Save As' dialog }
    if (hoContDispHdr in FOptions) and (FServer.AttachmentTypes <> '') then begin
        FileExt := ExtractFileExt(LowerCase(FDocument));
        if Pos (FileExt, FServer.AttachmentTypes) > 0 then
            Header := Header +  'Content-Disposition: attachment; ' +
                      IcsEncHttp2Params('filename', ExtractFileName(FDocument)) + IcsCRLF; { encodes UTF8/percent for unicode }
    end;

 { add custom headers and keep-alive }
    if CustomHeaders <> '' then
        Header := Header + CustomHeaders;   { V7.29 }
    Header := Header + GetKeepAliveHdrLines + IcsCRLF;
    SendHeader(Header);
    if FSendType = httpSendHead then begin   { V7.44 }
        FDocSize := 0;                       { V7.44 }
        Send(nil, 0);                        { V7.44 }
    end
    else
        SendStream;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SendHeader(Header : String);
begin
    if FServer.PersistentHeader <> '' then  { v7.29 }
         Insert(FServer.PersistentHeader, Header, Length(Header) - 1);{ v7.29 }
    PutStringInSendBuffer(Header);
    if Assigned(OnRespHdr) then
        OnRespHdr(Self, Header);                         { V8.69 header we sent do it can be logged }

 { V9.6 new debug logging }
    if (wsdlogHdr in FServer.WSDebugOptions) then begin
        DebugDisplay('> ' + StringReplace(Header, IcsCRLF, IcsCRLF + '> ', [rfReplaceAll]));
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SendStream;
begin
    if not Assigned(FDocStream) then begin
        { No Stream to send ! Create an empty one to continue }
        FDocStream := TMemoryStream.Create;
    end
    else
        FDocStream.Position := 0; { V8.67 Seek(0, 0);        { Go to start of stream           }
    FDocSize   := FDocStream.Size;    { Should it take care of ranges ? }
    FDataSent  := 0;
    OnDataSent := ConnectionDataSent;

    if FDocSize > 0 then begin  { 7.44 }
        { V7.40 speed up larger files by increasing buffer sizes }
        if (FDocSize > FSndBlkSize) and (FServer.MaxBlkSize > FSndBlkSize) then begin
            if (FDocSize >= FServer.MaxBlkSize) then
                SetSndBlkSize (FServer.MaxBlkSize)
            else
                SetSndBlkSize (FDocSize);  { don't need a max buffer }
        end;
        if SocketSndBufSize < FSndBlkSize then
            SocketSndBufSize := FSndBlkSize; { socket TCP buffer }
        if not Assigned(FDocBuf) then
            GetMem(FDocBuf, FSndBlkSize);
    end;

{ V9.6 debug logging }
    if (wsdlogHdr in FServer.WSDebugOptions) then begin
        DebugDisplay('= Start send body, size: ' + IcsIntToKbyte(FDocSize));
    end;

{ event is called repeatedly until stream is all sent }
    ConnectionDataSent(Self, 0);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.TriggerFilterDirEntry(DirEntry: THttpDirEntry);
begin
    if Assigned(FOnFilterDirEntry) then
        FOnFilterDirEntry(Self, Self, DirEntry);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpConnection.FormatDirEntry(F : THttpDirEntry) : String;
var
    Attr             : String;
    Link             : String;
    SizeString       : String;
const
    StrMonth : array [1..12] of String =
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
begin
{$IFNDEF VER80}{$WARNINGS OFF}{$ENDIF}
    if F.VolumeID or
       (F.Name = '.') or
       (F.Name = '..') then begin
        { Ignore hidden files, volume ID, current and parent dir entries }
        Result := '';
        Exit;
    end;

    Attr := '-rw--';
    if F.Directory then begin
        Attr[1] := 'd';
        SizeString := '';
    end
    else
        SizeString := IntToStr(F.SizeLow);

    if F.ReadOnly then
        Attr[3] := '-';

    if F.SysFile then
        Attr[4] := 's';

    if F.Hidden then
        Attr[5] := 'h';

{$IFNDEF VER80}{$WARNINGS ON}{$ENDIF}

    if Path = '/' then
        Link := '/' + SrvUrlEncode(F.Name)
    else if Path[Length(Path)] = '/' then
        Link := Path + SrvUrlEncode(F.Name)
    else
        Link := Path + '/' + SrvUrlEncode(F.Name);

    Result := '<TD>' + Attr + '</TD>' +
              '<TD ALIGN="right">' + SizeString + '</TD>' +
              '<TD WIDTH="10"></TD>' +
              '<TD>' + Format('%s %2.2d, %4.4d', [StrMonth[F.Month], F.Day, F.Year]) + '</TD>' +
              '<TD WIDTH="10"></TD>' +
              '<TD>' + Format('%2.2d:%2.2d:%2.2d',  [F.Hour, F.Min, F.Sec])   + '</TD>' +
              '<TD WIDTH="10"></TD>' +
              '<TD><A HREF="' + Link + '">' +
              TextToHtmlText(F.Name) + '</A></TD>' + IcsCRLF;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ builds HTML page with file links for single directory }
function THttpConnection.BuildDirList : String;
var
    Status     : Integer;
    F          : TSearchRec;
    ParentDir  : String;
    DirList    : TStringList;
    FileList   : TStringList;
    Data       : THttpDirEntry;
    I          : Integer;
    Total      : Cardinal;
    TotalBytes : Int64;
  {$IFDEF POSIX}
    UT: tm;
  {$ENDIF}
begin
    { Create a list of all directories }
    DirList := TStringList.Create;
    Status  := FindFirst(Document + PathDelim + '*.*', faAnyFile, F);
    while Status = 0 do begin
        if ((F.Attr and faDirectory) <> 0) and
           //((F.Attr and faVolumeID)  =  0) and
           (F.Name <> '.') and
           (F.Name <> '..') then begin
            Data           := THttpDirEntry.Create;
            Data.Visible   := TRUE;
            Data.Name      := F.Name;
            Data.SizeLow   := LongWord(F.Size);
          {$IFDEF HAS_SEARCHREC_SIZE64}
            Data.SizeHigh  := F.Size shr 32;
          {$ELSE}
            Data.SizeHigh  := 0;
          {$ENDIF}
          {$IFDEF MSWINDOWS}
            Data.Day       := (IcsHiWord(F.Time) and $1F);
            Data.Month     := ((IcsHiWord(F.Time) shr 5) and $0F);
            Data.Year      := ((IcsHiWord(F.Time) shr 9) and $3F) + 1980;
            Data.Sec       := ((F.Time and $1F) shl 1);
            Data.Min       := ((F.Time shr 5) and $3F);
            Data.Hour      := ((F.Time shr 11) and $1F);
          {$ENDIF}
          {$IFDEF POSIX}
            localtime_r(F.Time, UT);
            Data.Year  := UT.tm_year + 1900;
            Data.Month := UT.tm_mon + 1;
            Data.Day   := UT.tm_mday;
            Data.Hour  := UT.tm_hour;
            Data.Min   := UT.tm_min;
            Data.Sec   := UT.tm_sec;
          {$ENDIF}
            Data.VolumeID  := FALSE; //((F.Attr and faVolumeID)  <> 0);
            Data.Directory := ((F.Attr and faDirectory) <> 0);
            Data.ReadOnly  := ((F.Attr and faReadOnly)  <> 0);
            Data.SysFile   := ((F.Attr and faSysFile)   <> 0);
            Data.Hidden    := ((F.Attr and faHidden)    <> 0);
            TriggerFilterDirEntry(Data);
            if Data.Visible then
                DirList.AddObject(Data.Name, Data)
            else
                Data.Free;
        end;
        Status  := FindNext(F);
    end;
    FindClose(F);
    DirList.Sort;

    { Create a list of all files }
    FileList := TStringList.Create;
    Status  := FindFirst(Document + PathDelim + '*.*', faAnyFile, F);
    while Status = 0 do begin
        if ((F.Attr and faDirectory) = 0) then begin
           //((F.Attr and faVolumeID)  = 0) then begin
            Data           := THttpDirEntry.Create;
            Data.Visible   := TRUE;
            Data.Name      := F.Name;
            Data.SizeLow   := LongWord(F.Size);
          {$IFDEF HAS_SEARCHREC_SIZE64}
            Data.SizeHigh  := F.Size shr 32;
          {$ELSE}
            Data.SizeHigh  := 0;
          {$ENDIF}
          {$IFDEF MSWINDOWS}
            Data.Day       := (IcsHiWord(F.Time) and $1F);
            Data.Month     := ((IcsHiWord(F.Time) shr 5) and $0F);
            Data.Year      := ((IcsHiWord(F.Time) shr 9) and $3F) + 1980;
            Data.Sec       := ((F.Time and $1F) shl 1);
            Data.Min       := ((F.Time shr 5) and $3F);
            Data.Hour      := ((F.Time shr 11) and $1F);
          {$ENDIF}
          {$IFDEF POSIX}
            localtime_r(F.Time, UT);
            Data.Year  := UT.tm_year + 1900;
            Data.Month := UT.tm_mon + 1;
            Data.Day   := UT.tm_mday;
            Data.Hour  := UT.tm_hour;
            Data.Min   := UT.tm_min;
            Data.Sec   := UT.tm_sec;
          {$ENDIF}
            Data.VolumeID  := FALSE; //((F.Attr and faVolumeID)  <> 0);
            Data.Directory := ((F.Attr and faDirectory) <> 0);
            Data.ReadOnly  := ((F.Attr and faReadOnly)  <> 0);
            Data.SysFile   := ((F.Attr and faSysFile)   <> 0);
            Data.Hidden    := ((F.Attr and faHidden)    <> 0);
            TriggerFilterDirEntry(Data);
            if Data.Visible then
                FileList.AddObject(Data.Name, Data)
            else
                Data.Free;
        end;
        Status  := FindNext(F);
    end;
    FindClose(F);
    FileList.Sort;

    Result   := '<HTML>' + IcsCRLF +
                '<HEAD>' + IcsCRLF +
                  '' + IcsCRLF +
                  '<STYLE TYPE="text/css">' + IcsCRLF +
                    '.dirline { font-family: arial; color: black; font-style: normal; }' + IcsCRLF +
                  '</STYLE>' + IcsCRLF +
                  '<TITLE>Directory List</TITLE>' + IcsCRLF +
                  //'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' + IcsCRLF +
                '</HEAD>' + IcsCRLF +
              '<BODY><P>Directory of ' +
    TextToHtmlText(DosPathToUnixPath(IcsAbsolutisePath(AdjustOSPathDelimiters(SrvUrlDecode(Path))))) +
                       ':</P>' + IcsCRLF +
              '<TABLE CLASS="dirline">' + IcsCRLF;
    if Path = '/' then
        ParentDir := ''
    else if Path[Length(Path)] = '/' then
        ParentDir := DosPathToUnixPath(ExtractFilePath(AdjustOSPathDelimiters(Copy(Path, 1, Length(Path) - 1))))
    else
        ParentDir := DosPathToUnixPath(ExtractFilePath(AdjustOSPathDelimiters(Path)));
    if (ParentDir <> '') and (ParentDir <> '/') then
        SetLength(ParentDir, Length(ParentDir) - 1);
    if ParentDir <> '' then
        Result  := Result + '<TR><TD><A HREF="' + ParentDir +
                         '">[To Parent Directrory]</A></TD></TR>';

    TotalBytes := 0;
    Total      := DirList.Count + FileList.Count;
    if Total <= 0 then
        Result := Result +'<TR><TD>No file</TD></TR>'
    else begin
        for I := 0 to DirList.Count - 1 do begin
            Data   := THttpDirEntry(DirList.Objects[I]);
            Result := Result + '<TR>' + FormatDirEntry(Data) + '</TR>' + IcsCRLF;
            DirList.Objects[I].Free;
        end;
        DirList.Free;

        for I := 0 to FileList.Count - 1 do begin
            Data       := THttpDirEntry(FileList.Objects[I]);
            Result     := Result + '<TR>' + FormatDirEntry(Data) +
                                   '</TR>' + IcsCRLF;
            TotalBytes := TotalBytes + (Data.SizeLow or Int64(Data.SizeHigh) shl 32);
            FileList.Objects[I].Free;
        end;
        FileList.Free;
        Result := Result + '<TR><TD COLSPAN="8">Total: ' +
                           IntToStr(Total)      + ' file(s), ' +
                           IntToStr(TotalBytes) + ' byte(s)</TD></TR>';
    end;

    Result := Result + '</TABLE></BODY></HTML>' + IcsCRLF;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpConnection.SendDirList(SendType : THttpSendType);
var
    Body      : String;
    Header    : String;
begin
    FDocStream.Free;
    FDocStream := nil;

    Body   := BuildDirList;
    Header := Version +  ' 200 OK' + IcsCRLF +
              'Content-Type: text/html' + IcsCRLF +
              'Content-Length: ' + IntToStr(Length(Body)) + IcsCRLF +
              'Pragma: no-cache' + IcsCRLF;
    if (hoSendServerHdr in FOptions) and (FServer.FServerHeader <> '') then
        Header := Header + FServer.FServerHeader + IcsCRLF;    { V8.08 }
    Header := Header + GetKeepAliveHdrLines + IcsCRLF;         { V9.6 }
    FAnswerStatus := 200;   { V7.19 }
    SendHeader(Header);       { V8.69 }
    FDocStream := TMemoryStream.Create;
    if SendType = httpSendDoc then
        StreamWriteStrA(FDocStream, Body);
    FDocStream.Position := 0; { V8.67 Seek(0, 0); }
    SendStream;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{FTP MLSD command, same format for MSLT for a single file
much nice than LIST since it has a proper date with year, and seconds, and is much easier to parse
size=0;type=cdir;perm=fdelcmp;create=20020616151738;modify=20031002125810; .
size=0;type=pdir;perm=fdelcmp;create=20020616151738;modify=20031002125810; ..
size=17199;type=file;perm=fdrwa;create=20030616152030;modify=20031001190100; 00master.zip
size=182928;type=file;perm=fdrwa;create=20030922195127;modify=20030922190600; 12=page-004394.zip
size=0;type=dir;perm=fdelcmp;create=20020805160304;modify=20031002133003; sql logs
size=70806;type=file;perm=fdrwa;create=20030718113340;modify=20031001185600; vehinfiles.zip
size=0;type=dir;perm=fdelcmp;create=20020801100314;modify=20031004124403; zip logs  }

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.6 build PROPFIND Json Facts (FTP) directory response for one file - simpler than XML }
function IcsFileRectoFacts(FileRec: TIcsFDirRec): AnsiString;
begin
    with FileRec do begin
        if (FrFileAttr and faDirectory) <> 0 then begin
            if FrFileName = '.' then
                Result := 'size=0;type=cdir;perm=fdelcmp;'
            else if FrFileName = '..' then
                Result := 'size=0;type=pdir;perm=fdelcmp;'
            else
                Result := 'size=0;type=dir;perm=fdelcmp;'
        end
        else begin
            Result := 'size=' + AnsiString(IntToStr(FrFileBytes)) + ';type=file;perm=';
            if (FrFileAttr and faReadOnly) <> 0 then
                Result := Result + 'rw;'
            else
                Result := Result + 'fdrwa;';
        end;
        Result := Result +
            'create=' + AnsiString(FormatDateTime(UtcDateMaskPacked, FrCreateUDT)) +
            ';modify=' +AnsiString( FormatDateTime(UtcDateMaskPacked, FrFileUDT)) +
            '; ' + StringToUtf8(FrSubDirs + FrFileName);    { note space before filename is delimiter }
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.6 build PROPFIND XML directory response for one file }

// pending, pass ContentType, pass mask of list of properties parsed from XML request body

function IcsFileRectoXML(const Path: String; FileRec: TIcsFDirRec): AnsiString;
var
   URL, MyDirs, CType: String;
begin
    Result := '';
    with FileRec do begin
        if Length(FrSubDirs) = 0 then  // sanity test
            Exit;
        MyDirs := SrvUrlEncode(DosPathToUnixPath(Copy(FrSubDirs, 2)));
        MyDirs := StringReplace(MyDirs, '%2F', '/', [rfReplaceAll, rfIgnoreCase]);  // restore delimiiters
        URL := Path + MyDirs + SrvUrlEncode(FrFileName);
        if ((FrFileAttr AND faDirectory) > 0)  then         // V9.8
            URL := URL + '/';  // directory needs trailing delimiter
        Result := '<D:response>' +  // open tag 1
            '<D:href>' + AnsiString(URL) + '</D:href>' +
            '<D:propstat>' +         // open tag 2
            '<D:status>HTTP/1.1 200 OK</D:status>' +
            '<D:prop>';             // open tag 3
        Result := Result +
            '<D:displayname>' + StringToUtf8(FrFileName) + '</D:displayname>' +
            '<D:creationdate>' + AnsiString(RFC3339_DateToUtcStr(FrCreateUDT)) + ' GMT</D:creationdate>' +
            '<D:getlastmodified>' + AnsiString(RFC1123_Date(FrFileUDT)) + ' GMT</D:getlastmodified>';
         if ((FrFileAttr AND faDirectory) > 0)  then begin      // V9.8
            Result := Result +
                '<D:getcontentlength>0</D:getcontentlength>';
        end
        else begin
            CType := DocumentToContentType(FrFileName); // could lookup from MIME table
            Result := Result +
                '<D:getcontentlength>' + AnsiString(IntToStr(FrFileBytes))+ '</D:getcontentlength>' +
                '<D:getcontenttype>' + AnsiString(CType) + '</D:getcontenttype>';
           if (FrFileBytes > 0) and (FrFileDT > 0) then
            Result := Result +
                '<D:getetag>' +  IcsDQUOTE + AnsiString(IcsBase64UrlEncode(StrCRC32(RFC3339_DateToStr(FrFileUDT, False)) +
                                                                    IntToStr(FrFileBytes))) + IcsDQUOTE + '</D:getetag>';
        end;
        Result := Result +
            '</D:prop></D:propstat></D:response>';  // close tags 1, 2, 3
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ V9.6 build and send PROPFIND directory response, in XML or Json }
procedure THttpConnection.SendPropFindDir(var Flags : THttpGetFlag);
var
    Header, PartURL, PartDir, SearchName: String;
    Line: AnsiString;
    FileCopyClient: TIcsFileCopy;
    LocFiles: TIcsFDirRecs;
    LocFileList: TIcsFindList;
    SelOpt: TIcsFileCopyType;
    SubDirs, JsonForrmat: boolean;
    TotFiles, I, DoneNr: Integer;
    FileRecX: PTIcsFDirRec ;
begin
    if FRequestDepth = '' then
        FRequestDepth := '1';  // default one level
    PartDir := ExtractFilePath(FDocument);
    SearchName := '*';
    SubDirs := False;
    if Lowercase(FRequestDepth) =  'infinity' then begin
        SelOpt := FCTypeAllDir;
        SubDirs := True;
    end
    else if FRequestDepth = '1' then
        SelOpt := FCTypeAllDir
    else begin
        SelOpt := FCTypeSingle;
        SearchName := ExtractFileName(FDocument);
    end;
    PartURL := FRequestProtocol + '://' + RequestHost + '/';
    if (wsdlogInfo in FServer.WSDebugOptions) then begin
        DebugDisplay('PROPFIND directory listing for ' + FDocument);
    end;

  { non-standard ICS special, return Json response, not XML, simpler to create and parse }
    JsonForrmat := (Pos('json', FRequestAccept) > 0);

// pending, parse RequestXML to see if specific properties required, currently sent all of them

 // build list of files
    FileCopyClient := TIcsFileCopy.Create (self) ;
    LocFileList := TIcsFindList.Create;
    try
        try
            TotFiles := FileCopyClient.GetDirList(PartDir, SearchName, SelOpt, SubDirs, 0, 0, LocFiles, LocFileList, True);
            if TotFiles > 0 then begin
                if (wsdlogInfo in FServer.WSDebugOptions) then begin
                    DebugDisplay('Total files found: ' + IntToStr(TotFiles));
                end;
                FDocStream.Free;
                FDocStream := nil;
                FDocStream := TMemoryStream.Create;

            // start
                if JsonForrmat then
                    Line := '{"FileRecs":['
                else
                    Line := '<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">' + IcsCRLF;
                FDocStream.Write(Pointer(Line)^, Length(Line));  // utf8

            // each file
                DoneNr := 0;
                for I := 0 to (TotFiles - 1) do begin
                    if LocFileList [I] = Nil then
                        continue;
                    FileRecX := LocFileList [I] ;
                  // skip directories for single file
                    if (SelOpt = FCTypeSingle) and ((FileRecX^.FrFileAttr AND faDirectory) > 0)  then   // V9.8
                        continue;
                    if JsonForrmat then
                        Line := '"' + IcsEscapeJson(IcsFileRectoFacts(FileRecX^)) + '"'  // Json value
                    else
                        Line := IcsFileRectoXML(PartURL, FileRecX^);
                    if DoneNr > 0 then
                       Line := ',' + IcsCRLF + Line;
                    FDocStream.Write(Pointer(Line)^, Length(Line));  // utf8
                    DoneNr := DoneNr + 1;
                end;

            // end
                if JsonForrmat then
                    Line := ']}'
                else
                    Line := '</D:multistatus>';
                FDocStream.Write(Pointer(Line)^, Length(Line));  // utf8
            end;
        except
            if (wsdlogErrs in FServer.WSDebugOptions) then begin
                DebugDisplay('PROPFIND Exception');
            end;
            Flags := hg400;
            Exit;
        end;
    finally
        FreeAndNil (FileCopyClient) ;
        FreeAndNil(LocFileList);
    end;

// no XML if nothing found
    if TotFiles = 0 then begin
        Flags := hg404;
        Exit;
    end;
    Flags := hgWillSendMySelf;
    if JsonForrmat then
        Header := Version +  ' 200 OK' + IcsCRLF +
              'Content-Type: text/json' + IcsCRLF
    else
        Header := Version +  ' 207 Multi Status' + IcsCRLF +
              'Content-Type: text/xml' + IcsCRLF;
    Header := Header +
              'Content-Length: ' + IntToStr(FDocStream.Size) + IcsCRLF +
              'Pragma: no-cache' + IcsCRLF;
    if (hoSendServerHdr in FOptions) and (FServer.FServerHeader <> '') then
        Header := Header + FServer.FServerHeader + IcsCRLF;
    Header := Header + GetKeepAliveHdrLines + IcsCRLF;
    FAnswerStatus := 200;
    SendHeader(Header);
    FDocStream.Position := 0;
    SendStream;

end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Retrieve a single value by name out of an URL encoded data stream         }
{ In the stream, every space is replaced by a '+'. The '%' character is     }
{ an escape character. The next two are 2 digits hexadecimal codes ascii    }
{ code value. The stream is constitued by name=value couples separated      }
{ by a single '&' character. The special characters are coded by the '%'    }
{ followed by hex-ascii character code.                                     }
function ExtractURLEncodedValue(
    Msg         : PChar;    { URL Encoded stream                     }
    Name        : String;   { Variable name to look for              }
    var Value   : String;   { Where to put variable value            }
    SrcCodePage : LongWord; { D2006 and older CP_UTF8 only           }
    DetectUtf8  : Boolean)
    : Boolean;              { Found or not found that's the question }
begin
    Result := IcsExtractURLEncodedValue(Msg, Name, Value, SrcCodePage, DetectUtf8);  { V9.1 }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function ExtractURLEncodedValue(
    const Msg   : String;           { URL Encoded stream                    }
    Name        : String;           { Variable name to look for             }
    var Value   : String;           { Where to put variable value           }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Boolean; overload;
begin
    Result := IcsExtractURLEncodedValue(PChar(Msg), Name, Value, SrcCodePage, DetectUtf8);  { V9.1 }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ return parameters as TStrings, name or name=value }
{ unlike ExtractURLEncodedValue control codes are left escaped too avoid multiple line values }
function ExtractURLEncodedParamList(
    Msg       : PChar;             { URL Encoded stream                     }
    Params    : TStrings;          { Where to put the list of parameters    }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Integer;                     { Number of parameters found             }
begin
    Result := IcsExtractURLEncodedParamList(Msg, Params, False, SrcCodePage, DetectUtf8);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function ExtractURLEncodedParamList(
    const Msg : String;            { URL Encoded stream                     }
    Params    : TStrings;          { Where to put the list of parameters    }
    SrcCodePage : LongWord = CP_ACP;{ D2006 and older CP_UTF8 only          }
    DetectUtf8  : Boolean  = TRUE)
    : Integer;                     { Number of parameters found             }
begin
    Result := IcsExtractURLEncodedParamList(PChar(Msg), Params, False, SrcCodePage, DetectUtf8);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function GetCookieValue(
    const CookieString : String;   { Cookie string from header line         }
    const Name         : String;   { Cookie name to look for                }
    var   Value        : String)   { Where to put variable value            }
    : Boolean;                     { Found or not found that's the question }
begin
    Result := IcsGetCookieValue(CookieString, Name, Value);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TranslateChar(const Str: String; FromChar, ToChar: Char): String;
var
    I : Integer;
begin
    Result := Str;
    for I := 1 to Length(Result) do
      if Result[I] = FromChar then
          Result[I] := ToChar;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function UnixPathToDosPath(const Path: String): String;
begin
    Result := TranslateChar(Path, '/', '\');
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function DosPathToUnixPath(const Path: String): String;
begin
    Result := TranslateChar(Path, '\', '/');
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function AdjustOSPathDelimiters(const Path: String): String;
begin
  {$IFDEF MSWINDOWS}
    Result := TranslateChar(Path, '/', '\');
  {$ELSE}
    Result := TranslateChar(Path, '\', '/');
  {$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IsDirectory(const Path : String) : Boolean;
{$IFDEF MSWINDOWS}
var
    Attr : DWORD;
begin
    Attr   := GetFileAttributes(PChar(ExcludeTrailingPathdelimiter(Path)));
    Result := (Attr <> MaxDWord) and ((Attr and FILE_ATTRIBUTE_DIRECTORY) <> 0);
end;
{$ENDIF}
{$IFDEF POSIX}
begin
    Result := DirectoryExists(ExcludeTrailingPathdelimiter(Path));
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function AbsolutisePath(const Path : String) : String;
begin
    Result := IcsAbsolutisePath(Path);   { V9.1 moved to Utils }
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function MakeCookie(
    const Name, Value : String;
    Expires           : TDateTime;
    const Path        : String;
    const Domain      : String = '';
    const Secure      : Boolean = false) : String;   { V8.37 }
begin
    Result := 'Set-Cookie: ' + Name + '=' + SrvUrlEncode(Value);
    if Length(Value) = 0 then
        Result := Result + '_NONE_; EXPIRES=' + RFC1123_Date(Date - 7) { Last week }
    else if Expires <> 0 then
        Result := Result + '; EXPIRES=' + RFC1123_Date(Expires);
    if Domain <> '' then Result := Result + '; DOMAIN=' + Domain;   { 7.49 }
    Result := Result + '; PATH=' + Path;
    if Secure then Result := Result + '; Secure; HttpOnly';   { V8.37 }
    Result := Result + IcsCRLF;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function SrvUrlEncode(const S : String; DstCodePage: LongWord = CP_UTF8) : String;  { V9.1 was UrlEncode }
var
    I, J   : Integer;
    AStr   : AnsiString;
    RStr   : AnsiString;
    HexStr : String[2];
begin
{$IFDEF COMPILER12_UP}
    AStr := UnicodeToAnsi(S, DstCodePage);
{$ELSE}
    if DstCodePage = CP_UTF8 then
        AStr := StringToUtf8(S)
    else
        AStr := S;
{$ENDIF}
    SetLength(RStr, Length(AStr) * 3);
    J := 0;
    for I := 1 to Length(AStr) do begin
        case AStr[I] of
            '0'..'9', 'a'..'z', 'A'..'Z', '.' :
                begin
                    Inc(J);
                    RStr[J] := AStr[I];
                end
        else
            Inc(J);
            RStr[J] := '%';
            HexStr  := IcsIntToHexA(Ord(AStr[I]), 2);
            Inc(J);
            RStr[J] := HexStr[1];
            Inc(J);
            RStr[J] := HexStr[2];
        end;
    end;
    SetLength(RStr, J);
    Result := String(RStr);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function  SrvUrlDecode(const Url : String; SrcCodePage: LongWord = CP_ACP;       { V9.1 was UrlDecode }
  DetectUtf8: Boolean = TRUE) : String;
var
    I, J, L : Integer;
    U8Str : AnsiString;
    Ch : AnsiChar;
begin
    L := Length(Url);
    SetLength(U8Str, L);
    I := 1;
    J := 0;
    while (I <= L) do begin
        Ch := AnsiChar(Url[I]);
        if Ch = '%' then begin
            Ch := AnsiChar(htoi2(PChar(@Url[I + 1])));
            Inc(I, 2);
        end
        else if Ch = '+' then
            Ch := ' ';
        Inc(J);
        U8Str[J] := Ch;
        Inc(I);
    end;
    SetLength(U8Str, J);
    if (SrcCodePage = CP_UTF8) or (DetectUtf8 and IsUtf8Valid(U8Str)) then { V7.24 }
{$IFDEF COMPILER12_UP}
        Result := Utf8ToStringW(U8Str)
    else
        Result := AnsiToUnicode(U8Str, SrcCodePage);
{$ELSE}
        Result := Utf8ToStringA(U8Str)
    else
        Result := U8Str;
{$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF COMPILER12_UP}
function SrvUrlDecode(const Url: RawByteString; SrcCodePage: LongWord = CP_ACP;
  DetectUtf8: Boolean = TRUE): UnicodeString;                                             { V9.1 was UrlDecode }
var
    I, J, L : Integer;
    U8Str   : AnsiString;
    Ch      : AnsiChar;
begin
    L := Length(Url);
    SetLength(U8Str, L);
    I := 1;
    J := 0;
    while (I <= L) and (Url[I] <> '&') do begin
        Ch := AnsiChar(Url[I]);
        if Ch = '%' then begin
            Ch := AnsiChar(htoi2(PAnsiChar(@Url[I + 1])));
            Inc(I, 2);
        end
        else if Ch = '+' then
            Ch := ' ';
        Inc(J);
        U8Str[J] := Ch;
        Inc(I);
    end;
    SetLength(U8Str, J);
    if (SrcCodePage = CP_UTF8) or (DetectUtf8 and IsUtf8Valid(U8Str)) then
        Result := Utf8ToStringW(U8Str)
    else
        Result := AnsiToUnicode(U8Str, SrcCodePage);
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpServer.GetSrcVersion: String;
begin
    Result := Format('%d.%02.2d', [THttpServerVersion div 100,
                                   THttpServerVersion mod 100]);

end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TStringIndex.Add(const Key, Value: String);
begin
    if not Assigned(Flist) then
        Exit;
//OutputDebugString(PChar('TagData.Add(' + Key + ', ' + Value + ')'));
    FList.AddObject(Key, TStringIndexObject.Create(Value));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TStringIndex.Find(const Key: String; var Value: String): Boolean;
var
    Index : Integer;
begin
    if not Assigned(Flist) then begin
        Result := FALSE;
        Exit;
    end;
    Index := FList.IndexOf(Key);
    Result := Index >= 0;
    if Result then
        Value := TStringIndexObject(FList.Objects[Index]).Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TStringIndex.Clear;
var
    I : Integer;
begin
    if not Assigned(Flist) then
        Exit;
    for I := FList.Count - 1 downto 0 do
        FList.Objects[I].Free;
    FList.Clear;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TStringIndex.Create;
begin
    inherited Create;
    FList               := TStringList.Create;
{$IFDEF DELPHI6_UP}
    FList.CaseSensitive := FALSE;
{$ENDIF}
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TStringIndex.Destroy;
begin
    Clear;
    if Assigned(FList) then begin
        FList.Free;
        FList := nil;
    end;
    inherited Destroy;
end;

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TStringIndexObject.Create(const Data: String);
begin
    Value := Data;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TStringIndex.Count: Integer;
begin
    if not Assigned(Flist) then
        Result := 0
    else
        Result := FList.Count;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function DelimEnd(Ch : Char) : Boolean;
begin
    Result := (Ch = ' ') or (Ch = '>') or (Ch = #9);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function SearchTableRowsEnd(
    Buf    : PChar;
    BufLen : Integer) : PChar;
var
    I : Integer;
    Q : PChar;
    StartTag : String;
    End1Tag  : String;
    End2Tag  : String;
begin
    StartTag := '<'  + GTagPrefix + 'TABLE_ROWS';
    End1Tag  := '</' + GTagPrefix + 'TABLE_ROWS';
    End2Tag  := '<'  + GTagPrefix + '/TABLE_ROWS'; { Old version still supported }
    I := 0;
    while I < (BufLen - 13) do begin
        if (StrLIComp(Buf + I, @StartTag[1], Length(StartTag)) = 0) and
           DelimEnd((Buf + I + Length(StartTag))^) then begin
            { Embedded TABLE_ROWS ! }
            while (I < (BufLen - 1)) and (Buf[I] <> '>') do
                Inc(I);
            Q := SearchTableRowsEnd(Buf + I + 1, BufLen - I - 1);
            I := Q - Buf;
        end
        else if (StrLIComp(Buf + I, @End1Tag[1], Length(End1Tag)) = 0) and
                DelimEnd((Buf + I + Length(End1Tag))^) then begin
            I := I + Length(End1Tag);
            while (I < BufLen) and (Buf[I] <> '>') do
                Inc(I);
            Result := Buf + I + 1;
            Exit;
        end
        else if (StrLIComp(Buf + I, @End2Tag[1], Length(End2Tag)) = 0) and
                DelimEnd((Buf + I + Length(End2Tag))^) then begin
            I := I + Length(End2Tag);
            while (I < BufLen) and (Buf[I] <> '>') do
                Inc(I);
            Result := Buf + I + 1;
            Exit;
        end;
        Inc(I);
    end;
    Result := nil;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure HandleTableRow(
    TableName          : String;
    Buf                : PChar;
    BufLen             : Integer;
    RowDataGetter      : PTableRowDataGetter;
    UserData           : TObject;
    DestStream         : TStream
{$IFDEF COMPILER12_UP};
    DestCodePage       : LongWord = CP_ACP
{$ENDIF}
    );
var
    More    : Boolean;
    TagData : TStringIndex;
    Row     : Integer;
begin
    More := FALSE;
    if Assigned(RowDataGetter) then begin
        TagData := TStringIndex.Create;
        try
            Row := 0;
            while TRUE do begin
                Inc(Row);
                More := FALSE;
                TTableRowDataGetter(RowDataGetter)(TableName, Row, TagData,
                                                   More, UserData);
                if not More then
                    break;
                HtmlPageProducerFromMemory(Buf, BufLen, TagData,
                                           RowDataGetter, UserData,
                                           DestStream
                                       {$IFDEF COMPILER12_UP},
                                           DestCodePage
                                       {$ENDIF}
                                           );
                TagData.Clear;
            end;
        finally
            TagData.Free;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function HtmlPageProducerSetTagPrefix(const Value : String) : String;
begin
    Result     := GTagPrefix;
    GTagPrefix := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function HtmlPageProducerFromMemory(
    Buf                : PChar;
    BufLen             : Integer;
    TagData            : TStringIndex;
    RowDataGetter      : PTableRowDataGetter;
    UserData           : TObject;
    DestStream         : TStream
{$IFDEF COMPILER12_UP};
    DestCodePage       : LongWord = CP_ACP
{$ENDIF}
    ) : Boolean;
const
    MAX_BUF  = 50;
var
    I, J      : Integer;
    TagName   : String;
    TagParams : String;
    TagValue  : String;
    P, Q      : PChar;
    Cnt       : Integer;
begin
    Result := FALSE;
    if (not Assigned(DestStream)) then
        Exit;
    if (Buf = nil) or (BufLen <= 0) then
        Exit;

    P   := Buf;
    Cnt := BufLen;
    while TRUE do begin
        { Search starting delimiter }
        I := 0;
        repeat
            while (I < (Cnt - Length(GTagPrefix))) and ((P[I] <> '<') or (P[I + 1] <> GTagPrefix[1])) do
                Inc(I);
            Inc(I);
        until (I >= (Cnt - Length(GTagPrefix))) or
              (StrLIComp(P + I, @GTagPrefix[1], Length(GTagPrefix)) = 0);

        Dec(I);
        if P[I] <> '<' then begin
            { No starting tag found, write source to destination }
            StreamWriteA(DestStream, P, Cnt
                     {$IFDEF COMPILER12_UP},
                         DestCodePage
                     {$ENDIF}
                        );
            break;
        end;

        { Delimiter found
          Write from source to destination until start tag }
        if I > 0 then
            StreamWriteA(DestStream, P, I
                     {$IFDEF COMPILER12_UP},
                         DestCodePage
                     {$ENDIF}
                         );
        { Search ending delimiter }
        J := I;
        while (J < Cnt) and (P[J] <> '>') and (P[J] <> ' ') and (P[J] <> #9) do
            Inc(J);

        TagName := UpperCase(Copy(P, I + Length(GTagPrefix) + 2, J - I - Length(GTagPrefix) - 1));
//OutputDebugString(PChar('TagName = ' + TagName));
        if P[J] = '>' then
            TagParams := ''
        else begin
            I := J + 1;
            while (J < Cnt) and (P[J] <> '>') do
                Inc(J);
            TagParams := Trim(UpperCase(Copy(P, I, J - I + 1)));
        end;

        if TagName = 'TABLE_ROWS' then begin
            Q := SearchTableRowsEnd(P + J + 1, Cnt - J - 1);
            if Q = nil then
                Q := P + Cnt;
            //Feb 08, 2010 TRL the row to handle was 1 char too long
            HandleTableRow(TagParams, P + J + 1, Q - P - J - 1,
                           RowDataGetter, UserData, DestStream
                       {$IFDEF COMPILER12_UP},
                           DestCodePage
                       {$ENDIF}
                           );
            Cnt := P + Cnt - Q;
            P := Q;
            Continue;
        end;

        if TagData.Find(TagName, TagValue) then begin
//OutputDebugString(PChar('TagValue = ' + TagValue));
            StreamWriteStrA(DestStream, TagValue
                        {$IFDEF COMPILER12_UP},
                            DestCodePage
                        {$ENDIF}
                            );
        end;
        Inc(J);
        Inc(P, J);
        Dec(Cnt, J);
    end;
//    Feb 08, 2010 TRL no need to add extra line.
//    StreamWriteLnA(DestStream, '');
    Result := TRUE;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function VarRecToString(V : TVarRec) : String;
const
    BooleanToString : array [Boolean] of String = ('FALSE', 'TRUE');
begin
    case V.VType of
    vtInteger:        Result := IntToStr(V.VInteger);
    vtBoolean:        Result := BooleanToString[V.VBoolean];
    vtChar:           Result := String(V.VChar);
    vtExtended:       Result := FloatToStr(V.VExtended^);
    vtString:         Result := String(V.VString^);
    vtPointer:        Result := 'Unsupported TVarRec.VType = vtPointer';
    vtPChar:          Result := String(StrPas(V.VPChar));
    vtObject:         Result := 'Unsupported TVarRec.VType = vtObject';
    vtClass:          Result := 'Unsupported TVarRec.VType = vtClass';
    vtWideChar:       Result := String(V.VWideChar);
    vtPWideChar:      Result := String(V.VPWideChar);
    vtAnsiString:     Result := String(StrPas(V.VPChar));
    vtCurrency:       Result := 'Unsupported TVarRec.VType = vtCurrency';
    vtVariant:        Result := 'Unsupported TVarRec.VType = vtVariant';
    vtWideString:     Result := 'Unsupported TVarRec.VType = vtWideString';
    vtInterface:      Result := 'Unsupported TVarRec.VType = vtInterface';
    vtInt64:          Result := IntToStr(V.VInt64^);
{$IFDEF COMPILER12_UP}
    vtUnicodeString:  Result := PWideChar(V.VUnicodeString);
{$ENDIF}
    else
        Result := 'Unknown TVarRec.VType = "' + IntToStr(Ord(V.VType)) + '" ';
    end;

//OutputDebugString(PChar('VarRecToString ' + Result));
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function HtmlPageProducer(
    const FromStream  : TStream;
    Tags              : array of const;
    RowDataGetter     : PTableRowDataGetter;
    UserData          : TObject;
    DestStream        : TStream
{$IFDEF COMPILER12_UP};
    FromCodepage      : LongWord = CP_ACP;
    DestCodePage      : LongWord = CP_ACP
{$ENDIF}
    ) : Boolean;
var
    Str        : String;
    TagData    : TStringIndex;
    TagIndex   : Integer;
begin
    if ((High(Tags) - Low(Tags) + 1) and 1) <> 0 then begin
        StreamWriteLnA(DestStream, '<HTML><BODY>' +
                                   'Odd number of tags for substition<BR>' +
                                   '</BODY></HTML>');
        Result := FALSE;
        Exit;
    end;
    if not Assigned(FromStream) then begin
        StreamWriteLnA(DestStream, '<HTML><BODY>' +
                                   'Template stream not assigned<BR>'+
                                   '</BODY></HTML>');
        Result := FALSE;
        Exit;
    end;
    TagData := TStringIndex.Create;
    try
        TagIndex := Low(Tags);
        while TagIndex < High(Tags) do begin
            TagData.Add(VarRecToString(Tags[TagIndex]),
                        VarRecToString(Tags[TagIndex + 1]));
            Inc(TagIndex, 2);
        end;
        Str := StreamReadStrA(FromStream, FromStream.Size
                          {$IFDEF COMPILER12_UP},
                              FromCodepage
                          {$ENDIF}
                              );

        Result := HtmlPageProducerFromMemory(PChar(Str), Length(Str){ + 1},
                                             TagData,
                                             RowDataGetter, UserData,
                                             DestStream
                                         {$IFDEF COMPILER12_UP},
                                             DestCodePage
                                         {$ENDIF}
                                             );
    finally
        TagData.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function HtmlPageProducer(
    const ResName      : String;
    const ResType      : PChar;
    Tags               : array of const;
    RowDataGetter      : PTableRowDataGetter;
    UserData           : TObject;
    DestStream         : TStream
{$IFDEF COMPILER12_UP};
    ResCodepage        : LongWord = CP_ACP;
    DestCodePage       : LongWord = CP_ACP
{$ENDIF}
    ) : Boolean;
var
    FromStream : TResourceStream;
begin
    FromStream := Nil;
    try
        if FindResource(HInstance, PChar(ResName), ResType) <> 0 then    { V9.8 avoid exception for missing resource }
            FromStream := TResourceStream.Create(HInstance, ResName, ResType);
    except
     {   on E: Exception do begin
            StreamWriteLnA(DestStream, '<HTML><BODY>');
            StreamWriteLnA(DestStream, 'Unable to open resource ''' +  ResName + ' (' + ResType + ')''<BR>');
            StreamWriteLnA(DestStream, E.ClassName + ': ' + E.Message);
            StreamWriteLnA(DestStream, '</BODY></HTML>');
            Result := FALSE;
            Exit;
        end;  }
    end;
    if NOT Assigned(FromStream) then begin  { V9.8 }
     { really want to log this, but not part of the component....
        if (wsdlogErrs in WSDebugOptions) then begin
                    DebugDisplay('Unable to open resource ''' + ResName + ' (' + ResType + ')');   }
        StreamWriteLnA(DestStream, '<HTML><BODY>');
        StreamWriteLnA(DestStream, 'Unable to open resource ''' + ResName + ' (' + ResType + ')''<BR>');
        StreamWriteLnA(DestStream, '</BODY></HTML>');
        Result := FALSE;
        Exit;
    end;
    try
        Result := HtmlPageProducer(FromStream, Tags, RowDataGetter, UserData, DestStream
                               {$IFDEF COMPILER12_UP},
                                   ResCodepage, DestCodePage
                               {$ENDIF}
                                   );
    finally
        FromStream.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function HtmlPageProducer(
    const HtmlFileName : String;
    Tags               : array of const;
    RowDataGetter      : PTableRowDataGetter;
    UserData           : TObject;
    DestStream         : TStream
{$IFDEF COMPILER12_UP};
    FileCodepage       : LongWord = CP_ACP;
    DestCodePage       : LongWord = CP_ACP
{$ENDIF}
    ) : Boolean;
var
    FromStream : TFileStream;
begin
    try
        FromStream := TFileStream.Create(HtmlFileName,
                                         fmOpenRead or fmShareDenyWrite);
    except
        on E: Exception do begin
            StreamWriteLnA(DestStream, '<HTML><BODY>');
            StreamWriteLnA(DestStream, 'Unable to open ''' + HtmlFileName + '''<BR>');
            StreamWriteLnA(DestStream, E.ClassName + ': ' + E.Message);
            StreamWriteLnA(DestStream, '</BODY></HTML>');
            Result := FALSE;
            Exit;
        end;
    end;
    try
        Result := HtmlPageProducer(FromStream, Tags, RowDataGetter,
                                   UserData, DestStream
                               {$IFDEF COMPILER12_UP},
                                   FileCodepage,
                                   DestCodePage
                               {$ENDIF}
                                   );
    finally
        FromStream.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TCustomSslHttpServer.Create(AOwner: TComponent);
begin
    inherited Create(AOwner);
    FWSocketServer.SslMode                  := sslModeServer;
    FWSocketServer.OnSslVerifyPeer          := TransferSslVerifyPeer;
    FWSocketServer.OnSslSetSessionIDContext := TransferSslSetSessionIDContext;
    FWSocketServer.OnSslSvrNewSession       := TransferSslSvrNewSession;
    FWSocketServer.OnSslSvrGetSession       := TransferSslSvrGetSession;
    FWSocketServer.OnSslHandshakeDone       := TransferSslHandshakeDone;
    FWSocketServer.OnSslServerName          := TransferSslServerName;  // V8.09
    FWSocketServer.OnSslAlpnSelect          := TransferSslAlpnSelect;  { V8.56 }
    (FWSocketServer as TSslWSocketServer).OnBeforeContextInit := TransferBeforeCtxInit;  { V8.66 }
    fHttpSslEnable                          := TRUE;   // V8.02 Angus, renamed V8.50
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TCustomSslHttpServer.Destroy;
begin
    inherited Destroy;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.CreateSocket;
begin
    FWSocketServer := TSslWSocketServer.Create(Self);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.WSocketServerClientCreate(
    Sender : TObject;
    Client : TWSocketClient);
begin
    THttpConnection(Client).OnSslSetSessionIDContext := TransferSslSetSessionIDContext;
    THttpConnection(Client).OnSslVerifyPeer          := TransferSslVerifyPeer;
    THttpConnection(Client).OnSslSvrNewSession       := TransferSslSvrNewSession;
    THttpConnection(Client).OnSslSvrGetSession       := TransferSslSvrGetSession;
    THttpConnection(Client).OnSslSetSessionIDContext := TransferSslSetSessionIDContext;
    THttpConnection(Client).OnSslHandshakeDone       := TransferSslHandshakeDone;
    THttpConnection(Client).OnSslServerName          := TransferSslServerName; // V8.09 Angus
    THttpConnection(Client).OnSslAlpnSelect          := TransferSslAlpnSelect;  { V8.56 }
    FWSocketServer.SslEnable                         := fHttpSslEnable;    // V8.02 Angus, renamed V8.50
    inherited WSocketServerClientCreate(Sender, Client);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetSslContext: TSslContext;
begin
    Result := FWSocketServer.SslContext
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetSslContext(Value: TSslContext);
begin
    FWSocketServer.SslContext := Value
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetSslAcceptableHosts(Value : TStrings);
begin
    TSslWSocketServer(FWSocketServer).SslAcceptableHosts := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function  TCustomSslHttpServer.GetSslAcceptableHosts: TStrings;
begin
    Result := TSslWSocketServer(FWSocketServer).SslAcceptableHosts;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslVerifyPeer(
    Sender        : TObject;
    var Ok        : Integer;
    Cert          : TX509Base);
begin
    if Assigned(FOnSslVerifyPeer) then
        FOnSslVerifyPeer(Sender, Ok, Cert);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslSetSessionIDContext(Sender: TObject;
    var SessionIDContext: TSslSessionIdContext);
begin
    if Assigned(FOnSslSetSessionIDContext) then
        FOnSslSetSessionIDContext(Sender, SessionIDContext);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslSvrGetSession(Sender: TObject;
    var SslSession : Pointer; SessId: Pointer; IdLen: Integer;
    var IncRefCount: Boolean);
begin
    if Assigned(FOnSslSvrGetSession) then
        FOnSslSvrGetSession(Sender, SslSession, SessId, IdLen, IncRefCount);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslSvrNewSession(Sender: TObject;
    SslSession: Pointer; SessId : Pointer; Idlen : Integer;
    var AddToInternalCache : Boolean);
begin
    if Assigned(FOnSslSvrNewSession) then
        FOnSslSvrNewSession(Sender, SslSession, SessID, IDLen, AddToInternalCache);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslHandshakeDone(Sender: TObject;
    ErrCode: Word; PeerCert: TX509Base;  var Disconnect : Boolean);
begin
    if Assigned(FOnSslHandshakeDone) then
        FOnSslHandshakeDone(Sender, ErrCode, PeerCert, Disconnect);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslServerName(Sender: TObject;   // V8.09
    var Ctx: TSslContext; var ErrCode: TTlsExtError);
begin
    if Assigned(FOnSslServerName) then
        FOnSslServerName(Sender, Ctx, ErrCode);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferSslAlpnSelect(Sender: TObject;
    ProtoList: TStrings; var SelProto : String; var ErrCode: TTlsExtError);  { V8.56 }
begin
    if Assigned(FOnSslAlpnSelect) then
        FOnSslAlpnSelect(Sender, ProtoList, SelProto, ErrCode);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.TransferBeforeCtxInit(Sender: TObject; IcsHost: TIcsHost);    { V8.66 }
begin
    if Assigned(FonBeforeCtxInit) then
        FonBeforeCtxInit(Sender, IcsHost);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.WSocketServerClientConnect(
    Sender  : TObject;
    Client  : TWSocketClient;
    ErrCode : Word);
begin
    inherited WSocketServerClientConnect(Sender, Client, ErrCode);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetAcceptableHostsList(
    const SemiColonSeparatedList : String);
begin
    FWSocketServer.SetAcceptableHostsList(SemiColonSeparatedList);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetIcsHosts: TIcsHostCollection;                     { V8.45 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).GetIcsHosts
    else
        Result := nil;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetIcsHosts(const Value: TIcsHostCollection);      { V8.45 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).SetIcsHosts(Value);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetRootCA: String;                                  { V8.46 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).RootCA
    else
        Result := '';
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetRootCA(const Value: String);                    { V8.46 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).RootCA := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.ValidateHosts(Stop1stErr: Boolean=True;
                                              NoExceptions: Boolean=False): String; { V8.48 }

begin
    if Assigned(FWSocketServer) then begin
        Result := TSslWSocketServer(FWSocketServer).ValidateHosts(Stop1stErr, NoExceptions);
      { bodge because Start sets these again, make it backward compabible }
        if TSslWSocketServer(FWSocketServer).IcsHosts.Count > 0 then begin
            FPort := FWSocketServer.Port;
            FAddr := FWSocketServer.Addr;
            FHttpSslEnable := FWSocketServer.SslEnable; { V8.50 }
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.RecheckSslCerts(var CertsInfo: String;
                    Stop1stErr: Boolean=True; NoExceptions: Boolean=False): Boolean;  { V8.48 }
begin
    Result := False;
    if Assigned(FWSocketServer) then begin
        Result := TSslWSocketServer(FWSocketServer).RecheckSslCerts(CertsInfo,
                                                        Stop1stErr, NoExceptions);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetSslCliCertMethod: TSslCliCertMethod;             { V8.57 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).SslCliCertMethod
    else
        Result := sslCliCertNone;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetSslCliCertMethod(const Value : TSslCliCertMethod); { V8.57 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).SslCliCertMethod := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetSslCertAutoOrder: Boolean;                       { V8.57 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).SslCertAutoOrder
    else
        Result := False;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetSslCertAutoOrder(const Value : Boolean);         { V8.57 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).SslCertAutoOrder := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetCertExpireDays: Integer;                         { V8.57 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).CertExpireDays
    else
        Result := 30;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetCertExpireDays(const Value : Integer);           { V8.57 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).CertExpireDays := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomSslHttpServer.GetNoSSL: Boolean;                                  { V9.1 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).NoSSL
    else
        Result := False;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetNoSSL(const Value : Boolean);                    { V9.1 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).NoSSL := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF AUTO_X509_CERTS}  { V8.59 }
function TCustomSslHttpServer.GetSslX509Certs: TSslX509Certs;    { V8.57 }
begin
    if Assigned(FWSocketServer) then
        Result := TSslWSocketServer(FWSocketServer).GetSslX509Certs as TSslX509Certs
    else
        Result := nil;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomSslHttpServer.SetSslX509Certs(const Value : TSslX509Certs);    { V8.57 }
begin
    if Assigned(FWSocketServer) then
        TSslWSocketServer(FWSocketServer).SetSslX509Certs(Value);
end;
{$ENDIF} // AUTO_X509_CERTS


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRange.Assign(Source: THttpRange);
begin
    FRangeFrom := Source.RangeFrom;
    FRangeTo   := Source.RangeTo;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpRange.Create;
begin
    FRangeFrom := -1;
    FRangeTo   := -1;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRange.GetContentRangeString(
    CompleteDocSize: THttpRangeInt): String;
begin
    if RangeFrom < 0 then
        { The Last Bytes }
        Result := IntToStr(CompleteDocSize - RangeFrom) + '-' +
                  IntToStr(CompleteDocSize - 1) + '/' + IntToStr(CompleteDocSize)
    else if RangeTo < 0 then
        { The First Bytes }
        Result := IntToStr(RangeFrom) + '-' + IntToStr(CompleteDocSize - 1) +
                  '/' + IntToStr(CompleteDocSize)
    else
        { The First Bytes }
        Result := IntToStr(RangeFrom) + '-' + IntToStr(RangeTo) +
                  '/' + IntToStr(CompleteDocSize);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRange.SetRangeFrom(const Value: THttpRangeInt);
begin
    FRangeFrom := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRange.SetRangeTo(const Value: THttpRangeInt);
begin
    FRangeTo := Value;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ THttpRangeList }
procedure THttpRangeList.Assign(Source: THttpRangeList);
var
    I        : Integer;
    NewRange : THttpRange;
begin
    Clear;
    for I := 0 to Source.Count - 1 do begin
        NewRange := THttpRange.Create;
        NewRange.Assign(Source[i]);
        Add(NewRange);
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeList.CreateRangeStream(
    SourceStream    : TStream;
    ContentString   : String;
    CompleteDocSize : THttpRangeInt;
    var SyntaxError : Boolean): TStream;
var
    NewStream: THttpRangeStream;
begin
    NewStream := THttpRangeStream.Create;
    if NewStream.InitRangeStream(SourceStream, Self, ContentString, SyntaxError) then
        Result := NewStream
    else begin
        Result := nil;
        NewStream.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF TListNatInt}
function THttpRangeList.GetItems(NIndex: NativeInt): THttpRange;     { V9.3 Delphi 12.2 changed type }
begin
    Result := TObject(inherited Items[NIndex]) as THttpRange;
end;
{$ELSE}
function THttpRangeList.GetItems(NIndex: Integer): THttpRange;
begin
    Result := TObject(inherited Items[NIndex]) as THttpRange;
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF TListNatInt}
procedure THttpRangeList.SetItems(NIndex: NativeInt; const Value: THttpRange);   { V9.3 Delphi 12.2 changed type }
begin
    inherited Items[NIndex] := Value;
end;
{$ELSE}
procedure THttpRangeList.SetItems(NIndex: Integer; const Value: THttpRange);
begin
    inherited Items[NIndex] := Value;
end;
{$ENDIF}


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure ParseRangeString(
    var FromStr : String;
    var ToStr   : String;
    const Value : String);
var
    SeperatorPos: integer;
begin
    FromStr := '';
    ToStr   := '';
    SeperatorPos := Pos('-', Value);
    if SeperatorPos <> 0 then begin
        FromStr := Copy(Value, 1, SeperatorPos - 1);
        ToStr   := Copy(Value, SeperatorPos + 1, Length(Value));
        FromStr := Trim(FromStr);
        ToStr   := Trim(ToStr);
        { Numeric Testing }
        if FromStr <> '' then begin
            try
                StrToInt64(FromStr);
            except
                FromStr := '';
                ToStr   := '';
                exit;
            end;
        end;
        if ToStr <> '' then begin
            try
                StrToInt64(ToStr);
            except
                FromStr := '';
                ToStr   := '';
                exit;
            end;
        end;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRangeList.InitFromString(AStr: String);
var
    Values     : TStrings;
    NewRange   : THttpRange;
    CommaPos   : integer;
    WorkString : String;
    FromStr    : String;
    ToStr      : String;
begin
    Clear;

    Values := TStringList.Create;

    try
        System.Delete(AStr, 1, Length('bytes='));
        Trim(AStr);

        { Parse the string valid values are:
         '-500'
         '500-'
         '500-1000'
         '200-300,450-8450,64-10'
         '200-300,-600'
         '465-,2315-8499'
        }
        while AStr <> '' do begin
            { At first get the next comma }
            CommaPos := Pos(',', AStr);
            if CommaPos = 0 then begin
                WorkString := AStr;
                AStr       := '';
            end
            else begin
                WorkString := Trim(Copy(AStr, 1, CommaPos - 1));
                AStr := Trim(Copy(AStr, CommaPos + 1, Length(AStr)));
            end;

            ParseRangeString(FromStr, ToStr, WorkString);
            if (FromStr <> '') or (ToStr <> '') then begin
                NewRange := THttpRange.Create;
                if FromStr = '' then
                    NewRange.RangeFrom := -1
                else
                    NewRange.RangeFrom := StrToInt64(FromStr);
                if ToStr = '' then
                    NewRange.RangeTo := -1
                else
                    NewRange.RangeTo := StrToInt64(ToStr);
                Add(NewRange);
            end;
        end;
    finally
        Values.Free;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeList.Valid: boolean;
begin
    Result := (Count > 0);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRangeList.Clear;
var
    I: Integer;
begin
    for I := 0 to Count - 1 do begin
        if Items[I] <> nil then begin
            Items[I].Free;
            Items[I] := nil;
        end;
    end;
    inherited Clear;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor THttpRangeList.Destroy;
begin
    Clear;
    inherited Destroy;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor THttpRangeStream.Create;
begin
    inherited Create;
    FPartStreams := TList.Create;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor THttpRangeStream.Destroy;
begin
    if Assigned(FPartStreams) then begin
        ClearPartStreams;
        FPartStreams.Free;
        FPartStreams := nil;
    end;
    if Assigned(FSourceStream) then begin
        FSourceStream.Free;
        FSourceStream := nil;
    end;
    inherited Destroy;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRangeStream.AddPartStream(
    Value     : TStream;
    AStartPos : THttpRangeInt;
    AEndPos   : THttpRangeInt);
var
    Part : THttpPartStream;
begin
    Part := THttpPartStream.Create;
    with Part do begin
        Stream   := Value;
        StartPos := AStartPos;
        EndPos   := AEndPos;
        Offset   := 0;
        Size     := 0;
    end;
    FPartStreams.Add(Part);
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRangeStream.ClearPartStreams;
var
    I : Integer;
begin
    for I := 0 to FPartStreams.Count - 1 do begin
        with THttpPartStream(FPartStreams.Items[I]) do begin
            if Stream <> FSourceStream then
                Stream.Free;
        end;
        THttpPartStream(FPartStreams.Items[I]).Free;
    end;
    FPartStreams.Clear;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeStream.PartStreamsCount : Integer;
begin
    Result := FPartStreams.Count;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeStream.GetPartStreams(
    NIndex: Integer): THttpPartStream;
begin
    Result := FPartStreams.Items[NIndex];
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeStream.InitRangeStream(
    SourceStream    : TStream;
    RangeList       : THttpRangeList;
    ContentString   : String;
    var SyntaxError : Boolean): boolean;
var
    FromVal         : THttpRangeInt;
    ToVal           : THttpRangeInt;
    I               : Integer;
    CompleteDocSize : THttpRangeInt;
    AStream         : TStream;
begin
    FSourceStream := SourceStream;
    Result        := False;
    SyntaxError   := False;
    if RangeList.Count > 0 then begin
        CompleteDocSize := SourceStream.Size;
        ClearPartStreams;

        for I := 0 to RangeList.Count-1 do begin
            if RangeList.Count > 1 then begin
                AStream := TMemoryStream.Create;
                if I <> 0 then
                    StreamWriteLnA(AStream, '');
                StreamWriteLnA(AStream, '--' + ByteRangeSeparator);
                StreamWriteLnA(AStream, 'Content-Type: ' + ContentString);
                StreamWriteLnA(AStream, 'Content-Range: bytes ' +
                    RangeList.Items[i].GetContentRangeString(CompleteDocSize));
                StreamWriteLnA(AStream, '');
                AddPartStream(AStream, 0, AStream.Size);
            end;
            FromVal := RangeList.Items[I].RangeFrom;
            ToVal   := RangeList.Items[I].RangeTo;

            { The first-byte-pos value in a byte-range-spec gives the          }
            { byte-offset of the first byte in a range. The last-byte-pos      }
            { value gives the byte-offset of the last byte in the range; that  }
            { is, the byte positions specified are inclusive. Byte offsets     }
            { start at zero.                                                   }
            { If the last-byte-pos value is present, it MUST be greater than   }
            { or equal to the first-byte-pos in that byte-range-spec, or the   }
            { byte- range-spec is syntactically invalid. The recipient of a    }
            { byte-range- set that includes one or more syntactically invalid  }
            { byte-range-spec values MUST ignore the header field that includes}
            { that byte-range- set.                                            }
            { If the last-byte-pos value is absent, or if the value is greater }
            { than or equal to the current length of the entity-body,          }
            { last-byte-pos is taken to be equal to one less than the current  }
            { length of the entity- body in bytes.                             }

            if (FromVal < 0) and (ToVal > 0) then begin
                { Need the last number of bytes }
                FromVal := SourceStream.Size - ToVal;
                ToVal   := SourceStream.Size;
            end
            else begin
                if (ToVal < 0) or (ToVal >= SourceStream.Size) then
                    ToVal := SourceStream.Size
                else
                    ToVal := ToVal + 1;
            end;
            { If the byte-range-set is unsatisfiable, the server SHOULD return }
            { a response with a status of 416 (Requested range not satisfiable)}
            { In case of invalid syntax we'll ignore the range request.        }
            SyntaxError := (FromVal < ToVal) and (FromVal < SourceStream.Size);

            if (FromVal > SourceStream.Size) or (FromVal < 0) or
               (ToVal > SourceStream.Size)   or (ToVal <= FromVal) then begin
                { wrong Range -> we'll check for SyntaxError later in SendDocument }
                ClearPartStreams;
                FSourceStream := nil;
                Exit;
            end;
            AddPartStream(SourceStream, FromVal, ToVal);
        end;
        if RangeList.Count > 1 then begin
            AStream := TMemoryStream.Create;
            StreamWriteLnA(AStream, '');
            StreamWriteLnA(AStream, '--' + ByteRangeSeparator + '--');
            StreamWriteLnA(AStream, '');
            AddPartStream(AStream, 0, AStream.Size);
        end;
        CalculateOffsets;
        Result := TRUE;
    end;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeStream.Read(var Buffer; Count: Longint): Longint;
var
    DataRead  : Integer;
    Index     : Integer;
    ActSize   : Integer;
    ActOffset : THttpRangeInt;
    SizeRead  : Integer;
    Rec       : THttpPartStream;
begin
{$IFNDEF WIN64}  { V7.37 }
  {$IFNDEF COMPILER24_UP}
    Rec := nil;  { Just to remove a compiler warning }
  {$ENDIF}
{$ENDIF}
    if (FPosition >= 0) and (Count >= 0) then begin
        if (FSize - FPosition) > 0 then begin
            Index    := 0;
            DataRead := 0;
            while DataRead < Count do begin
                while TRUE do begin
                    if Index >= PartStreamsCount then begin
                        { Error }
                        Result := 0;
                        Exit;
                    end;
                    Rec := PartStreams[Index];
                    if (Rec.Offset + Rec.Size) > FPosition then
                        Break;
                    Inc(Index);
                end;

                ActOffset := FPosition - Rec.Offset;
                ActSize   := min(Count - DataRead, Rec.Size - (ActOffset));
                Rec.Stream.Position := ActOffset + Rec.StartPos;
{$IFDEF WIN64}
                SizeRead := Rec.Stream.Read(Pointer(NativeUInt(@Buffer) + NativeUInt(DataRead))^, ActSize); { V8.71 JK x64 }
{$ELSE}
                SizeRead := Rec.Stream.Read(Pointer(DWORD(@Buffer) + DWORD(DataRead))^, ActSize);
{$ENDIF}
                Inc(DataRead, SizeRead);
                Inc(FPosition, SizeRead);
                if (Rec.Offset + Rec.Size) > FPosition then  { V8.03 }
                    Break
                else
                    Inc(Index);
            end;
            Result := DataRead;
            Exit;
        end;
    end;
    Result := 0;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeStream.Seek(
    const Offset: Int64;
    Origin: TSeekOrigin): Int64;
begin
    case WORD(Origin) of
        soFromBeginning : FPosition := Offset;
        soFromCurrent   : Inc(FPosition, Offset);
        soFromEnd       : FPosition := FSize + Offset;
    end;
    Result := FPosition;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function THttpRangeStream.Write(const Buffer; Count: Longint): Longint;
begin
    raise Exception.Create('Stream is readonly');
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure THttpRangeStream.CalculateOffsets;
var
    I, J    : Integer;
    AOffset : THttpRangeInt;
    Rec     : THttpPartStream;
begin
    Rec     := nil;  { Just to remove a compiler warning }
    AOffset := 0;
    I       := 0;
    J       := PartStreamsCount;  { Costly function, optimize }
    while I < J do begin
        Rec := PartStreams[I];
        with Rec do begin
            Offset  := AOffset;
            Size    := EndPos - StartPos;
            Inc(AOffset, Size);
        end;
        Inc(I);
    end;
    FSize := Rec.Size + Rec.Offset;
end;


{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF NO_AUTHENTICATION_SUPPORT}
function AuthTypesToString(Types : TAuthenticationTypes) : String;
begin
    Result := '';
    if atNone in Types then
        Result := Result + 'atNone ';
    if atBasic in Types then
        Result := Result + 'atBasic ';
{$IFNDEF NO_DIGEST_AUTH}
    if atDigest in Types then
        Result := Result + 'atDigest ';
    if atDigestSha2 in Types then
        Result := Result + 'atDigestSha2 ';     { V8.69 }
{$ENDIF}
{$IFDEF USE_NTLM_AUTH}
    if atNtlm in Types then
        Result := Result + 'atNtlm ';
{$ENDIF}
    Result := Trim(Result);
end;
{$ENDIF}

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

end.
