Source Edit

This module implements a high-level cross-platform sockets interface. The procedures implemented in this module are primarily for blocking sockets. For asynchronous non-blocking sockets use the asyncnet module together with the asyncdispatch module.

The first thing you will always need to do in order to start using sockets, is to create a new instance of the Socket type using the newSocket procedure.

SSL

In order to use the SSL procedures defined in this module, you will need to compile your application with the -d:ssl flag. See the newContext procedure for additional details.

SSL on Windows

On Windows the SSL library checks for valid certificates. It uses the cacert.pem file for this purpose which was extracted from https://curl.se/ca/cacert.pem. Besides the OpenSSL DLLs (e.g. libssl-1_1-x64.dll, libcrypto-1_1-x64.dll) you also need to ship cacert.pem with your .exe file.

Examples

Connecting to a server

After you create a socket with the newSocket procedure, you can easily connect it to a server running at a known hostname (or IP address) and port. To do so over TCP, use the example below.

Example: cmd: -r:off

  1. import std/net
  2. let socket = newSocket()
  3. socket.connect("google.com", Port(80))

For SSL, use the following example:

Example: cmd: -r:off -d:ssl

  1. import std/net
  2. let socket = newSocket()
  3. let ctx = newContext()
  4. wrapSocket(ctx, socket)
  5. socket.connect("google.com", Port(443))

UDP is a connectionless protocol, so UDP sockets don’t have to explicitly call the connect procedure. They can simply start sending data immediately.

Example: cmd: -r:off

  1. import std/net
  2. let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  3. socket.sendTo("192.168.0.1", Port(27960), "status\n")

Example: cmd: -r:off

  1. import std/net
  2. let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
  3. let ip = parseIpAddress("192.168.0.1")
  4. doAssert socket.sendTo(ip, Port(27960), "status\c\l") == 8

Creating a server

After you create a socket with the newSocket procedure, you can create a TCP server by calling the bindAddr and listen procedures.

Example: cmd: -r:off

  1. import std/net
  2. let socket = newSocket()
  3. socket.bindAddr(Port(1234))
  4. socket.listen()
  5. # You can then begin accepting connections using the `accept` procedure.
  6. var client: Socket
  7. var address = ""
  8. while true:
  9. socket.acceptAddr(client, address)
  10. echo "Client connected from: ", address

Imports

since, nativesockets, os, strutils, times, sets, options, monotimes, ssl_config, winlean, openssl, ssl_certs, winlean

Types

  1. Certificate = string

DER encoded certificate Source Edit

  1. IpAddress = object
  2. case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6)
  3. of IpAddressFamily.IPv6:
  4. address_v6*: array[0 .. 15, uint8] ## Contains the IP address in bytes in
  5. ## case of IPv6
  6. of IpAddressFamily.IPv4:
  7. address_v4*: array[0 .. 3, uint8] ## Contains the IP address in bytes in
  8. ## case of IPv4

stores an arbitrary IP address Source Edit

  1. IpAddressFamily {.pure.} = enum
  2. IPv6, ## IPv6 address
  3. IPv4 ## IPv4 address

Describes the type of an IP address Source Edit

  1. ReadLineResult = enum
  2. ReadFullLine, ReadPartialLine, ReadDisconnected, ReadNone

result for readLineAsync Source Edit

  1. SOBool = enum
  2. OptAcceptConn, OptBroadcast, OptDebug, OptDontRoute, OptKeepAlive,
  3. OptOOBInline, OptReuseAddr, OptReusePort, OptNoDelay

Boolean socket options. Source Edit

  1. Socket = ref SocketImpl

Source Edit

  1. SocketFlag {.pure.} = enum
  2. Peek, SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown.

Source Edit

  1. SocketImpl = object
  2. when defineSsl:
  3. ## stores the last error on this socket

socket type Source Edit

  1. SslAcceptResult = enum
  2. AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess

Source Edit

  1. SslClientGetPskFunc = proc (hint: string): tuple[identity: string, psk: string]

Source Edit

  1. SslContext = ref object
  2. context*: SslCtx

