C Collections

chttpclient · Overview

chttpclient

chttpclient - overview of the HTTP/1.1 client of the C Collections Library

C Collections (libccollections, -lccollections)

#include <ccollections/chttpclient.h>

chttpclient sends HTTP/1.1 requests and reads their responses, over
plain TCP, TLS or a Unix domain socket. chttpclient.h includes chttp.h,
which holds the types that the client shares with the server:
  - chttp_method.
  - chttp_request_body and its CHTTP_*_BODY macros.
  - chttp_tls_config.
  - The CHTTP_STATUS_* constants.
  - The base64 helpers and the Basic auth helpers.
 
Link a program that uses the client with -lccollections. The library
itself depends on OpenSSL (libssl and libcrypto), so a link against the
shared library needs nothing else. For a static link, take the full
list from pkg-config:
 
    cc app.c $(pkg-config --cflags --libs --static ccollections)
 
You can build the library without the client (make
WITH_CHTTPCLIENT=0), and a program that uses the client then fails to
link.

chttpcli is an opaque VALUE handle, a uint64_t and not a pointer. Do
not cast it to or from a pointer, and do not use it as an address.
CHTTPCLI_NULL is 0 and plays the role of NULL for chttpcli, so
"if (!cli)" tests whether you have a client.
 
Every call resolves the handle before it touches the client, so a
stale handle (one whose client was destroyed) is detected and refused.
A stale handle gives:
  - ccol_invalid_args from a function.
  - NULL from a function that returns a future.
  - A fatal error from chttpcli_destroy.
It never leads to a read of freed memory.
 
chttpcli_create and chttpcli_create_mp make a client, and
chttpcli_construct, chttpcli_construct_scoped, chttpcli_declare and
chttpcli_declare_scoped are wrappers around them. chttpcli_destroy
destroys a client.
 
chttp_default_client returns a single client for the whole process,
which chttp_get, chttp_post, chttp_put, chttp_delete, chttp_patch,
chttp_do_default and chttp_perform use. The library owns that client, so do
not destroy it.

Every client, the default client included, has three timeouts, each
set in microseconds and turned off by 0:
  - The connect timeout bounds the TCP connect and, for HTTPS, the
    TLS handshake. It is 30 s by default.
  - The inactivity timeout bounds the time a request waits on its
    connection with no byte moving either way. It is 60 s by default,
    so a server that stops answering never holds a request for ever,
    and a slow transfer that keeps moving is never cut off.
  - The request timeout bounds the whole request. It is off by
    default.
A request that runs out of any of them ends with ccol_timed_out. See
chttpcli_set_connect_timeout(3),
chttpcli_set_inactivity_timeout(3) and
chttpcli_set_request_timeout(3).

A chttp_request holds a method, a URL, a body and a set of headers.
chttp_request_create and chttp_request_create_mp copy the URL and the
body, so the caller can free its own buffers immediately. The method,
expect_continue and prevent_tls_downgrade_on_redirect fields are public
to read and to write. The url and body fields are public to read only,
because the request owns those copies and chttp_request_free frees them
with the request's allocator; never assign to them, and build another
request when you need another URL or another body. Set and read headers
with chttp_request_set_header and chttp_request_get_header, and free
the request with chttp_request_free.
 
Header names, protocol tokens, URI schemes and host names are compared
and folded by ASCII case only, whatever the process's LC_CTYPE locale.
Under a Turkish locale, for example, "AUTHORIZATION" names the
Authorization header just as it does everywhere else.

chttpcli_response has four public fields:
 
  status_code  the HTTP status of the final response.
  body         a heap buffer that ends with a NUL, or NULL.
  body_len     the number of bytes in body before that NUL.
  headers      a chmap(char * -> char *) from each lower-case field
               name to its value.
 
body is NULL and body_len is 0 in these cases:
  - A body of zero length, such as a 204, a response to HEAD or a
    "Content-Length: 0".
  - Every streaming request, whose body goes to the write callback.
