Difference between revisions of "TWSocketServer"

From Overbyte
Jump to navigation Jump to search
 
(5 intermediate revisions by the same user not shown)
Line 17: Line 17:
 
Note:  When a TWSocketClient is closed, it automatically frees itself.  With a normal [[TWSocket]], the programmer is responsible for freeing the object.
 
Note:  When a TWSocketClient is closed, it automatically frees itself.  With a normal [[TWSocket]], the programmer is responsible for freeing the object.
  
Note: this page documents the properties of the SSL enabled version TSslWSocketServer.  
+
Note this page documents the properties of the SSL enabled version TSslWSocketServer.
  
 +
TWSocketServer is used in most other ICS servers, specifically TSslHttpServer, TSslHttpAppSrv, TIcsProx, TIcsProxy, TIcsHttpProxy, TSimpleWebSrv, TSslFtpServer and TSslSmtpServer, most of which expose the same properties and methods.  Note the FTP and SMTP servers don't support IcsHosts yet.
  
 
== Properties ==
 
== Properties ==
Line 66: Line 67:
 
| valign="top" | [[TWSocketServer.SocketErrs | SocketErrs ]] ||||How socket error messages should be presented as type TSocketErrs, wsErrTech or wsErrFriendly.
 
| valign="top" | [[TWSocketServer.SocketErrs | SocketErrs ]] ||||How socket error messages should be presented as type TSocketErrs, wsErrTech or wsErrFriendly.
 
|-
 
|-
| valign="top" | [[TWSocketServer.SocketFamily |SocketFamily ]] |||| IP address socket family as TSocketFamily, from sfIPv4, sfIPv6.
+
| valign="top" | [[TWSocketServer.SocketFamily |SocketFamily ]] |||| SocketFamily determines whether connections can use IPv4, IPv6 addresses or both, if both are available.  
 
|-
 
|-
 
| valign="top" | [[TWSocketServer.SslCertAutoOrder | SslCertAutoOrder ]] |||| True if IcsHosts are allowed to order and install SSL certificates automatically.  Requires SslX509Certs property to be set, and CertSupplierProto set for any IcsHost that will order certificates.
 
| valign="top" | [[TWSocketServer.SslCertAutoOrder | SslCertAutoOrder ]] |||| True if IcsHosts are allowed to order and install SSL certificates automatically.  Requires SslX509Certs property to be set, and CertSupplierProto set for any IcsHost that will order certificates.
Line 76: Line 77:
 
| valign="top" | [[TWSocketServer.SslContext |SslContext]] |||| Assign to an TSslContext component for SSL support, where SSL certificates, keys, protocols and ciphers are specified, ignored if any IcsHosts specified.
 
| valign="top" | [[TWSocketServer.SslContext |SslContext]] |||| Assign to an TSslContext component for SSL support, where SSL certificates, keys, protocols and ciphers are specified, ignored if any IcsHosts specified.
 
|-
 
|-
| valign="top" | [[TWSocketServer.SslX509Certs | SslX509Certs ]] |||| Assign to a TSslX509Certs component if automatic SSL certificate ordering is required.  Ir ia very important that the onCertProg is used to log progress messages from the certificate ordering process in case of errors.  The onCertsChallengeDNS event is called if a DNS server should be updated, onCertsOAuthAuthUrl if 0Auth2 authenication is needed, and onCertsNewCert when a new certificate is available which should be logged and the               RecheckSslCerts method called to cause the server to load it.
+
| valign="top" | [[TWSocketServer.SslX509Certs | SslX509Certs ]] |||| Assign to a TSslX509Certs component if automatic SSL certificate ordering is required.  Ir ia very important that the onCertProg is used to log progress messages from the certificate ordering process in case of errors.  The onCertsChallengeDNS event is called if a DNS server should be updated, onCertsOAuthAuthUrl if 0Auth2 authenication is needed, and onCertsNewCert when a new certificate is available which should be logged and the RecheckSslCerts method called to cause the server to load it.
 +
|-
 
| valign="top" | [[TWSocketServer.State | State]] |||| Gives the state of the component.
 
| valign="top" | [[TWSocketServer.State | State]] |||| Gives the state of the component.
|-
 
 
 
|}
 
|}
  
Line 97: Line 97:
 
| valign="top" | [[TWSocketServer.IsClient | IsClient]] |||| Check if a component reference is one of the connected clients.
 
| valign="top" | [[TWSocketServer.IsClient | IsClient]] |||| Check if a component reference is one of the connected clients.
 
|-
 
