kvarn::host

Struct Host

source
pub struct Host {
    pub name: CompactString,
    pub alternative_names: Vec<CompactString>,
    pub certificate: RwLock<Option<Arc<CertifiedKey>>>,
    pub path: CompactString,
    pub extensions: Extensions,
    pub file_cache: Option<FileCache>,
    pub response_cache: Option<ResponseCache>,
    pub limiter: LimitManager,
    pub vary: Vary,
    pub options: Options,
    pub compression_options_oneshot: CompressionOptions,
    pub compression_options_cached: CompressionOptions,
}
Expand description

A set of settings for a virtual host, allowing multiple DNS entries (domain names) to share a single IP address.

This is an integral part of Kvarn; the ability to host multiple webpages on a single instance without crosstalk and with high performance makes it a viable option.

Let’s talk about the relations of Host::unsecure and PortDescriptor::unsecure. A host can be secure and contain a certificate (if the https feature is enabled). A PortDescriptor can accept HTTPS or HTTP requests. PortDescriptor::new will set up the descriptor to accept only HTTP requests if none of the hosts contains a certificate. It accepts only HTTPS messages if any of the hosts have a certificate. Then, connections to all the other hosts with no certificate are rejected.

For example, in the reference implementation, I use PortDescriptor::unsecure to bind port 80 and PortDescriptor::new to bind port 443. Then, all hosts are reachable on port 80, but only the ones with a certificate on port 443.

§Examples

See RunConfig::execute().

Fields§

§name: CompactString

The name of the host, will be used in matching the requests SNI hostname and host header to get the requested host to handle the request.

§alternative_names: Vec<CompactString>

The alternative names this host is recognized by. This should probably be empty unless your certificate also covers these names.

§certificate: RwLock<Option<Arc<CertifiedKey>>>
Available on crate feature https only.

The certificate of this host, if any.

§path: CompactString

Base path of all data for this host.

If you enabled the fs feature (enabled by default), the public files are in the directory <path>/public (public by default; see Options::public_data_dir).

Also, all extensions should use this to access data on disk.

§extensions: Extensions

The extensions of this host.

§file_cache: Option<FileCache>

The file cache of this host.

The caches are separated to limit the performance fluctuations of multiple hosts on the same instance.

Can be used to clear the cache and to pass to the read functions in read.

§response_cache: Option<ResponseCache>

The response cache of this host. See comprash and Host::file_cache for more info.

§limiter: LimitManager

The LimitManager checking for spam attacks for this host.

Having this host-specific enables different virtual hosts to have varying degrees of strictness.

§vary: Vary

Settings for handling caching of responses with the vary header.

§options: Options

Other settings.

§compression_options_oneshot: CompressionOptions

Preferences and options for compression when a response is not cached.

§compression_options_cached: CompressionOptions

Preferences and options for compression when a response is cached.

Implementations§

source§

impl Host

source

pub fn try_read_fs( host_name: impl AsRef<str>, cert_path: impl AsRef<str>, private_key_path: impl AsRef<str>, path: impl AsRef<str>, extensions: Extensions, options: Options, ) -> Result<Self, (CertificateError, Self)>

Available on crate feature https only.

Creates a new Host. Will read PEM encoded certificates in the specified locations and return an non-secure host if parsing fails.

To achieve greater security, use Host::with_http_to_https_redirect and call Host::with_hsts.

See Host::unsecure for a non-failing function, available regardless of features.

§Errors

Will return any error from get_certified_key() with a Host containing no certificates.

source

pub fn read_fs_name_from_cert( cert_path: impl AsRef<str>, private_key_path: impl AsRef<str>, path: impl AsRef<str>, extensions: Extensions, options: Options, ) -> Result<Self, CertificateError>

Available on crate feature https only.

Same as Self::try_read_fs, but extracts the host name from the certificate. This also doesn’t fall back to Self::unsecure, as we don’t know the name if the certificate couldn’t be parsed.

§Panics

Panics if the parsed certificate .is_empty() or if the first certificate in the parsed chain is invalid.

§Errors

Will return any error from get_certified_key().

source

pub fn new( name: impl AsRef<str>, key: CertifiedKey, path: impl AsRef<str>, extensions: Extensions, options: Options, ) -> Self

Available on crate feature https only.

Creates a new Host from the [rustls] cert and pk. When they are in files, consider Self::new which reads from files.

See the considerations of Self::new for security.

§Examples
let certificate =
    rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let cert = vec![rustls::Certificate(certificate.serialize_der().unwrap())];
let pk = rustls::PrivateKey(certificate.serialize_private_key_der());
let pk = Arc::new(rustls::sign::any_supported_type(&pk).unwrap());

Host::new(
    "localhost",
    cert,
    pk,
    "tests",
    Extensions::default(),
    host::Options::default(),
);
source