So check that body != NULL or body_len > 0 before you read body, even
after a success.
 
When the server sends a name on more than one line, the name maps to
its values joined with ", ", except Set-Cookie, which maps to its first
value; see chttpcli_resp_header(3). chttpcli_resp_free frees the
response. A response does not depend on the client that made it, so
you can free it before or after chttpcli_destroy.
 
Every entry point that takes a resp_out sets *resp_out to NULL before
anything else and leaves it NULL on every return that is not a
success. Since chttpcli_resp_free(NULL) does nothing, calling it
after such a request is always safe.

Tier 1 is chttpcli_do and chttpcli_do_streaming. The request runs
on the calling thread, which blocks until it ends. The client's pool
size (chttpcli_set_pool_size) caps how many Tier 1 requests run at
the same time, and a caller over that cap waits for a slot.
 
Tier 2 is chttpcli_do_async and chttpcli_do_async_streaming. The
request goes to a shared reactor engine and the call returns a
cthrpool_future at once; chttpcli_async_result_get waits for the
result.
 
Tier 3 is chttpcli_do_pooled and chttpcli_do_pooled_streaming.
The request is submitted through the same engine and the call blocks
until it ends, with the same call shape as Tier 1. Many callers then
share the engine's few threads, instead of each request tying up a
thread of its own.
 
Tiers 2 and 3 use one engine per process, shared by all clients. It
starts on first use and stops on its own when no request is in progress
and no connection is left in the pool. You configure it with
chttpcli_set_engine_logger, chttpcli_set_engine_mem_mgmt_procs and
chttpcli_set_engine_num_reactor_threads, and it is separate from
chttpserver's reactor. The engine stops on its own thread after the
last client lets go of it, and chttpcli_engine_wait blocks until that
stop is complete; once it returns, the engine makes no call to its
allocator or through its logger. The write_fn of
chttpcli_do_async_streaming and chttpcli_do_pooled_streaming runs
on an engine thread, so calling chttpcli_destroy on any client, or
chttpcli_engine_wait, from there is fatal: Each of them waits for work
that those threads run.
 
All three tiers apply the same rules to URLs, redirects, headers, TLS,
"Expect: 100-continue", interim responses and limits, and they all
return the same result codes.

After a response on a keep-alive connection, the client keeps the
connection in an idle pool keyed by origin:
  - "scheme://host:port", where hosts are compared without regard to
    case.
  - "unix://<path>" for a Unix domain socket.
An HTTPS connection keeps its TLS session, so a later request to the
same origin skips DNS, the TCP handshake and the TLS handshake.
 
The pool has a cap per origin and a cap in total, and an idle
connection expires after a short time. Over a cap, the client closes a
finished connection instead of putting it in the pool.
 
Before it reuses a pooled connection, the client checks it. If the peer
closed the connection or sent data on it while it was idle, the client
closes it and takes another one, at no cost to the caller. Bytes that
arrive after a complete response answer no request, and the client
never reads them as the response to the next request.
 
A reused connection can turn out to be dead, which the client can only
see after it has written the request. If nothing came back on that
connection, the client sends the request once more on a new connection,
but only in these cases:
  - The connection did not take the whole request, so the server never
    received it as a whole.
  - The request is idempotent: Its method is GET, HEAD, OPTIONS, PUT or
    DELETE (RFC 9110 section 9.2.2), or it carries an Idempotency-Key
    or an X-Idempotency-Key header.
A POST or PATCH without either header that went out in full may have
run on the server already, so the client doesn't send it again. The
request fails with ccol_http_transfer_aborted, and the application
decides whether to repeat it. The client also never resends a request
after it sent a body that a "100 Continue" confirmed, whatever the
method, because the server accepted that body.
 
The client never keeps these connections:
  - A connection whose request had a Connection header that lists the
    "close" option (RFC 9112 section 9.6), in any ASCII case, whatever
    the response says.
  - A connection whose response started before the client sent the
    full request.
  - A connection whose request had an "Expect: 100-continue" that got
    a final status as the answer.
  - A connection whose HTTP/1.0 response has Transfer-Encoding, which
    RFC 9112 section 6.1 calls faulty framing.