Source Edit

  1. SslCVerifyMode = enum
  2. CVerifyNone, CVerifyPeer, CVerifyPeerUseEnvVars

Source Edit

  1. SslError = object of CatchableError

Source Edit

  1. SslHandshakeType = enum
  2. handshakeAsClient, handshakeAsServer

Source Edit

  1. SslProtVersion = enum
  2. protSSLv2, protSSLv3, protTLSv1, protSSLv23

Source Edit

  1. SslServerGetPskFunc = proc (identity: string): string

Source Edit

  1. TimeoutError = object of CatchableError

Source Edit

Consts

  1. BufferSize: int = 4000

size of a buffered socket’s buffer Source Edit

  1. MaxLineLength = 1000000

Source Edit

Procs

  1. proc `$`(address: IpAddress): string {....raises: [], tags: [], forbids: [].}

Converts an IpAddress into the textual representation Source Edit

  1. proc `==`(lhs, rhs: IpAddress): bool {....raises: [], tags: [], forbids: [].}

Compares two IpAddresses for Equality. Returns true if the addresses are equal Source Edit

  1. proc accept(server: Socket; client: var owned(Socket); flags = {SafeDisconn};
  2. inheritable = defined(nimInheritHandles)) {....tags: [ReadIOEffect],
  3. raises: [OSError, IOError, SslError], forbids: [].}

Equivalent to acceptAddr but doesn’t return the address, only the socket.

The SocketHandle associated with the resulting client will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.

Source Edit

  1. proc acceptAddr(server: Socket; client: var owned(Socket); address: var string;
  2. flags = {SafeDisconn}; inheritable = defined(nimInheritHandles)) {.
  3. ...tags: [ReadIOEffect], gcsafe, raises: [OSError, IOError, SslError],
  4. forbids: [].}

Blocks until a connection is being made from a client. When a connection is made sets client to the client socket and address to the address of the connecting client. This function will raise OSError if an error occurs.

The resulting client will inherit any properties of the server socket. For example: whether the socket is buffered or not.

The SocketHandle associated with the resulting client will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

The accept call may result in an error if the connecting socket disconnects during the duration of the accept. If the SafeDisconn flag is specified then this error will not be raised and instead accept will be called again.

Source Edit

  1. proc bindAddr(socket: Socket; port = Port(0); address = "") {.
  2. ...tags: [ReadIOEffect], raises: [ValueError, OSError], forbids: [].}

Binds address:port to the socket.

If address is “” then ADDR_ANY will be bound.

Source Edit

  1. proc bindUnix(socket: Socket; path: string) {....raises: [], tags: [], forbids: [].}

