tup/socket
Bindings to the Erlang modules for accepting and working with TCP and TLS connections.
Types
Whether received data is delivered as Messages or read with receive.
pub type ActiveState {
Passive
Always
Once
Packets(count: Int)
}
Constructors
-
PassiveNothing is delivered. Read the socket with
receive. -
AlwaysEvery message as it arrives.
-
OnceOne message, then back to
Passive. -
Packets(count: Int)countmessages, then back toPassive.
The address family of a socket.
pub type AddressFamily {
Inet
Inet6
}
Constructors
-
InetIPv4.
-
Inet6IPv6.
What a TLS alert says, as listed in RFC 8446.
pub type AlertDescription {
CloseNotify
UnexpectedMessage
BadRecordMac
RecordOverflow
HandshakeFailure
BadCertificate
UnsupportedCertificate
CertificateRevoked
CertificateExpired
CertificateUnknown
IllegalParameter
UnknownCa
AccessDenied
DecodeError
DecryptError
ProtocolVersion
InsufficientSecurity
InternalError
InappropriateFallback
UserCanceled
NoRenegotiation
MissingExtension
UnsupportedExtension
CertificateUnobtainable
UnrecognizedName
BadCertificateStatusResponse
UnknownPskIdentity
CertificateRequired
NoApplicationProtocol
UnknownAlert
}
Constructors
-
CloseNotifyThe sender is closing the connection cleanly.
-
UnexpectedMessageA message arrived out of order.
-
BadRecordMacA record failed its authentication check.
-
RecordOverflowA record was longer than the protocol allows.
-
HandshakeFailureNo set of security parameters could be agreed.
-
BadCertificateThe certificate is corrupt.
-
UnsupportedCertificateThe certificate is of an unsupported type.
-
CertificateRevokedThe certificate was revoked by its signer.
-
CertificateExpiredThe certificate has expired or is not yet valid.
-
CertificateUnknownThe certificate was rejected for an unspecified reason.
-
IllegalParameterA handshake field was out of range or inconsistent.
-
UnknownCaThe certificate chain does not end at a trusted authority.
-
AccessDeniedThe certificate is valid but was refused access.
-
DecodeErrorA message could not be decoded.
-
DecryptErrorA cryptographic operation failed.
-
ProtocolVersionThe peer offered an unsupported protocol version.
-
InsufficientSecurityThe peer’s security parameters are too weak.
-
InternalErrorA local error unrelated to the protocol or the peer.
-
InappropriateFallbackThe peer attempted a version downgrade.
-
UserCanceledThe handshake was cancelled for a reason unrelated to the protocol.
-
NoRenegotiationRenegotiation was refused.
-
MissingExtensionA required extension was absent.
-
UnsupportedExtensionThe peer returned an extension that was never offered.
-
CertificateUnobtainableThe certificate could not be fetched.
-
UnrecognizedNameThe server does not serve the requested SNI name.
-
BadCertificateStatusResponseThe OCSP response is invalid.
-
UnknownPskIdentityThe pre shared key identity is not known.
-
CertificateRequiredA certificate was required and the client sent none.
-
NoApplicationProtocolThe ALPN lists have no protocol in common.
-
UnknownAlertAn alert with no fixed shape.
A certificate chain together with the private key of the certificate it ends in.
pub type CertificateKey {
CertificateFiles(
certificate_file: String,
key_file: String,
password: option.Option(String),
)
CertificateChain(chain: List(BitArray), key: PrivateKey)
}
Constructors
-
CertificateFiles( certificate_file: String, key_file: String, password: option.Option(String), )PEM files on disk.
passworddecrypts the key file when it is encrypted. -
CertificateChain(chain: List(BitArray), key: PrivateKey)DER in memory. The server’s own certificate first and then each issuer.
Whether a verified certificate is also checked against a revocation list.
Only applies with Verify(VerifyPeer).
pub type CrlMode {
CrlDisabled
CrlWholeChain
CrlPeerOnly
CrlBestEffort
}
Constructors
-
CrlDisabledNo revocation check.
-
CrlWholeChainCheck every certificate in the chain. A list that cannot be fetched fails the connection.
-
CrlPeerOnlyCheck the peer’s own certificate only.
-
CrlBestEffortCheck what can be checked. A list that cannot be fetched is ignored.
Which local address a listen socket binds.
pub type Interface {
Address(IpAddress)
Any
Loopback
Local(String)
}
Constructors
-
Address(IpAddress)The interface that has this address.
-
AnyEvery interface. The default.
-
LoopbackThe loopback interface only.
-
Local(String)The path of a Unix domain socket. Needs
portto be0.
An IPv4 or IPv6 address.
pub type IpAddress {
Ipv4(Int, Int, Int, Int)
Ipv6(Int, Int, Int, Int, Int, Int, Int, Int)
}
Constructors
-
Ipv4(Int, Int, Int, Int)Four octets.
-
Ipv6(Int, Int, Int, Int, Int, Int, Int, Int)Eight 16 bit groups.
A group the key exchange may use. Either an elliptic curve or a finite field Diffie-Hellman group from RFC 7919.
pub type KeyExchangeGroup {
X25519
X448
Secp256r1
Secp384r1
Secp521r1
Ffdhe2048
Ffdhe3072
Ffdhe4096
Ffdhe6144
Ffdhe8192
}
Constructors
-
X25519Curve25519.
-
X448Curve448.
-
Secp256r1NIST P-256.
-
Secp384r1NIST P-384.
-
Secp521r1NIST P-521.
-
Ffdhe20482048 bit finite field.
-
Ffdhe30723072 bit finite field.
-
Ffdhe40964096 bit finite field.
-
Ffdhe61446144 bit finite field.
-
Ffdhe81928192 bit finite field.
A socket that accepts connections.
pub type ListenSocket
How much a TLS connection writes to the logger.
pub type LogLevel {
LogNothing
LogError
LogWarning
LogNotice
LogInformation
LogDebug
LogEverything
}
Constructors
-
LogNothingNothing.
-
LogErrorErrors.
-
LogWarningErrors and warnings.
-
LogNoticeThe above and notices.
-
LogInformationThe above and informational messages.
-
LogDebugThe above and debug messages.
-
LogEverythingEverything.
What a non-Passive socket delivers to its owner. Build a selector for
them with selector.
pub type Message {
Incoming(BitArray)
Disconnected
Failed(reason: SocketError)
Exhausted
}
Constructors
-
Incoming(BitArray)Data received.
-
DisconnectedThe peer closed the connection.
-
Failed(reason: SocketError)The connection failed and is now closed.
-
ExhaustedThe socket has gone back to
Passive.
Why a private key could not be read from PEM.
pub type PemError {
NoPrivateKey
EncryptedPrivateKey
WrongPassword
}
Constructors
-
NoPrivateKeyThe bytes hold no private key.
-
EncryptedPrivateKeyThe key is encrypted and no password was given.
-
WrongPasswordThe password does not decrypt the key.
A DER encoded private key named after the ASN.1 structure it is encoded as. Encrypted keys have to be decrypted before they get here.
pub type PrivateKey {
RsaPrivateKey(BitArray)
DsaPrivateKey(BitArray)
EcPrivateKey(BitArray)
PrivateKeyInfo(BitArray)
}
Constructors
-
RsaPrivateKey(BitArray)A PKCS #1
RSAPrivateKey. -
DsaPrivateKey(BitArray)A
DSAPrivateKey. -
EcPrivateKey(BitArray)A SEC 1
ECPrivateKey. -
PrivateKeyInfo(BitArray)A PKCS #8
PrivateKeyInfo.
Which direction of a connection shutdown closes.
pub type ShutdownMode {
Read
Write
ReadWrite
}
Constructors
-
ReadStop receiving. Anything the peer sends from now on is discarded.
-
WriteStop sending. The peer sees the end of the stream.
-
ReadWriteStop both.
Why a call failed. The variants starting with E are the operating
system’s errno values under their usual names.
pub type SocketError {
Closed
Timeout
NotOwner
SystemLimit
Unsupported
NotNegotiated
NoPeerCertificate
TlsAlert(description: AlertDescription, detail: String)
BadTlsOption(option: String, detail: String)
Eacces
Eaddrinuse
Eaddrnotavail
Eafnosupport
Eagain
Ealready
Ebadf
Econnaborted
Econnrefused
Econnreset
Ehostdown
Ehostunreach
Einprogress
Eintr
Einval
Eio
Eisconn
Emfile
Emsgsize
Enetdown
Enetreset
Enetunreach
Enfile
Enobufs
Enomem
Enoprotoopt
Enotconn
Enotsock
Enotsup
Eperm
Epipe
Eproto
Eprotonosupport
Eprototype
Etimedout
Ewouldblock
Exbadport
Exbadseq
Failure(reason: dynamic.Dynamic)
}
Constructors
-
ClosedThe socket is closed.
-
TimeoutThe call’s timeout ran out.
-
NotOwnerThe calling process does not own the socket.
-
SystemLimitAn Erlang system limit was reached.
-
UnsupportedThe call does not exist on this transport.
-
NotNegotiatedNo ALPN protocol was agreed.
-
NoPeerCertificateThe peer sent no certificate.
-
TlsAlert(description: AlertDescription, detail: String)A TLS alert sent by the peer or raised locally.
detailis Erlang’s wording of it. -
BadTlsOption(option: String, detail: String)A
TlsOptionwas rejected before the socket opened. This always indicates a configuration mistake. -
EaccesPermission denied.
-
EaddrinuseThe address and port are already bound by another socket.
-
EaddrnotavailThe address is not one of this host’s.
-
EafnosupportThe address family is not supported.
-
EagainThe operation would block on a non-blocking socket.
-
EalreadyAn operation is already in progress on the socket.
-
EbadfThe descriptor is not valid.
-
EconnabortedThe connection was aborted before it was accepted.
-
EconnrefusedThe peer refused the connection.
-
EconnresetThe peer reset the connection.
-
EhostdownThe remote host is down.
-
EhostunreachNo route to the remote host.
-
EinprogressThe operation is in progress.
-
EintrThe call was interrupted by a signal.
-
EinvalAn argument was invalid.
-
EioAn input or output error.
-
EisconnThe socket is already connected.
-
EmfileThe process ran out of file descriptors.
-
EmsgsizeThe message is longer than the transport allows.
-
EnetdownThe network is down.
-
EnetresetThe connection was reset by the network.
-
EnetunreachThe network is unreachable.
-
EnfileThe system ran out of file descriptors.
-
EnobufsThe system ran out of buffer space.
-
EnomemThe system ran out of memory.
-
EnoprotooptThe protocol does not know the option.
-
EnotconnThe socket is not connected.
-
EnotsockThe descriptor is not a socket.
-
EnotsupThe operating system does not support the operation.
-
EpermThe operation is not permitted.
-
EpipeThe write end is closed.
-
EprotoA protocol error.
-
EprotonosupportThe protocol is not supported.
-
EprototypeThe wrong protocol type for the socket.
-
EtimedoutThe connection timed out.
-
EwouldblockThe operation would block. The same as
Eagainon most systems. -
ExbadportThe inet driver was given a bad port.
-
ExbadseqThe inet driver was given commands out of sequence.
-
Failure(reason: dynamic.Dynamic)A reason with no fixed shape.
Options for either transport. The ones marked “listen only” are fixed when
the socket opens. The rest can also be changed later with set_options.
Sockets are always opened in binary mode and deliver bytes unframed.
pub type TcpOption {
Backlog(Int)
BindAddress(Interface)
Family(AddressFamily)
Ipv6Only(Bool)
FileDescriptor(Int)
Active(ActiveState)
ReuseAddress(Bool)
ReusePort(Bool)
NoDelay(Bool)
DelaySend(Bool)
KeepAlive(Bool)
Linger(enabled: Bool, seconds: Int)
SendTimeout(Timeout)
SendTimeoutClose(Bool)
ExitOnClose(Bool)
ShowConnectionReset(Bool)
Buffer(Int)
ReceiveBuffer(Int)
SendBuffer(Int)
HighWatermark(Int)
LowWatermark(Int)
HighMessageQueueWatermark(Int)
LowMessageQueueWatermark(Int)
}
Constructors
-
Backlog(Int)Listen only. How many pending connections the kernel queues.
-
BindAddress(Interface)Listen only. The local address to bind.
-
Family(AddressFamily)Listen only. The address family which has to match
BindAddress. -
Ipv6Only(Bool)Listen only. Refuse IPv4 mapped addresses on an IPv6 socket.
-
FileDescriptor(Int)Listen only. An already open file descriptor to listen on.
-
Active(ActiveState)How received data reaches the owner.
-
ReuseAddress(Bool)Allow binding a port that is still in
TIME_WAIT. That allows a restarted server to reclaim its port. -
ReusePort(Bool)Let several sockets bind the same port.
-
NoDelay(Bool)Send small writes at once instead of coalescing them (Nagle’s algorithm).
-
DelaySend(Bool)Let the driver queue writes rather than sending each one immediately.
-
KeepAlive(Bool)Send periodic TCP keepalive probes.
-
Linger(enabled: Bool, seconds: Int)Whether
closeblocks to flush unsent data and for how long. -
SendTimeout(Timeout)How long a send waits on a peer that is not reading.
-
SendTimeoutClose(Bool)Close the socket when a send times out.
-
ExitOnClose(Bool)Whether the socket closes when the peer closes its end.
Falsekeeps the write side usable after the peer has finished sending. -
ShowConnectionReset(Bool)Report a reset as
Econnresetinstead of a plain close. -
Buffer(Int)The driver’s user level receive buffer in bytes.
-
ReceiveBuffer(Int)The kernel receive buffer in bytes.
-
SendBuffer(Int)The kernel send buffer in bytes.
-
HighWatermark(Int)The send queue size at which the port counts as busy.
-
LowWatermark(Int)The send queue size at which the port counts as idle again.
-
HighMessageQueueWatermark(Int)HighWatermarkfor the driver’s message queue. -
LowMessageQueueWatermark(Int)LowWatermarkfor the driver’s message queue.
Which TLS 1.3 session resumption the server offers.
pub type TicketMode {
TicketsDisabled
Stateful
Stateless
}
Constructors
-
TicketsDisabledNone.
-
StatefulThe server keeps the session state.
-
StatelessThe session state travels inside the ticket.
How long a blocking call may wait.
pub type Timeout {
Milliseconds(Int)
Never
}
Constructors
-
Milliseconds(Int)Give up after this many milliseconds.
-
NeverWait forever.
The TLS options a listener takes alongside its TcpOptions.
pub type TlsOption {
CertificateKeys(List(CertificateKey))
ServerNameCertificates(List(#(String, CertificateKey)))
CertificateAuthorityFile(String)
CertificateAuthorities(List(BitArray))
SendCertificateAuthorities(Bool)
Verify(VerifyMode)
FailWithoutPeerCertificate(Bool)
Depth(Int)
CrlCheck(CrlMode)
Versions(List(TlsVersion))
SupportedGroups(List(KeyExchangeGroup))
AlpnPreferredProtocols(List(BitArray))
HonorCipherOrder(Bool)
ReuseSessions(Bool)
SecureRenegotiate(Bool)
ClientRenegotiation(Bool)
SessionTickets(TicketMode)
DiffieHellmanFile(String)
HibernateAfter(Int)
MaximumHandshakeSize(Int)
Logging(LogLevel)
}
Constructors
-
CertificateKeys(List(CertificateKey))The server’s own certificates and keys. It is required to have at least one specified since an empty list opens a socket that accepts connections and then fails every handshake.
-
ServerNameCertificates(List(#(String, CertificateKey)))Certificates to serve instead of
CertificateKeyswhen the client asks for a particular name through SNI keyed by that name. -
CertificateAuthorityFile(String)A PEM file of trusted certificate authorities.
-
CertificateAuthorities(List(BitArray))Trusted certificate authorities as DER.
-
SendCertificateAuthorities(Bool)Whether the server tells the client which authorities it accepts when asking for a certificate. TLS 1.3 only.
-
Verify(VerifyMode)Whether the client is asked for a certificate.
-
FailWithoutPeerCertificate(Bool)With
VerifyPeer, reject a client that sends no certificate. -
Depth(Int)How many intermediate certificates a chain may have.
-
CrlCheck(CrlMode)Whether a verified certificate is also checked against a revocation list.
-
Versions(List(TlsVersion))The protocol versions the server accepts.
-
SupportedGroups(List(KeyExchangeGroup))The groups the key exchange may use, most preferred first. Applies to TLS 1.3 and to the TLS 1.2 elliptic curve exchanges.
-
AlpnPreferredProtocols(List(BitArray))The protocols the server picks from the client’s ALPN list, most preferred first.
-
HonorCipherOrder(Bool)Use the server’s cipher order rather than the client’s.
-
ReuseSessions(Bool)Allow TLS 1.2 session resumption.
-
SecureRenegotiate(Bool)Refuse to renegotiate with a peer that does not support RFC 5746. TLS 1.2 only, since 1.3 has no renegotiation.
-
ClientRenegotiation(Bool)Whether the client may ask to renegotiate. TLS 1.2 only.
-
SessionTickets(TicketMode)Which TLS 1.3 session resumption to offer.
-
DiffieHellmanFile(String)A PEM file of Diffie-Hellman parameters.
-
HibernateAfter(Int)Hibernate an idle connection process after this many milliseconds.
-
MaximumHandshakeSize(Int)The largest handshake message accepted.
-
Logging(LogLevel)How much the connection writes to the logger.
A TLS protocol version. 1.0 and 1.1 are deprecated by RFC 8996 and are not offered.
pub type TlsVersion {
Tls13
Tls12
}
Constructors
-
Tls13TLS 1.3.
-
Tls12TLS 1.2.
Which Erlang module a socket belongs to. Returned by listen and listen_tls
and passed to everything else.
pub type Transport {
Tcp
Ssl
}
Constructors
-
TcpPlain TCP.
-
SslTLS.
Whether the server asks the client for a certificate.
pub type VerifyMode {
VerifyNone
VerifyPeer
}
Constructors
-
VerifyNoneNo certificate is requested.
-
VerifyPeerA certificate is requested and checked.
Values
pub fn accept(
transport: Transport,
socket: ListenSocket,
timeout: Timeout,
) -> Result(Socket, SocketError)
Wait for the next connection. On Ssl this accepts only the TCP
connection and the socket carries no data until handshake has run which
leaves room to hand the socket to another process first.
pub fn certificates_from_pem(pem: BitArray) -> List(BitArray)
Every certificate in a PEM file. Entries that are not certificates are skipped.
pub fn close(
transport: Transport,
socket: Socket,
) -> Result(Nil, SocketError)
Close a connection. Unsent data is flushed or dropped according to
Linger.
pub fn close_listener(
transport: Transport,
socket: ListenSocket,
) -> Result(Nil, SocketError)
Close a listen socket and release its port. Every accept blocked on it
returns Closed.
pub fn controlling_process(
transport: Transport,
socket: Socket,
pid: process.Pid,
) -> Result(Nil, SocketError)
Make pid the owner of the socket. Only the current owner may do this.
Messages already delivered stay in the caller’s mailbox so transfer
before taking the socket out of Passive.
pub fn describe_alert_description(
description: AlertDescription,
) -> String
An AlertDescription as a lower case phrase that reads after a colon.
pub fn describe_error(error: SocketError) -> String
A SocketError as a lower case phrase that reads after a colon.
"Could not open the listen socket: " <> describe_error(error)
pub fn describe_pem_error(error: PemError) -> String
A PemError as a lower case phrase that reads after a colon.
pub fn endpoint_to_string(endpoint: Endpoint) -> String
An endpoint as text. IPv6 addresses are bracketed. An abstract Unix socket
whose path starts with a NUL byte is written with a leading @. An unnamed
Unix endpoint is the empty string.
pub fn handshake(
transport: Transport,
socket: Socket,
timeout: Timeout,
) -> Result(Socket, SocketError)
Run the TLS handshake on an accepted socket. Use the socket it returns
from then on as the one passed in is consumed. On Tcp the socket is
returned unchanged so this function is safe to call on every transport.
pub fn ip_address_to_string(address: IpAddress) -> String
An address as text, following
RFC 5952: the lower case hex, the
longest run of zero groups collapsed to :: and IPv4 mapped addresses in
their mixed form such as ::ffff:192.0.2.1.
pub fn listen(
port: Int,
options: List(TcpOption),
) -> Result(#(Transport, ListenSocket), SocketError)
Open a TCP listen socket on port or on a port the system picks when
port is 0. The socket belongs to the calling process and closes when
that process exits.
pub fn listen_tls(
port: Int,
options: List(TcpOption),
tls_options: List(TlsOption),
) -> Result(#(Transport, ListenSocket), SocketError)
listen over TLS. A rejected TLS option fails as BadTlsOption.
pub fn negotiated_protocol(
transport: Transport,
socket: Socket,
) -> Result(BitArray, SocketError)
The protocol agreed through ALPN. Returns NotNegotiated when none was
agreed and Unsupported on Tcp.
pub fn peer_certificate(
transport: Transport,
socket: Socket,
) -> Result(BitArray, SocketError)
The peer’s DER certificate. Only present when the listener asked for one
with Verify(VerifyPeer). Returns NoPeerCertificate otherwise and
Unsupported on Tcp.
pub fn peername(
transport: Transport,
socket: Socket,
) -> Result(Endpoint, SocketError)
The address and port of the peer.
pub fn private_key_from_pem(
pem: BitArray,
password: option.Option(String),
) -> Result(PrivateKey, PemError)
The first private key in a PEM file. password is needed when the key is
encrypted.
pub fn receive(
transport: Transport,
socket: Socket,
bytes: Int,
timeout: Timeout,
) -> Result(BitArray, SocketError)
Read from a Passive socket. Blocking until bytes bytes have arrived or
timeout runs out. 0 takes whatever is there.
pub fn selector(
transport: Transport,
) -> process.Selector(Message)
A selector for the messages of a socket on this transport. Merge it into
the selector of the process that owns a non-Passive socket.
pub fn send(
transport: Transport,
socket: Socket,
data: bytes_tree.BytesTree,
) -> Result(Nil, SocketError)
Send data. Blocking until it is queued or until SendTimeout elapses.
pub fn set_options(
transport: Transport,
socket: Socket,
options: List(TcpOption),
) -> Result(Nil, SocketError)
Change the options of an open connection. Listen only options are rejected
with Einval.
pub fn shutdown(
transport: Transport,
socket: Socket,
mode: ShutdownMode,
) -> Result(Nil, SocketError)
Close one or both directions of a connection.
pub fn sockname(
transport: Transport,
socket: Socket,
) -> Result(Endpoint, SocketError)
The local address and port of a connection.
pub fn sockname_listener(
transport: Transport,
socket: ListenSocket,
) -> Result(Endpoint, SocketError)
The address and port a listen socket is bound to. This is how to learn
the port after listening on 0.
pub fn system_certificate_authorities() -> List(BitArray)
The certificates the operating system trusts. Raises when the host has no trust store to read.