chttpcli_set_tls closes all of the client's idle HTTPS connections,
because the pool key does not include the TLS settings of a handshake.

A URL of the form "http+unix://<percent-encoded socket path>/path?query"
reaches a server on a Unix domain socket. It works in every tier and
with keep-alive pooling.
 
Percent-encode every byte of the socket path that is not an RFC 3986
unreserved character, '/' included, so "/run/app.sock" becomes
"%2Frun%2Fapp.sock".
 
The Host header defaults to "localhost", as with curl --unix-socket,
and a request can set its own Host header. A path too long for
sockaddr_un.sun_path gives ccol_http_invalid_url; on Linux that limit
is 108 bytes, the terminating NUL included.
 
There is no "https+unix://", and chttpcli_set_tls has no effect on
such a request. A URL of this form carries no credentials. A redirect
can never move a request onto this transport, or from one socket to
another; see chttpcli_do(3).

The client adds a value for these headers:
  - Host.
  - Accept ("*/*").
  - User-Agent.
  - Content-Length and Content-Type, from the body.
  - Authorization, from credentials in the URL.
  - Expect, from expect_continue.
It adds none of them when the request sets that header itself (names
are compared without regard to case), and it sends a header that the
request sets exactly as given. Only POST, PUT and PATCH have a body;
see chttp_request_create_mp(3).

A TLS connection can renegotiate (TLS 1.2) or receive a KeyUpdate
(TLS 1.3) in the middle of a request, and then has to read before it
can write, or write before it can read. Every tier waits for the
direction that the connection asks for, so such a connection keeps
making progress.
 
The client opens every socket close-on-exec, and also every file that
its TLS layer reads, the system CA bundle included, so a process that
the application starts (system, popen, posix_spawn, fork and exec)
inherits no connection and no file of the client. The one exception is
a system with no default CA file, where OpenSSL itself opens the files
of its hashed certificate directory during a handshake; see
chttpcli_set_tls(3).
 
The client never changes the SIGPIPE disposition, and none of its
writes raises SIGPIPE; see chttpcli_do(3).
 
There are two supported ways to use fork(2) with the client:
  - Call fork(2) before you create a client and before the first
    request of Tier 2 or Tier 3, so that each process makes its own
    clients.
  - Call fork(2) and then call exec(3) in the child immediately, as
    popen and system do. This is supported at all times, whatever the
    client does.
A child that carries on without exec(3) while a client created before
the fork is live is not supported, because fork(2) does not copy the
threads of the client and its engine.
 
A process can destroy every client that used Tier 2 or Tier 3 before
it forks, and the child can then use both tiers and starts its own
engine. The engine stops on its own thread after the last destroy, and
fork(2) waits until that thread has ended, so no client thread runs at
the fork. A build with CCOL_FORK_SAFETY_REQUIRED=0 has no such wait,
so there you call chttpcli_engine_wait(3) after the last destroy and
before fork(2).

Every function that takes a chttpcli is thread-safe, so many threads
can run requests on one client and change its settings at the same
time.
 
chttpcli_destroy can run while other threads use the client, and it
waits for the requests in progress. Two overlapping destroys of the
same handle are a fatal error, so the application must serialize the
destroy, and the destroy must be the last thing any thread does with
that handle.
 
A chttp_request and a chttpcli_response have no lock. A thread that
changes one of them needs exclusive access, and so does a thread that
reads one while another thread changes it.

chttpcli_do(3), chttpcli_engine_wait(3), chttpcli_do_async(3), chttpcli_do_pooled(3), chttpcli_set_tls(3), chttpcli_set_inactivity_timeout(3), chttp_request_create(3), chttp_default_client(3), chttpcli_resp_header(3), CHTTP_TLS_DEFAULT(3), CHTTP_STATUS(3), chttp(7), chttpserver(7)