|-
| valign="top" | [[TWSocketServer.Listen | Listen]] |||| Start accepting connections.
+
| valign="top" | [[TWSocketServer.Listen | Listen]] |||| Start accepting connections on Addr/Port, but not any MultiListenSockets if defined.  
 +
|-
 +
| valign="top" | [[TWSocketServer.ListenAllOK | ListenAllOK]] |||| Returns true is all sockets are listening OK.                 
 +
|-
 +
| valign="top" | [[TWSocketServer.ListenStates | ListenStates]] |||| Returns a multiline string with state, IP address and port for all sockets.                 
 +
|-
 +
| valign="top" | [[TWSocketServer.LoadOneCert | LoadOneCert]] |||| Load existing SSL/TLS certificate, private key and intermediates for an IcsHost, either forced or only if newer than when last loaded. Also validates the certificate chain with the results in CertInfo and CertErrs.  Calls OrderCert if necessary.   
 
|-
 
|-
 
| valign="top" | [[TWSocketServer.MessageLoop | MessageLoop]] |||| Internal message loop.
 
| valign="top" | [[TWSocketServer.MessageLoop | MessageLoop]] |||| Internal message loop.
 
|-
 
|-
 
| valign="top" | [[TWSocketServer.MessagePump | MessagePump]] |||| Internal message pump.
 
| valign="top" | [[TWSocketServer.MessagePump | MessagePump]] |||| Internal message pump.
 +
|-
 +
| valign="top" | [[TWSocketServer.MultiClose | MultiClose]] |||| Stops listening on Addr/Port and any MultiListenSockets defined, does not disconnect connected clients.
 +
|-
 +
| valign="top" | [[TWSocketServer.MultiListen | MultiListen]] |||| Start accepting connections on Addr/Port and any MultiListenSockets defined.
 +
Beware this function gives an exception on the first listener that fails due to port conflicts and does not try any more.
 +
|-
 +
| valign="top" | [[TWSocketServer.MultiListenEx | MultiListenEx]] |||| Similar to MultiListen, but ignores port conflicts that prevent listening, returning an error string listing all addresses and ports with conflicts instead of one exception. 
 +
|-
 +
| valign="top" | [[TWSocketServer.OrderCert | OrderCert]] |||| Order a new SSL/TLS certificates from supplier for an IcsHost, provided the various settings allow this.
 
|-
 
|-
 
| valign="top" | [[TWSocketServer.ProcessMessage | ProcessMessage]] |||| Process a single message.
 
| valign="top" | [[TWSocketServer.ProcessMessage | ProcessMessage]] |||| Process a single message.
Line 107: Line 122:
 
| valign="top" | [[TWSocketServer.ProcessMessages | ProcessMessages]] |||| Process messages until message queue is empty.
 
| valign="top" | [[TWSocketServer.ProcessMessages | ProcessMessages]] |||| Process messages until message queue is empty.
 
|-
 
|-
| valign="top" | [[TWSocketServer.Release | Release]] |||| Destroy the current instance after the current event is terminated.
+
| valign="top" | [[TWSocketServer.RecheckSslCerts | RecheckSslCerts]] |||| If IcsHost have been specified, recheck SSL certificates to see if new files found (returns True) or old certificates will expire within CertExpireDays, calls LoadOneCert and OrderCert if necessary.  This should be called once the server has started listening to allow new certificates to be ordered, then at least once a day for expiring certificates.
 +
|-| valign="top" | [[TWSocketServer.Release | Release]] |||| Destroy the current instance after the current event is terminated.
 
|-
 
|-
 
| valign="top" | [[TWSocketServer.ThreadAttach | ThreadAttach]] |||| Detach from current thread.
 
| valign="top" | [[TWSocketServer.ThreadAttach | ThreadAttach]] |||| Detach from current thread.
 
|-
 
|-
 
| valign="top" | [[TWSocketServer.ThreadDetach | ThreadDetach]] |||| Attach to current thread.
 
| valign="top" | [[TWSocketServer.ThreadDetach | ThreadDetach]] |||| Attach to current thread.
 +
|-
 +
| valign="top" | [[TWSocketServer.ValidateHosts | ValidateHosts]] |||| If IcsHosts have been specified, these are used to define all server bindings and SSL contexts, including SSL certificates and security, with SSL Server Name Indication (SNI) used to select the correct host. HTTP descendants of SocketServer might check the Host: header for non=SSL connections.  \Returns a string with any errors, optionally ignores errors or stops on first error, such as SSL certificate not found.  This method is called before the server can start listening, so can not order any new SSL certificates.                 
 +
|-
 +
 +
 
|}
 
|}
  

Latest revision as of 10:55, 6 February 2019

Main page -> ICS component reference -> TWSocketServer

Overview