Binds Unix socket to path. This only works on Unix-style systems: Mac OS X, BSD and Linux Source Edit

  1. proc clientGetPskFunc(ctx: SslContext): SslClientGetPskFunc {....raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc clientGetPskFunc=(ctx: SslContext; fun: SslClientGetPskFunc) {....raises: [],
  2. tags: [], forbids: [].}

Sets function that returns the client identity and the PSK based on identity hint from the server.

Only used in PSK ciphersuites.

Source Edit

  1. proc close(socket: Socket; flags = {SafeDisconn}) {.
  2. ...raises: [LibraryError, Exception, SslError, OSError], tags: [RootEffect],
  3. forbids: [].}

Closes a socket.

If socket is an SSL/TLS socket, this proc will also send a closure notification to the peer. If SafeDisconn is in flags, failure to do so due to disconnections will be ignored. This is generally safe in practice. See here for more details.

Source Edit

  1. proc connect(socket: Socket; address: string; port = Port(0)) {.
  2. ...tags: [ReadIOEffect, RootEffect], raises: [OSError, SslError], forbids: [].}

Connects socket to address:port. Address can be an IP address or a host name. If address is a host name, this function will try each IP of that host name. htons is already performed on port so you must not do it.

If socket is an SSL socket a handshake will be automatically performed.

Source Edit

  1. proc connect(socket: Socket; address: string; port = Port(0); timeout: int) {.
  2. ...tags: [ReadIOEffect, WriteIOEffect, RootEffect],
  3. raises: [OSError, TimeoutError], forbids: [].}

Connects to server as specified by address on port specified by port.

The timeout parameter specifies the time in milliseconds to allow for the connection to the server to be made.

Source Edit

  1. proc connectUnix(socket: Socket; path: string) {....raises: [], tags: [],
  2. forbids: [].}

Connects to Unix socket on path. This only works on Unix-style systems: Mac OS X, BSD and Linux Source Edit

  1. proc destroyContext(ctx: SslContext) {....raises: [SslError], tags: [], forbids: [].}

Free memory referenced by SslContext. Source Edit

  1. proc dial(address: string; port: Port; protocol = IPPROTO_TCP; buffered = true): owned(
  2. Socket) {....tags: [ReadIOEffect, WriteIOEffect], raises: [OSError, IOError],
  3. forbids: [].}

Establishes connection to the specified address:port pair via the specified protocol. The procedure iterates through possible resolutions of the address until it succeeds, meaning that it seamlessly works with both IPv4 and IPv6. Returns Socket ready to send or receive data. Source Edit

  1. proc fromSockAddr(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6;
  2. sl: SockLen; address: var IpAddress; port: var Port) {.inline.}

Converts SockAddr and SockLen to IpAddress and Port. Raises ObjectConversionDefect in case of invalid sa and sl arguments. Source Edit

  1. proc getExtraData(ctx: SslContext; index: int): RootRef {....raises: [SslError],
  2. tags: [], forbids: [].}

Retrieves arbitrary data stored inside SslContext. Source Edit

  1. proc getFd(socket: Socket): SocketHandle {....raises: [], tags: [], forbids: [].}

Returns the socket’s file descriptor Source Edit

  1. proc getLocalAddr(socket: Socket): (string, Port) {.
  2. ...raises: [OSError, Exception], tags: [], forbids: [].}

Get the socket’s local address and port number.

This is high-level interface for getsockname.

Source Edit

  1. proc getPeerAddr(socket: Socket): (string, Port) {....raises: [OSError, Exception],
  2. tags: [], forbids: [].}

Get the socket’s peer address and port number.

This is high-level interface for getpeername.

Source Edit

  1. proc getPeerCertificates(socket: Socket): seq[Certificate] {.
  2. ...raises: [Exception], tags: [], forbids: [].}

Returns the certificate chain received by the peer we are connected to through the given socket. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. Source Edit

  1. proc getPeerCertificates(sslHandle: SslPtr): seq[Certificate] {.
  2. ...raises: [Exception], tags: [], forbids: [].}

Returns the certificate chain received by the peer we are connected to through the OpenSSL connection represented by sslHandle. The handshake must have been completed and the certificate chain must have been verified successfully or else an empty sequence is returned. The chain is ordered from leaf certificate to root certificate. Source Edit

  1. proc getPrimaryIPAddr(dest = parseIpAddress("8.8.8.8")): IpAddress {.
  2. ...raises: [OSError, OSError, SslError, ValueError, Exception, LibraryError],
  3. tags: [ReadIOEffect, RootEffect], forbids: [].}

Finds the local IP address, usually assigned to eth0 on LAN or wlan0 on WiFi, used to reach an external address. Useful to run local services.

No traffic is sent.

Supports IPv4 and v6. Raises OSError if external networking is not set up.

Example: cmd: -r:off

  1. echo getPrimaryIPAddr() # "192.168.1.2"

Source Edit

  1. proc getPskIdentity(socket: Socket): string {....raises: [], tags: [], forbids: [].}

Gets the PSK identity provided by the client. Source Edit

  1. proc getSocketError(socket: Socket): OSErrorCode {....raises: [OSError], tags: [],
  2. forbids: [].}

Checks osLastError for a valid error. If it has been reset it uses the last error stored in the socket object. Source Edit

  1. proc getSockOpt(socket: Socket; opt: SOBool; level = SOL_SOCKET): bool {.
  2. ...tags: [ReadIOEffect], raises: [OSError], forbids: [].}

Retrieves option opt as a boolean value. Source Edit

  1. proc gotHandshake(socket: Socket): bool {....raises: [SslError], tags: [],
  2. forbids: [].}

Determines whether a handshake has occurred between a client (socket) and the server that socket is connected to.

Throws SslError if socket is not an SSL socket.

Source Edit

  1. proc hasDataBuffered(s: Socket): bool {....raises: [], tags: [], forbids: [].}

Determines whether a socket has data buffered. Source Edit

  1. proc IPv4_any(): IpAddress {....raises: [], tags: [], forbids: [].}

Returns the IPv4 any address, which can be used to listen on all available network adapters Source Edit

  1. proc IPv4_broadcast(): IpAddress {....raises: [], tags: [], forbids: [].}

Returns the IPv4 broadcast address (255.255.255.255) Source Edit

  1. proc IPv4_loopback(): IpAddress {....raises: [], tags: [], forbids: [].}

Returns the IPv4 loopback address (127.0.0.1) Source Edit

  1. proc IPv6_any(): IpAddress {....raises: [], tags: [], forbids: [].}

Returns the IPv6 any address (::0), which can be used to listen on all available network adapters Source Edit

  1. proc IPv6_loopback(): IpAddress {....raises: [], tags: [], forbids: [].}

Returns the IPv6 loopback address (::1) Source Edit

  1. proc isDisconnectionError(flags: set[SocketFlag]; lastError: OSErrorCode): bool {.
  2. ...raises: [], tags: [], forbids: [].}

Determines whether lastError is a disconnection error. Only does this if flags contains SafeDisconn. Source Edit

  1. proc isIpAddress(addressStr: string): bool {....tags: [], raises: [], forbids: [].}

Checks if a string is an IP address Returns true if it is, false otherwise Source Edit

  1. proc isSsl(socket: Socket): bool {....raises: [], tags: [], forbids: [].}

Determines whether socket is a SSL socket. Source Edit

  1. proc listen(socket: Socket; backlog = SOMAXCONN) {....tags: [ReadIOEffect],
  2. raises: [OSError], forbids: [].}

Marks socket as accepting connections. Backlog specifies the maximum length of the queue of pending connections.

Raises an OSError error upon failure.

Source Edit

  1. proc newContext(protVersion = protSSLv23; verifyMode = CVerifyPeer;
  2. certFile = ""; keyFile = ""; cipherList = CiphersIntermediate;
  3. caDir = ""; caFile = ""; ciphersuites = CiphersModern): SslContext {.
  4. ...raises: [LibraryError, SslError, Exception, IOError, OSError],
  5. tags: [RootEffect, ReadDirEffect, ReadEnvEffect, ReadIOEffect], forbids: [].}

Creates an SSL context.

Protocol version is currently ignored by default and TLS is used. With -d:openssl10, only SSLv23 and TLSv1 may be used.

There are three options for verify mode: CVerifyNone: certificates are not verified; CVerifyPeer: certificates are verified; CVerifyPeerUseEnvVars: certificates are verified and the optional environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to locate certificates

The nimDisableCertificateValidation define overrides verifyMode and disables certificate verification globally!

CA certificates will be loaded, in the following order, from:

  • caFile, caDir, parameters, if set
  • if verifyMode is set to CVerifyPeerUseEnvVars, the SSL_CERT_FILE and SSL_CERT_DIR environment variables are used
  • a set of files and directories from the ssl_certs file.

The last two parameters specify the certificate file path and the key file path, a server socket will most likely not work without these.

Certificates can be generated using the following command:

  • openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout mykey.pem -out mycert.pem

or using ECDSA:

  • openssl ecparam -out mykey.pem -name secp256k1 -genkey
  • openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem

Source Edit

  1. proc newSocket(domain, sockType, protocol: cint; buffered = true;
  2. inheritable = defined(nimInheritHandles)): owned(Socket) {.
  3. ...raises: [OSError], tags: [], forbids: [].}

Creates a new socket.

The SocketHandle associated with the resulting Socket will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

If an error occurs OSError will be raised.

Source Edit

  1. proc newSocket(domain: Domain = AF_INET; sockType: SockType = SOCK_STREAM;
  2. protocol: Protocol = IPPROTO_TCP; buffered = true;
  3. inheritable = defined(nimInheritHandles)): owned(Socket) {.
  4. ...raises: [OSError], tags: [], forbids: [].}

Creates a new socket.

The SocketHandle associated with the resulting Socket will not be inheritable by child processes by default. This can be changed via the inheritable parameter.

If an error occurs OSError will be raised.

Source Edit

  1. proc newSocket(fd: SocketHandle; domain: Domain = AF_INET;
  2. sockType: SockType = SOCK_STREAM;
  3. protocol: Protocol = IPPROTO_TCP; buffered = true): owned(Socket) {.
  4. ...raises: [], tags: [], forbids: [].}

Creates a new socket as specified by the params. Source Edit

  1. proc parseIpAddress(addressStr: string): IpAddress {....raises: [ValueError],
  2. tags: [], forbids: [].}

Parses an IP address

Raises ValueError on error.

For IPv4 addresses, only the strict form as defined in RFC 6943 is considered valid, see https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1.

Source Edit

  1. proc pskIdentityHint=(ctx: SslContext; hint: string) {....raises: [SslError],
  2. tags: [], forbids: [].}

Sets the identity hint passed to server.

Only used in PSK ciphersuites.

Source Edit

  1. proc raiseSSLError(s = "") {....raises: [SslError], tags: [], forbids: [].}

Raises a new SSL error. Source Edit

  1. proc readLine(socket: Socket; line: var string; timeout = -1;
  2. flags = {SafeDisconn}; maxLength = MaxLineLength) {.
  3. ...tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError, SslError],
  4. forbids: [].}