pub fn new_name_from_cert( key: CertifiedKey, path: impl AsRef<str>, extensions: Extensions, options: Options, ) -> Self

Available on crate feature https only.

Same as Self::new, but extracts the host name from the certificate.

§Panics

Panics if cert.is_empty() or if the first certificate in cert is invalid.

source

pub fn unsecure( host_name: impl AsRef<str>, path: impl AsRef<str>, extensions: Extensions, options: Options, ) -> Self

Creates a new Host without a certificate.

This host will only support non-encrypted HTTP/1 connections. Consider enabling the https feature and use a self-signed certificate or one from Let’s Encrypt.

source

pub fn http_redirect_or_unsecure( host_name: impl AsRef<str>, cert_path: impl AsRef<str>, private_key_path: impl AsRef<str>, path: impl AsRef<str>, extensions: Extensions, options: Options, ) -> Self

Available on crate feature https only.

Same as Host::try_read_fs with Host::with_http_to_https_redirect. This does however consider the error from Host::try_read_fs to be ok. We log it as an log::Level::Error and continue without encryption.

Consider running Host::try_read_fs with Host::with_http_to_https_redirect and Host::with_hsts to harden the system.

source

pub fn with_http_to_https_redirect(&mut self) -> &mut Self

Available on crate feature https only.

Adds extensions to redirect unsecure HTTP requests to the secure HTTPS URI.

See Extensions::with_http_to_https_redirect.

source

pub fn with_hsts(&mut self) -> &mut Self

Available on crate feature https only.

Enables HSTS on this Host.

The Package extension has a priority of 8.

You should be careful using this feature. If you do not plan to have a certificate for your domain for at least the following two years, take a look in the source code, copy paste it and lower the max-age.

Also see hstspreload.org

source

pub fn add_alternative_name(&mut self, name: impl AsRef<str>) -> &mut Self

Add an alternative name to this host.

See the fiels for more details.

source

pub fn disable_client_cache(&mut self) -> &mut Self

Disables client cache on this host.

This makes all comprash::ClientCachePreferences no-store. Use Kvarn extensions’ force_cache to force certain files to cache.

source

pub fn disable_fs_cache(&mut self) -> &mut Self

Disables the file system cache for this host. This can cause degraded performance under heavy load, but reduces the memoy used.

source

pub fn disable_response_cache(&mut self) -> &mut Self

Disables the response cache for this host. This can cause degraded performance under heavy load, but reduces the memoy used.

source

pub fn disable_server_cache(&mut self) -> &mut Self

Disables all server caches. This can cause degraded performance under heavy load, but reduces the memoy used.

Right now calls Self::disable_fs_cache and Self::disable_response_cache.

source

pub fn is_secure(&self) -> bool

Available on crate feature https only.

Whether or not this this host is secured with a certificate.

See Host::certificate.

source

pub fn set_brotli_level(&mut self, level: u32) -> &mut Self

Available on crate feature br only.

Set the brotli compression level. 1-10, lower values are faster, but compress less. Default = 3.

See some benchmarks for more context.

source

pub fn set_gzip_level(&mut self, level: u32) -> &mut Self

Available on crate feature gzip only.

Set the gzip compression level. 1-10, lower values are faster, but compress less. Default = 1.

See some benchmarks for more context.

source

pub fn set_zstd_level(&mut self, level: i32) -> &mut Self

Available on crate feature zstd only.

Set the zstd compression level. Lower values are faster, but compress less. Negative values are allowed. See the link for more info. Default = 4. https://facebook.github.io/zstd/

source

pub fn set_brotli_level_oneshot(&mut self, level: u32) -> &mut Self

Available on crate feature br only.

Like Host::set_brotli_level but for responses which are not cached.

source

pub fn set_gzip_level_oneshot(&mut self, level: u32) -> &mut Self

Available on crate feature gzip only.

Like Host::set_gzip_level but for responses which are not cached.

source

pub fn set_zstd_level_oneshot(&mut self, level: i32) -> &mut Self

Available on crate feature zstd only.

Like Host::set_zstd_level but for responses which are not cached.

source

pub fn live_set_certificate(&self, key: CertifiedKey)

Available on crate feature https only.

Can be done while the server is running, since this only takes a reference to self

Sets the certificate if it was None before. It’s however unclear what consequences that will have while it’s running (if you only had unsecure hosts when starting Kvarn, it you might not have bound 443?).

source§

impl Host

source

pub fn clone_without_extensions(&self) -> Self

Clones this Host without carrying with any extensions or cache contents. You’ll have to add all extensions (and related “settings”, such as CSP, CORS, HSTS) manually.

Use sparingly.

Trait Implementations§

source§

impl Debug for Host

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !Freeze for Host

§

impl !RefUnwindSafe for Host

§

impl !Send for Host

§

impl !Sync for Host

§

impl Unpin for Host

§

impl !UnwindSafe for Host

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

source§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more