unit OverbyteIcsWSocketS.pas
inheritance TWSocket

TWSocketServer will normally be used to listen on a given TCP port. When a client connects, it will instantiate a new TWSocketClient component to handle communication with client. Normally you will derive your own component from TWSocketClient to add private data and methods to handle your processing needs. You tell TWSocketServer which component class it has to instantiate using ClientClass property. You have to initialize each instance created to handle each client from OnClientConnect event handler. TWSocketServer maintain a list of connected clients. You can access it using Client[] indexed property. ClientCount property is the size of Client[] array.

Since it is derived from TWSocket and TSslWSocket, lots of properties and events are unused and not listed here. Properties and events that have a meaning in both server or client component are listed here.

Note that TWSocketServer is only usable for incoming TCP connections. Use TWSocket if you need to use UDP.

Note: When a TWSocketClient is closed, it automatically frees itself. With a normal TWSocket, the programmer is responsible for freeing the object.

Note this page documents the properties of the SSL enabled version TSslWSocketServer.

TWSocketServer is used in most other ICS servers, specifically TSslHttpServer, TSslHttpAppSrv, TIcsProx, TIcsProxy, TIcsHttpProxy, TSimpleWebSrv, TSslFtpServer and TSslSmtpServer, most of which expose the same properties and methods. Note the FTP and SMTP servers don't support IcsHosts yet.

Properties