Reads a line of data from socket.

If a full line is read \r\L is not added to line, however if solely \r\L is read then line will be set to it.

If the socket is disconnected, line will be set to “”.

An OSError exception will be raised in the case of a socket error.

A timeout can be specified in milliseconds, if data is not received within the specified time a TimeoutError exception will be raised.

The maxLength parameter determines the maximum amount of characters that can be read. The result is truncated after that.

Warning: Only the SafeDisconn flag is currently supported.

Source Edit

  1. proc recv(socket: Socket; data: pointer; size: int): int {....tags: [ReadIOEffect],
  2. raises: [], forbids: [].}

Receives data from a socket.

Note: This is a low-level function, you may be interested in the higher level versions of this function which are also named recv.

Source Edit

  1. proc recv(socket: Socket; data: pointer; size: int; timeout: int): int {.
  2. ...tags: [ReadIOEffect, TimeEffect], raises: [TimeoutError, OSError],
  3. forbids: [].}

overload with a timeout parameter in milliseconds. Source Edit

  1. proc recv(socket: Socket; data: var string; size: int; timeout = -1;
  2. flags = {SafeDisconn}): int {....raises: [TimeoutError, OSError, SslError],
  3. tags: [ReadIOEffect, TimeEffect],
  4. forbids: [].}

