Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

stSocket

Feature notes: Bounded DNS lookups: safe DLL and package shutdown

Classes, interfaces and records

classEstSocketError

inherits from Exception

constructor CreateCode(aErrorCode: Integer; const aMessage: string);
Zero means no native code was supplied. Inherited Exception constructors retain that value; CreateCode stores a code captured at the failure site. Windows' bounded connect expiry uses WSAETIMEDOUT.
property ErrorCode: Integer read fErrorCode;

classtAbstractSocket

procedure Listen(const aAddress: string; aPort: Word; aQueueSize: Integer = 128); virtual; abstract;
Server-side entry point: binds aAddress/aPort and puts the socket into the listening state so AcceptHandle can pull in incoming connections (see StreamSec.SSH.SocketServer.pas's accept loop). Full description »
procedure Open(const aAddress: string; aPort: Word); overload; virtual; abstract;
Client-side entry point: connects out to aAddress/aPort (see StreamSec.SSH.SocketClient.pas). Not normally called directly by application code -- reached via a *Client component's connect logic.
procedure Open(const aAddress: string; aPort: Word; const aSourceIP: string); overload; virtual;
Opens with an explicit LOCAL source address and an OS-assigned port. The source is a literal, never a host name. Empty preserves automatic source selection. A bind failure raises and closes the socket; it NEVER retries unbound. The base refuses a non-empty source so older descendants cannot silently ignore it.
procedure Open(const aAddress: string; aPort: Word; const aSourceIP: string; aTimeout: Cardinal); overload; virtual;
Adds a TCP connect limit in milliseconds. Zero preserves the original platform behaviour. A finite limit leaves the connected socket non-blocking so later Send calls can be bounded by WaitForWrite. Name resolution is outside this limit: pass a resolved literal when an end-to-end deadline is required. Older descendants refuse a finite limit.
function AcceptHandle: TSocketHandle; virtual; abstract;
Neutral accept: returns the new connection's OS handle (the peer address is re-derived by the wrapper). tWinSocket keeps an addr-bearing Accept. Server-side only: called from a listening socket's accept loop after Listen to hand off each newly-arrived client connection (e.g. StreamSec.SSH.SocketServer.pas).
procedure Close; virtual; abstract;
Tears down the OS handle/events on both client and server sockets; safe to call whether the socket came from Open (client) or Listen/AcceptHandle (server side). Full description »
procedure ShutdownSend; virtual; abstract;
Half-close: shuts the SENDING direction only (shutdown SD_SEND / SHUT_WR), so the peer sees EOF on its reads while this end can still receive whatever the peer has left to send. Full description »
function WaitForData(aMSec: Cardinal): Boolean; virtual; abstract;
Blocking poll used by both client and server code (e.g. AbstractOcsp's HTTP client wait vs PkixOcspServer's accept-loop wait) to avoid a busy loop while waiting for a peer to send data, a listener to gain a pending connection, or the socket to close; see tWinSocket's implementation notes on manua... Full description »
function WaitForWrite(aMSec: Cardinal): Boolean; virtual; abstract;
Blocking poll for WRITABILITY, the counterpart of WaitForData: True once the socket can accept more outbound bytes, False on timeout, on a Wake, or when the socket is gone. Full description »
procedure Wake; virtual; abstract;
Makes a WaitForData/WaitForWrite blocked on this socket return False promptly, and - because the signal is STICKY - makes the next such call return False immediately if none is blocked yet. Full description »
function ReceiveLength: Integer; virtual; abstract;
Reports how many bytes are already buffered and ready to Receive without blocking; used to size a single non-blocking read (e.g. TLSOctetConnection's message framing). 0 does NOT tell an idle connection from one that has ended: an orderly close, a reset and an abort all read 0 here. Ask ConnectionEnded for that.
function ConnectionEnded(aErrorCode: PInteger = nil): Boolean; virtual;
True when the connection has ENDED, as far as that can be seen without waiting and without taking any data: - the peer has closed its end (FIN) and every byte it sent before has been read; - the connection has failed - reset by the peer, or aborted by this end's stack, which on Windows also disca... Full description »
function Receive(var aBuf; aCount: Integer; aErrorCode: PInteger = nil): Integer; virtual; abstract;
Non-blocking-friendly read: application/protocol code (TLS, SSH, OCSP transports) calls this after WaitForData/ReceiveLength indicate data is available, on either a client or an accepted server connection; aErrorCode lets the caller handle a broken connection without an exception. Full description »
function Send(var aBuf; aCount: Integer; aErrorCode: PInteger = nil): Integer; virtual; abstract;
Writes outgoing bytes on a connected socket, client or server side alike; aErrorCode lets the caller handle a broken connection without an exception. Full description »
function SendAll(var aBuf; aCount: Integer; aStallTimeout: Cardinal; aCancel: PBoolean = nil): Integer; overload;
Writes ALL aCount bytes: the remedy the Send contract prescribes, in one place. A partial count sends the rest; a would-block waits on WaitForWrite and retries with the same bytes. Full description »
function SendAll(var aBuf; aCount: Integer; aStallTimeout: Cardinal; aCancel: PBoolean; aOnStall: TSocketStallProc): Integer; overload;
SendAll, calling aOnStall (when assigned) each time a send finds no room, before it waits for room - then for at most 1 ms at a time, so that aOnStall is called again soon. aOnStall runs on the calling thread, inside SendAll. » member page
procedure Lock; virtual; abstract;
Serializes Send/Close and similar socket operations across threads; application code using the higher-level components normally relies on those components' own locking rather than calling this directly.
procedure Unlock; virtual; abstract;
Releases the lock taken by Lock; balance every Lock with exactly one Unlock (typically via try/finally). Same caveat as Lock: application code using the higher-level components normally relies on those components' own locking.
property Connected: Boolean read GetConnected;
True whenever the socket holds a live OS handle -- after Open (client) has connected, after Listen has bound a listener, or on an accepted server-side handle; becomes False after Close (the getter is simply handle <> invalid). Callers such as SocketClient poll this to detect disconnection.
property LocalPort: Word read GetLocalPort;
Local bound/ephemeral port; on a listening (server) socket this is the bind port, on a client socket it is the OS-assigned outbound port.
property LocalAddress: string read GetLocalAddress;
Local bound address, mirroring LocalPort's client/server duality.
property RemotePort: Word read GetRemotePort;
Peer's port: on a server-side accepted connection this is the connecting client's port; on a client socket it is the port passed to Open.
property RemoteAddress: string read GetRemoteAddress;
Peer's address, mirroring RemotePort's client/server duality.

classtAbstractDatagramSocket

A UDP socket: one datagram per call, whole or not at all, each with its own peer. Unlike tAbstractSocket there is no connection, so there is no end of stream and NO ERROR CLOSES THE SOCKET - an ICMP report about an earlier datagram, a datagram too large for the buffer, a full send buffer are all things that happen to one datagram, and the next is unaffected. Only Close closes it. The socket is non-blocking on every platform: a call never waits, and WaitForData is the way to wait. On Windows the system's habit of failing a RECEIVE with WSAECONNRESET after an earlier send drew an ICMP port-unreachable is switched off (see stWinsock2), so one unreachable peer cannot disturb the others. An IPv6 socket is IPv6-only on every platform (the defaults differ); bind a second socket for IPv4. IP fragmentation (the DF bit) and path-MTU discovery follow the system's defaults until SetDontFragment is called.

procedure Bind(const aLocal: tSocketAddress); virtual; abstract;
Creates the socket and binds it to aLocal - an address literal of the family wanted, its wildcard (AnySocketAddress) for every interface, and port 0 for one the system picks (LocalAddress then says which). Raises EstSocketError when the socket cannot be made or bound.
procedure Close; virtual; abstract;
Safe from any thread, also while another waits on this socket: the wait returns False at once, and every later call answers cDatagramClosed.
function SendTo(const aBuf; aCount: Integer; const aTo: tSocketAddress; aErrorCode: PInteger = nil): Integer; virtual; abstract;
Sends aCount octets to aTo as ONE datagram. = aCount sent - handed to the system whole. < 0 and aErrorCode^ = 0 WOULD BLOCK: the send buffer is full, and nothing was sent. Full description »
function SendSegmentsTo(const aBuf; aCount, aSegmentSize: Integer; const aTo: tSocketAddress; aErrorCode: PInteger = nil): Integer; virtual;
Sends aCount octets to aTo as consecutive datagrams of aSegmentSize octets, the last one possibly shorter. Full description »
function SendSegmentsToEcn(const aBuf; aCount, aSegmentSize: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; aErrorCode: PInteger = nil): Integer; virtual;
SendSegmentsTo with every datagram marked aEcn (deNotEct, deEct0 or deEct1), as SendToEcn marks one. 0 with aErrorCode^ = cDatagramUnsupported means that nothing was sent: send the datagrams again with SendSegmentsTo. The default calls SendSegmentsTo for deNotEct and SendToEcn once per datagram otherwise.
function ReceiveFrom(var aBuf; aCount: Integer; out aFrom: tSocketAddress; aErrorCode: PInteger = nil): Integer; virtual; abstract;
Takes the next datagram, if one is waiting. >= 0 its length; aFrom is its sender. 0 is a real, empty datagram, NOT an end of stream - a datagram socket has none. Full description »
function WaitForData(aMSec: Cardinal): Boolean; virtual; abstract;
True once a datagram is waiting; False on timeout, after a Wake (sticky, as tAbstractSocket.Wake), and when the socket is closed.
procedure Wake; virtual; abstract; procedure SetBufferSizes(aReceive, aSend: Integer); virtual; abstract;
The system's receive and send buffer sizes in octets; 0 leaves one as it is. A server that takes a burst of datagrams on one socket wants a receive buffer far above the default, or the system drops the burst.
function SetDontFragment(aEnabled: Boolean; out aError: Integer): Boolean; virtual;
aEnabled True forbids IP fragmentation of outgoing datagrams (sets DF), as QUIC requires; False allows it, which need not be the system's original setting. Result False: aError is cDatagramClosed, cDatagramUnsupported or a system error. A backend that does not override this reports cDatagramUnsupported, so tQuicClient cannot start on it.
function SetEcnReception(aEnabled: Boolean; out aError: Integer): Boolean; virtual;
Receiving ECN (Explicit Congestion Notification) marks is off until SetEcnReception(True) succeeds; then ReceiveFromEcn reports each datagram's ECN bits in aEcn (deUnknown where the platform cannot). Full description »
function SendToEcn(const aBuf; aCount: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; aErrorCode: PInteger = nil): Integer; virtual; function ReceiveFromEcn(var aBuf; aCount: Integer; out aFrom: tSocketAddress; out aEcn: tDatagramEcn; aErrorCode: PInteger = nil): Integer; virtual; property Bound: Boolean read GetBound; property LocalAddress: tSocketAddress read GetLocalAddress;

classtWinDatagramSocket

inherits from tAbstractDatagramSocket

constructor Create; destructor Destroy; override; procedure Bind(const aLocal: tSocketAddress); override; procedure Close; override; function SendTo(const aBuf; aCount: Integer; const aTo: tSocketAddress; aErrorCode: PInteger = nil): Integer; override; function SendSegmentsTo(const aBuf; aCount, aSegmentSize: Integer; const aTo: tSocketAddress; aErrorCode: PInteger = nil): Integer; override; function ReceiveFrom(var aBuf; aCount: Integer; out aFrom: tSocketAddress; aErrorCode: PInteger = nil): Integer; override; function WaitForData(aMSec: Cardinal): Boolean; override; procedure Wake; override; procedure SetBufferSizes(aReceive, aSend: Integer); override; function SetDontFragment(aEnabled: Boolean; out aError: Integer): Boolean; override; function SetEcnReception(aEnabled: Boolean; out aError: Integer): Boolean; override; function SendToEcn(const aBuf; aCount: Integer; const aTo: tSocketAddress; aEcn: tDatagramEcn; aErrorCode: PInteger = nil): Integer; override; function ReceiveFromEcn(var aBuf; aCount: Integer; out aFrom: tSocketAddress; out aEcn: tDatagramEcn; aErrorCode: PInteger = nil): Integer; override;

classtWinSocket

inherits from tAbstractSocket

constructor Create(aSocket: TSocket = INVALID_SOCKET; aAddr: PSockAddrIn = nil); destructor Destroy; override; class function LookupName(const aName: string): TSockAddrIn;
getaddrinfo's first IPv4 or IPv6 answer for aName, with port 0: a name with both kinds of address may come back as either, so read sin_family before sin_addr (LookupNameEx prefers IPv4). A name that does not resolve raises EstSocketError with getaddrinfo's code in ErrorCode.
class function LookupNameEx(const aName: string; var aAddr: TSockAddrIn): string; class function LookupService(const aService: string): Integer; procedure Listen(const aAddress: string; aPort: Word; aQueueSize: Integer = SOMAXCONN); override; procedure Open(const aAddress: string; aPort: Word); overload; override; procedure Open(const aAddress: string; aPort: Word; const aSourceIP: string); overload; override; procedure Open(const aAddress: string; aPort: Word; const aSourceIP: string; aTimeout: Cardinal); overload; override; function Accept(aAddr: PSockAddr): TSocket; function AcceptHandle: TSocketHandle; override;
Delegates to TSocketHandle, passing 1 argument(s), and returns its result.
procedure Close; override; procedure ShutdownSend; override; function WaitForData(aMSec: Cardinal): Boolean; override; function WaitForWrite(aMSec: Cardinal): Boolean; override; procedure Wake; override; function ReceiveLength: Integer; override; function ConnectionEnded(aErrorCode: PInteger = nil): Boolean; override; function Receive(var aBuf; aCount: Integer; aErrorCode: PInteger = nil): Integer; override; function Send(var aBuf; aCount: Integer; aErrorCode: PInteger = nil): Integer; override; procedure Lock; override; procedure Unlock; override; property Connected: Boolean read GetConnected; property LocalPort: Word read GetLocalPort; property LocalAddress: string read GetLocalAddress; property RemotePort: Word read GetRemotePort; property RemoteAddress: string read GetRemoteAddress;

recordtHostLookupAnswer

What a lookup answered.

Address: string;
hlrFound: an address literal.
ErrorCode: Integer;
hlrNotFound: getaddrinfo's code, or 0 when an answer held no usable address; HostLookupErrorText describes it.
Failure: string;
hlrFailed: what the lookup raised (class and message), or why it could not be started.

Types (enumerations, sets, aliases)

typeTSocketHandle

  TSocketHandle = NativeUInt;   // WinSock SOCKET = UINT_PTR (pointer-sized); NativeUInt is universally available

typeTSocketHandle

  TSocketHandle = Integer;      // POSIX socket fd is a 32-bit int on all targets

procTSocketStallProc

What SendAll calls each time a send finds no room, before it waits for room: for a caller that has to go on reading the connection while it waits to write, because the peer may itself be waiting to write until it is read.

  TSocketStallProc = procedure of object;

procTSocketErrorProc

  TSocketErrorProc = procedure (aErrorCode: Integer);

enumtHostLookupFamily

Which addresses LookupHostWithin asks the system resolver for. With
hlfPreferIPv4 it answers as LookupHost does: on Windows an IPv4 address when the name has one and whatever it has otherwise, elsewhere an IPv4 address only. hlfIPv4 and hlfIPv6 ask for that family only.

  tHostLookupFamily = (hlfPreferIPv4, hlfIPv4, hlfIPv6);

enumtHostLookupResult

How LookupHostWithin ended. hlrFailed: the lookup raised, or no thread could be started for it (Failure says which). hlrBusy: none was started, because cHostLookupMaxRunning lookups are still running; retry later or fail the request. hlrStopped: ShutdownHostLookups has closed admission for good; every later LookupHostWithin in this module returns it.

  tHostLookupResult = (hlrFound, hlrNotFound, hlrFailed, hlrTimedOut,
                       hlrCancelled, hlrBusy, hlrStopped);

proctHostLookupCancelQuery

Asked between waits, on the calling thread: True once the caller has given up.

  tHostLookupCancelQuery = function: Boolean of object;

proctHostResolveFunc

A resolver LookupHostWithin can run in getaddrinfo's place. It answers as getaddrinfo would - an address literal, or '' with a code - and runs on the lookup's own thread, possibly after the caller has stopped waiting, so it must touch nothing the caller owns.

  tHostResolveFunc = function(const aName: string; aFamily: tHostLookupFamily;
                              out aErrorCode: Integer): string;

Routines