Addr Server listen IP address, IPv4 or IPv6, maybe 0.0.0.0 or :: to listen on all available addresses, ignored if any IcsHosts specified. IP address must exist and not be in use elsewhere for the same port.
Banner A short message line sent when each client connects. Should generally be blank.
BannerTooBusy A short message sent when a client connects and the number of clients already exceeds the MaxClients limit.
CertExpireDays When using IcsHosts, the number of days before an SSL server certificate is due to expire that warnings will be generated (by the method RecheckSslCerts, perhaps triggering automatic SSL certificate ordering.
Client Currently active clients of ClientClass, indexed base zero. Note the index value may change each time a new client connects or disconnects, so check CliId to confirm it's the correct one.
ClientClass The class type the application has derived from TSslWSocketClient for client application code.
ClientCount Number of connected clients.
DHParams Specifies a DHParams file name, created using the PenTools sample, or use the provided dhparam1024.pem or dhparam2048.pem files. Used for DH and DHE ciphers, but not needed for modern ECDHE ciphers. Rather than a file name, may be an ASCII PEM string containing the DHParams without any line endings.
Handle Handle of the hidden window used for socket operation.
HSocket Underlying winsock socket handle.
IcsHosts Allows one or more TIcsHosts to be set, as TIcsHostCollection, an alternate way for specifying multiple listeners that 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 (perhaps combined in a bundle), SSL context and security level, and other web server host related properties (used by higher level components). Each IcsHost has one or more HostNames to which it will recognise, that can share IP addresses.
LastError Last error which occurred.
ListenBacklog How many new client connections should be queued by Windows while the server accepts them, before the server starts rejecting new connections by immediately closing them. Recommended as 15 for heavy use servers, may be up to 250.
MaxClients Maximum number of simultaneous clients the server should accept if non-zero. Any further clients will receive then BannerTooBusy response and the connection closed, until earlier connections are closed.
MultiListenSockets Allows one or more extra server listen IP addresses and ports to be specified, as type TWSocketMultiListenCollection, allowing server to listen on several IP addresses/ports at the same time, in addition to the that specified as Addr/Port props. Each TWSocketMultiListenItem has Addr, Port, SocketFamily, SslEnable and ListenBacklog properties. Better to use IcsHosts for new applications which does the same, ignored if any IcsHosts specified.
MultiListenIndex Read only, which listen socket accepted last connection, -1 if default Addr.Poprt used, 0 or above is index into MultiListenSockets collection.
Port TCP port or service name to listen to, usually 80 or 443, ignored if any IcsHosts specified.
PortNum Readonly property with numeric value corresponding to Port.
Proto Protocol used. Must be 'tcp'.
RootCA Specifying a file name containing a PEM bundle of trusted root SSL certificates allows validation of SSL server certificate chains. ICS includes RootCaCertsBundle.pem (large) and TrustedCABundle.pem (medium size), and a default built-in (small) that will be used if no file is specified.
SocketErrs How socket error messages should be presented as type TSocketErrs, wsErrTech or wsErrFriendly.
SocketFamily SocketFamily determines whether connections can use IPv4, IPv6 addresses or both, if both are available.
SslCertAutoOrder True if IcsHosts are allowed to order and install SSL certificates automatically. Requires SslX509Certs property to be set, and CertSupplierProto set for any IcsHost that will order certificates.
SslEnable True if an SSL connection should be negotiated. ignored if any IcsHosts specified.
SslCliCertMethod Allows server to request a client SSL certificate from the browser or remote application, as type TSslCliCertMethod, with sslCliCertNone, sslCliCertOptional or sslCliCertRequire. Require will close the connection unless a valid certificate is received and validated against RootCA. Beware requesting a client certificate usually causes the browser to prompt the user for which certificate to send which can be obtrusive.
SslContext Assign to an TSslContext component for SSL support, where SSL certificates, keys, protocols and ciphers are specified, ignored if any IcsHosts specified.
SslX509Certs Assign to a TSslX509Certs component if automatic SSL certificate ordering is required. Ir ia very important that the onCertProg is used to log progress messages from the certificate ordering process in case of errors. The onCertsChallengeDNS event is called if a DNS server should be updated, onCertsOAuthAuthUrl if 0Auth2 authenication is needed, and onCertsNewCert when a new certificate is available which should be logged and the RecheckSslCerts method called to cause the server to load it.
State Gives the state of the component.

Methods

Abort Abort current asynchronous operation.
Close Stops listening, does not disconnect connected clients.
CloseDelayed Same as Close however it's executed delayed, after current event has finished.
Create Create a new instance of the component.
Destroy Destroy the current instance.
IsClient Check if a component reference is one of the connected clients.
Listen Start accepting connections on Addr/Port, but not any MultiListenSockets if defined.
ListenAllOK Returns true is all sockets are listening OK.
ListenStates Returns a multiline string with state, IP address and port for all sockets.
LoadOneCert Load existing SSL/TLS certificate, private key and intermediates for an IcsHost, either forced or only if newer than when last loaded. Also validates the certificate chain with the results in CertInfo and CertErrs. Calls OrderCert if necessary.
MessageLoop Internal message loop.
MessagePump Internal message pump.
MultiClose Stops listening on Addr/Port and any MultiListenSockets defined, does not disconnect connected clients.
MultiListen Start accepting connections on Addr/Port and any MultiListenSockets defined.

Beware this function gives an exception on the first listener that fails due to port conflicts and does not try any more.

MultiListenEx Similar to MultiListen, but ignores port conflicts that prevent listening, returning an error string listing all addresses and ports with conflicts instead of one exception.
OrderCert Order a new SSL/TLS certificates from supplier for an IcsHost, provided the various settings allow this.
ProcessMessage Process a single message.
ProcessMessages Process messages until message queue is empty.
RecheckSslCerts If IcsHost have been specified, recheck SSL certificates to see if new files found (returns True) or old certificates will expire within CertExpireDays, calls LoadOneCert and OrderCert if necessary. This should be called once the server has started listening to allow new certificates to be ordered, then at least once a day for expiring certificates.
ThreadAttach Detach from current thread.
ThreadDetach Attach to current thread.
ValidateHosts If IcsHosts have been specified, these are used to define all server bindings and SSL contexts, including SSL certificates and security, with SSL Server Name Indication (SNI) used to select the correct host. HTTP descendants of SocketServer might check the Host: header for non=SSL connections. \Returns a string with any errors, optionally ignores errors or stops on first error, such as SSL certificate not found. This method is called before the server can start listening, so can not order any new SSL certificates.

Events

OnBgException When a background exception occurs.
OnChangeState When the component state changes.
OnClientConnect When a new client is connecting.
OnClientCreate When a new client component instance is created.
OnClientDisconnect When a client disconnects.
OnError When an error occurs. Better to use exception handling.
OnMessagePump To call your own external message pump instead of built-in one.


TWSocketClient

Each new incoming connection to TSslWSocketServer causes a new instance of TSslWSocketClient to be created, with a number of read only properties set, that may be useful for client application code. Generally, applications will create their own class descended from TSslWSocketClient which is where all the code to listen to requests and send responses will go.


Server TCustomWSocketServer component to which the client belongs.
PeerAddr Remote IP address of the client, IPv4 or IPv6.
PeerPort Remote IP port of the client.
SessionClosedFlag True if the client is in the process of closing.
CliId A sequential client ID number that may be used to identify the client, note clients are creating and destroyed regularly.
IcsHostIdx If 0 or higher index into the IcsHosts collection, -1 if IcsHosts not used.
MultiListenIdx -1 if default SocketServer listener used, 0 or above is index into MultiListenSockets collection.
HostTag A short alphabetic name for the IcsHost, used variously in high level servers.
CServerAddr Local server IP address for listener.
CServerPort Local server IP port for listener.

How to



ICS Components Reference