Higher-level version of recv.

Reads up to size bytes from socket into data.

For buffered sockets this function will attempt to read all the requested data. It will read this data in BufferSize chunks.

For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it.

When 0 is returned the socket’s connection has been closed.

This function will throw an OSError exception when an error occurs. A value lower than 0 is never returned.

A timeout may be specified in milliseconds, if enough data is not received within the time specified a TimeoutError exception will be raised.

Warning: Only the SafeDisconn flag is currently supported.

Source Edit

  1. proc recv(socket: Socket; size: int; timeout = -1; flags = {SafeDisconn}): string {.
  2. inline, ...raises: [TimeoutError, OSError, SslError],
  3. tags: [ReadIOEffect, TimeEffect], forbids: [].}

Higher-level version of recv which returns a string.

Reads up to size bytes from socket into the result.

For buffered sockets this function will attempt to read all the requested data. It will read this data in BufferSize chunks.

For unbuffered sockets this function makes no effort to read all the data requested. It will return as much data as the operating system gives it.

When “” is returned the socket’s connection has been closed.

This function will throw an OSError exception when an error occurs.

A timeout may be specified in milliseconds, if enough data is not received within the time specified a TimeoutError exception will be raised.

Warning: Only the SafeDisconn flag is currently supported.

Source Edit

  1. proc recvFrom[T: string | IpAddress](socket: Socket; data: var string;
  2. length: int; address: var T;
  3. port: var Port; flags = 0'i32): int {.
  4. ...tags: [ReadIOEffect].}

