# `Teals`
[🔗](https://github.com/upmaru/teals/blob/v0.1.0/lib/teals.ex#L1)

TLS 1.3 server sockets that keep the half-close TLS 1.3 allows, for Ranch
and Cowboy, backed by rustls in a NIF.

It provides `config/1`, `handshake/3` on an accepted TCP socket, passive
`recv/3` and active mode, `send/2` from any process, half-close with
`shutdown/2`, `controlling_process/2` and bounded `close/1`,
`half_close: false` for sockets that should end on the peer's
`close_notify`, the Ranch transport `Teals.Ranch`, and
`Teals.Cowboy.StreamHandler`, which gives Cowboy and Plug the client
certificate and ends WebSockets on the peer's `close_notify`.

## Connections

`handshake/3` hands the accepted socket to a connection process, which
owns it and holds the TLS session, with a writer process beside it for the
blocking sends. The caller becomes the socket's owner (controlling process).
When the owner exits, the connection closes as `close/1` does: what was
already sent goes out, then `close_notify`, within `close_timeout`.

TCP is read only during the handshake, while a `recv/3` waits and while the
owner is in active mode, so a peer that sends faster than the owner reads
is held back by TCP.

## Active mode

With `setopts(socket, active: true | :once | n)` the owner receives, as
`:gen_tcp` owners do:

  * `{:teals, socket, data}` - plaintext, at most 64 KiB per message, or
    the smaller `buffer` option (see `setopts/2`).
  * `{:teals_read_closed, socket}` - the peer sent `close_notify` after all
    earlier data, and the socket can still send. It sets the socket passive
    without a `:teals_passive` message, and each later arm reports it once
    more.
  * `{:teals_closed, socket}` - both directions have ended (or reading was
    shut down).
  * `{:teals_error, socket, reason}` - `:truncated` when TCP ended without
    `close_notify`, or why the connection failed. A failure is reported in
    any mode before the connection ends.
  * `{:teals_passive, socket}` - an `active: n` count reached 0.

# `config_error`

```elixir
@type config_error() ::
  {:unknown_option, atom()}
  | {:missing_option, atom()}
  | {:conflicting_options, [atom()]}
  | {:invalid_option, atom()}
  | {:unexpected_option, atom()}
  | {:file, atom(), File.posix()}
  | :no_certificate
  | :invalid_certificate
  | :invalid_key
  | :key_mismatch
  | {:unsupported_key, String.t()}
  | :no_cacerts
  | :invalid_cacerts
  | {:tls, String.t()}
```

Why `config/1` refused its options.

# `config_option`

```elixir
@type config_option() ::
  {:certfile, Path.t()}
  | {:cert, binary()}
  | {:keyfile, Path.t()}
  | {:key, binary()}
  | {:verify, Teals.Config.verify()}
  | {:cacertfile, Path.t()}
  | {:cacerts, binary()}
  | {:alpn, [binary()]}
  | {:close_timeout, pos_integer()}
```

Options for `config/1`.

  * `:certfile` or `:cert` - the server certificate chain, leaf first, as a
    PEM file path or PEM binary. Required.
  * `:keyfile` or `:key` - the leaf's private key (PKCS#8, PKCS#1 or SEC1),
    as a PEM file path or PEM binary. Required.
  * `:verify` - client certificate verification, `:none` (default),
    `:request`, `:optional` or `:required`. See below.
  * `:cacertfile` or `:cacerts` - the CA certificates that issue client
    certificates, as a PEM file path or PEM binary. Required for `:optional`
    and `:required`, refused otherwise.
  * `:alpn` - ALPN protocols to offer, in preference order, for example
    `["http/1.1"]`. Default none.
  * `:close_timeout` - milliseconds that closing may take to flush data
    already accepted, including when the socket's owner exits. Default
    1,000.

Client verification modes:

  * `:none` - no certificate is asked for.
  * `:request` - a certificate is asked for, naming no CA. Any certificate
    is accepted, and none; the client must prove it holds the certificate's
    key. Nothing else in the certificate is checked, so a host that uses
    it to authenticate must decide trust itself, for example by
    fingerprint.
  * `:optional` - no certificate, or one issued by a configured CA.
  * `:required` - only a certificate issued by a configured CA.

Server keys may be ECDSA P-256 or P-384, Ed25519, or RSA of 2048 to 4096
bits. Only TLS 1.3 is offered.

# `close`

```elixir
@spec close(Teals.Socket.t()) :: :ok
```

Closes the connection. Any process may call it.

It accepts no more data and answers waiting calls with `{:error, :closed}`,
sends what is already queued and then `close_notify` (unless the write side
is already shut down), and closes the TCP socket. It returns within the
configuration's `close_timeout`: if the peer does not read, what is still
queued is dropped and the connection is reset.

# `config`

```elixir
@spec config([config_option()]) :: {:ok, Teals.Config.t()} | {:error, config_error()}
```

Validates a server configuration and builds it once, for use by every
connection.

Returns `{:ok, config}`, or `{:error, reason}` without a configuration. An
error never contains key material.

    {:ok, config} =
      Teals.config(
        certfile: "server.pem",
        keyfile: "server-key.pem",
        verify: :request,
        alpn: ["http/1.1"]
      )

See `t:config_option/0` for the options.

# `controlling_process`

```elixir
@spec controlling_process(Teals.Socket.t(), pid()) :: :ok | {:error, term()}
```

Makes `pid` the socket's owner. Only the owner may call it.

Active-mode messages for the socket already in the caller's mailbox move to
the new owner, in order and ahead of any later message.

Returns `:ok`, or `{:error, reason}` where `reason` is `:not_owner`,
`:closed`, or `:ealready` while an earlier handover is unfinished.

# `handshake`

```elixir
@spec handshake(:gen_tcp.socket(), Teals.Config.t(), timeout()) ::
  {:ok, Teals.Socket.t()} | {:error, term()}
```

Performs a TLS 1.3 server handshake on an accepted, passive `:gen_tcp`
socket, within `timeout` milliseconds.

The caller must be the socket's controlling process. It becomes the owner of
the returned `Teals.Socket`, which starts passive. On failure the socket is
closed, after a TLS alert where one applies.

Returns `{:ok, socket}` or `{:error, reason}`, where `reason` is `:timeout`,
`:closed` (the peer ended the connection), `{:tls, message}` (the handshake
failed, for example a client offering only TLS 1.2 or a certificate the
verification mode refuses), `:not_owner` or an `:inet` error.

# `negotiated_protocol`

```elixir
@spec negotiated_protocol(Teals.Socket.t()) ::
  {:ok, binary()} | {:error, :protocol_not_negotiated | :closed}
```

The protocol chosen by ALPN, or `{:error, :protocol_not_negotiated}`.

# `peercert`

```elixir
@spec peercert(Teals.Socket.t()) :: {:ok, binary()} | {:error, :no_peercert | :closed}
```

The client's certificate in DER, or `{:error, :no_peercert}` if it sent none.

# `peername`

```elixir
@spec peername(Teals.Socket.t()) ::
  {:ok, {:inet.ip_address(), :inet.port_number()}} | {:error, term()}
```

The peer's address and port. Any process may call it.

# `recv`

```elixir
@spec recv(Teals.Socket.t(), non_neg_integer(), timeout()) ::
  {:ok, binary()} | {:error, term()}
```

Receives plaintext on a passive socket, as `:gen_tcp.recv/3` does. Only the
owner may call it.

With `length` 0 it returns all the data available, waiting for some if there
is none. Otherwise it returns exactly `length` bytes, except that once
reading has ended the remaining bytes come back even if fewer, before the
reason. With `timeout` 0 it takes what has already arrived without waiting.

Errors:

  * `:read_closed` - the peer sent `close_notify` and all earlier data has
    been received; the socket can still send.
  * `:truncated` - TCP ended without `close_notify`, so the data may be
    incomplete.
  * `:timeout` - nothing arrived in time; the connection stays usable.
  * `:closed` - the connection has ended.
  * `:not_owner` - the caller is not the owner.
  * `:einval` - the socket is in active mode.
  * `{:tls, message}` - the peer sent something TLS refuses; the connection
    ends.

# `send`

```elixir
@spec send(Teals.Socket.t(), iodata()) :: :ok | {:error, term()}
```

Sends data on the socket. Any process may call it.

It returns once all of `data` is encrypted and queued for the wire, which
happens only while less than 512 KiB of ciphertext is waiting to be sent,
so a peer that stops reading holds `send/2` back instead of filling memory.
Concurrent sends are served in the order they arrive, and one send's bytes
never mix with another's. Receiving goes on while a send waits.

Errors:

  * `:timeout` - the send could not progress within `send_timeout` (see
    `setopts/2`). Part of `data` may have been sent. With
    `send_timeout_close: true` the connection is then closed.
  * `:closed` - the connection has ended, or writing failed earlier.
  * a reason from the socket, if writing failed while the send waited.

# `setopts`

```elixir
@spec setopts(Teals.Socket.t(), keyword()) :: :ok | {:error, :einval | :closed}
```

Sets socket options. Any process may call it.

  * `active` - `false` (the default), `true`, `:once`, or a count from
    -32,768 to 32,767 that adds to the current one; at 0 or less the socket
    becomes passive and the owner receives `{:teals_passive, socket}`. See
    the module documentation for the messages.
  * `send_timeout` - milliseconds a `send/2` may go without progress before
    it returns `{:error, :timeout}`, or `:infinity` (the default). Applies
    to sends that start afterwards.
  * `send_timeout_close` - whether such a timeout closes the connection.
    Default `false`.
  * `half_close` - `true` (the default) keeps writing open after the
    peer's `close_notify`. With `false` the peer's `close_notify` ends the
    connection, as on OTP's `:ssl`: after the data before it, the owner
    gets `{:teals_closed, socket}` or `{:error, :closed}`, `close_notify`
    goes back after the sends already waiting, and later sends return
    `{:error, :closed}`. Set after read EOF, it takes effect at once: the
    next arm or `recv/3` reports the connection closed.
  * `buffer` - the most plaintext, in bytes, in one active-mode
    `{:teals, socket, data}` message. Default and limit 64 KiB; a larger
    value means 64 KiB. Passive `recv/3` is unaffected.

Any other option, or an invalid value, returns `{:error, :einval}` and sets
nothing.

# `shutdown`

```elixir
@spec shutdown(Teals.Socket.t(), :read | :write | :read_write) ::
  :ok | {:error, :closed}
```

Ends one or both directions. Any process may call it.

  * `:write` - sends `close_notify` after every send that arrived first,
    then shuts down the TCP write side once it has gone out. Receiving goes
    on; later sends return `{:error, :write_closed}`. Once the peer's
    `close_notify` arrives too, `recv/3` reports `{:error, :closed}`.
  * `:read` - drops further input; `recv/3` then reports
    `{:error, :closed}`.
  * `:read_write` - both.

The connection stays until `close/1` or the owner's exit.

# `sockname`

```elixir
@spec sockname(Teals.Socket.t()) ::
  {:ok, {:inet.ip_address(), :inet.port_number()}} | {:error, term()}
```

The local address and port. Any process may call it.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
