VMOD std - Varnish Standard Module·续

Converts the string s to the first IP number returned by the system library function getaddrinfo(3). If conversion fails, fallback will be returned or VCL failure will happen.

The IP address includes a port number that can be found with std.port() that defaults to 80. The default port can be set to a different value with the p argument. It will be overridden if s contains both an IP address and a port number or service name.

When s contains both, the syntax is either address:port or address port. If the address is a numerical IPv6 address it must be enclosed between brackets, for example [::1] 80 or [::1]:http. The fallback may also contain both an address and a port, but its default port is always 80.

If resolve is false, getaddrinfo(3) is called using AI_NUMERICHOST and AI_NUMERICSERV to avoid network lookups depending on the system’s getaddrinfo(3) or nsswitch configuration. This makes “numerical” IP strings and services cheaper to convert.

Example:

if (std.ip(req.http.X-forwarded-for, "0.0.0.0") ~ my_acl) {
        ...
}

REAL real([STRING s], [REAL fallback], [INT integer], [BOOL bool], [BYTES bytes], [DURATION duration], [TIME time])#

REAL real(
   [STRING s],
   [REAL fallback],
   [INT integer],
   [BOOL bool],
   [BYTES bytes],
   [DURATION duration],
   [TIME time]
)

Returns a REAL from a STRING, BOOL or other quantity.

If the conversion of an s argument fails, fallback will be returned if provided, or a VCL failure will be triggered.

A bool argument will be returned as 0.0 for false and 1.0 for true.

For a bytes argument, the number of bytes will be returned.

For a duration argument, the number of seconds will be returned.

An integer argument will be returned as a REAL.

For a time argument, the number of seconds since the UNIX epoch (1970-01-01 00:00:00 UTC) will be returned.

None of these conversions other than s will fail.

Only one of the s , integer , bool , bytes , duration or time arguments may be given or a VCL failure will be triggered.

Example:

if (std.real(req.http.foo, 0.0) > 5.5) {
        ...
}

TIME time([STRING s], [TIME fallback], [REAL real], [INT integer])#

TIME time([STRING s], [TIME fallback], [REAL real], [INT integer])

Returns a TIME from a STRING, REAL or INT argument.

For a STRING s argument, the following formats are supported:

"Sun, 06 Nov 1994 08:49:37 GMT"
"Sunday, 06-Nov-94 08:49:37 GMT"
"Sun Nov  6 08:49:37 1994"
"1994-11-06T08:49:37"
"784111777.00"
"784111777"

real and integer arguments are taken as seconds since the epoch.

If the conversion of an s argument fails or a negative real or integer argument is given, fallback will be returned if provided, or a VCL failure will be triggered.

Examples:

if (std.time(resp.http.last-modified, now) < now - 1w) {
        ...
}

if (std.time(int=2147483647) < now - 1w) {
        ...
}

STRING strftime(TIME time, STRING format)#

Format the time argument with the format argument using strftime(3) and return the result for the UTC (historically GMT) timezone.

The empty string is returned if formatting fails, but may also be returned as a valid result.

Example:

set req.http.iso = std.strftime(now, "%Y%m%dT%H%M%SZ");
# e.g. 20210521T175241Z

LOGGING functions#

VOID log(STRING s)#

Logs the string s to the shared memory log, using VSL tag SLT_VCL_Log.

Example:

std.log("Something fishy is going on with the vhost " + req.http.host);

VOID syslog(INT priority, STRING s)#

Logs the string s to syslog tagged with priority. priority is formed by ORing the facility and level values. See your system’s syslog.h file for possible values.

Notice: Unlike VCL and other functions in the std vmod, this function will not fail VCL processing for workspace overflows: For an out of workspace condition, the std.syslog() function has no effect.

Example:

std.syslog(9, "Something is wrong");

This will send a message to syslog using LOG_USER | LOG_ALERT.

VOID timestamp(STRING s)#

Introduces a timestamp in the log with the current time, using the string s as the label. This is useful to time the execution of lengthy VCL subroutines, and makes the timestamps inserted automatically by Varnish more accurate.

Example:

std.timestamp("curl-request");

CONTROL and INFORMATION functions#

BOOL syntax(REAL)#

Returns true if VCL version is at least REAL.

STRING getenv(STRING name)#

Return environment variable name or the empty string. See getenv(3).

Example:

set req.http.My-Env = std.getenv("MY_ENV");

BOOL cache_req_body(BYTES size)#

Caches the request body if it is smaller than size. Returns true if the body was cached, false otherwise.

Normally the request body can only be sent once. Caching it enables retrying backend requests with a request body, as usually the case with POST and PUT.

Example:

if (std.cache_req_body(1KB)) {
        ...
}