Receives data from socket. This function should normally be used with connection-less sockets (UDP sockets). The source address of the data packet is stored in the address argument as either a string or an IpAddress.

If an error occurs an OSError exception will be raised. Otherwise the return value will be the length of data received.

Warning: This function does not yet have a buffered implementation, so when socket is buffered the non-buffered implementation will be used. Therefore if socket contains something in its buffer this function will make no effort to return it.

Source Edit

  1. proc recvLine(socket: Socket; timeout = -1; flags = {SafeDisconn};
  2. maxLength = MaxLineLength): string {.
  3. ...raises: [TimeoutError, OSError, SslError], tags: [ReadIOEffect, TimeEffect],
  4. forbids: [].}

Reads a line of data from socket.

If a full line is read \r\L is not added to the result, however if solely \r\L is read then the result will be set to it.

If the socket is disconnected, the result will be set to “”.

An OSError exception will be raised in the case of a socket error.

A timeout can be specified in milliseconds, if data is not received within the specified time a TimeoutError exception will be raised.

The maxLength parameter determines the maximum amount of characters that can be read. The result is truncated after that.

Warning: Only the SafeDisconn flag is currently supported.

Source Edit

  1. proc send(socket: Socket; data: pointer; size: int): int {.
  2. ...tags: [WriteIOEffect], raises: [], forbids: [].}

Sends data to a socket.

Note: This is a low-level version of send. You likely should use the version below.

Source Edit

  1. proc send(socket: Socket; data: string; flags = {SafeDisconn}; maxRetries = 100) {.
  2. ...tags: [WriteIOEffect], raises: [SslError, OSError], forbids: [].}

Sends data to a socket. Will try to send all the data by handling interrupts and incomplete writes up to maxRetries. Source Edit

  1. proc sendTo(socket: Socket; address: IpAddress; port: Port; data: string;
  2. flags = 0'i32): int {.discardable, ...tags: [WriteIOEffect],
  3. raises: [OSError], forbids: [].}

This proc sends data to the specified IpAddress and returns the number of bytes written.

Generally for use with connection-less (UDP) sockets.

If an error occurs an OSError exception will be raised.

This is the high-level version of the above sendTo function.

Source Edit

  1. proc sendTo(socket: Socket; address: string; port: Port; data: pointer;
  2. size: int; af: Domain = AF_INET; flags = 0'i32) {.
  3. ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}

This proc sends data to the specified address, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname. This function should normally be used with connection-less sockets (UDP sockets).

If an error occurs an OSError exception will be raised.

Note: You may wish to use the high-level version of this function which is defined below.

Note: This proc is not available for SSL sockets.

Source Edit

  1. proc sendTo(socket: Socket; address: string; port: Port; data: string) {.
  2. ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}

This proc sends data to the specified address, which may be an IP address or a hostname, if a hostname is specified this function will try each IP of that hostname.

Generally for use with connection-less (UDP) sockets.

If an error occurs an OSError exception will be raised.

This is the high-level version of the above sendTo function.

Source Edit

  1. proc serverGetPskFunc(ctx: SslContext): SslServerGetPskFunc {....raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc serverGetPskFunc=(ctx: SslContext; fun: SslServerGetPskFunc) {....raises: [],
  2. tags: [], forbids: [].}

Sets function that returns PSK based on the client identity.

Only used in PSK ciphersuites.

Source Edit

  1. proc sessionIdContext=(ctx: SslContext; sidCtx: string) {....raises: [SslError],
  2. tags: [], forbids: [].}

Sets the session id context in which a session can be reused. Used for permitting clients to reuse a session id instead of doing a new handshake.

TLS clients might attempt to resume a session using the session id context, thus it must be set if verifyMode is set to CVerifyPeer or CVerifyPeerUseEnvVars, otherwise the connection will fail and SslError will be raised if resumption occurs.

  • Only useful if set server-side.
  • Should be unique per-application to prevent clients from malfunctioning.
  • sidCtx must be at most 32 characters in length.

Source Edit

  1. proc setExtraData(ctx: SslContext; index: int; data: RootRef) {.
  2. ...raises: [SslError], tags: [], forbids: [].}

Stores arbitrary data inside SslContext. The unique index should be retrieved using getSslContextExtraDataIndex. Source Edit

  1. proc setSockOpt(socket: Socket; opt: SOBool; value: bool; level = SOL_SOCKET) {.
  2. ...tags: [WriteIOEffect], raises: [OSError], forbids: [].}

Sets option opt to a boolean value specified by value.

Example: cmd: -r:off

  1. let socket = newSocket()
  2. socket.setSockOpt(OptReusePort, true)
  3. socket.setSockOpt(OptNoDelay, true, level = IPPROTO_TCP.cint)

Source Edit

  1. proc skip(socket: Socket; size: int; timeout = -1) {.
  2. ...raises: [TimeoutError, OSError], tags: [TimeEffect, ReadIOEffect],
  3. forbids: [].}

Skips size amount of bytes.

An optional timeout can be specified in milliseconds, if skipping the bytes takes longer than specified a TimeoutError exception will be raised.

Returns the number of skipped bytes.

Source Edit

  1. proc socketError(socket: Socket; err: int = -1; async = false;
  2. lastError = -1.OSErrorCode; flags: set[SocketFlag] = {}) {.
  3. ...gcsafe, raises: [SslError, OSError], tags: [], forbids: [].}

Source Edit

  1. proc sslHandle(self: Socket): SslPtr {....raises: [], tags: [], forbids: [].}

Retrieve the ssl pointer of socket. Useful for interfacing with openssl. Source Edit

  1. proc toCInt(opt: SOBool): cint {....raises: [], tags: [], forbids: [].}

Converts a SOBool into its Socket Option cint representation. Source Edit

  1. proc toOSFlags(socketFlags: set[SocketFlag]): cint {....raises: [], tags: [],
  2. forbids: [].}

Converts the flags into the underlying OS representation. Source Edit

  1. proc toSockAddr(address: IpAddress; port: Port; sa: var Sockaddr_storage;
  2. sl: var SockLen) {....raises: [], tags: [], forbids: [].}

Converts IpAddress and Port to SockAddr and SockLen Source Edit

  1. proc trySend(socket: Socket; data: string): bool {....tags: [WriteIOEffect],
  2. raises: [], forbids: [].}

Safe alternative to send. Does not raise an OSError when an error occurs, and instead returns false on failure. Source Edit

  1. proc wrapConnectedSocket(ctx: SslContext; socket: Socket;
  2. handshake: SslHandshakeType; hostname: string = "") {.
  3. ...raises: [SslError, Exception], tags: [RootEffect], forbids: [].}

Wraps a connected socket in an SSL context. This function effectively turns socket into an SSL socket. hostname should be specified so that the client knows which hostname the server certificate should be validated against.

This should be called on a connected socket, and will perform an SSL handshake immediately.

FIXME: Disclaimer: This code is not well tested, may be very unsafe and prone to security vulnerabilities.

Source Edit

  1. proc wrapSocket(ctx: SslContext; socket: Socket) {....raises: [SslError], tags: [],
  2. forbids: [].}

Wraps a socket in an SSL context. This function effectively turns socket into an SSL socket.

This must be called on an unconnected socket; an SSL session will be started when the socket is connected.

FIXME: Disclaimer: This code is not well tested, may be very unsafe and prone to security vulnerabilities.

Source Edit

Templates

  1. template `&=`(socket: Socket; data: typed)

an alias for ‘send’. Source Edit

Exports

Port, $, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, \==, Domain, SockType, Protocol