Restricted to: vcl_recv.

VOID late_100_continue(BOOL late)#

Controls when varnish reacts to an Expect: 100-continue client request header.

Varnish always generates a 100 Continue response if requested by the client trough the Expect: 100-continue header when waiting for request body data.

But, by default, the 100 Continue response is already generated immediately after vcl_recv returns to reduce latencies under the assumption that the request body will be read eventually.

Calling std.late_100_continue(true) in vcl_recv will cause the 100 Continue response to only be sent when needed. This may cause additional latencies for processing request bodies, but is the correct behavior by strict interpretation of RFC7231.

This function has no effect outside vcl_recv and after calling std.cache_req_body() or any other function consuming the request body.

Example:

vcl_recv {
        std.late_100_continue(true);

        if (req.method == "POST") {
                std.late_100_continue(false);
                return (pass);
        }
        ...
 }

Restricted to: vcl_recv.

VOID set_ip_tos(INT tos)#

Sets the Differentiated Services Codepoint (DSCP) / IPv4 Type of Service (TOS) / IPv6 Traffic Class (TCLASS) byte for the current session to tos. Silently ignored if the listen address is a Unix domain socket.

Please note that setting the traffic class affects all requests on the same http1.1 / http2 TCP connection and, in particular, is not removed at the end of the request.

Example:

if (req.url ~ "^/slow/") {
        std.set_ip_tos(0);
}

Restricted to: client.

VOID rollback(HTTP h)#

Restores the h HTTP headers to their original state.

Example:

std.rollback(bereq);

Restricted to: backend, vcl_recv, vcl_pass, vcl_hash, vcl_purge, vcl_miss, vcl_hit, vcl_deliver, vcl_synth.

BOOL ban(STRING)#

Invalidates all objects in cache that match the given expression with the ban mechanism. Returns true if the ban succeeded and false otherwise. Error details are available via std.ban_error().

The format of STRING is:

&lt;field> &lt;operator> &lt;arg> [&& &lt;field> &lt;oper> &lt;arg> ...]
  • __:

  • string fields:

  • req.url: The request url

    • req.http.*: Any request header
    • obj.status: The cache object status
    • obj.http.*: Any cache object header

obj.status is treated as a string despite the fact that it is actually an integer.

  • duration fields:

  • obj.ttl: Remaining ttl

    • obj.age: Object age
    • obj.grace: The grace time of the object
    • obj.keep: The keep time of the object
    • obj.last_hit: Time since the last hit

obj.ttl, obj.age and obj.last_hit are relative to the submission time of the ban, such that they represent a fixed point in time despite being specified as a duration.

  • __:

  • for all fields:

  • ==: __and __are equal

    • !=: __and __are unequal

strings are compared case-sensitively

  • for string fields:

  • ~: __matches the regular expression __

    • !~: __does not match the regular expression __
  • for duration fields:

  • >: __is greater than __

    • >=: __is greater than or equal to __
    • <: __is less than __
    • <=: __is less than or equal to __
  • __:

  • for string fields:

Either a literal string or a regular expression. Note that __does not use any of the string delimiters like" or {" …"} or """ …""" used elsewhere in varnish. To match against strings containing whitespace, regular expressions containing \s can be used.

  • for duration fields:

A VCL duration like 10s, 5m or 1h, see Durations

Expressions can be chained using the and operator &&. For or semantics, use several bans.

The unset is not equal to any string, such that, for a non-existing header, the operators== and ~ always evaluate as false, while the operators != and !~ always evaluate as true, respectively, for any value of .

obj.last_hit can be used almost as a “last accessed” time, so, for example, ban obj.last_hit > 1d removes all objects which were last accessed more than one day ago. Also, it can be used to remove objects stuck at request bans by issuing ban obj.last_hit > X, with X being slightly less than the time since the request ban.

obj.last_hit is based on an internal last LRU time, which might not be implemented by all storage engines. Where it is not available, ban expressions using obj.last_hit evaluate to false, which means that the respective ban behaves as if it was not present. Where implemented, the last LRU time might only get updated by the lru_interval parameter, which therefore is the maximum precision of obj.last_hit bans.

STRING ban_error()#

Returns a textual error description of the last std.ban() call from the same task or the empty string if there either was no error or no std.ban() call.

TIME now()#

Returns the current time. In contrast to the now built-in variable, every call returns a new value.

DURATION timed_call(SUB)#

Call the given SUB and return a high precision measurement of the execution time.

SEE ALSO#

Copyright (c) 2010-2017 Varnish Software AS
All rights reserved.

Author: Poul-Henning Kamp &lt;phk@FreeBSD.org>

SPDX-License-Identifier: BSD-2-Clause

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.