diff --git a/doc/admin-guide/files/records.yaml.en.rst b/doc/admin-guide/files/records.yaml.en.rst index ee37ceda0ab..0b06b3eb6aa 100644 --- a/doc/admin-guide/files/records.yaml.en.rst +++ b/doc/admin-guide/files/records.yaml.en.rst @@ -4173,7 +4173,7 @@ Client-Related Configuration Can be useful if using a crypto engine that communicates off chip. The thread will be rescheduled for other work until the crypto engine operation completes. A test crypto engine that inserts a 5 second delay on private key - operations can be found at :ts:git:`contrib/openssl/async_engine.c`. + operations can be found at :ts:git:`contrib/openssl/async_engine.cc`. .. ts:cv:: CONFIG proxy.config.ssl.engine.conf_file STRING NULL diff --git a/doc/developer-guide/api/functions/TSClientProtocolStack.en.rst b/doc/developer-guide/api/functions/TSClientProtocolStack.en.rst index f9a169838d7..d9d0fa0f805 100644 --- a/doc/developer-guide/api/functions/TSClientProtocolStack.en.rst +++ b/doc/developer-guide/api/functions/TSClientProtocolStack.en.rst @@ -61,7 +61,7 @@ protocol :arg:`tag` being present in the stack. Each protocol is represented by tag which is a null terminated string. A particular tag will always be returned as the same character pointer and so protocols can be reliably checked with pointer comparisons. :func:`TSNormalizedProtocolTag` will return this character pointer for a specific -:arg:`tag`. A return value of :const:`NULL` indicates the provided :arg:`tag` is not registered as +:arg:`tag`. A return value of :const:`nullptr` indicates the provided :arg:`tag` is not registered as a known protocol tag. :func:`TSRegisterProtocolTag` registers the :arg:`tag` and then returns its normalized value. This is useful for plugins that provide custom protocols for user agents. @@ -69,7 +69,7 @@ The protocols are ordered from higher level protocols to the lower level ones on operate. For instance a stack might look like "http/1.1,tls/1.2,tcp,ipv4". For :func:`TSHttpTxnClientProtocolStackGet`, :func:`TSHttpSsnClientProtocolStackGet`, and :func:`TSHttpTxnServerProtocolStackGet` these values are placed in the array :arg:`result`. :arg:`count` is the maximum number of elements of -:arg:`result` that may be modified by the function call. If :arg:`actual` is not :const:`NULL` then +:arg:`result` that may be modified by the function call. If :arg:`actual` is not :const:`nullptr` then the actual number of elements in the protocol stack will be returned. If this is equal or less than :arg:`count` then all elements were returned. If it is larger then some layers were omitted from :arg:`result`. If the full stack is required :arg:`actual` can be used to resize :arg:`result` to @@ -80,7 +80,7 @@ than 10 which therefore should suffice. These functions return :const:`TS_SUCCES The :func:`TSHttpTxnClientProtocolStackContains`, :func:`TSHttpSsnClientProtocolStackContains`, and :func:`TSHttpTxnServerProtocolStackContains` functions are provided for the convenience when only the presence of a protocol is of interest, not -its location or the presence of other protocols. These functions return :const:`NULL` if the protocol +its location or the presence of other protocols. These functions return :const:`nullptr` if the protocol :arg:`tag` is not present, and a pointer to the normalized tag if it is present. The strings are matched with an anchor prefix search, as with debug tags. For instance if :arg:`tag` is "tls" then it will match "tls/1.2" or "tls/1.3". This makes checking for TLS or IP more convenient. If more precision diff --git a/doc/developer-guide/api/functions/TSHttpConnectWithPluginId.en.rst b/doc/developer-guide/api/functions/TSHttpConnectWithPluginId.en.rst index 8e35698c4f5..4e5f9274cb0 100644 --- a/doc/developer-guide/api/functions/TSHttpConnectWithPluginId.en.rst +++ b/doc/developer-guide/api/functions/TSHttpConnectWithPluginId.en.rst @@ -61,7 +61,7 @@ stack via the loopback interface. the connection. It is accessible via the log field :ref:`pitag `. This is intended as a class or type identifier that is consistent across all connections for this plugin. In effect, - the name of the plugin. This can be :literal:`NULL`. + the name of the plugin. This can be :literal:`nullptr`. :arg:`id` This is a numeric identifier that is passed through to the HTTP diff --git a/doc/developer-guide/api/functions/TSHttpHookAdd.en.rst b/doc/developer-guide/api/functions/TSHttpHookAdd.en.rst index b2c80b1ec0e..b79422e6564 100644 --- a/doc/developer-guide/api/functions/TSHttpHookAdd.en.rst +++ b/doc/developer-guide/api/functions/TSHttpHookAdd.en.rst @@ -141,7 +141,7 @@ transaction hooks:: TSPluginInit (int argc, const char *argv[]) { TSCont contp; - contp = TSContCreate(handler, NULL); + contp = TSContCreate(handler, nullptr); TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, contp); } diff --git a/doc/developer-guide/api/functions/TSHttpParserCreate.en.rst b/doc/developer-guide/api/functions/TSHttpParserCreate.en.rst index d03d1fb37ac..7bd48a25be3 100644 --- a/doc/developer-guide/api/functions/TSHttpParserCreate.en.rst +++ b/doc/developer-guide/api/functions/TSHttpParserCreate.en.rst @@ -68,7 +68,7 @@ It should be called after :data:`TS_HTTP_READ_RESPONSE_HDR_HOOK`. may be used again. :func:`TSHttpParserDestroy` destroys the TSHttpParser object pointed -to by :arg:`parser`. The :arg:`parser` pointer must not be NULL. +to by :arg:`parser`. The :arg:`parser` pointer must not be nullptr. Return Values ============= diff --git a/doc/developer-guide/api/functions/TSHttpTxnOutgoingAddrGet.en.rst b/doc/developer-guide/api/functions/TSHttpTxnOutgoingAddrGet.en.rst index 4f1b99ad336..5e1c28a6d7f 100644 --- a/doc/developer-guide/api/functions/TSHttpTxnOutgoingAddrGet.en.rst +++ b/doc/developer-guide/api/functions/TSHttpTxnOutgoingAddrGet.en.rst @@ -54,5 +54,5 @@ what was passing :arg:`addr` if :ts:cv:`session sharing generates, and it will -be NULL terminated. +be null terminated. Return Values ============= @@ -102,7 +102,7 @@ the UUID object. Several of the functions returns a normal Traffic Server return status code, :type:`TSReturnCode`. You should verify the success of those APIs, of course. -The :func:`TSUuidStringGet` function will return ``NULL`` if the :type:`TSUuid` +The :func:`TSUuidStringGet` function will return ``nullptr`` if the :type:`TSUuid` object is not properly initialized. Likewise, :func:`TSUuidVersionGet` would then return ``TS_UUID_UNDEFINED``. diff --git a/doc/developer-guide/api/functions/TSVConnFdCreate.en.rst b/doc/developer-guide/api/functions/TSVConnFdCreate.en.rst index 03fccfa2afd..b09b40f6a7b 100644 --- a/doc/developer-guide/api/functions/TSVConnFdCreate.en.rst +++ b/doc/developer-guide/api/functions/TSVConnFdCreate.en.rst @@ -43,7 +43,7 @@ Return Values ============= On success, the returned :type:`TSVConn` object owns the socket and the -caller must not close it. If :func:`TSVConnFdCreate` fails, :literal:`NULL` +caller must not close it. If :func:`TSVConnFdCreate` fails, :literal:`nullptr` is returned, the socket is unchanged and the caller must close it. Examples diff --git a/doc/developer-guide/api/functions/TSfgets.en.rst b/doc/developer-guide/api/functions/TSfgets.en.rst index eaf0143e05f..3947a7da34c 100644 --- a/doc/developer-guide/api/functions/TSfgets.en.rst +++ b/doc/developer-guide/api/functions/TSfgets.en.rst @@ -38,5 +38,5 @@ Reads a line from the file pointed to by :arg:`filep` into the buffer Lines are terminated by a line feed character, ' '. The line placed in the buffer includes the line feed character and is terminated with -a ``NULL``. If the line is longer than length bytes then only the first +a ``nullptr``. If the line is longer than length bytes then only the first length-minus-1 bytes are placed in :arg:`buf`. diff --git a/doc/developer-guide/api/functions/TSmalloc.en.rst b/doc/developer-guide/api/functions/TSmalloc.en.rst index cbaf27568c5..b031874fdf2 100644 --- a/doc/developer-guide/api/functions/TSmalloc.en.rst +++ b/doc/developer-guide/api/functions/TSmalloc.en.rst @@ -32,6 +32,7 @@ Synopsis #include .. function:: void * TSmalloc(size_t size) +.. cpp:function:: template T * malloc(size_t count = 1) .. function:: void * TSrealloc(void * ptr , size_t size) .. function:: char * TSstrdup(const char * str) .. function:: char * TSstrndup(const char * str, size_t size) @@ -48,7 +49,7 @@ For example, :func:`TSrealloc` behaves like the C library routine :code:`realloc There are two reasons to use the routines provided by Traffic Server. The first is portability. The Traffic Server API routines behave the same on all of Traffic Servers supported platforms. For example, :code:`realloc` does -not accept an argument of ``NULL`` on some platforms. The second reason is +not accept an argument of ``nullptr`` on some platforms. The second reason is that the Traffic Server routines actually track the memory allocations by file and line number. This tracking is very efficient, is always turned on, and is useful for tracking down memory leaks. @@ -58,6 +59,12 @@ heap. Traffic Server uses :func:`TSmalloc` internally for memory allocations. Always use :func:`TSfree` to release memory allocated by :func:`TSmalloc`; do not use :code:`free`. +**malloc()**, which is in the :code:`tsapi` namespace, returns a pointer, of type :code:`T *`, +to allocated memory with enough bytes to hold an array of :code:`count` (default value +of :code;`1`) instances of :code:`T`. No constructor of :code:`T` is called for the +array elements. This function in turn calls :func:`TSmalloc`, so the memory it allocates +should be released by calling :func:`TSfree`. + :func:`TSstrdup` returns a pointer to a new string that is a duplicate of the string pointed to by str. The memory for the new string is allocated using :func:`TSmalloc` and should be freed by a call to :func:`TSfree`. @@ -77,7 +84,11 @@ will append at most :arg:`size` - :code:`strlen(dst)` - 1 bytes, NUL-terminating result. :func:`TSfree` releases the memory allocated by :func:`TSmalloc` or :func:`TSrealloc`. If -ptr is ``NULL``, :func:`TSfree` does no operation. +ptr is ``nullptr``, :func:`TSfree` does no operation. + +Use of these functions should be avoided in new code. For dynamic memory allocation, +prefer in general to use C++ Standard Library containers and smart pointers. Use of C++ +:code:`new` and :code:`delete` operators is the next best option. See also ======== diff --git a/doc/developer-guide/cache-architecture/data-structures.en.rst b/doc/developer-guide/cache-architecture/data-structures.en.rst index d360c1d2e2c..6c54b329455 100644 --- a/doc/developer-guide/cache-architecture/data-structures.en.rst +++ b/doc/developer-guide/cache-architecture/data-structures.en.rst @@ -112,7 +112,7 @@ Data Structures This class is a wrapper for :class:`HTTPCacheAlt`. It provides the external API for accessing data in the wrapped class. It contains only a - pointer (possibly ``NULL``) to an instance of the wrapped class. + pointer (possibly ``nullptr``) to an instance of the wrapped class. .. class:: CacheHTTPInfo diff --git a/doc/developer-guide/config-vars.en.rst b/doc/developer-guide/config-vars.en.rst index 2ebbd396284..8c7a833e72c 100644 --- a/doc/developer-guide/config-vars.en.rst +++ b/doc/developer-guide/config-vars.en.rst @@ -43,9 +43,9 @@ .. _overridable_txn_vars.cc: https://github.com/apache/trafficserver/blob/master/src/shared/overridable_txn_vars.cc -.. |ts_lua_http_config.c| replace:: ``ts_lua_http_config.c`` +.. |ts_lua_http_config.cc| replace:: ``ts_lua_http_config.cc`` -.. _ts_lua_http_config.c: https://github.com/apache/trafficserver/blob/master/plugins/experimental/ts_lua/ts_lua_http_config.c +.. _ts_lua_http_config.cc: https://github.com/apache/trafficserver/blob/master/plugins/experimental/ts_lua/ts_lua_http_config.cc .. |TSHttpOverridableConfig.en.rst| replace:: ``TSHttpOverridableConfig.en.rst`` @@ -153,7 +153,7 @@ check:``RecCheckT`` pattern:``char const*`` This provides a regular expressions (PCRE format) for validating the value, beyond the basic type validation performed by ``RecCheckT``. This can be - ``NULL`` if there is no regular expression to use. + ``nullptr`` if there is no regular expression to use. access:``RecAccessT`` Access control. The valid values are: @@ -320,7 +320,7 @@ required for generic access: #. Update the testing logic in |InkAPITest.cc|_ by adding the string name of the configuration variable to the ``SDK_Overridable_Configs`` array. -#. Update the Lua plugin enumeration ``TSLuaOverridableConfigKey`` in |ts_lua_http_config.c|_. +#. Update the Lua plugin enumeration ``TSLuaOverridableConfigKey`` in |ts_lua_http_config.cc|_. #. Update the documentation of :ref:`ts-overridable-config` in |TSHttpOverridableConfig.en.rst|_. diff --git a/doc/developer-guide/plugins/actions/index.en.rst b/doc/developer-guide/plugins/actions/index.en.rst index 7ea25614de0..8275caa915e 100644 --- a/doc/developer-guide/plugins/actions/index.en.rst +++ b/doc/developer-guide/plugins/actions/index.en.rst @@ -75,11 +75,11 @@ Below is an example of typical usage for an action: } } else if (event == TS_EVENT_NET_CONNECT) { /* Net connection succeeded */ - TSContDataSet (contp, NULL); + TSContDataSet (contp, nullptr); return 0; } else if (event == TS_EVENT_NET_CONNECT_FAILED) { /* Net connection failed */ - TSContDataSet (contp, NULL); + TSContDataSet (contp, nullptr); return 0; } return 0; @@ -145,12 +145,12 @@ cancel the action. The following sample code implements this: case (TS_EVENT_NET_CONNECT): /* Net connection succeeded */ - TSContDataSet (contp, NULL); + TSContDataSet (contp, nullptr); break; case (TS_EVENT_NET_CONNECT_FAILED): /* Net connection failed */ - TSContDataSet (contp, NULL); + TSContDataSet (contp, nullptr); break; } diff --git a/doc/developer-guide/plugins/continuations/index.en.rst b/doc/developer-guide/plugins/continuations/index.en.rst index 41722b1465d..e1148825624 100644 --- a/doc/developer-guide/plugins/continuations/index.en.rst +++ b/doc/developer-guide/plugins/continuations/index.en.rst @@ -115,7 +115,7 @@ members after a reentrant call - just exit the handler. non-null mutexes because they're called within the processing of an HTTP transaction, and therefore have the transaction's mutex. -It is also possible to specify a continuation's mutex as ``NULL``. This +It is also possible to specify a continuation's mutex as ``nullptr``. This should be done only when registering a continuation to a global hook, by a call to ``TSHttpHookAdd``. In this case, the continuation can be called simultaneously by different instances of HTTP SM running on @@ -125,8 +125,8 @@ mutex. The drawback of not having a mutex is that such a continuation cannot have data associated with it (i.e., ``TSContDataGet/Set`` cannot be used). -When using a ``NULL`` mutex it is dangerous to access the continuation's -data, but usually continuations with ``NULL`` mutexes have no data +When using a ``nullptr`` mutex it is dangerous to access the continuation's +data, but usually continuations with ``nullptr`` mutexes have no data associated with them anyway. An example of such a continuation is one that gets called back every time an HTTP request is read, and then determines from the request alone if the request should go through or be diff --git a/doc/developer-guide/plugins/example-plugins/basic-authorization/implementing-the-handler-and-getting-a-handle-to-the-transaction.en.rst b/doc/developer-guide/plugins/example-plugins/basic-authorization/implementing-the-handler-and-getting-a-handle-to-the-transaction.en.rst index 62585572682..99192a7ff09 100644 --- a/doc/developer-guide/plugins/example-plugins/basic-authorization/implementing-the-handler-and-getting-a-handle-to-the-transaction.en.rst +++ b/doc/developer-guide/plugins/example-plugins/basic-authorization/implementing-the-handler-and-getting-a-handle-to-the-transaction.en.rst @@ -29,7 +29,7 @@ as follows: auth_plugin (TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn) edata; + TSHttpTxn txnp = static_cast(edata); switch (event) { case TS_EVENT_HTTP_OS_DNS: handle_dns (txnp, contp); diff --git a/doc/developer-guide/plugins/example-plugins/basic-authorization/index.en.rst b/doc/developer-guide/plugins/example-plugins/basic-authorization/index.en.rst index d80a5763ccf..17a33ad5f3c 100644 --- a/doc/developer-guide/plugins/example-plugins/basic-authorization/index.en.rst +++ b/doc/developer-guide/plugins/example-plugins/basic-authorization/index.en.rst @@ -22,7 +22,7 @@ Basic Authorization Plugin ************************** -The sample basic authorization plugin, ``basic_auth.c``, checks for +The sample basic authorization plugin, ``basic_auth.cc``, checks for basic HTTP proxy authorization. In HTTP basic proxy authorization, client user names and passwords are contained in the ``Proxy-Authorization`` header. The password is encoded using base64 @@ -37,7 +37,7 @@ Creating the Plugin's Parent Continuation and Global Hook The parent continuation and global hook are created as follows: -``TSHttpHookAdd (TS_HTTP_OS_DNS_HOOK, TSContCreate (auth_plugin, NULL));`` +``TSHttpHookAdd (TS_HTTP_OS_DNS_HOOK, TSContCreate (auth_plugin, nullptr));`` .. important:: diff --git a/doc/developer-guide/plugins/example-plugins/denylist/accessing-the-transaction-being-processed.en.rst b/doc/developer-guide/plugins/example-plugins/denylist/accessing-the-transaction-being-processed.en.rst index 9742418be6f..d9d7ad7e354 100644 --- a/doc/developer-guide/plugins/example-plugins/denylist/accessing-the-transaction-being-processed.en.rst +++ b/doc/developer-guide/plugins/example-plugins/denylist/accessing-the-transaction-being-processed.en.rst @@ -45,7 +45,7 @@ Denylist plugin's handler: static int denylist_plugin (TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn) edata; + TSHttpTxn txnp = static_cast(edata); switch (event) { case TS_EVENT_HTTP_OS_DNS: handle_dns (txnp, contp); diff --git a/doc/developer-guide/plugins/example-plugins/denylist/index.en.rst b/doc/developer-guide/plugins/example-plugins/denylist/index.en.rst index e45ed39f100..e08ad46ac1e 100644 --- a/doc/developer-guide/plugins/example-plugins/denylist/index.en.rst +++ b/doc/developer-guide/plugins/example-plugins/denylist/index.en.rst @@ -23,7 +23,7 @@ Denylist Plugin **************** The sample denylisting plugin included in the Traffic Server SDK is -``denylist_1.c``. This plugin checks every incoming HTTP client request +``denylist_1.cc``. This plugin checks every incoming HTTP client request against a list of listed web sites. If the client requests a listed site, then the plugin returns an ``Access forbidden`` message to the client. @@ -52,7 +52,7 @@ Traffic Server has a multi-threaded design, race conditions can occur if several threads try to access the same continuation's data. Here is how the static parent continuation is created in -``denylist_1.c``: +``denylist_1.cc``: .. code-block:: c @@ -62,7 +62,7 @@ Here is how the static parent continuation is created in // ... TSCont contp; - contp = TSContCreate (denylist_plugin, NULL); + contp = TSContCreate (denylist_plugin, nullptr); // ... } @@ -77,7 +77,7 @@ that might be sent to it: static int denylist_plugin (TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn) edata; + TSHttpTxn txnp = static_cast(edata); switch (event) { case TS_EVENT_HTTP_OS_DNS: handle_dns (txnp, contp); diff --git a/doc/developer-guide/plugins/example-plugins/denylist/setting-a-global-hook.en.rst b/doc/developer-guide/plugins/example-plugins/denylist/setting-a-global-hook.en.rst index 66f51d20025..ef22a45f426 100644 --- a/doc/developer-guide/plugins/example-plugins/denylist/setting-a-global-hook.en.rst +++ b/doc/developer-guide/plugins/example-plugins/denylist/setting-a-global-hook.en.rst @@ -23,7 +23,7 @@ Setting a Global Hook Global hooks are always added in ``TSPluginInit`` using ``TSHttpHookAdd``. The two arguments of ``TSHttpHookAdd`` are the hook ID and the continuation to call when processing the event corresponding -to the hook. In ``denylist_1.c``, the global hook is added as follows: +to the hook. In ``denylist_1.cc``, the global hook is added as follows: .. code-block:: c diff --git a/doc/developer-guide/plugins/example-plugins/denylist/source-code.en.rst b/doc/developer-guide/plugins/example-plugins/denylist/source-code.en.rst index b6c828de348..73446f33869 100644 --- a/doc/developer-guide/plugins/example-plugins/denylist/source-code.en.rst +++ b/doc/developer-guide/plugins/example-plugins/denylist/source-code.en.rst @@ -22,13 +22,13 @@ Sample Source Code ****************** -.. _denylist-1.c: +.. _denylist-1.cc: -denylist_1.c -------------- +denylist_1.cc +-------------- The sample denylisting plugin included in the Traffic Server SDK is -``denylist_1.c``. This plugin checks every incoming HTTP client request +``denylist_1.cc``. This plugin checks every incoming HTTP client request against a list of web sites. If the client requests a listed site, then the plugin returns an ``Access forbidden`` message to the client. @@ -43,5 +43,5 @@ This plugin illustrates: - How to use the plugin configuration management interface -.. literalinclude:: ../../../../../example/plugins/c-api/denylist_1/denylist_1.c +.. literalinclude:: ../../../../../example/plugins/c-api/denylist_1/denylist_1.cc :language: c diff --git a/doc/developer-guide/plugins/example-plugins/index.en.rst b/doc/developer-guide/plugins/example-plugins/index.en.rst index f9b740d3201..b40c4e9562d 100644 --- a/doc/developer-guide/plugins/example-plugins/index.en.rst +++ b/doc/developer-guide/plugins/example-plugins/index.en.rst @@ -47,8 +47,8 @@ understand the following topics: - Working with HTTP header functions -The two sample plugins discussed in this chapter are ``denylist_1.c`` -and ``basic_auth.c``. To build and install the example plugins use :: +The two sample plugins discussed in this chapter are ``denylist_1.cc`` +and ``basic_auth.cc``. To build and install the example plugins use :: ./configure --enable-example-plugins diff --git a/doc/developer-guide/plugins/example-plugins/query_remap/example-query-remap.en.rst b/doc/developer-guide/plugins/example-plugins/query_remap/example-query-remap.en.rst index edb796ec4a7..240846f1bf3 100644 --- a/doc/developer-guide/plugins/example-plugins/query_remap/example-query-remap.en.rst +++ b/doc/developer-guide/plugins/example-plugins/query_remap/example-query-remap.en.rst @@ -20,7 +20,7 @@ Example: Query Remap Plugin *************************** -The sample remap plugin, ``query_remap.c``, maps client requests to a +The sample remap plugin, ``query_remap.cc``, maps client requests to a number of servers based on a hash of the request's URL query parameter. This can be useful for spreading load for a given type of request among backend servers, while still maintaining "stickiness" to a single server @@ -54,7 +54,7 @@ function. In ``query_remap``, ``tsremap_new_instance`` creates a plugin-defined ``query_remap_info`` struct to store its configuration parameters. -.. literalinclude:: ../../../../../example/plugins/c-api/query_remap/query_remap.c +.. literalinclude:: ../../../../../example/plugins/c-api/query_remap/query_remap.cc :language: c :lines: 37-42 @@ -62,7 +62,7 @@ The :code:`ihandle`, an opaque pointer that can be used to pass per-instance data, is set to this struct pointer and will be passed to the :code:`TSRemapDoRemap` function when it is triggered for a request. -.. literalinclude:: ../../../../../example/plugins/c-api/query_remap/query_remap.c +.. literalinclude:: ../../../../../example/plugins/c-api/query_remap/query_remap.cc :language: c :lines: 53-88 @@ -83,6 +83,6 @@ struct contains input and output members for the remap operation. parameter. If the parameter is found, the plugin sets a ``new_host`` to modify the request host: -.. literalinclude:: ../../../../../example/plugins/c-api/query_remap/query_remap.c +.. literalinclude:: ../../../../../example/plugins/c-api/query_remap/query_remap.cc :language: c :lines: 112-166 diff --git a/doc/developer-guide/plugins/getting-started/a-simple-plugin.en.rst b/doc/developer-guide/plugins/getting-started/a-simple-plugin.en.rst index 2b53d5c5170..ef17fb90a3e 100644 --- a/doc/developer-guide/plugins/getting-started/a-simple-plugin.en.rst +++ b/doc/developer-guide/plugins/getting-started/a-simple-plugin.en.rst @@ -47,10 +47,10 @@ platforms. Example ------- -Assuming the sample program is stored in the file ``hello_world.c``, you +Assuming the sample program is stored in the file ``hello_world.cc``, you could use the following commands to build a shared library:: - tsxs -o hello_world.so -c hello_world.c + tsxs -o hello_world.so -c hello_world.cc ``tsxs`` is installed in the ``bin`` directory of |TS|. diff --git a/doc/developer-guide/plugins/getting-started/index.en.rst b/doc/developer-guide/plugins/getting-started/index.en.rst index 33d92314068..b05f383df9a 100644 --- a/doc/developer-guide/plugins/getting-started/index.en.rst +++ b/doc/developer-guide/plugins/getting-started/index.en.rst @@ -29,9 +29,10 @@ Getting Started plugin-registration-and-version-checking.en naming-conventions.en -The Traffic Server API enables you to create plugins, using the C +The Traffic Server API enables you to create plugins, using the C++ programming language, that customize the behavior of your Traffic Server -installation. This chapter contains the following sections: +installation. (Your plugin may not work properly if you use a version of C++ +older than C++17.) This chapter contains the following sections: - `Understanding Traffic Server Plugins`_ -- a brief introduction to plugins. @@ -137,21 +138,21 @@ The figure below, :ref:`possibleTSplugins`, illustrates several types of plugins You can find basic examples for many plugins in the SDK sample code: -- ``append_transform.c`` adds text from a specified file to HTTP/text +- ``append_transform.cc`` adds text from a specified file to HTTP/text responses. This plugin is explained in :ref:`developer-plugins-http-transformations-append` - The compression plugin in the figure communicates with the server - that actually does the compression. The ``server-transform.c`` plugin + that actually does the compression. The ``server-transform.cc`` plugin shows how to open a connection to a transformation server, have the server do the transformation, and send transformed data back to the client. Although the transformation is null in - ``server-transform.c``, a compression or image translation plugin + ``server-transform.cc``, a compression or image translation plugin could be implemented in a similar way. -- ``basic_auth.c`` performs basic HTTP proxy authorization. +- ``basic_auth.cc`` performs basic HTTP proxy authorization. -- ``denylist_1.c`` reads a list of servers from a configuration file +- ``denylist_1.cc`` reads a list of servers from a configuration file and denies client access to these servers. This plugin is explained in :ref:`developer-plugins-examples-denylist`. diff --git a/doc/developer-guide/plugins/getting-started/naming-conventions.en.rst b/doc/developer-guide/plugins/getting-started/naming-conventions.en.rst index 88249774186..ba2aeddfc30 100644 --- a/doc/developer-guide/plugins/getting-started/naming-conventions.en.rst +++ b/doc/developer-guide/plugins/getting-started/naming-conventions.en.rst @@ -19,11 +19,18 @@ .. _developer-plugins-getting-started-naming: -Naming Conventions -****************** +Naming/namespace Conventions +**************************** The Traffic Server API adheres to the following naming conventions: +- Unless otherwise noted, all C++ declarations provided by the API are in + the ``tsapi::c`` namspace. However, there are ``using namespace tsapi::c`` + directives in the appropriate API header files, so explicit use of this + namespace is generally unnecessary. (The ``c`` sub-namespace is used because + the design of the API reflects the fact that it was originally a straight + C API. As new declarations, designed to use C++ features, are added to the + API, they will be placed directly in the ``tsapi`` namespace.) - The ``TS`` prefix is used for all function and variable names defined in the Traffic Server API. **Examples**: ``TS_EVENT_NONE``,\ ``TSMutex``, and ``TSContCreate`` diff --git a/doc/developer-guide/plugins/getting-started/plugin-registration-and-version-checking.en.rst b/doc/developer-guide/plugins/getting-started/plugin-registration-and-version-checking.en.rst index 8e444339dd1..9122364631b 100644 --- a/doc/developer-guide/plugins/getting-started/plugin-registration-and-version-checking.en.rst +++ b/doc/developer-guide/plugins/getting-started/plugin-registration-and-version-checking.en.rst @@ -34,7 +34,7 @@ Use the following interfaces: The plugin registers the plugin and ensures it's running with a compatible version of Traffic Server. -.. literalinclude:: ../../../../example/plugins/c-api/version/version.c +.. literalinclude:: ../../../../example/plugins/c-api/version/version.cc :language: c :lines: 23- diff --git a/doc/developer-guide/plugins/hooks-and-transactions/http-alternate-selection.en.rst b/doc/developer-guide/plugins/hooks-and-transactions/http-alternate-selection.en.rst index 28f61c3c72d..aaa4b3bf5c6 100644 --- a/doc/developer-guide/plugins/hooks-and-transactions/http-alternate-selection.en.rst +++ b/doc/developer-guide/plugins/hooks-and-transactions/http-alternate-selection.en.rst @@ -73,8 +73,8 @@ The sample code below shows how to call the alternate APIs. TSMLoc content_transform_field; int accept_transform_len = -1, content_transform_len = -1; - const char* accept_transform_value = NULL; - const char* content_transform_value = NULL; + const char* accept_transform_value = nullptr; + const char* content_transform_value = nullptr; int content_plugin, accept_plugin; float quality; @@ -141,7 +141,7 @@ The sample code below shows how to call the alternate APIs. switch (event) { case TS_EVENT_HTTP_SELECT_ALT: - infop = (TSHttpAltInfo)edata; + infop = static_cast(edata); handle_select_alt(infop); break; @@ -155,7 +155,7 @@ The sample code below shows how to call the alternate APIs. void TSPluginInit (int argc, const char *argv[]) { TSHttpHookAdd(TS_HTTP_SELECT_ALT_HOOK, TSContCreate (alt_plugin, - NULL)); + nullptr)); } Traffic Server augments the alternate selection through these callouts diff --git a/doc/developer-guide/plugins/hooks-and-transactions/http-transactions.en.rst b/doc/developer-guide/plugins/hooks-and-transactions/http-transactions.en.rst index 84d4e927c88..85c2d210461 100644 --- a/doc/developer-guide/plugins/hooks-and-transactions/http-transactions.en.rst +++ b/doc/developer-guide/plugins/hooks-and-transactions/http-transactions.en.rst @@ -49,21 +49,20 @@ transaction and associate data to the transaction. #include - #define DBG_TAG "txn" + char const DBG_TAG[] = "txn"; /* Structure to be associated to txns */ - typedef struct { + struct TxnData { int i; float f; - char *s; - } TxnData; + char const *s; + }; /* Allocate memory and init a TxnData structure */ TxnData * txn_data_alloc() { - TxnData *data; - data = TSmalloc(sizeof(TxnData)); + auto data{new TxnData}; data->i = 1; data->f = 0.5; @@ -71,19 +70,12 @@ transaction and associate data to the transaction. return data; } - /* Free up a TxnData structure */ - void - txn_data_free(TxnData *data) - { - TSfree(data); - } - /* Handler for event READ_REQUEST and TXN_CLOSE */ static int local_hook_handler (TSCont contp, TSEvent event, void *edata) { TSHttpTxn txnp = (TSHttpTxn) edata; - TxnData *txn_data = TSContDataGet(contp); + auto txn_data = static_cast(TSContDataGet(contp)); switch (event) { case TS_EVENT_HTTP_READ_REQUEST_HDR: /* Modify values of txn data */ @@ -97,7 +89,7 @@ transaction and associate data to the transaction. TSDebug(DBG_TAG, "Txn data i=%d f=%f s=%s", txn_data->i, txn_data->f, txn_data->s); /* Then destroy the txn cont and its data */ - txn_data_free(txn_data); + delete txn_data; TSContDestroy(contp); break; @@ -114,7 +106,7 @@ transaction and associate data to the transaction. static int global_hook_handler (TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn) edata; + auto txnp = static_cast(edata); TSCont txn_contp; TxnData *txn_data; @@ -143,11 +135,9 @@ transaction and associate data to the transaction. void TSPluginInit (int argc, const char *argv[]) { - TSCont contp; - /* Note that we do not need a mutex for this txn since it registers globally and doesn't have any data associated with it */ - contp = TSContCreate(global_hook_handler, NULL); + TSCont contp = TSContCreate(global_hook_handler, nullptr); /* Register globally */ TSHttpHookAdd(TS_HTTP_TXN_START_HOOK, contp); diff --git a/doc/developer-guide/plugins/http-headers/mime-headers.en.rst b/doc/developer-guide/plugins/http-headers/mime-headers.en.rst index 77dbe183949..241fc17bdf2 100644 --- a/doc/developer-guide/plugins/http-headers/mime-headers.en.rst +++ b/doc/developer-guide/plugins/http-headers/mime-headers.en.rst @@ -63,7 +63,7 @@ and a location (``TSMLoc``) within the buffer. After a call to ``TSMimeHdrFieldDestroy`` or ``TSMimeHdrFieldRemove`` is made, you must deallocate the ``TSMLoc`` handle with a call to -``TSHandleMLocRelease``. You do not need to deallocate a ``NULL`` handles. +``TSHandleMLocRelease``. You do not need to deallocate a ``nullptr`` handles. For example: if you call ``TSMimeHdrFieldValueStringGet`` to get the value of the content type field and the field does not exist, then it returns ``TS_NULL_MLOC``. In such a case, you wouldn't need to deallocate the handle diff --git a/doc/developer-guide/plugins/http-headers/trafficserver-http-header-system.en.rst b/doc/developer-guide/plugins/http-headers/trafficserver-http-header-system.en.rst index 938f24c850a..035aaea7b42 100644 --- a/doc/developer-guide/plugins/http-headers/trafficserver-http-header-system.en.rst +++ b/doc/developer-guide/plugins/http-headers/trafficserver-http-header-system.en.rst @@ -32,14 +32,14 @@ It's not safe to assume that string data contained in marshal buffers (such as URLs and MIME fields) is stored in null-terminated string copies. Therefore, your plugins should always use the length parameter when retrieving or manipulating these strings. You **cannot** pass in -``NULL`` for string-length return values; string values returned from +``nullptr`` for string-length return values; string values returned from marshall buffers are not null-terminated. If you need a null-terminated value, then use ``TSstrndup`` to automatically null-terminate a string. The strings that come back and are not null-terminated **cannot** be passed into the common ``str*()`` routines .. note:: - Values returned from a marshall buffer can be ``NULL``, which means the + Values returned from a marshall buffer can be ``nullptr``, which means the field or object requested does not exist. For example (from the ``denylist_1`` sample) diff --git a/doc/developer-guide/plugins/http-transformations/append-transform-plugin.en.rst b/doc/developer-guide/plugins/http-transformations/append-transform-plugin.en.rst index f30b95c6fd1..50a66c68733 100644 --- a/doc/developer-guide/plugins/http-transformations/append-transform-plugin.en.rst +++ b/doc/developer-guide/plugins/http-transformations/append-transform-plugin.en.rst @@ -31,11 +31,11 @@ containing the append text is a parameter you specify in append_transform.so path/to/file -The append_transform plugin is based on ``null_transform.c``. The only +The append_transform plugin is based on ``null_transform.cc``. The only difference is that after the plugin feeds the document through the transformation, it adds text to the response. -Below is a list of the functions in ``append_transform.c``, in the order +Below is a list of the functions in ``append_transform.cc``, in the order they appear in the source code. Below each entry is a description of what the function does: @@ -46,12 +46,12 @@ what the function does: .. code-block:: c - typedef struct { + struct MyData { TSVIO output_vio; TSIOBuffer output_buffer; TSIOBufferReader output_reader; int append_needed; - } MyData; + }; The ``MyData`` structure is used to represent data that the transformation (vconnection) needs. The transformation's data pointer diff --git a/doc/developer-guide/plugins/http-transformations/index.en.rst b/doc/developer-guide/plugins/http-transformations/index.en.rst index de75c6b7e30..32ff730fedc 100644 --- a/doc/developer-guide/plugins/http-transformations/index.en.rst +++ b/doc/developer-guide/plugins/http-transformations/index.en.rst @@ -182,5 +182,5 @@ and will keep the transaction and the origin server connection up. This is usefu run to completion even if the user agent disconnects. Examples would be a standard transform that is expensive to initiate, or expensive origin server connections that should be :ts:cv:`shared `. -There is an `example plugin `_ that demonstrates +There is an `example plugin `_ that demonstrates this used as a pure data sink to keep the transaction up regardless of whether the user agent disconnects. diff --git a/doc/developer-guide/plugins/http-transformations/sample-buffered-null-transformation-plugin.en.rst b/doc/developer-guide/plugins/http-transformations/sample-buffered-null-transformation-plugin.en.rst index 55cd3a5ebc3..f258b8d9d78 100644 --- a/doc/developer-guide/plugins/http-transformations/sample-buffered-null-transformation-plugin.en.rst +++ b/doc/developer-guide/plugins/http-transformations/sample-buffered-null-transformation-plugin.en.rst @@ -22,7 +22,7 @@ Sample Buffered Null Transform Plugin ************************************* -The buffered null transform, ``bnull_transform.c``, reads the response +The buffered null transform, ``bnull_transform.cc``, reads the response content into a buffer and then writes the full buffer out to the client. Many examples of transformations, such as compression, require you to gather the full response content in order to perform the transformation. @@ -41,7 +41,7 @@ transform: void TSPluginInit (int argc, const char *argv[]) { TSHttpHookAdd (TS_HTTP_READ_RESPONSE_HDR_HOOK, - TSContCreate (transform_plugin, NULL)); } + TSContCreate (transform_plugin, nullptr)); } With this ``TSPluginInit`` routine, the plugin is called back every time Traffic Server reads a response header. diff --git a/doc/developer-guide/plugins/http-transformations/sample-null-transformation-plugin.en.rst b/doc/developer-guide/plugins/http-transformations/sample-null-transformation-plugin.en.rst index 86a2400838b..6bde913cdbe 100644 --- a/doc/developer-guide/plugins/http-transformations/sample-null-transformation-plugin.en.rst +++ b/doc/developer-guide/plugins/http-transformations/sample-null-transformation-plugin.en.rst @@ -38,7 +38,7 @@ Below is an overview of the null transform plugin: void TSPluginInit (int argc, const char *argv[]) { TSHttpHookAdd (TS_HTTP_READ_RESPONSE_HDR_HOOK, - TSContCreate (transform_plugin, NULL)); + TSContCreate (transform_plugin, nullptr)); With this ``TSPluginInit`` routine, the plugin is called back every time Traffic Server reads a response header. @@ -48,7 +48,7 @@ Below is an overview of the null transform plugin: .. code-block:: c static int transform_plugin (TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn) edata; + TSHttpTxn txnp = static_cast(edata); switch (event) { case TS_EVENT_HTTP_READ_RESPONSE_HDR: if (transformable (txnp)) { diff --git a/doc/developer-guide/plugins/introduction.en.rst b/doc/developer-guide/plugins/introduction.en.rst index 1a17043fdf5..fc62112167c 100644 --- a/doc/developer-guide/plugins/introduction.en.rst +++ b/doc/developer-guide/plugins/introduction.en.rst @@ -173,7 +173,7 @@ them into activity. A plugin may consist of just one static continuation that is called whenever certain events happen. Examples of such plugins include -``denylist_1.c``, ``basic_auth.c``, and ``redirect_1.c``. +``denylist_1.cc``, ``basic_auth.cc``, and ``redirect_1.cc``. Alternatively, a plugin might dynamically create other continuations as needed. Transform plugins are built in this manner: a static parent continuation checks all transactions to see if any are transformable; diff --git a/doc/developer-guide/plugins/io/cache-api.en.rst b/doc/developer-guide/plugins/io/cache-api.en.rst index ce7c8143beb..db8d731d7af 100644 --- a/doc/developer-guide/plugins/io/cache-api.en.rst +++ b/doc/developer-guide/plugins/io/cache-api.en.rst @@ -44,7 +44,7 @@ differs from the HTTP type). TSCacheKey key; TSCacheKeyCreate (&key); - TSCacheKeyDigestSet (key, (unsigned char *) key_name , strlen(key_name)); + TSCacheKeyDigestSet (key, const_cast(key_name), strlen(key_name)); TSCacheKeyDestroy (key); Cache Reads @@ -124,9 +124,9 @@ as ``content_length``. Assume the following data: TSIOBuffer cache_bufp = TSIOBufferCreate (); TSIOBufferReader cache_readerp = TSIOBufferReaderAlloc (out_bufp); - TSVConn cache_vconnp = NULL; - TSVIO cache_vio = NULL; - int content_length = 0; + TSVConn cache_vconnp = nullptr; + TSVIO cache_vio = nullptr; + int content_length = 0; In the ``TS_CACHE_OPEN_READ`` handler: diff --git a/doc/developer-guide/plugins/io/transformations.en.rst b/doc/developer-guide/plugins/io/transformations.en.rst index e0135bbf73f..91022aad777 100644 --- a/doc/developer-guide/plugins/io/transformations.en.rst +++ b/doc/developer-guide/plugins/io/transformations.en.rst @@ -142,7 +142,7 @@ Here's how to make sure that all incoming data is consumed: - After reading or copying data, make sure that you consume the data and increase the value of ndone for the input VIO, as in the - following example taken from ``null_transform.c``: + following example taken from ``null_transform.cc``: .. code-block:: c diff --git a/doc/developer-guide/plugins/mutexes.en.rst b/doc/developer-guide/plugins/mutexes.en.rst index 74a39f29148..c7e891de5e1 100644 --- a/doc/developer-guide/plugins/mutexes.en.rst +++ b/doc/developer-guide/plugins/mutexes.en.rst @@ -71,12 +71,12 @@ by other continuations). Locking Global Data =================== -The :ref:`denylist-1.c` sample plugin implements a mutex that locks global +The :ref:`denylist-1.cc` sample plugin implements a mutex that locks global data. The denylist plugin reads sites to be denied from a configuration file; file read operations are protected by a mutex -created in :c:func:`TSPluginInit`. The :ref:`denylist-1.c` code uses +created in :c:func:`TSPluginInit`. The :ref:`denylist-1.cc` code uses :c:func:`TSMutexLockTry` instead of :c:func:`TSMutexLock`. For more detailed -information, see the :ref:`denylist-1.c` code; +information, see the :ref:`denylist-1.cc` code; start by looking at the :c:func:`TSPluginInit` function. General guidelines for locking shared data are as follows: @@ -153,7 +153,7 @@ uses a transaction-specific continuation called ``txn_contp``. { /* Plugin continuation */ TSCont contp; - if ((contp = TSContCreate (plugin_cont_handler, NULL)) == TS_ERROR_PTR) { + if ((contp = TSContCreate (plugin_cont_handler, nullptr)) == TS_ERROR_PTR) { LOG_ERROR("TSContCreate"); } else { if (TSHttpHookAdd (TS_HTTP_TXN_START_HOOK, contp) == TS_ERROR) { @@ -170,13 +170,13 @@ In the plugin continuation handler, create the new continuation static int plugin_cont_handler(TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn)edata; + TSHttpTxn txnp = static_cast(edata); TSCont txn_contp; switch (event) { case TS_EVENT_HTTP_TXN_START: /* Create the HTTP txn continuation */ - txn_contp = TSContCreate(txn_cont_handler, NULL); + txn_contp = TSContCreate(txn_cont_handler, nullptr); /* Register txn_contp to be called back when txnp reaches TS_HTTP_TXN_CLOSE_HOOK */ if (TSHttpTxnHookAdd (txnp, TS_HTTP_TXN_CLOSE_HOOK, txn_contp) == TS_ERROR) { @@ -209,7 +209,7 @@ will have a memory leak. TSHttpTxn txnp; switch (event) { case TS_EVENT_HTTP_TXN_CLOSE: - txnp = (TSHttpTxn) edata; + txnp = static_cast(edata); TSContDestroy(txn_contp); break; @@ -234,9 +234,9 @@ suppose you want to store the state of the HTTP transaction: .. code-block:: c - typedef struct { + struct ContData { int state; - } ContData; + }; You need to allocate the memory and initialize this structure for each HTTP ``txnp``. You can do that in the plugin continuation handler when @@ -246,14 +246,14 @@ it is called back with ``TS_EVENT_HTTP_TXN_START`` static int plugin_cont_handler(TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn)edata; + TSHttpTxn txnp = static_cast(edata); TSCont txn_contp; ContData *contData; switch (event) { case TS_EVENT_HTTP_TXN_START: /* Create the HTTP txn continuation */ - txn_contp = TSContCreate(txn_cont_handler, NULL); + txn_contp = TSContCreate(txn_cont_handler, nullptr); /* Allocate and initialize the txn_contp data */ contData = (ContData*) TSmalloc(sizeof(ContData)); @@ -304,7 +304,7 @@ Remember to free this memory before destroying the continuation: ContData *contData; switch (event) { case TS_EVENT_HTTP_TXN_CLOSE: - txnp = (TSHttpTxn) edata; + txnp = static_cast(edata); contData = TSContDataGet(txn_contp); if (contData == TS_ERROR_PTR) { LOG_ERROR("TSContDataGet"); @@ -335,7 +335,7 @@ example above, the continuation ``txn_contp`` has registered itself to be called back at HTTP hooks and it only uses the HTTP APIs. In this case only, it's safe to access data shared between ``txnp`` and ``txn_contp`` without grabbing a lock. In the example above, -``txn_contp`` is created with a ``NULL`` mutex. This works because the +``txn_contp`` is created with a ``nullptr`` mutex. This works because the HTTP transaction ``txnp`` is the only one that will call back ``txn_contp``, and you are guaranteed that ``txn_contp`` will be called back only one hook at a time. After processing is finished, @@ -367,7 +367,7 @@ continuation created in ``txn_handler``: txn_handler (TSHttpTxn txnp, TSCont contp) { TSCont newCont; .... - newCont = TSContCreate (newCont_handler, NULL); + newCont = TSContCreate (newCont_handler, nullptr); // It's not necessary to create a new mutex for newCont. ... @@ -377,7 +377,7 @@ continuation created in ``txn_handler``: static int test_plugin (TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn) edata; + TSHttpTxn txnp = static_cast(edata); switch (event) { case TS_EVENT_HTTP_READ_REQUEST_HDR: diff --git a/doc/developer-guide/plugins/new-protocol-plugins.en.rst b/doc/developer-guide/plugins/new-protocol-plugins.en.rst index bda3c7745d3..093ad654681 100644 --- a/doc/developer-guide/plugins/new-protocol-plugins.en.rst +++ b/doc/developer-guide/plugins/new-protocol-plugins.en.rst @@ -267,46 +267,46 @@ Processing a Typical Transaction The code is contained in the following files: -- ``Protocol.c`` and ``Protocol.h`` +- ``Protocol.cc`` and ``Protocol.h`` -- ``TxnSM.c`` and ``TxnSM.h`` +- ``TxnSM.cc`` and ``TxnSM.h`` Below is a step-by-step walk-through of the code that processes a typical transaction. -#. The :c:func:`TSPluginInit` function is in the ``Protocol.c`` file. It +#. The :c:func:`TSPluginInit` function is in the ``Protocol.cc`` file. It checks the validity of the :file:`plugin.config` entries (there must be two: a client accept port and a server port) and runs an initialization routine, ``init``. -#. The ``init`` function (in ``Protocol.c``) creates the plugin's +#. The ``init`` function (in ``Protocol.cc``) creates the plugin's log file using :c:func:`TSTextLogObjectCreate`. #. The ``init`` function creates the accept state machine using ``AcceptCreate``. The code for ``AcceptCreate`` is in the - ``Accept.c`` file. + ``Accept.cc`` file. #. The ``init`` function arranges the callback of the accept state machine when there is a network connection by using :c:func:`TSNetAccept`. #. The handler for the accept state machine is ``accept_handler`` in - the ``Protocol.c`` file. When Traffic Server's Net Processor sends :c:macro:`TS_EVENT_NET_ACCEPT` + the ``Protocol.cc`` file. When Traffic Server's Net Processor sends :c:macro:`TS_EVENT_NET_ACCEPT` to the accept state machine, ``accept_handler`` creates a transaction state machine (``txn_sm``) by calling ``TxnSMCreate``. Notice that ``accept_event`` creates a mutex for the transaction state machine, since each transaction state machine has its own mutex. -#. The ``TxnSMCreate`` function is in the ``TxnSM.c`` file. The +#. The ``TxnSMCreate`` function is in the ``TxnSM.cc`` file. The first thing it does is initialize the transaction's data, which is of type ``TxnSM`` (as defined in ``TxnSM.h``). Notice that the current handler (``q_current_handler``) is set to ``state_start``. #. ``TxnSMCreate`` then creates a transaction state machine using :c:func`TSContCreate`. The handler for the transaction state machine - is ``main_handler``, which is in the ``TxnSM.c`` file. + is ``main_handler``, which is in the ``TxnSM.cc`` file. #. When ``accept_event`` receives :c:macro:`TS_EVENT_NET_ACCEPT`, it calls the transaction state machine ( - ``TSContCall (txn_sm, 0, NULL);`` ). The event passed to + ``TSContCall (txn_sm, 0, nullptr);`` ). The event passed to ``main_handler`` is ``0`` (:c:macro:`TS_EVENT_NONE`). #. The first thing ``main_handler`` does is examine the current @@ -317,7 +317,7 @@ typical transaction. ``state_start`` by using the function pointer ``TxnSMHandler`` (as defined in ``TxnSM.h``). -#. The ``state_start`` handler function (in the ``TxnSM.c`` file) +#. The ``state_start`` handler function (in the ``TxnSM.cc`` file) is handed an event (at this stage, the event is :c:macro:`TS_EVENT_NET_ACCEPT`) and a client vconnection. ``state_start`` checks to see if this client vconnection is closed; if it is not, then ``state_start`` attempts to read data from the client vconnection into an diff --git a/doc/developer-guide/plugins/plugin-interfaces.en.rst b/doc/developer-guide/plugins/plugin-interfaces.en.rst index 7011bf8c546..2c0ffaacd2a 100644 --- a/doc/developer-guide/plugins/plugin-interfaces.en.rst +++ b/doc/developer-guide/plugins/plugin-interfaces.en.rst @@ -84,7 +84,7 @@ example, ``TSrealloc`` behaves like the C library routine ``realloc``. There are two main reasons for using the routines provided by Traffic Server. The first is portability: the Traffic Server API routines behave the same on all of Traffic Server's supported platforms. For example, -``realloc`` does not accept an argument of ``NULL`` on some platforms. +``realloc`` does not accept an argument of ``nullptr`` on some platforms. The second reason is that the Traffic Server routines actually track the memory allocations by file and line number. This tracking is very efficient, always turned on, and quite useful when tracking down memory diff --git a/doc/developer-guide/plugins/plugin-management/logging-api.en.rst b/doc/developer-guide/plugins/plugin-management/logging-api.en.rst index 013d39e6f81..bcca4931ce7 100644 --- a/doc/developer-guide/plugins/plugin-management/logging-api.en.rst +++ b/doc/developer-guide/plugins/plugin-management/logging-api.en.rst @@ -58,7 +58,7 @@ The logging API enables you to: :c:func:`TSTextLogObjectDestroy` The steps below show how the logging API is used in the -``denylist_1.c`` sample plugin. For the complete source code, see the +``denylist_1.cc`` sample plugin. For the complete source code, see the :ref:`developer-plugins-examples-denylist-code` section. #. A new log file is defined as a global variable. @@ -75,7 +75,7 @@ The steps below show how the logging API is used in the TS_LOG_MODE_ADD_TIMESTAMP, &log); The new log is named ``denylist.log``. Each entry written to the log - will have a timestamp. The ``NULL`` argument specifies that the new + will have a timestamp. The ``nullptr`` argument specifies that the new log does not have a log header. The error argument stores the result of the log creation; if the log is created successfully, then an error will be equal to ``TS_LOG_ERROR_NO_ERROR``. diff --git a/doc/release-notes/whats-new.en.rst b/doc/release-notes/whats-new.en.rst index eb641e68a11..3da755e0ab4 100644 --- a/doc/release-notes/whats-new.en.rst +++ b/doc/release-notes/whats-new.en.rst @@ -46,3 +46,9 @@ Logging and Metrics Plugins ------- + +Switch to C++17 +^^^^^^^^^^^^^^^ + +Plugins are now required to be compiled as C++ code, rather than straight C. +The API is tested with C++17, so code compatible with this version is preferred. diff --git a/example/plugins/c-api/Makefile.am b/example/plugins/c-api/Makefile.am index 26e9b22dfb3..43e56e8c84a 100644 --- a/example/plugins/c-api/Makefile.am +++ b/example/plugins/c-api/Makefile.am @@ -68,45 +68,45 @@ pkglib_LTLIBRARIES = $(example_Plugins) endif -add_header_la_SOURCES = add_header/add_header.c -append_transform_la_SOURCES = append_transform/append_transform.c -basic_auth_la_SOURCES = basic_auth/basic_auth.c -denylist_0_la_SOURCES = denylist_0/denylist_0.c -denylist_1_la_SOURCES = denylist_1/denylist_1.c -bnull_transform_la_SOURCES = bnull_transform/bnull_transform.c +add_header_la_SOURCES = add_header/add_header.cc +append_transform_la_SOURCES = append_transform/append_transform.cc +basic_auth_la_SOURCES = basic_auth/basic_auth.cc +denylist_0_la_SOURCES = denylist_0/denylist_0.cc +denylist_1_la_SOURCES = denylist_1/denylist_1.cc +bnull_transform_la_SOURCES = bnull_transform/bnull_transform.cc cert_update_la_SOURCES = cert_update/cert_update.cc -request_buffer_la_SOURCES = request_buffer/request_buffer.c +request_buffer_la_SOURCES = request_buffer/request_buffer.cc cache_scan_la_SOURCES = cache_scan/cache_scan.cc client_context_dump_la_SOURCES = client_context_dump/client_context_dump.cc -file_1_la_SOURCES = file_1/file_1.c -hello_la_SOURCES = hello/hello.c +file_1_la_SOURCES = file_1/file_1.cc +hello_la_SOURCES = hello/hello.cc intercept_la_SOURCES = intercept/intercept.cc -lifecycle_plugin_la_SOURCES = lifecycle_plugin/lifecycle_plugin.c -null_transform_la_SOURCES = null_transform/null_transform.c -output_header_la_SOURCES = output_header/output_header.c +lifecycle_plugin_la_SOURCES = lifecycle_plugin/lifecycle_plugin.cc +null_transform_la_SOURCES = null_transform/null_transform.cc +output_header_la_SOURCES = output_header/output_header.cc passthru_la_SOURCES = passthru/passthru.cc -protocol_la_SOURCES = protocol/Protocol.c protocol/TxnSM.c +protocol_la_SOURCES = protocol/Protocol.cc protocol/TxnSM.cc protocol_stack_la_SOURCES = protocol_stack/protocol_stack.cc -psi_la_SOURCES = thread_pool/psi.c thread_pool/thread.c -query_remap_la_SOURCES = query_remap/query_remap.c +psi_la_SOURCES = thread_pool/psi.cc thread_pool/thread.cc +query_remap_la_SOURCES = query_remap/query_remap.cc remap_header_add_la_SOURCES = remap_header_add/remap_header_add.cc remap_la_SOURCES = remap/remap.cc -replace_header_la_SOURCES = replace_header/replace_header.c -response_header_1_la_SOURCES = response_header_1/response_header_1.c -secure_link_la_SOURCES = secure_link/secure_link.c -server_push_la_SOURCES = server_push/server_push.c -server_transform_la_SOURCES = server_transform/server_transform.c +replace_header_la_SOURCES = replace_header/replace_header.cc +response_header_1_la_SOURCES = response_header_1/response_header_1.cc +secure_link_la_SOURCES = secure_link/secure_link.cc +server_push_la_SOURCES = server_push/server_push.cc +server_transform_la_SOURCES = server_transform/server_transform.cc ssl_preaccept_la_SOURCES = ssl_preaccept/ssl_preaccept.cc ssl_sni_la_SOURCES = ssl_sni/ssl_sni.cc ssl_sni_allowlist_la_SOURCES = ssl_sni_allowlist/ssl_sni_allowlist.cc disable_http2_la_SOURCES = disable_http2/disable_http2.cc verify_cert_la_SOURCES = verify_cert/verify_cert.cc statistic_la_SOURCES = statistic/statistic.cc -thread_1_la_SOURCES = thread_1/thread_1.c +thread_1_la_SOURCES = thread_1/thread_1.cc txn_data_sink_la_SOURCES = txn_data_sink/txn_data_sink.cc -version_la_SOURCES = version/version.c -redirect_1_la_SOURCES = redirect_1/redirect_1.c -session_hooks_la_SOURCES = session_hooks/session_hooks.c +version_la_SOURCES = version/version.cc +redirect_1_la_SOURCES = redirect_1/redirect_1.cc +session_hooks_la_SOURCES = session_hooks/session_hooks.cc vconn_args_la_SOURCES = vconn_args/vconn_args.cc clang-tidy-local: $(DIST_SOURCES) diff --git a/example/plugins/c-api/add_header/add_header.c b/example/plugins/c-api/add_header/add_header.cc similarity index 100% rename from example/plugins/c-api/add_header/add_header.c rename to example/plugins/c-api/add_header/add_header.cc diff --git a/example/plugins/c-api/append_transform/append_transform.c b/example/plugins/c-api/append_transform/append_transform.cc similarity index 95% rename from example/plugins/c-api/append_transform/append_transform.c rename to example/plugins/c-api/append_transform/append_transform.cc index aca2fdbe34b..90c772d91d4 100644 --- a/example/plugins/c-api/append_transform/append_transform.c +++ b/example/plugins/c-api/append_transform/append_transform.cc @@ -66,9 +66,9 @@ my_data_alloc() data = (MyData *)TSmalloc(sizeof(MyData)); TSReleaseAssert(data); - data->output_vio = NULL; - data->output_buffer = NULL; - data->output_reader = NULL; + data->output_vio = nullptr; + data->output_buffer = nullptr; + data->output_reader = nullptr; data->append_needed = 1; return data; @@ -104,9 +104,9 @@ handle_transform(TSCont contp) /* Get our data structure for this operation. The private data structure contains the output VIO and output buffer. If the - private data structure pointer is NULL, then we'll create it + private data structure pointer is nullptr, then we'll create it and initialize its internals. */ - data = TSContDataGet(contp); + data = static_cast(TSContDataGet(contp)); if (!data) { towrite = TSVIONBytesGet(write_vio); if (towrite != INT64_MAX) { @@ -119,8 +119,8 @@ handle_transform(TSCont contp) TSContDataSet(contp, data); } - /* We also check to see if the write VIO's buffer is non-NULL. A - NULL buffer indicates that the write operation has been + /* We also check to see if the write VIO's buffer is non-null. A + null buffer indicates that the write operation has been shutdown and that the continuation does not want us to send any more WRITE_READY or WRITE_COMPLETE events. For this simplistic transformation that means we're done. In a more complex @@ -204,7 +204,7 @@ append_transform(TSCont contp, TSEvent event, void *edata ATS_UNUSED) /* Check to see if the transformation has been closed by a call to TSVConnClose. */ if (TSVConnClosedGet(contp)) { - my_data_destroy(TSContDataGet(contp)); + my_data_destroy(static_cast(TSContDataGet(contp))); TSContDestroy(contp); return 0; } else { @@ -363,7 +363,7 @@ TSPluginInit(int argc, const char *argv[]) goto Lerror; } - TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(transform_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(transform_plugin, nullptr)); return; Lerror: diff --git a/example/plugins/c-api/basic_auth/basic_auth.c b/example/plugins/c-api/basic_auth/basic_auth.cc similarity index 97% rename from example/plugins/c-api/basic_auth/basic_auth.c rename to example/plugins/c-api/basic_auth/basic_auth.cc index 5c50c55f566..581cf5d0e5a 100644 --- a/example/plugins/c-api/basic_auth/basic_auth.c +++ b/example/plugins/c-api/basic_auth/basic_auth.cc @@ -109,7 +109,7 @@ handle_dns(TSHttpTxn txnp, TSCont contp) } val = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, -1, &authval_length); - if (NULL == val) { + if (nullptr == val) { TSError("[%s] No value in Proxy-Authorization field", PLUGIN_NAME); TSHandleMLocRelease(bufp, hdr_loc, field_loc); TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc); @@ -236,8 +236,8 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) for (i = '0'; i <= '9'; i++) { base64_codes[i] = cc++; } - base64_codes['+'] = cc++; - base64_codes['/'] = cc++; + base64_codes[unsigned('+')] = cc++; + base64_codes[unsigned('/')] = cc++; - TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(auth_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(auth_plugin, nullptr)); } diff --git a/example/plugins/c-api/bnull_transform/bnull_transform.c b/example/plugins/c-api/bnull_transform/bnull_transform.cc similarity index 95% rename from example/plugins/c-api/bnull_transform/bnull_transform.c rename to example/plugins/c-api/bnull_transform/bnull_transform.cc index db41fdbb93b..02def68ff84 100644 --- a/example/plugins/c-api/bnull_transform/bnull_transform.c +++ b/example/plugins/c-api/bnull_transform/bnull_transform.cc @@ -41,7 +41,7 @@ #define PLUGIN_NAME "bnull_transform" -#define TS_NULL_MUTEX NULL +#define TS_NULL_MUTEX nullptr #define STATE_BUFFER_DATA 0 #define STATE_OUTPUT_DATA 1 @@ -59,9 +59,9 @@ my_data_alloc() data = (MyData *)TSmalloc(sizeof(MyData)); data->state = STATE_BUFFER_DATA; - data->output_vio = NULL; - data->output_buffer = NULL; - data->output_reader = NULL; + data->output_vio = nullptr; + data->output_buffer = nullptr; + data->output_reader = nullptr; return data; } @@ -97,8 +97,8 @@ handle_buffering(TSCont contp, MyData *data) TSAssert(data->output_reader); } - /* We also check to see if the write VIO's buffer is non-NULL. A - NULL buffer indicates that the write operation has been + /* We also check to see if the write VIO's buffer is non-null. A + null buffer indicates that the write operation has been shutdown and that the continuation does not want us to send any more WRITE_READY or WRITE_COMPLETE events. For this buffered transformation that means we're done buffering data. */ @@ -179,13 +179,13 @@ handle_transform(TSCont contp) /* Get our data structure for this operation. The private data structure contains the output VIO and output buffer. If the - private data structure pointer is NULL, then we'll create it + private data structure pointer is null, then we'll create it and initialize its internals. */ data = (MyData *)TSContDataGet(contp); if (!data) { data = my_data_alloc(); - TSContDataSet(contp, (void *)data); + TSContDataSet(contp, data); } do { diff --git a/example/plugins/c-api/denylist_0/denylist_0.c b/example/plugins/c-api/denylist_0/denylist_0.cc similarity index 97% rename from example/plugins/c-api/denylist_0/denylist_0.c rename to example/plugins/c-api/denylist_0/denylist_0.cc index 93066f1cbc7..da9e7a0c58b 100644 --- a/example/plugins/c-api/denylist_0/denylist_0.c +++ b/example/plugins/c-api/denylist_0/denylist_0.cc @@ -115,7 +115,7 @@ handle_response(TSHttpTxn txnp) goto done; } - buf = TSmalloc(4096); + buf = tsapi::malloc(4096); url_str = TSUrlStringGet(bufp, url_loc, &url_length); snprintf(buf, 4096, "You are forbidden from accessing \"%s\"\n", url_str); @@ -123,7 +123,7 @@ handle_response(TSHttpTxn txnp) TSHandleMLocRelease(bufp, hdr_loc, url_loc); TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc); - TSHttpTxnErrorBodySet(txnp, buf, strlen(buf), NULL); + TSHttpTxnErrorBodySet(txnp, buf, strlen(buf), nullptr); done: TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); @@ -168,6 +168,6 @@ TSPluginInit(int argc, const char *argv[]) sites[i] = TSstrdup(argv[i + 1]); } - TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(denylist_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(denylist_plugin, nullptr)); } } diff --git a/example/plugins/c-api/denylist_1/denylist_1.c b/example/plugins/c-api/denylist_1/denylist_1.cc similarity index 93% rename from example/plugins/c-api/denylist_1/denylist_1.c rename to example/plugins/c-api/denylist_1/denylist_1.cc index e61884f36e0..fca46db4330 100644 --- a/example/plugins/c-api/denylist_1/denylist_1.c +++ b/example/plugins/c-api/denylist_1/denylist_1.cc @@ -40,12 +40,14 @@ static TSCont global_contp; static void handle_txn_start(TSCont contp, TSHttpTxn txnp); +enum calling_func { + HANDLE_DNS, + HANDLE_RESPONSE, + READ_BLOCKLIST, +}; + typedef struct contp_data { - enum calling_func { - HANDLE_DNS, - HANDLE_RESPONSE, - READ_BLOCKLIST, - } cf; + calling_func cf; TSHttpTxn txnp; @@ -54,10 +56,10 @@ typedef struct contp_data { static void destroy_continuation(TSHttpTxn txnp, TSCont contp) { - cdata *cd = NULL; + cdata *cd = nullptr; cd = (cdata *)TSContDataGet(contp); - if (cd != NULL) { + if (cd != nullptr) { TSfree(cd); } TSContDestroy(contp); @@ -167,7 +169,7 @@ handle_response(TSHttpTxn txnp, TSCont contp ATS_UNUSED) TSHandleMLocRelease(bufp, hdr_loc, url_loc); TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc); - TSHttpTxnErrorBodySet(txnp, buf, strlen(buf), NULL); + TSHttpTxnErrorBodySet(txnp, buf, strlen(buf), nullptr); done: TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); @@ -185,28 +187,28 @@ read_denylist(TSCont contp) /* If the Mutex lock is not successful try again in RETRY_TIME */ if (TSMutexLockTry(sites_mutex) != TS_SUCCESS) { - if (file != NULL) { + if (file != nullptr) { TSfclose(file); } TSContScheduleOnPool(contp, RETRY_TIME, TS_THREAD_POOL_NET); return; } - if (file != NULL) { + if (file != nullptr) { char buffer[1024]; - while (TSfgets(file, buffer, sizeof(buffer) - 1) != NULL && nsites < MAX_NSITES) { + while (TSfgets(file, buffer, sizeof(buffer) - 1) != nullptr && nsites < MAX_NSITES) { char *eol; - if ((eol = strstr(buffer, "\r\n")) != NULL) { + if ((eol = strstr(buffer, "\r\n")) != nullptr) { /* To handle newlines on Windows */ *eol = '\0'; - } else if ((eol = strchr(buffer, '\n')) != NULL) { + } else if ((eol = strchr(buffer, '\n')) != nullptr) { *eol = '\0'; } else { /* Not a valid line, skip it */ continue; } - if (sites[nsites] != NULL) { + if (sites[nsites] != nullptr) { TSfree(sites[nsites]); } sites[nsites] = TSstrdup(buffer); @@ -259,7 +261,7 @@ denylist_plugin(TSCont contp, TSEvent event, void *edata) } case TS_EVENT_TIMEOUT: /* when mutex lock is not acquired and continuation is rescheduled, - the plugin is called back with TS_EVENT_TIMEOUT with a NULL + the plugin is called back with TS_EVENT_TIMEOUT with a null edata. We need to decide, in which function did the MutexLock failed and call that function again */ if (contp != global_contp) { @@ -329,7 +331,7 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) nsites = 0; for (i = 0; i < MAX_NSITES; i++) { - sites[i] = NULL; + sites[i] = nullptr; } global_contp = TSContCreate(denylist_plugin, sites_mutex); diff --git a/example/plugins/c-api/file_1/file_1.c b/example/plugins/c-api/file_1/file_1.cc similarity index 100% rename from example/plugins/c-api/file_1/file_1.c rename to example/plugins/c-api/file_1/file_1.cc diff --git a/example/plugins/c-api/hello/hello.c b/example/plugins/c-api/hello/hello.cc similarity index 100% rename from example/plugins/c-api/hello/hello.c rename to example/plugins/c-api/hello/hello.cc diff --git a/example/plugins/c-api/lifecycle_plugin/lifecycle_plugin.c b/example/plugins/c-api/lifecycle_plugin/lifecycle_plugin.cc similarity index 94% rename from example/plugins/c-api/lifecycle_plugin/lifecycle_plugin.c rename to example/plugins/c-api/lifecycle_plugin/lifecycle_plugin.cc index 41d8d56f960..237e76b6524 100644 --- a/example/plugins/c-api/lifecycle_plugin/lifecycle_plugin.c +++ b/example/plugins/c-api/lifecycle_plugin/lifecycle_plugin.cc @@ -33,9 +33,8 @@ #define PLUGIN_NAME "lifecycle" int -CallbackHandler(TSCont this, TSEvent id, void *data) +CallbackHandler(TSCont, TSEvent id, void *data) { - (void)this; // make compiler shut up about unused variable. switch (id) { case TS_EVENT_LIFECYCLE_PORTS_INITIALIZED: TSDebug(PLUGIN_NAME, "Proxy ports initialized"); @@ -78,7 +77,7 @@ TSPluginInit(int argc, const char *argv[]) goto Lerror; } - cb = TSContCreate(CallbackHandler, NULL); + cb = TSContCreate(CallbackHandler, nullptr); TSLifecycleHookAdd(TS_LIFECYCLE_PORTS_INITIALIZED_HOOK, cb); TSLifecycleHookAdd(TS_LIFECYCLE_PORTS_READY_HOOK, cb); diff --git a/example/plugins/c-api/null_transform/null_transform.c b/example/plugins/c-api/null_transform/null_transform.cc similarity index 95% rename from example/plugins/c-api/null_transform/null_transform.c rename to example/plugins/c-api/null_transform/null_transform.cc index 992841aa2f9..de69c63b6be 100644 --- a/example/plugins/c-api/null_transform/null_transform.c +++ b/example/plugins/c-api/null_transform/null_transform.cc @@ -41,9 +41,9 @@ my_data_alloc() MyData *data; data = (MyData *)TSmalloc(sizeof(MyData)); - data->output_vio = NULL; - data->output_buffer = NULL; - data->output_reader = NULL; + data->output_vio = nullptr; + data->output_buffer = nullptr; + data->output_reader = nullptr; return data; } @@ -83,10 +83,10 @@ handle_transform(TSCont contp) /* Get our data structure for this operation. The private data * structure contains the output VIO and output buffer. If the - * private data structure pointer is NULL, then we'll create it + * private data structure pointer is null, then we'll create it * and initialize its internals. */ - data = TSContDataGet(contp); + data = static_cast(TSContDataGet(contp)); if (!data) { data = my_data_alloc(); data->output_buffer = TSIOBufferCreate(); @@ -96,8 +96,8 @@ handle_transform(TSCont contp) TSContDataSet(contp, data); } - /* We also check to see if the input VIO's buffer is non-NULL. A - * NULL buffer indicates that the write operation has been + /* We also check to see if the input VIO's buffer is non-null. A + * null buffer indicates that the write operation has been * shutdown and that the upstream continuation does not want us to send any * more WRITE_READY or WRITE_COMPLETE events. For this simplistic * transformation that means we're done. In a more complex @@ -189,7 +189,7 @@ null_transform(TSCont contp, TSEvent event, void *edata) if (TSVConnClosedGet(contp)) { TSDebug(PLUGIN_NAME, "\tVConn is closed"); - my_data_destroy(TSContDataGet(contp)); + my_data_destroy(static_cast(TSContDataGet(contp))); TSContDestroy(contp); return 0; } else { @@ -308,7 +308,7 @@ TSPluginInit(int argc, const char *argv[]) goto Lerror; } - TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(transform_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(transform_plugin, nullptr)); return; Lerror: diff --git a/example/plugins/c-api/output_header/output_header.c b/example/plugins/c-api/output_header/output_header.cc similarity index 98% rename from example/plugins/c-api/output_header/output_header.c rename to example/plugins/c-api/output_header/output_header.cc index ea4de980a3c..26bfd23fda1 100644 --- a/example/plugins/c-api/output_header/output_header.c +++ b/example/plugins/c-api/output_header/output_header.cc @@ -163,7 +163,7 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) goto error; } - TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(hdr_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(hdr_plugin, nullptr)); error: TSError("[%s] Plugin not initialized", PLUGIN_NAME); diff --git a/example/plugins/c-api/protocol/Protocol.c b/example/plugins/c-api/protocol/Protocol.cc similarity index 98% rename from example/plugins/c-api/protocol/Protocol.c rename to example/plugins/c-api/protocol/Protocol.cc index 56c3086d1a8..469bc762565 100644 --- a/example/plugins/c-api/protocol/Protocol.c +++ b/example/plugins/c-api/protocol/Protocol.cc @@ -55,7 +55,7 @@ accept_handler(TSCont contp, TSEvent event, void *edata) /* This is no reason for not grabbing the lock. So skip the routine which handle LockTry failure case. */ TSMutexLockTry(pmutex); // TODO: why should it not check if we got the lock?? - TSContCall(txn_sm, 0, NULL); + TSContCall(txn_sm, TS_EVENT_NONE, nullptr); TSMutexUnlock(pmutex); break; diff --git a/example/plugins/c-api/protocol/TxnSM.c b/example/plugins/c-api/protocol/TxnSM.cc similarity index 88% rename from example/plugins/c-api/protocol/TxnSM.c rename to example/plugins/c-api/protocol/TxnSM.cc index 98d2265852f..b48555c244f 100644 --- a/example/plugins/c-api/protocol/TxnSM.c +++ b/example/plugins/c-api/protocol/TxnSM.cc @@ -103,43 +103,43 @@ TxnSMCreate(TSMutex pmutex, TSVConn client_vc, int server_port) txn_sm = (TxnSM *)TSmalloc(sizeof(TxnSM)); txn_sm->q_mutex = pmutex; - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; /* Txn will use this server port to connect to the origin server. */ txn_sm->q_server_port = server_port; /* The client_vc is returned by TSNetAccept, refer to Protocol.c. */ txn_sm->q_client_vc = client_vc; /* The server_vc will be created if Txn connects to the origin server. */ - txn_sm->q_server_vc = NULL; + txn_sm->q_server_vc = nullptr; - txn_sm->q_client_read_vio = NULL; - txn_sm->q_client_write_vio = NULL; - txn_sm->q_client_request_buffer = NULL; - txn_sm->q_client_response_buffer = NULL; - txn_sm->q_client_request_buffer_reader = NULL; - txn_sm->q_client_response_buffer_reader = NULL; + txn_sm->q_client_read_vio = nullptr; + txn_sm->q_client_write_vio = nullptr; + txn_sm->q_client_request_buffer = nullptr; + txn_sm->q_client_response_buffer = nullptr; + txn_sm->q_client_request_buffer_reader = nullptr; + txn_sm->q_client_response_buffer_reader = nullptr; - txn_sm->q_server_read_vio = NULL; - txn_sm->q_server_write_vio = NULL; - txn_sm->q_server_request_buffer = NULL; - txn_sm->q_server_response_buffer = NULL; - txn_sm->q_server_request_buffer_reader = NULL; + txn_sm->q_server_read_vio = nullptr; + txn_sm->q_server_write_vio = nullptr; + txn_sm->q_server_request_buffer = nullptr; + txn_sm->q_server_response_buffer = nullptr; + txn_sm->q_server_request_buffer_reader = nullptr; /* Char buffers to store client request and server response. */ txn_sm->q_client_request = (char *)TSmalloc(sizeof(char) * (MAX_REQUEST_LENGTH + 1)); memset(txn_sm->q_client_request, '\0', (sizeof(char) * (MAX_REQUEST_LENGTH + 1))); - txn_sm->q_server_response = NULL; + txn_sm->q_server_response = nullptr; txn_sm->q_server_response_length = 0; txn_sm->q_block_bytes_read = 0; - txn_sm->q_cache_vc = NULL; + txn_sm->q_cache_vc = nullptr; txn_sm->q_cache_response_length = 0; - txn_sm->q_cache_read_buffer = NULL; - txn_sm->q_cache_read_buffer_reader = NULL; + txn_sm->q_cache_read_buffer = nullptr; + txn_sm->q_cache_read_buffer_reader = nullptr; txn_sm->q_server_name = (char *)TSmalloc(sizeof(char) * (MAX_SERVER_NAME_LENGTH + 1)); txn_sm->q_file_name = (char *)TSmalloc(sizeof(char) * (MAX_FILE_NAME_LENGTH + 1)); - txn_sm->q_key = NULL; + txn_sm->q_key = nullptr; txn_sm->q_magic = TXN_SM_ALIVE; /* Set the current handler to be state_start. */ @@ -194,7 +194,7 @@ state_interface_with_client(TSCont contp, TSEvent event, TSVIO vio) TSDebug(PLUGIN_NAME, "enter state_interface_with_client"); - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; if (vio == txn_sm->q_client_read_vio) { return state_read_request_from_client(contp, event, vio); @@ -225,7 +225,7 @@ state_read_request_from_client(TSCont contp, TSEvent event, TSVIO vio ATS_UNUSED TSfree(temp_buf); /* Check if the request is fully read, if so, do cache lookup. */ - if (strstr(txn_sm->q_client_request, "\r\n\r\n") != NULL) { + if (strstr(txn_sm->q_client_request, "\r\n\r\n") != nullptr) { temp_buf = (char *)TSmalloc(sizeof(char) * (strlen(txn_sm->q_client_request) + 1)); memcpy(temp_buf, txn_sm->q_client_request, strlen(txn_sm->q_client_request)); temp_buf[strlen(txn_sm->q_client_request)] = '\0'; @@ -282,7 +282,7 @@ state_handle_cache_lookup(TSCont contp, TSEvent event, TSVConn vc) } txn_sm->q_cache_vc = vc; - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; /* Get the size of the cached doc. */ response_size = TSVConnCacheObjectSizeGet(txn_sm->q_cache_vc); @@ -365,19 +365,19 @@ state_handle_cache_read_response(TSCont contp, TSEvent event, TSVIO vio ATS_UNUS TSDebug(PLUGIN_NAME, "enter state_handle_cache_read_response"); - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; switch (event) { case TS_EVENT_VCONN_READ_COMPLETE: load_buffer_cache_data(txn_sm); TSVConnClose(txn_sm->q_cache_vc); - txn_sm->q_cache_vc = NULL; - txn_sm->q_cache_read_vio = NULL; - txn_sm->q_cache_write_vio = NULL; + txn_sm->q_cache_vc = nullptr; + txn_sm->q_cache_read_vio = nullptr; + txn_sm->q_cache_write_vio = nullptr; TSIOBufferReaderFree(txn_sm->q_cache_read_buffer_reader); TSIOBufferDestroy(txn_sm->q_cache_read_buffer); - txn_sm->q_cache_read_buffer_reader = NULL; - txn_sm->q_cache_read_buffer = NULL; + txn_sm->q_cache_read_buffer_reader = nullptr; + txn_sm->q_cache_read_buffer = nullptr; return send_response_to_client(contp); case TS_EVENT_VCONN_READ_READY: @@ -390,15 +390,15 @@ state_handle_cache_read_response(TSCont contp, TSEvent event, TSVIO vio ATS_UNUS /* Error */ if (txn_sm->q_cache_vc) { TSVConnClose(txn_sm->q_cache_vc); - txn_sm->q_cache_vc = NULL; - txn_sm->q_cache_read_vio = NULL; - txn_sm->q_cache_write_vio = NULL; + txn_sm->q_cache_vc = nullptr; + txn_sm->q_cache_read_vio = nullptr; + txn_sm->q_cache_write_vio = nullptr; } /* Open the write_vc, after getting doc from the origin server, write the doc into the cache. */ set_handler(txn_sm->q_current_handler, (TxnSMHandler)&state_handle_cache_prepare_for_write); - TSAssert(txn_sm->q_pending_action == NULL); + TSAssert(txn_sm->q_pending_action == nullptr); txn_sm->q_pending_action = TSCacheWrite(contp, txn_sm->q_key); break; } @@ -415,7 +415,7 @@ state_handle_cache_prepare_for_write(TSCont contp, TSEvent event, TSVConn vc) TSDebug(PLUGIN_NAME, "enter state_handle_cache_prepare_for_write"); - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; switch (event) { case TS_EVENT_CACHE_OPEN_WRITE: @@ -423,11 +423,11 @@ state_handle_cache_prepare_for_write(TSCont contp, TSEvent event, TSVConn vc) break; default: TSError("[%s] Can't open cache write_vc, aborting txn", PLUGIN_NAME); - txn_sm->q_cache_vc = NULL; + txn_sm->q_cache_vc = nullptr; return prepare_to_die(contp); break; } - return state_build_and_send_request(contp, 0, NULL); + return state_build_and_send_request(contp, TS_EVENT_NONE, nullptr); } /* Cache miss or error case. Start the process to send the request @@ -439,7 +439,7 @@ state_build_and_send_request(TSCont contp, TSEvent event ATS_UNUSED, void *data TSDebug(PLUGIN_NAME, "enter state_build_and_send_request"); - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; txn_sm->q_server_request_buffer = TSIOBufferCreate(); if (!txn_sm->q_server_request_buffer) { @@ -463,7 +463,7 @@ state_build_and_send_request(TSCont contp, TSEvent event ATS_UNUSED, void *data /* First thing to do is to get the server IP from the server host name. */ set_handler(txn_sm->q_current_handler, (TxnSMHandler)&state_dns_lookup); - TSAssert(txn_sm->q_pending_action == NULL); + TSAssert(txn_sm->q_pending_action == nullptr); txn_sm->q_pending_action = TSHostLookup(contp, txn_sm->q_server_name, strlen(txn_sm->q_server_name)); TSAssert(txn_sm->q_pending_action); @@ -484,14 +484,14 @@ state_dns_lookup(TSCont contp, TSEvent event, TSHostLookupResult host_info) if (event != TS_EVENT_HOST_LOOKUP || !host_info) { return prepare_to_die(contp); } - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; /* Get the server IP from data structure TSHostLookupResult. */ struct sockaddr const *sa = TSHostLookupResultAddrGet(host_info); /* Connect to the server using its IP. */ set_handler(txn_sm->q_current_handler, (TxnSMHandler)&state_connect_to_server); - TSAssert(txn_sm->q_pending_action == NULL); + TSAssert(txn_sm->q_pending_action == nullptr); TSAssert(sa->sa_family == AF_INET); /* NO IPv6 in this plugin */ struct sockaddr_in *addr = (struct sockaddr_in *)(sa); @@ -517,7 +517,7 @@ state_connect_to_server(TSCont contp, TSEvent event, TSVConn vc) if (event != TS_EVENT_NET_CONNECT) { return prepare_to_die(contp); } - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; txn_sm->q_server_vc = vc; @@ -564,7 +564,7 @@ state_interface_with_server(TSCont contp, TSEvent event, TSVIO vio) TSDebug(PLUGIN_NAME, "enter state_interface_with_server"); - txn_sm->q_pending_action = NULL; + txn_sm->q_pending_action = nullptr; switch (event) { /* This is returned from cache_vc. */ @@ -584,35 +584,35 @@ state_interface_with_server(TSCont contp, TSEvent event, TSVIO vio) /* There is no more use of server_vc, close it. */ if (txn_sm->q_server_vc) { TSVConnClose(txn_sm->q_server_vc); - txn_sm->q_server_vc = NULL; + txn_sm->q_server_vc = nullptr; } - txn_sm->q_server_read_vio = NULL; - txn_sm->q_server_write_vio = NULL; + txn_sm->q_server_read_vio = nullptr; + txn_sm->q_server_write_vio = nullptr; /* Check if the response is good */ if (txn_sm->q_server_response_length == 0) { /* This is the bad response. Close client_vc. */ if (txn_sm->q_client_vc) { TSVConnClose(txn_sm->q_client_vc); - txn_sm->q_client_vc = NULL; + txn_sm->q_client_vc = nullptr; } - txn_sm->q_client_read_vio = NULL; - txn_sm->q_client_write_vio = NULL; + txn_sm->q_client_read_vio = nullptr; + txn_sm->q_client_write_vio = nullptr; /* Close cache_vc as well. */ if (txn_sm->q_cache_vc) { TSVConnClose(txn_sm->q_cache_vc); - txn_sm->q_cache_vc = NULL; + txn_sm->q_cache_vc = nullptr; } - txn_sm->q_cache_write_vio = NULL; - return state_done(contp, 0, NULL); + txn_sm->q_cache_write_vio = nullptr; + return state_done(contp, TS_EVENT_NONE, nullptr); } if (txn_sm->q_cache_response_length >= txn_sm->q_server_response_length) { /* Write is complete, close the cache_vc. */ TSVConnClose(txn_sm->q_cache_vc); - txn_sm->q_cache_vc = NULL; - txn_sm->q_cache_write_vio = NULL; + txn_sm->q_cache_vc = nullptr; + txn_sm->q_cache_write_vio = nullptr; TSIOBufferReaderFree(txn_sm->q_cache_response_buffer_reader); /* Open cache_vc to read data and send to client. */ @@ -697,7 +697,7 @@ state_write_to_cache(TSCont contp, TSEvent event, TSVIO vio) txn_sm->q_cache_response_length += TSVIONBytesGet(vio); /* If not all data have been read in, we have to reenable the read_vio */ - if (txn_sm->q_server_vc != NULL) { + if (txn_sm->q_server_vc != nullptr) { TSDebug(PLUGIN_NAME, "re-enable server_read_vio"); TSVIOReenable(txn_sm->q_server_read_vio); return TS_SUCCESS; @@ -708,8 +708,8 @@ state_write_to_cache(TSCont contp, TSEvent event, TSVIO vio) TSDebug(PLUGIN_NAME, "close cache_vc, cache_response_length is %d, server_response_length is %d", txn_sm->q_cache_response_length, txn_sm->q_server_response_length); TSVConnClose(txn_sm->q_cache_vc); - txn_sm->q_cache_vc = NULL; - txn_sm->q_cache_write_vio = NULL; + txn_sm->q_cache_vc = nullptr; + txn_sm->q_cache_write_vio = nullptr; TSIOBufferReaderFree(txn_sm->q_cache_response_buffer_reader); /* Open cache_vc to read data and send to client. */ @@ -752,12 +752,12 @@ state_send_response_to_client(TSCont contp, TSEvent event, TSVIO vio) /* Finished sending all data to client, close client_vc. */ if (txn_sm->q_client_vc) { TSVConnClose(txn_sm->q_client_vc); - txn_sm->q_client_vc = NULL; + txn_sm->q_client_vc = nullptr; } - txn_sm->q_client_read_vio = NULL; - txn_sm->q_client_write_vio = NULL; + txn_sm->q_client_read_vio = nullptr; + txn_sm->q_client_write_vio = nullptr; - return state_done(contp, 0, NULL); + return state_done(contp, TS_EVENT_NONE, nullptr); default: TSDebug(PLUGIN_NAME, " . default handler"); @@ -779,26 +779,26 @@ prepare_to_die(TSCont contp) TSDebug(PLUGIN_NAME, "enter prepare_to_die"); if (txn_sm->q_client_vc) { TSVConnAbort(txn_sm->q_client_vc, 1); - txn_sm->q_client_vc = NULL; + txn_sm->q_client_vc = nullptr; } - txn_sm->q_client_read_vio = NULL; - txn_sm->q_client_write_vio = NULL; + txn_sm->q_client_read_vio = nullptr; + txn_sm->q_client_write_vio = nullptr; if (txn_sm->q_server_vc) { TSVConnAbort(txn_sm->q_server_vc, 1); - txn_sm->q_server_vc = NULL; + txn_sm->q_server_vc = nullptr; } - txn_sm->q_server_read_vio = NULL; - txn_sm->q_server_write_vio = NULL; + txn_sm->q_server_read_vio = nullptr; + txn_sm->q_server_write_vio = nullptr; if (txn_sm->q_cache_vc) { TSVConnAbort(txn_sm->q_cache_vc, 1); - txn_sm->q_cache_vc = NULL; + txn_sm->q_cache_vc = nullptr; } - txn_sm->q_cache_read_vio = NULL; - txn_sm->q_cache_write_vio = NULL; + txn_sm->q_cache_read_vio = nullptr; + txn_sm->q_cache_write_vio = nullptr; - return state_done(contp, 0, NULL); + return state_done(contp, TS_EVENT_NONE, nullptr); } int @@ -815,16 +815,16 @@ state_done(TSCont contp, TSEvent event ATS_UNUSED, TSVIO vio ATS_UNUSED) TSDebug(PLUGIN_NAME, "action is done %p", txn_sm->q_pending_action); } - txn_sm->q_pending_action = NULL; - txn_sm->q_mutex = NULL; + txn_sm->q_pending_action = nullptr; + txn_sm->q_mutex = nullptr; if (txn_sm->q_client_request_buffer) { if (txn_sm->q_client_request_buffer_reader) { TSIOBufferReaderFree(txn_sm->q_client_request_buffer_reader); } TSIOBufferDestroy(txn_sm->q_client_request_buffer); - txn_sm->q_client_request_buffer = NULL; - txn_sm->q_client_request_buffer_reader = NULL; + txn_sm->q_client_request_buffer = nullptr; + txn_sm->q_client_request_buffer_reader = nullptr; } if (txn_sm->q_client_response_buffer) { @@ -833,8 +833,8 @@ state_done(TSCont contp, TSEvent event ATS_UNUSED, TSVIO vio ATS_UNUSED) } TSIOBufferDestroy(txn_sm->q_client_response_buffer); - txn_sm->q_client_response_buffer = NULL; - txn_sm->q_client_response_buffer_reader = NULL; + txn_sm->q_client_response_buffer = nullptr; + txn_sm->q_client_response_buffer_reader = nullptr; } if (txn_sm->q_cache_read_buffer) { @@ -842,8 +842,8 @@ state_done(TSCont contp, TSEvent event ATS_UNUSED, TSVIO vio ATS_UNUSED) TSIOBufferReaderFree(txn_sm->q_cache_read_buffer_reader); } TSIOBufferDestroy(txn_sm->q_cache_read_buffer); - txn_sm->q_cache_read_buffer = NULL; - txn_sm->q_cache_read_buffer_reader = NULL; + txn_sm->q_cache_read_buffer = nullptr; + txn_sm->q_cache_read_buffer_reader = nullptr; } if (txn_sm->q_server_request_buffer) { @@ -851,23 +851,23 @@ state_done(TSCont contp, TSEvent event ATS_UNUSED, TSVIO vio ATS_UNUSED) TSIOBufferReaderFree(txn_sm->q_server_request_buffer_reader); } TSIOBufferDestroy(txn_sm->q_server_request_buffer); - txn_sm->q_server_request_buffer = NULL; - txn_sm->q_server_request_buffer_reader = NULL; + txn_sm->q_server_request_buffer = nullptr; + txn_sm->q_server_request_buffer_reader = nullptr; } if (txn_sm->q_server_response_buffer) { TSIOBufferDestroy(txn_sm->q_server_response_buffer); - txn_sm->q_server_response_buffer = NULL; + txn_sm->q_server_response_buffer = nullptr; } if (txn_sm->q_server_name) { TSfree(txn_sm->q_server_name); - txn_sm->q_server_name = NULL; + txn_sm->q_server_name = nullptr; } if (txn_sm->q_file_name) { TSfree(txn_sm->q_file_name); - txn_sm->q_file_name = NULL; + txn_sm->q_file_name = nullptr; } if (txn_sm->q_key) { @@ -876,12 +876,12 @@ state_done(TSCont contp, TSEvent event ATS_UNUSED, TSVIO vio ATS_UNUSED) if (txn_sm->q_client_request) { TSfree(txn_sm->q_client_request); - txn_sm->q_client_request = NULL; + txn_sm->q_client_request = nullptr; } if (txn_sm->q_server_response) { TSfree(txn_sm->q_server_response); - txn_sm->q_server_response = NULL; + txn_sm->q_server_response = nullptr; } txn_sm->q_magic = TXN_SM_DEAD; @@ -920,14 +920,14 @@ get_info_from_buffer(TSIOBufferReader the_reader) int64_t read_avail, read_done; if (!the_reader) { - return NULL; + return nullptr; } read_avail = TSIOBufferReaderAvail(the_reader); info = (char *)TSmalloc(sizeof(char) * read_avail); - if (info == NULL) { - return NULL; + if (info == nullptr) { + return nullptr; } info_start = info; @@ -961,17 +961,17 @@ is_request_end(char *buf) int parse_request(char *request, char *server_name, char *file_name) { - char *saveptr = NULL; + char *saveptr = nullptr; char *temp = strtok_r(request, " ", &saveptr); - if (temp != NULL) { + if (temp != nullptr) { TSstrlcpy(server_name, temp, MAX_SERVER_NAME_LENGTH + 1); } else { return 0; } - temp = strtok_r(NULL, " ", &saveptr); - if (temp != NULL) { + temp = strtok_r(nullptr, " ", &saveptr); + if (temp != nullptr) { TSstrlcpy(file_name, temp, MAX_FILE_NAME_LENGTH + 1); } else { return 0; diff --git a/example/plugins/c-api/query_remap/query_remap.c b/example/plugins/c-api/query_remap/query_remap.cc similarity index 95% rename from example/plugins/c-api/query_remap/query_remap.c rename to example/plugins/c-api/query_remap/query_remap.cc index 18e58b228f9..a5e2249b869 100644 --- a/example/plugins/c-api/query_remap/query_remap.c +++ b/example/plugins/c-api/query_remap/query_remap.cc @@ -46,7 +46,7 @@ TSRemapInit(TSRemapInterface *api_info ATS_UNUSED, char *errbuf ATS_UNUSED, int { /* Called at TS startup. Nothing needed for this plugin */ TSDebug(PLUGIN_NAME, "remap plugin initialized"); - return 0; + return TS_SUCCESS; } TSReturnCode @@ -58,7 +58,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf ATS_UNUSED, i if (argc < 4) { TSError("[%s] Missing parameters", PLUGIN_NAME); - return -1; + return TS_ERROR; } /* initialize the struct to store info about this remap instance @@ -84,7 +84,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf ATS_UNUSED, i *ih = (void *)qri; TSDebug(PLUGIN_NAME, "created instance %p", *ih); - return 0; + return TS_SUCCESS; } void @@ -114,7 +114,7 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh ATS_UNUSED, TSRemapRequestInfo *rri) query_remap_info *qri = (query_remap_info *)ih; if (!qri || !rri) { - TSError("[%s] NULL private data or RRI", PLUGIN_NAME); + TSError("[%s] null private data or RRI", PLUGIN_NAME); return TSREMAP_NO_REMAP; } @@ -123,14 +123,14 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh ATS_UNUSED, TSRemapRequestInfo *rri) if (req_query && req_query_len > 0) { char *q, *key; - char *s = NULL; + char *s = nullptr; int hostidx = -1; /* make a copy of the query, as it is read only */ q = TSstrndup(req_query, req_query_len + 1); /* parse query parameters */ - for (key = strtok_r(q, "&", &s); key != NULL;) { + for (key = strtok_r(q, "&", &s); key != nullptr;) { char *val = strchr(key, '='); if (val && (size_t)(val - key) == qri->param_len && !strncmp(key, qri->param_name, qri->param_len)) { ++val; @@ -140,7 +140,7 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh ATS_UNUSED, TSRemapRequestInfo *rri) TSDebug(PLUGIN_NAME, "modifying host based on %s", key); break; } - key = strtok_r(NULL, "&", &s); + key = strtok_r(nullptr, "&", &s); } TSfree(q); diff --git a/example/plugins/c-api/redirect_1/redirect_1.c b/example/plugins/c-api/redirect_1/redirect_1.cc similarity index 96% rename from example/plugins/c-api/redirect_1/redirect_1.c rename to example/plugins/c-api/redirect_1/redirect_1.cc index 45b83408700..419de7c0a3e 100644 --- a/example/plugins/c-api/redirect_1/redirect_1.c +++ b/example/plugins/c-api/redirect_1/redirect_1.cc @@ -92,7 +92,7 @@ handle_client_lookup(TSHttpTxn txnp, TSCont contp) if (addr_size > 0) { char clientstring[INET6_ADDRSTRLEN]; - if (NULL != inet_ntop(addr->sa_family, addr, clientstring, addr_size)) { + if (nullptr != inet_ntop(addr->sa_family, addr, clientstring, addr_size)) { TSDebug(PLUGIN_NAME, "clientip is %s and block_ip is %s", clientstring, block_ip); } } @@ -157,7 +157,7 @@ handle_response(TSHttpTxn txnp) { TSMBuffer bufp; TSMLoc hdr_loc, newfield_loc; - char *errormsg_body = "All requests from this IP address are redirected.\n"; + char const *errormsg_body = "All requests from this IP address are redirected.\n"; char *tmp_body; if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) { @@ -179,7 +179,7 @@ handle_response(TSHttpTxn txnp) * will try to free the passed buffer with TSfree(). */ tmp_body = TSstrdup(errormsg_body); - TSHttpTxnErrorBodySet(txnp, tmp_body, strlen(tmp_body), NULL); + TSHttpTxnErrorBodySet(txnp, tmp_body, strlen(tmp_body), nullptr); TSHandleMLocRelease(bufp, hdr_loc, newfield_loc); TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc); @@ -249,7 +249,7 @@ update_redirected_method_stats(TSMBuffer bufp, TSMLoc hdr_loc) txn_method = TSHttpHdrMethodGet(bufp, hdr_loc, &length); - if (NULL != txn_method) { + if (nullptr != txn_method) { if (0 == strncmp(txn_method, TS_HTTP_METHOD_CONNECT, length)) { TSStatIntIncrement(redirect_count_connect, 1); } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_DELETE, length)) { @@ -307,7 +307,7 @@ TSPluginInit(int argc, const char *argv[]) url_redirect = TSstrdup(argv[2]); int uri_len = strlen(prefix) + strlen(url_redirect) + 1; - uri_redirect = TSmalloc(uri_len); + uri_redirect = tsapi::malloc(uri_len); TSstrlcpy(uri_redirect, prefix, uri_len); TSstrlcat(uri_redirect, url_redirect, uri_len); @@ -320,7 +320,7 @@ TSPluginInit(int argc, const char *argv[]) TSDebug(PLUGIN_NAME, "initializing stats"); init_stats(); - TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(redirect_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(redirect_plugin, nullptr)); TSDebug(PLUGIN_NAME ".init", "block_ip is %s, url_redirect is %s, and uri_redirect is %s", block_ip, url_redirect, uri_redirect); diff --git a/example/plugins/c-api/remap_header_add/remap_header_add.cc b/example/plugins/c-api/remap_header_add/remap_header_add.cc index 702da50251d..9855af84642 100644 --- a/example/plugins/c-api/remap_header_add/remap_header_add.cc +++ b/example/plugins/c-api/remap_header_add/remap_header_add.cc @@ -44,9 +44,8 @@ struct remap_line { }; #define PLUGIN_NAME "headeradd_remap" -#define EXTERN extern "C" -EXTERN void +void ParseArgIntoNv(const char *arg, char **n, char **v) { const char *colon_pos = strchr(arg, ':'); diff --git a/example/plugins/c-api/replace_header/replace_header.c b/example/plugins/c-api/replace_header/replace_header.cc similarity index 99% rename from example/plugins/c-api/replace_header/replace_header.c rename to example/plugins/c-api/replace_header/replace_header.cc index 7832d9e1133..8da7a0dfea7 100644 --- a/example/plugins/c-api/replace_header/replace_header.c +++ b/example/plugins/c-api/replace_header/replace_header.cc @@ -108,5 +108,5 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) TSError("[%s] Plugin registration failed", PLUGIN_NAME); } - TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(replace_header_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(replace_header_plugin, nullptr)); } diff --git a/example/plugins/c-api/request_buffer/request_buffer.c b/example/plugins/c-api/request_buffer/request_buffer.cc similarity index 92% rename from example/plugins/c-api/request_buffer/request_buffer.c rename to example/plugins/c-api/request_buffer/request_buffer.cc index 475c71fbc2e..1402e7e7a60 100644 --- a/example/plugins/c-api/request_buffer/request_buffer.c +++ b/example/plugins/c-api/request_buffer/request_buffer.cc @@ -31,26 +31,26 @@ #define PLUGIN_NAME "request_buffer" -#define TS_NULL_MUTEX NULL +#define TS_NULL_MUTEX nullptr static char * request_body_get(TSHttpTxn txnp, int *len) { - char *ret = NULL; + char *ret = nullptr; TSIOBufferReader post_buffer_reader = TSHttpTxnPostBufferReaderGet(txnp); int64_t read_avail = TSIOBufferReaderAvail(post_buffer_reader); if (read_avail == 0) { TSIOBufferReaderFree(post_buffer_reader); - return NULL; + return nullptr; } ret = (char *)TSmalloc(sizeof(char) * read_avail); int64_t consumed = 0; int64_t data_len = 0; - const char *char_data = NULL; + const char *char_data = nullptr; TSIOBufferBlock block = TSIOBufferReaderStart(post_buffer_reader); - while (block != NULL) { + while (block != nullptr) { char_data = TSIOBufferBlockReadStart(block, post_buffer_reader, &data_len); memcpy(ret + consumed, char_data, data_len); consumed += data_len; @@ -130,9 +130,9 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) info.support_email = "dev@trafficserver.apache.org"; if (TSPluginRegister(&info) != TS_SUCCESS) { - TSDebug(PLUGIN_NAME, "[%s] Plugin registration failed", PLUGIN_NAME); + TSDebug(PLUGIN_NAME, "[%s] Plugin registration failed, plugin disabled", PLUGIN_NAME); - goto Lerror; + return; } /* This is call we could use if we need to protect global data */ @@ -141,8 +141,4 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) TSMutex mutex = TS_NULL_MUTEX; TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(global_plugin, mutex)); TSDebug(PLUGIN_NAME, "[%s] Plugin registration succeeded", PLUGIN_NAME); - return; - -Lerror: - TSDebug(PLUGIN_NAME, "[%s] Plugin disabled", PLUGIN_NAME); } diff --git a/example/plugins/c-api/response_header_1/response_header_1.c b/example/plugins/c-api/response_header_1/response_header_1.cc similarity index 98% rename from example/plugins/c-api/response_header_1/response_header_1.c rename to example/plugins/c-api/response_header_1/response_header_1.cc index 9a0430f5438..535bfc39cd5 100644 --- a/example/plugins/c-api/response_header_1/response_header_1.c +++ b/example/plugins/c-api/response_header_1/response_header_1.cc @@ -114,7 +114,7 @@ modify_header(TSHttpTxn txnp) TSMimeHdrFieldAppend(resp_bufp, resp_loc, new_field_loc); TSMimeHdrFieldNameSet(resp_bufp, resp_loc, new_field_loc, mimehdr2_name, strlen(mimehdr2_name)); - time_t recvd_time = time(NULL); + time_t recvd_time = time(nullptr); TSMimeHdrFieldValueDateInsert(resp_bufp, resp_loc, new_field_loc, recvd_time); TSHandleMLocRelease(resp_bufp, resp_loc, new_field_loc); @@ -144,7 +144,7 @@ modify_header(TSHttpTxn txnp) /* Get the cached MIME value for this name in this HTTP header */ chkptr = TSMimeHdrFieldValueStringGet(cached_bufp, cached_loc, cached_field_loc, -1, &chklength); - if (NULL == chkptr || !chklength) { + if (nullptr == chkptr || !chklength) { TSError("[%s] Could not find value for cached MIME field name %s", PLUGIN_NAME, mimehdr1_name); TSHandleMLocRelease(resp_bufp, TS_NULL_MLOC, resp_loc); TSHandleMLocRelease(cached_bufp, TS_NULL_MLOC, cached_loc); @@ -265,7 +265,7 @@ TSPluginInit(int argc, const char *argv[]) TSDebug(PLUGIN_NAME, "init buffer hdr, field and value locs are %p, %p and %p", hdr_loc, field_loc, value_loc); init_buffer_status = 1; - TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(modify_response_header_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, TSContCreate(modify_response_header_plugin, nullptr)); /* * The following code demonstrates how to extract the field_loc from the header. diff --git a/example/plugins/c-api/secure_link/secure_link.c b/example/plugins/c-api/secure_link/secure_link.cc similarity index 83% rename from example/plugins/c-api/secure_link/secure_link.c rename to example/plugins/c-api/secure_link/secure_link.cc index 661f831acc4..b3fe90b04c1 100644 --- a/example/plugins/c-api/secure_link/secure_link.c +++ b/example/plugins/c-api/secure_link/secure_link.cc @@ -44,6 +44,7 @@ typedef struct { TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) { + TSRemapStatus status{TSREMAP_ERROR}; int i, len; time_t t, e; EVP_MD_CTX *ctx; @@ -51,8 +52,8 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) const char *qh, *ph, *ip; unsigned char md[MD5_DIGEST_LENGTH]; secure_link_info *sli = (secure_link_info *)ih; - char *token = NULL, *tokenptr = NULL, *expire = NULL, *expireptr = NULL, *path = NULL; - char *s, *ptr, *saveptr = NULL, *val, hash[32] = ""; + char *token = nullptr, *tokenptr = nullptr, *expire = nullptr, *expireptr = nullptr, *path = nullptr; + char *s, *ptr, *saveptr = nullptr, *val, hash[32] = ""; in = (struct sockaddr_in *)TSHttpTxnClientAddrGet(rh); ip = inet_ntoa(in->sin_addr); @@ -63,9 +64,9 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) qh = TSUrlHttpQueryGet(rri->requestBufp, rri->requestUrl, &len); if (qh && len > 0) { s = TSstrndup(qh, len); - if ((ptr = strtok_r(s, "&", &saveptr)) != NULL) { + if ((ptr = strtok_r(s, "&", &saveptr)) != nullptr) { do { - if ((val = strchr(ptr, '=')) != NULL) { + if ((val = strchr(ptr, '=')) != nullptr) { *val++ = '\0'; if (strcmp(ptr, "st") == 0) { tokenptr = val; @@ -76,9 +77,9 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) TSError("[%s] Invalid parameter [%s]", PLUGIN_NAME, ptr); break; } - } while ((ptr = strtok_r(NULL, "&", &saveptr)) != NULL); - token = (NULL == tokenptr ? NULL : TSstrdup(tokenptr)); - expire = (NULL == expireptr ? NULL : TSstrdup(expireptr)); + } while ((ptr = strtok_r(nullptr, "&", &saveptr)) != nullptr); + token = (nullptr == tokenptr ? nullptr : TSstrdup(tokenptr)); + expire = (nullptr == expireptr ? nullptr : TSstrdup(expireptr)); } else { TSError("[%s] strtok didn't find a & in the query string", PLUGIN_NAME); /* this is just example, so set fake params to prevent plugin crash */ @@ -93,7 +94,7 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) ph = TSUrlPathGet(rri->requestBufp, rri->requestUrl, &len); if (ph && len > 0) { s = TSstrndup(ph, len); - if ((ptr = strrchr(s, '/')) != NULL) { + if ((ptr = strrchr(s, '/')) != nullptr) { *++ptr = '\0'; } path = TSstrdup(s); @@ -108,7 +109,7 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) #else ctx = EVP_MD_CTX_create(); #endif - EVP_DigestInit_ex(ctx, EVP_md5(), NULL); + EVP_DigestInit_ex(ctx, EVP_md5(), nullptr); EVP_DigestUpdate(ctx, sli->secret, strlen(sli->secret)); EVP_DigestUpdate(ctx, ip, strlen(ip)); @@ -118,7 +119,7 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) if (expire) { EVP_DigestUpdate(ctx, expire, strlen(expire)); } - EVP_DigestFinal_ex(ctx, md, NULL); + EVP_DigestFinal_ex(ctx, md, nullptr); #ifdef HAVE_EVP_MD_CTX_FREE EVP_MD_CTX_free(ctx); #else @@ -128,9 +129,9 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) snprintf(&hash[i * 2], sizeof(hash) - (i * 2), "%02x", md[i]); } time(&t); - e = (NULL == expire ? 0 : strtol(expire, NULL, 16)); - i = TSREMAP_DID_REMAP; - if (e < t || (NULL == token || 0 != strcmp(hash, token))) { + e = (nullptr == expire ? 0 : strtol(expire, nullptr, 16)); + status = TSREMAP_DID_REMAP; + if (e < t || (nullptr == token || 0 != strcmp(hash, token))) { if (e < t) { TSDebug(PLUGIN_NAME, "link expired: [%lu] vs [%lu]", t, e); } else { @@ -139,24 +140,24 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) if (sli->strict) { TSDebug(PLUGIN_NAME, "request is DENY"); TSHttpTxnStatusSet(rh, TS_HTTP_STATUS_FORBIDDEN); - i = TSREMAP_NO_REMAP; + status = TSREMAP_NO_REMAP; } else { TSDebug(PLUGIN_NAME, "request is PASS"); } } - if (i == TSREMAP_DID_REMAP) { + if (status == TSREMAP_DID_REMAP) { if (TSUrlHttpQuerySet(rri->requestBufp, rri->requestUrl, "", -1) == TS_SUCCESS) { s = TSUrlStringGet(rri->requestBufp, rri->requestUrl, &len); TSDebug(PLUGIN_NAME, "new request string is [%.*s]", len, s); TSfree(s); } else { - i = TSREMAP_NO_REMAP; + status = TSREMAP_NO_REMAP; } } TSfree(expire); TSfree(token); TSfree(path); - return i; + return status; } TSReturnCode @@ -170,15 +171,15 @@ TSRemapNewInstance(int argc, char **argv, void **ih, char *errbuf, int errbuf_si (void)errbuf_size; sli = (secure_link_info *)TSmalloc(sizeof(secure_link_info)); - sli->secret = NULL; + sli->secret = nullptr; sli->strict = 0; for (i = 2; i < argc; i++) { char *ptr; - if ((ptr = strchr(argv[i], ':')) != NULL) { + if ((ptr = strchr(argv[i], ':')) != nullptr) { *ptr++ = '\0'; if (strcmp(argv[i], "secret") == 0) { - if (sli->secret != NULL) { + if (sli->secret != nullptr) { TSfree(sli->secret); } sli->secret = TSstrdup(ptr); @@ -192,7 +193,7 @@ TSRemapNewInstance(int argc, char **argv, void **ih, char *errbuf, int errbuf_si } } - if (sli->secret == NULL) { + if (sli->secret == nullptr) { sli->secret = TSstrdup(""); } diff --git a/example/plugins/c-api/server_push/server_push.c b/example/plugins/c-api/server_push/server_push.cc similarity index 97% rename from example/plugins/c-api/server_push/server_push.c rename to example/plugins/c-api/server_push/server_push.cc index c921269aa1b..9e2d1af92e5 100644 --- a/example/plugins/c-api/server_push/server_push.c +++ b/example/plugins/c-api/server_push/server_push.cc @@ -109,6 +109,6 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) } TSstrlcpy(url, argv[1], sizeof(url)); - TSCont handler = TSContCreate(server_push_plugin, NULL); + TSCont handler = TSContCreate(server_push_plugin, nullptr); TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, handler); } diff --git a/example/plugins/c-api/server_transform/server_transform.c b/example/plugins/c-api/server_transform/server_transform.cc similarity index 90% rename from example/plugins/c-api/server_transform/server_transform.c rename to example/plugins/c-api/server_transform/server_transform.cc index 3d1d90d3ed7..43a58230a59 100644 --- a/example/plugins/c-api/server_transform/server_transform.c +++ b/example/plugins/c-api/server_transform/server_transform.cc @@ -93,15 +93,15 @@ transform_create(TSHttpTxn txnp) data = (TransformData *)TSmalloc(sizeof(TransformData)); data->state = STATE_BUFFER; data->txn = txnp; - data->input_buf = NULL; - data->input_reader = NULL; - data->output_buf = NULL; - data->output_reader = NULL; - data->output_vio = NULL; - data->output_vc = NULL; - data->pending_action = NULL; - data->server_vc = NULL; - data->server_vio = NULL; + data->input_buf = nullptr; + data->input_reader = nullptr; + data->output_buf = nullptr; + data->output_reader = nullptr; + data->output_vio = nullptr; + data->output_vc = nullptr; + data->pending_action = nullptr; + data->server_vc = nullptr; + data->server_vio = nullptr; data->content_length = 0; TSContDataSet(contp, data); @@ -111,10 +111,8 @@ transform_create(TSHttpTxn txnp) static void transform_destroy(TSCont contp) { - TransformData *data; - - data = TSContDataGet(contp); - if (data != NULL) { + auto data = static_cast(TSContDataGet(contp)); + if (data != nullptr) { if (data->input_buf) { TSIOBufferDestroy(data->input_buf); } @@ -133,7 +131,7 @@ transform_destroy(TSCont contp) TSfree(data); } else { - TSError("[%s] Unable to get Continuation's Data. TSContDataGet returns NULL", PLUGIN_NAME); + TSError("[%s] Unable to get Continuation's Data. TSContDataGet returns null", PLUGIN_NAME); } TSContDestroy(contp); @@ -218,10 +216,10 @@ transform_read_status(TSCont contp, TransformData *data) data->output_buf = TSIOBufferCreate(); data->output_reader = TSIOBufferReaderAlloc(data->output_buf); - if (data->output_reader != NULL) { + if (data->output_reader != nullptr) { data->server_vio = TSVConnRead(data->server_vc, contp, data->output_buf, sizeof(int)); } else { - TSError("[%s] Error in Allocating a Reader to output buffer. TSIOBufferReaderAlloc returns NULL", PLUGIN_NAME); + TSError("[%s] Error in Allocating a Reader to output buffer. TSIOBufferReaderAlloc returns null", PLUGIN_NAME); } return 0; @@ -233,17 +231,17 @@ transform_read(TSCont contp, TransformData *data) data->state = STATE_READ; TSIOBufferDestroy(data->input_buf); - data->input_buf = NULL; - data->input_reader = NULL; + data->input_buf = nullptr; + data->input_reader = nullptr; data->server_vio = TSVConnRead(data->server_vc, contp, data->output_buf, data->content_length); data->output_vc = TSTransformOutputVConnGet((TSVConn)contp); - if (data->output_vc == NULL) { - TSError("[%s] TSTransformOutputVConnGet returns NULL", PLUGIN_NAME); + if (data->output_vc == nullptr) { + TSError("[%s] TSTransformOutputVConnGet returns null", PLUGIN_NAME); } else { data->output_vio = TSVConnWrite(data->output_vc, contp, data->output_reader, data->content_length); - if (data->output_vio == NULL) { - TSError("[%s] TSVConnWrite returns NULL", PLUGIN_NAME); + if (data->output_vio == nullptr) { + TSError("[%s] TSVConnWrite returns null", PLUGIN_NAME); } } @@ -257,24 +255,24 @@ transform_bypass(TSCont contp, TransformData *data) if (data->server_vc) { TSVConnAbort(data->server_vc, 1); - data->server_vc = NULL; - data->server_vio = NULL; + data->server_vc = nullptr; + data->server_vio = nullptr; } if (data->output_buf) { TSIOBufferDestroy(data->output_buf); - data->output_buf = NULL; - data->output_reader = NULL; + data->output_buf = nullptr; + data->output_reader = nullptr; } TSIOBufferReaderConsume(data->input_reader, sizeof(int)); data->output_vc = TSTransformOutputVConnGet((TSVConn)contp); - if (data->output_vc == NULL) { - TSError("[%s] TSTransformOutputVConnGet returns NULL", PLUGIN_NAME); + if (data->output_vc == nullptr) { + TSError("[%s] TSTransformOutputVConnGet returns null", PLUGIN_NAME); } else { data->output_vio = TSVConnWrite(data->output_vc, contp, data->input_reader, TSIOBufferReaderAvail(data->input_reader)); - if (data->output_vio == NULL) { - TSError("[%s] TSVConnWrite returns NULL", PLUGIN_NAME); + if (data->output_vio == nullptr) { + TSError("[%s] TSVConnWrite returns null", PLUGIN_NAME); } } return 1; @@ -297,8 +295,8 @@ transform_buffer_event(TSCont contp, TransformData *data, TSEvent event ATS_UNUS empty. */ write_vio = TSVConnWriteVIOGet(contp); - /* We also check to see if the write VIO's buffer is non-NULL. A - NULL buffer indicates that the write operation has been + /* We also check to see if the write VIO's buffer is non-null. A + null buffer indicates that the write operation has been shutdown and that the continuation does not want us to send any more WRITE_READY or WRITE_COMPLETE events. For this buffered transformation that means we're done buffering data. */ @@ -357,12 +355,12 @@ transform_connect_event(TSCont contp, TransformData *data, TSEvent event, void * case TS_EVENT_NET_CONNECT: TSDebug(PLUGIN_NAME, "connected"); - data->pending_action = NULL; + data->pending_action = nullptr; data->server_vc = (TSVConn)edata; return transform_write(contp, data); case TS_EVENT_NET_CONNECT_FAILED: TSDebug(PLUGIN_NAME, "connect failed"); - data->pending_action = NULL; + data->pending_action = nullptr; return transform_bypass(contp, data); default: break; @@ -437,26 +435,26 @@ transform_read_event(TSCont contp ATS_UNUSED, TransformData *data, TSEvent event switch (event) { case TS_EVENT_ERROR: TSVConnAbort(data->server_vc, 1); - data->server_vc = NULL; - data->server_vio = NULL; + data->server_vc = nullptr; + data->server_vio = nullptr; TSVConnAbort(data->output_vc, 1); - data->output_vc = NULL; - data->output_vio = NULL; + data->output_vc = nullptr; + data->output_vio = nullptr; break; case TS_EVENT_VCONN_EOS: TSVConnAbort(data->server_vc, 1); - data->server_vc = NULL; - data->server_vio = NULL; + data->server_vc = nullptr; + data->server_vio = nullptr; TSVConnAbort(data->output_vc, 1); - data->output_vc = NULL; - data->output_vio = NULL; + data->output_vc = nullptr; + data->output_vio = nullptr; break; case TS_EVENT_VCONN_READ_COMPLETE: TSVConnClose(data->server_vc); - data->server_vc = NULL; - data->server_vio = NULL; + data->server_vc = nullptr; + data->server_vio = nullptr; TSVIOReenable(data->output_vio); break; @@ -506,7 +504,7 @@ transform_handler(TSCont contp, TSEvent event, void *edata) int val = 0; data = (TransformData *)TSContDataGet(contp); - if (data == NULL) { + if (data == nullptr) { TSError("[%s] Didn't get Continuation's Data, ignoring event", PLUGIN_NAME); return 0; } @@ -643,6 +641,6 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) server_ip = htonl(server_ip); server_port = 7; - cont = TSContCreate(transform_plugin, NULL); + cont = TSContCreate(transform_plugin, nullptr); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, cont); } diff --git a/example/plugins/c-api/session_hooks/session_hooks.c b/example/plugins/c-api/session_hooks/session_hooks.cc similarity index 98% rename from example/plugins/c-api/session_hooks/session_hooks.c rename to example/plugins/c-api/session_hooks/session_hooks.cc index a10c17dd4e9..96aa997d943 100644 --- a/example/plugins/c-api/session_hooks/session_hooks.c +++ b/example/plugins/c-api/session_hooks/session_hooks.cc @@ -97,7 +97,7 @@ TSPluginInit(int argc, const char *argv[]) transaction_count_stat = TSStatCreate("transaction.count", TS_RECORDDATATYPE_INT, TS_STAT_NON_PERSISTENT, TS_STAT_SYNC_SUM); session_count_stat = TSStatCreate("session.count", TS_RECORDDATATYPE_INT, TS_STAT_NON_PERSISTENT, TS_STAT_SYNC_SUM); - contp = TSContCreate(ssn_handler, NULL); + contp = TSContCreate(ssn_handler, nullptr); TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, contp); error: diff --git a/example/plugins/c-api/thread_1/thread_1.c b/example/plugins/c-api/thread_1/thread_1.cc similarity index 98% rename from example/plugins/c-api/thread_1/thread_1.c rename to example/plugins/c-api/thread_1/thread_1.cc index 84e1156845f..d7b73d5d85c 100644 --- a/example/plugins/c-api/thread_1/thread_1.c +++ b/example/plugins/c-api/thread_1/thread_1.cc @@ -36,7 +36,7 @@ reenable_txn(void *data) { TSHttpTxn txnp = (TSHttpTxn)data; TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); - return NULL; + return nullptr; } static int @@ -71,5 +71,5 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) TSError("[%s] Plugin registration failed", PLUGIN_NAME); } - TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(thread_plugin, NULL)); + TSHttpHookAdd(TS_HTTP_OS_DNS_HOOK, TSContCreate(thread_plugin, nullptr)); } diff --git a/example/plugins/c-api/thread_pool/include/Makefile.am b/example/plugins/c-api/thread_pool/include/Makefile.am index b6f43516b1f..f177fec482d 100644 --- a/example/plugins/c-api/thread_pool/include/Makefile.am +++ b/example/plugins/c-api/thread_pool/include/Makefile.am @@ -16,8 +16,8 @@ all: gen -gen: gen.c - $(CC) -o gen gen.c +gen: gen.cc + $(CC) -o gen gen.cc clean-local: rm -f gen gen.o diff --git a/example/plugins/c-api/thread_pool/include/gen.c b/example/plugins/c-api/thread_pool/include/gen.cc similarity index 100% rename from example/plugins/c-api/thread_pool/include/gen.c rename to example/plugins/c-api/thread_pool/include/gen.cc diff --git a/example/plugins/c-api/thread_pool/psi.c b/example/plugins/c-api/thread_pool/psi.cc similarity index 94% rename from example/plugins/c-api/thread_pool/psi.c rename to example/plugins/c-api/thread_pool/psi.cc index 730341c32dd..21a38670f1a 100644 --- a/example/plugins/c-api/thread_pool/psi.c +++ b/example/plugins/c-api/thread_pool/psi.cc @@ -121,12 +121,12 @@ cont_data_alloc() data = (ContData *)TSmalloc(sizeof(ContData)); data->magic = MAGIC_ALIVE; - data->output_vio = NULL; - data->output_buffer = NULL; - data->output_reader = NULL; + data->output_vio = nullptr; + data->output_buffer = nullptr; + data->output_reader = nullptr; - data->psi_buffer = NULL; - data->psi_reader = NULL; + data->psi_buffer = nullptr; + data->psi_reader = nullptr; data->psi_filename[0] = '\0'; data->psi_filename_len = 0; data->psi_success = 0; @@ -157,25 +157,31 @@ cont_data_destroy(ContData *data) TSAssert(data->magic == MAGIC_ALIVE); if (data->output_reader) { TSIOBufferReaderFree(data->output_reader); - data->output_reader = NULL; + data->output_reader = nullptr; } if (data->output_buffer) { TSIOBufferDestroy(data->output_buffer); - data->output_buffer = NULL; + data->output_buffer = nullptr; } if (data->psi_reader) { TSIOBufferReaderFree(data->psi_reader); - data->psi_reader = NULL; + data->psi_reader = nullptr; } if (data->psi_buffer) { TSIOBufferDestroy(data->psi_buffer); - data->psi_buffer = NULL; + data->psi_buffer = nullptr; } data->magic = MAGIC_DEAD; TSfree(data); } } +inline ContData * +contDataGet(TSCont cont) +{ + return static_cast(TSContDataGet(cont)); +} + /*------------------------------------------------------------------------- strsearch_ioreader Looks for string pattern in an iobuffer @@ -204,7 +210,7 @@ strsearch_ioreader(TSIOBufferReader reader, const char *pattern, int *nparse) *nparse = 0; /* Loop thru each block while we've not yet found the pattern */ - while ((block != NULL) && (index < slen)) { + while ((block != nullptr) && (index < slen)) { int64_t blocklen; const char *blockptr = TSIOBufferBlockReadStart(block, reader, &blocklen); const char *ptr; @@ -271,7 +277,7 @@ strextract_ioreader(TSIOBufferReader reader, int offset, const char *end_pattern } /* Now start extraction */ - while ((block != NULL) && (p_idx < plen) && (buf_idx < PSI_FILENAME_MAX_SIZE)) { + while ((block != nullptr) && (p_idx < plen) && (buf_idx < PSI_FILENAME_MAX_SIZE)) { int64_t blocklen; const char *blockptr = TSIOBufferBlockReadStart(block, reader, &blocklen); @@ -346,7 +352,7 @@ parse_data(TSCont contp, TSIOBufferReader input_reader, int avail, int *toconsum int nparse = 0; int status; - data = TSContDataGet(contp); + data = contDataGet(contp); TSAssert(data->magic == MAGIC_ALIVE); if (data->parse_state == PARSE_SEARCH) { @@ -419,10 +425,10 @@ parse_data(TSCont contp, TSIOBufferReader input_reader, int avail, int *toconsum static const char * _basename(const char *filename) { - char *cptr; + const char *cptr; const char *ptr = filename; - while ((cptr = strchr(ptr, '/')) != NULL) { + while ((cptr = strchr(ptr, '/')) != nullptr) { ptr = cptr + 1; } return ptr; @@ -454,7 +460,7 @@ psi_include(TSCont contp, void *edata ATS_UNUSED) /* We manipulate plugin continuation data from a separate thread. Grab mutex to avoid concurrent access */ TSMutexLock(TSContMutexGet(contp)); - data = TSContDataGet(contp); + data = contDataGet(contp); TSAssert(data->magic == MAGIC_ALIVE); if (!data->psi_buffer) { @@ -468,11 +474,11 @@ psi_include(TSCont contp, void *edata ATS_UNUSED) snprintf(inc_file, sizeof(inc_file), "%s/%s", psi_directory, _basename(data->psi_filename)); /* Read the include file and copy content into iobuffer */ - if ((filep = TSfopen(inc_file, "r")) != NULL) { + if ((filep = TSfopen(inc_file, "r")) != nullptr) { TSDebug(PLUGIN_NAME, "Reading include file %s", inc_file); char buf[BUFFER_SIZE]; - while (TSfgets(filep, buf, BUFFER_SIZE) != NULL) { + while (TSfgets(filep, buf, BUFFER_SIZE) != nullptr) { int64_t len, ndone, ntodo; len = strlen(buf); @@ -538,7 +544,7 @@ wake_up_streams(TSCont contp) ContData *data; int ntodo; - data = TSContDataGet(contp); + data = contDataGet(contp); TSAssert(data->magic == MAGIC_ALIVE); input_vio = TSVConnWriteVIOGet(contp); @@ -585,7 +591,7 @@ handle_transform(TSCont contp) /* Get upstream vio */ input_vio = TSVConnWriteVIOGet(contp); - data = TSContDataGet(contp); + data = contDataGet(contp); TSAssert(data->magic == MAGIC_ALIVE); if (!data->output_buffer) { @@ -596,9 +602,9 @@ handle_transform(TSCont contp) data->output_vio = TSVConnWrite(output_conn, contp, data->output_reader, INT64_MAX); } - /* If the input VIO's buffer is NULL, the transformation is over */ + /* If the input VIO's buffer is null, the transformation is over */ if (!TSVIOBufferGet(input_vio)) { - TSDebug(PLUGIN_NAME, "input_vio NULL, terminating transformation"); + TSDebug(PLUGIN_NAME, "input_vio null, terminating transformation"); TSVIONBytesSet(data->output_vio, data->transform_bytes); TSVIOReenable(data->output_vio); return 1; @@ -652,7 +658,7 @@ handle_transform(TSCont contp) data->state = STATE_READ_PSI; /* Create a new job request and add it to the queue */ - new_job = job_create(contp, &psi_include, NULL); + new_job = job_create(contp, &psi_include, nullptr); add_to_queue(&job_queue, new_job); /* Signal to the threads there is a new job */ @@ -685,7 +691,7 @@ dump_psi(TSCont contp) { ContData *data; - data = TSContDataGet(contp); + data = contDataGet(contp); TSAssert(data->magic == MAGIC_ALIVE); /* If script exec succeeded, copy its output to the downstream vconn */ @@ -734,8 +740,8 @@ transform_handler(TSCont contp, TSEvent event, void *edata ATS_UNUSED) /* Handle TryLock result */ if (TSMutexLockTry(TSContMutexGet(contp)) != TS_SUCCESS) { - TSCont c = TSContCreate(trylock_handler, NULL); - TryLockData *d = TSmalloc(sizeof(TryLockData)); + TSCont c = TSContCreate(trylock_handler, nullptr); + auto d = tsapi::malloc(); d->contp = contp; d->event = event; @@ -744,7 +750,7 @@ transform_handler(TSCont contp, TSEvent event, void *edata ATS_UNUSED) return 1; } - data = TSContDataGet(contp); + data = contDataGet(contp); TSAssert(data->magic == MAGIC_ALIVE); state = data->state; @@ -759,7 +765,7 @@ transform_handler(TSCont contp, TSEvent event, void *edata ATS_UNUSED) TSContScheduleOnPool(contp, 10, TS_THREAD_POOL_NET); } else { TSMutexUnlock(TSContMutexGet(contp)); - cont_data_destroy(TSContDataGet(contp)); + cont_data_destroy(contDataGet(contp)); TSContDestroy(contp); return 1; } @@ -821,8 +827,8 @@ transform_handler(TSCont contp, TSEvent event, void *edata ATS_UNUSED) static int trylock_handler(TSCont contp, TSEvent event ATS_UNUSED, void *edata ATS_UNUSED) { - TryLockData *data = TSContDataGet(contp); - transform_handler(data->contp, data->event, NULL); + auto data = static_cast(TSContDataGet(contp)); + transform_handler(data->contp, data->event, nullptr); TSfree(data); TSContDestroy(contp); return 0; @@ -863,8 +869,8 @@ transformable(TSHttpTxn txnp) return 0; } - const char *value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, -1, NULL); - if ((value == NULL) || (strncasecmp(value, "text/", sizeof("text/") - 1) != 0)) { + const char *value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, -1, nullptr); + if ((value == nullptr) || (strncasecmp(value, "text/", sizeof("text/") - 1) != 0)) { TSHandleMLocRelease(bufp, hdr_loc, field_loc); TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc); return 0; @@ -969,7 +975,7 @@ TSPluginInit(int argc ATS_UNUSED, const char *argv[] ATS_UNUSED) retval = TSTextLogObjectCreate("psi", TS_LOG_MODE_ADD_TIMESTAMP, &log); if (retval == TS_ERROR) { TSError("[%s] Failed creating log for psi plugin", PLUGIN_NAME); - log = NULL; + log = nullptr; } /* Create working threads */ diff --git a/example/plugins/c-api/thread_pool/thread.c b/example/plugins/c-api/thread_pool/thread.cc similarity index 83% rename from example/plugins/c-api/thread_pool/thread.c rename to example/plugins/c-api/thread_pool/thread.cc index f5e8b536b96..c53e6dedf8e 100644 --- a/example/plugins/c-api/thread_pool/thread.c +++ b/example/plugins/c-api/thread_pool/thread.cc @@ -39,27 +39,27 @@ static pthread_mutex_t cond_mutex; void init_queue(Queue *q) { - q->head = NULL; /* Pointer on head cell */ - q->tail = NULL; /* Pointer on tail cell */ - q->nb_elem = 0; /* Nb elem in the queue */ + q->head = nullptr; /* Pointer on head cell */ + q->tail = nullptr; /* Pointer on tail cell */ + q->nb_elem = 0; /* Nb elem in the queue */ q->mutex = TSMutexCreate(); } void add_to_queue(Queue *q, void *data) { - if (data != NULL) { + if (data != nullptr) { TSMutexLock(q->mutex); /* Init the new cell */ - Cell *new_cell = TSmalloc(sizeof(Cell)); + auto new_cell = tsapi::malloc(); new_cell->magic = MAGIC_ALIVE; new_cell->ptr_data = data; new_cell->ptr_next = q->tail; - new_cell->ptr_prev = NULL; + new_cell->ptr_prev = nullptr; /* Add this new cell to the queue */ - if (q->tail == NULL) { - TSAssert(q->head == NULL); + if (q->tail == nullptr) { + TSAssert(q->head == nullptr); TSAssert(q->nb_elem == 0); q->tail = new_cell; q->head = new_cell; @@ -80,7 +80,7 @@ add_to_queue(Queue *q, void *data) void * remove_from_queue(Queue *q) { - void *data = NULL; + void *data = nullptr; Cell *remove_cell; TSMutexLock(q->mutex); @@ -90,12 +90,12 @@ remove_from_queue(Queue *q) data = remove_cell->ptr_data; q->head = remove_cell->ptr_prev; - if (q->head == NULL) { + if (q->head == nullptr) { TSAssert(q->nb_elem == 1); - q->tail = NULL; + q->tail = nullptr; } else { TSAssert(q->head->magic == MAGIC_ALIVE); - q->head->ptr_next = NULL; + q->head->ptr_next = nullptr; } remove_cell->magic = MAGIC_DEAD; @@ -120,9 +120,7 @@ get_nbelem_queue(Queue *q) Job * job_create(TSCont contp, ExecFunc func, void *data) { - Job *new_job; - - new_job = TSmalloc(sizeof(Job)); + auto new_job = tsapi::malloc(); new_job->magic = MAGIC_ALIVE; new_job->cont = contp; new_job->func = func; @@ -148,7 +146,7 @@ thread_signal_job() void thread_init() { - pthread_cond_init(&cond, NULL); + pthread_cond_init(&cond, nullptr); } void * @@ -156,10 +154,10 @@ thread_loop(void *arg ATS_UNUSED) { /* Infinite loop */ for (;;) { - /* returns a job or NULL if no jobs to do */ - Job *job_todo = remove_from_queue(&job_queue); + /* returns a job or null if no jobs to do */ + auto job_todo = static_cast(remove_from_queue(&job_queue)); - if (job_todo != NULL) { + if (job_todo != nullptr) { TSAssert(job_todo->magic == MAGIC_ALIVE); /* Simply execute the job function */ @@ -174,5 +172,5 @@ thread_loop(void *arg ATS_UNUSED) pthread_mutex_unlock(&cond_mutex); } } - return NULL; + return nullptr; } diff --git a/example/plugins/c-api/version/version.c b/example/plugins/c-api/version/version.cc similarity index 100% rename from example/plugins/c-api/version/version.c rename to example/plugins/c-api/version/version.cc diff --git a/include/ts/InkAPIPrivateIOCore.h b/include/ts/InkAPIPrivateIOCore.h index 6b088582967..e3833b8a8be 100644 --- a/include/ts/InkAPIPrivateIOCore.h +++ b/include/ts/InkAPIPrivateIOCore.h @@ -32,73 +32,78 @@ #include "P_Net.h" #endif -enum INKContInternalMagic_t { - INKCONT_INTERN_MAGIC_ALIVE = 0x00009631, - INKCONT_INTERN_MAGIC_DEAD = 0xDEAD9631, -}; - -class INKContInternal : public DummyVConnection +namespace tsapi { -public: - INKContInternal(); - INKContInternal(TSEventFunc funcp, TSMutex mutexp); - - void init(TSEventFunc funcp, TSMutex mutexp, void *context = 0); - virtual void destroy(); - - void handle_event_count(int event); - int handle_event(int event, void *edata); - -protected: - virtual void clear(); - virtual void free(); - -public: - void *mdata; - TSEventFunc m_event_func; - int m_event_count; - int m_closed; - int m_deletable; - int m_deleted; - void *m_context; - // INKqa07670: Nokia memory leak bug fix - INKContInternalMagic_t m_free_magic; -}; - -class INKVConnInternal : public INKContInternal +namespace c { -public: - INKVConnInternal(); - INKVConnInternal(TSEventFunc funcp, TSMutex mutexp); - void destroy() override; + enum INKContInternalMagic_t { + INKCONT_INTERN_MAGIC_ALIVE = 0x00009631, + INKCONT_INTERN_MAGIC_DEAD = 0xDEAD9631, + }; + + class INKContInternal : public DummyVConnection + { + public: + INKContInternal(); + INKContInternal(TSEventFunc funcp, TSMutex mutexp); + + void init(TSEventFunc funcp, TSMutex mutexp, void *context = 0); + virtual void destroy(); + + void handle_event_count(int event); + int handle_event(int event, void *edata); + + protected: + virtual void clear(); + virtual void free(); + + public: + void *mdata; + TSEventFunc m_event_func; + int m_event_count; + int m_closed; + int m_deletable; + int m_deleted; + void *m_context; + // INKqa07670: Nokia memory leak bug fix + INKContInternalMagic_t m_free_magic; + }; + + class INKVConnInternal : public INKContInternal + { + public: + INKVConnInternal(); + INKVConnInternal(TSEventFunc funcp, TSMutex mutexp); + + void destroy() override; - VIO *do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf) override; + VIO *do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf) override; - VIO *do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool owner = false) override; + VIO *do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *buf, bool owner = false) override; - void do_io_transform(VConnection *vc); + void do_io_transform(VConnection *vc); - void do_io_close(int lerrno = -1) override; + void do_io_close(int lerrno = -1) override; - void do_io_shutdown(ShutdownHowTo_t howto) override; + void do_io_shutdown(ShutdownHowTo_t howto) override; - void reenable(VIO *vio) override; + void reenable(VIO *vio) override; - void retry(unsigned int delay); + void retry(unsigned int delay); - bool get_data(int id, void *data) override; - bool set_data(int id, void *data) override; + bool get_data(int id, void *data) override; + bool set_data(int id, void *data) override; -protected: - void clear() override; - void free() override; + protected: + void clear() override; + void free() override; -public: - VIO m_read_vio; - VIO m_write_vio; - VConnection *m_output_vc; -}; + public: + VIO m_read_vio; + VIO m_write_vio; + VConnection *m_output_vc; + }; /**************************************************************** * IMPORTANT - READ ME @@ -115,88 +120,85 @@ class INKVConnInternal : public INKContInternal sdk_assert(((INKContInternal *)_c)->mutex); \ SCOPED_MUTEX_LOCK(ml, ((INKContInternal *)_c)->mutex, this_ethread()); -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -TSReturnCode sdk_sanity_check_mutex(TSMutex); -TSReturnCode sdk_sanity_check_hostlookup_structure(TSHostLookupResult); -TSReturnCode sdk_sanity_check_iocore_structure(void *); - -/* ---------------------------------------------------------------------- - * - * Interfaces for Raft project - * - * ---------------------------------------------------------------------- */ - -tsapi TSMutex TSMutexCreateInternal(void); -tsapi int TSMutexCheck(TSMutex mutex); - -/* IOBuffer */ -tsapi int64_t TSIOBufferBlockDataSizeGet(TSIOBufferBlock blockp); -tsapi void TSIOBufferBlockDestroy(TSIOBufferBlock blockp); -typedef void *INKUDPPacket; -typedef void *INKUDPacketQueue; -typedef void *INKUDPConn; -/* ===== UDP Connections ===== */ -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi TSAction INKUDPBind(TSCont contp, unsigned int ip, int port); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi TSAction INKUDPSendTo(TSCont contp, INKUDPConn udp, unsigned int ip, int port, char *buf, int len); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi TSAction INKUDPRecvFrom(TSCont contp, INKUDPConn udp); - -/**************************************************************************** - * Return file descriptor. - * contact: OXYGEN - ****************************************************************************/ -tsapi int INKUDPConnFdGet(INKUDPConn udp); - -/* ===== UDP Packet ===== */ -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi INKUDPPacket INKUDPPacketCreate(); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi TSIOBufferBlock INKUDPPacketBufferBlockGet(INKUDPPacket packet); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi unsigned int INKUDPPacketFromAddressGet(INKUDPPacket packet); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi int INKUDPPacketFromPortGet(INKUDPPacket packet); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi INKUDPConn INKUDPPacketConnGet(INKUDPPacket packet); - -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi void INKUDPPacketDestroy(INKUDPPacket packet); - -/* ===== Packet Queue ===== */ -/**************************************************************************** - * contact: OXYGEN - ****************************************************************************/ -tsapi INKUDPPacket INKUDPPacketGet(INKUDPacketQueue queuep); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ + TSReturnCode sdk_sanity_check_mutex(TSMutex); + TSReturnCode sdk_sanity_check_hostlookup_structure(TSHostLookupResult); + TSReturnCode sdk_sanity_check_iocore_structure(void *); + + /* ---------------------------------------------------------------------- + * + * Interfaces for Raft project + * + * ---------------------------------------------------------------------- */ + + TSMutex TSMutexCreateInternal(void); + int TSMutexCheck(TSMutex mutex); + + /* IOBuffer */ + int64_t TSIOBufferBlockDataSizeGet(TSIOBufferBlock blockp); + void TSIOBufferBlockDestroy(TSIOBufferBlock blockp); + using INKUDPPacket = void *; + using INKUDPacketQueue = void *; + using INKUDPConn = void *; + /* ===== UDP Connections ===== */ + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + TSAction INKUDPBind(TSCont contp, unsigned int ip, int port); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + TSAction INKUDPSendTo(TSCont contp, INKUDPConn udp, unsigned int ip, int port, char *buf, int len); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + TSAction INKUDPRecvFrom(TSCont contp, INKUDPConn udp); + + /**************************************************************************** + * Return file descriptor. + * contact: OXYGEN + ****************************************************************************/ + int INKUDPConnFdGet(INKUDPConn udp); + + /* ===== UDP Packet ===== */ + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + INKUDPPacket INKUDPPacketCreate(); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + TSIOBufferBlock INKUDPPacketBufferBlockGet(INKUDPPacket packet); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + unsigned int INKUDPPacketFromAddressGet(INKUDPPacket packet); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + int INKUDPPacketFromPortGet(INKUDPPacket packet); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + INKUDPConn INKUDPPacketConnGet(INKUDPPacket packet); + + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + void INKUDPPacketDestroy(INKUDPPacket packet); + + /* ===== Packet Queue ===== */ + /**************************************************************************** + * contact: OXYGEN + ****************************************************************************/ + INKUDPPacket INKUDPPacketGet(INKUDPacketQueue queuep); + +} // end namespace c +} // end namespace tsapi + +using namespace ::tsapi::c; diff --git a/include/ts/apidefs.h.in b/include/ts/apidefs.h.in index 9f135b34761..1108da0c9d4 100644 --- a/include/ts/apidefs.h.in +++ b/include/ts/apidefs.h.in @@ -42,15 +42,10 @@ * */ -#include -#include // NOLINT(modernize-deprecated-headers) +#include #include #include -#ifndef tsapi -#define tsapi -#endif - /** Apply printf format string compile-time argument checking to a function. * * @@ -121,23 +116,38 @@ #endif #endif -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ +namespace tsapi +{ +namespace c +{ -/* Version info - */ -/* clang-format off */ -#define TS_VERSION_STRING "@TS_VERSION_STRING@" + /* Version info + * + * Version numbers need to be preprocessor symbols for conditional compilation. + */ + /* clang-format off */ +char const TS_VERSION_STRING[] = "@TS_VERSION_STRING@"; #define TS_VERSION_NUMBER @TS_VERSION_NUMBER@ #define TS_VERSION_MAJOR @TS_VERSION_MAJOR@ #define TS_VERSION_MINOR @TS_VERSION_MINOR@ #define TS_VERSION_MICRO @TS_VERSION_MICRO@ -/* clang-format on */ - -#define TS_HTTP_VERSION(a, b) ((((a)&0xFFFF) << 16) | ((b)&0xFFFF)) -#define TS_HTTP_MINOR(v) ((v)&0xFFFF) -#define TS_HTTP_MAJOR(v) (((v) >> 16) & 0xFFFF) + /* clang-format on */ + + constexpr long + TS_HTTP_VERSION(int a, int b) + { + return ((long(a) & 0xFFFF) << 16) | (b & 0xFFFF); + } + constexpr int + TS_HTTP_MINOR(long v) + { + return int(v & 0xFFFF); + } + constexpr int + TS_HTTP_MAJOR(long v) + { + return int((v >> 16) & 0xFFFF); + } #ifndef TS_RES_MEM_PATH #define __TS_RES_PATH(x) #x @@ -146,332 +156,328 @@ extern "C" { #define TS_RES_MEM_PATH TS_RES_PATH("memory/") #endif -#ifndef TS_DEPRECATED -#define TS_DEPRECATED __attribute__((deprecated)) -#endif - -/** - The following struct is used by TSPluginRegister(). It stores - registration information about the plugin. - - */ -typedef struct { - const char *plugin_name; - const char *vendor_name; - const char *support_email; -} TSPluginRegistrationInfo; - -typedef struct { - const char *tag; ///< Message tag (null terminated). - void const *data; ///< Message data (payload) - size_t data_size; ///< Amount of message data. -} TSPluginMsg; - -/** - This set of enums are possible values returned by - TSHttpHdrParseReq() and TSHttpHdrParseResp(). - - */ -typedef enum { - TS_PARSE_ERROR = -1, - TS_PARSE_DONE = 0, - TS_PARSE_CONT = 1, -} TSParseResult; - -/** - This set of enums represents the possible HTTP types that - can be assigned to an HTTP header. When a header is created - with TSHttpHdrCreate(), it is automatically assigned a type of - TS_HTTP_TYPE_UNKNOWN. You can modify the HTTP type ONCE after it - the header is created, using TSHttpHdrTypeSet(). After setting the - HTTP type once, you cannot set it again. Use TSHttpHdrTypeGet() - to obtain the TSHttpType of an HTTP header. + /** + The following struct is used by TSPluginRegister(). It stores + registration information about the plugin. - */ -typedef enum { - TS_HTTP_TYPE_UNKNOWN, - TS_HTTP_TYPE_REQUEST, - TS_HTTP_TYPE_RESPONSE, -} TSHttpType; - -/** - This set of enums represents possible return values from - TSHttpHdrStatusGet(), which retrieves the status code from an - HTTP response header (TSHttpHdrStatusGet() retrieves status codes - only from headers of type TS_HTTP_TYPE_RESPONSE). You can also set - the TSHttpStatus of a response header using TSHttpHdrStatusSet(). + */ + struct TSPluginRegistrationInfo { + const char *plugin_name; + const char *vendor_name; + const char *support_email; + }; + + struct TSPluginMsg { + const char *tag; ///< Message tag (null terminated). + void const *data; ///< Message data (payload) + size_t data_size; ///< Amount of message data. + }; + + /** + This set of enums are possible values returned by + TSHttpHdrParseReq() and TSHttpHdrParseResp(). - */ -typedef enum { - TS_HTTP_STATUS_NONE = 0, - TS_HTTP_STATUS_CONTINUE = 100, - TS_HTTP_STATUS_SWITCHING_PROTOCOL = 101, - TS_HTTP_STATUS_EARLY_HINTS = 103, - TS_HTTP_STATUS_OK = 200, - TS_HTTP_STATUS_CREATED = 201, - TS_HTTP_STATUS_ACCEPTED = 202, - TS_HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203, - TS_HTTP_STATUS_NO_CONTENT = 204, - TS_HTTP_STATUS_RESET_CONTENT = 205, - TS_HTTP_STATUS_PARTIAL_CONTENT = 206, - TS_HTTP_STATUS_MULTI_STATUS = 207, - TS_HTTP_STATUS_ALREADY_REPORTED = 208, - TS_HTTP_STATUS_IM_USED = 211, - TS_HTTP_STATUS_MULTIPLE_CHOICES = 300, - TS_HTTP_STATUS_MOVED_PERMANENTLY = 301, - TS_HTTP_STATUS_MOVED_TEMPORARILY = 302, - TS_HTTP_STATUS_SEE_OTHER = 303, - TS_HTTP_STATUS_NOT_MODIFIED = 304, - TS_HTTP_STATUS_USE_PROXY = 305, - TS_HTTP_STATUS_TEMPORARY_REDIRECT = 307, - TS_HTTP_STATUS_PERMANENT_REDIRECT = 308, - TS_HTTP_STATUS_BAD_REQUEST = 400, - TS_HTTP_STATUS_UNAUTHORIZED = 401, - TS_HTTP_STATUS_PAYMENT_REQUIRED = 402, - TS_HTTP_STATUS_FORBIDDEN = 403, - TS_HTTP_STATUS_NOT_FOUND = 404, - TS_HTTP_STATUS_METHOD_NOT_ALLOWED = 405, - TS_HTTP_STATUS_NOT_ACCEPTABLE = 406, - TS_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407, - TS_HTTP_STATUS_REQUEST_TIMEOUT = 408, - TS_HTTP_STATUS_CONFLICT = 409, - TS_HTTP_STATUS_GONE = 410, - TS_HTTP_STATUS_LENGTH_REQUIRED = 411, - TS_HTTP_STATUS_PRECONDITION_FAILED = 412, - TS_HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE = 413, - TS_HTTP_STATUS_REQUEST_URI_TOO_LONG = 414, - TS_HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415, - TS_HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416, - TS_HTTP_STATUS_EXPECTATION_FAILED = 417, - TS_HTTP_STATUS_UNPROCESSABLE_ENTITY = 422, - TS_HTTP_STATUS_LOCKED = 423, - TS_HTTP_STATUS_FAILED_DEPENDENCY = 424, - TS_HTTP_STATUS_UPGRADE_REQUIRED = 426, - TS_HTTP_STATUS_PRECONDITION_REQUIRED = 428, - TS_HTTP_STATUS_TOO_MANY_REQUESTS = 429, - TS_HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431, - TS_HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451, - TS_HTTP_STATUS_INTERNAL_SERVER_ERROR = 500, - TS_HTTP_STATUS_NOT_IMPLEMENTED = 501, - TS_HTTP_STATUS_BAD_GATEWAY = 502, - TS_HTTP_STATUS_SERVICE_UNAVAILABLE = 503, - TS_HTTP_STATUS_GATEWAY_TIMEOUT = 504, - TS_HTTP_STATUS_HTTPVER_NOT_SUPPORTED = 505, - TS_HTTP_STATUS_VARIANT_ALSO_NEGOTIATES = 506, - TS_HTTP_STATUS_INSUFFICIENT_STORAGE = 507, - TS_HTTP_STATUS_LOOP_DETECTED = 508, - TS_HTTP_STATUS_NOT_EXTENDED = 510, - TS_HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511 -} TSHttpStatus; + */ + enum TSParseResult { + TS_PARSE_ERROR = -1, + TS_PARSE_DONE = 0, + TS_PARSE_CONT = 1, + }; + + /** + This set of enums represents the possible HTTP types that + can be assigned to an HTTP header. When a header is created + with TSHttpHdrCreate(), it is automatically assigned a type of + TS_HTTP_TYPE_UNKNOWN. You can modify the HTTP type ONCE after it + the header is created, using TSHttpHdrTypeSet(). After setting the + HTTP type once, you cannot set it again. Use TSHttpHdrTypeGet() + to obtain the TSHttpType of an HTTP header. -/** - TSEvents are sent to continuations when they are called back. - The TSEvent provides the continuation's handler function with - information about the callback. Based on the event it receives, - the handler function can decide what to do. - */ -typedef enum { - TS_EVENT_NONE = 0, - TS_EVENT_IMMEDIATE = 1, - TS_EVENT_TIMEOUT = 2, - TS_EVENT_ERROR = 3, - TS_EVENT_CONTINUE = 4, - - TS_EVENT_VCONN_READ_READY = 100, - TS_EVENT_VCONN_WRITE_READY = 101, - TS_EVENT_VCONN_READ_COMPLETE = 102, - TS_EVENT_VCONN_WRITE_COMPLETE = 103, - TS_EVENT_VCONN_EOS = 104, - TS_EVENT_VCONN_INACTIVITY_TIMEOUT = 105, - TS_EVENT_VCONN_ACTIVE_TIMEOUT = 106, - TS_EVENT_VCONN_START = 107, - TS_EVENT_VCONN_CLOSE = 108, - TS_EVENT_VCONN_OUTBOUND_START = 109, - TS_EVENT_VCONN_OUTBOUND_CLOSE = 110, - TS_EVENT_VCONN_PRE_ACCEPT = TS_EVENT_VCONN_START, // Deprecated but still compatible - - TS_EVENT_NET_CONNECT = 200, - TS_EVENT_NET_CONNECT_FAILED = 201, - TS_EVENT_NET_ACCEPT = 202, - TS_EVENT_NET_ACCEPT_FAILED = 204, - - TS_EVENT_INTERNAL_206 = 206, - TS_EVENT_INTERNAL_207 = 207, - TS_EVENT_INTERNAL_208 = 208, - TS_EVENT_INTERNAL_209 = 209, - TS_EVENT_INTERNAL_210 = 210, - TS_EVENT_INTERNAL_211 = 211, - TS_EVENT_INTERNAL_212 = 212, - - TS_EVENT_HOST_LOOKUP = 500, - - TS_EVENT_CACHE_OPEN_READ = 1102, - TS_EVENT_CACHE_OPEN_READ_FAILED = 1103, - TS_EVENT_CACHE_OPEN_WRITE = 1108, - TS_EVENT_CACHE_OPEN_WRITE_FAILED = 1109, - TS_EVENT_CACHE_REMOVE = 1112, - TS_EVENT_CACHE_REMOVE_FAILED = 1113, - TS_EVENT_CACHE_SCAN = 1120, - TS_EVENT_CACHE_SCAN_FAILED = 1121, - TS_EVENT_CACHE_SCAN_OBJECT = 1122, - TS_EVENT_CACHE_SCAN_OPERATION_BLOCKED = 1123, - TS_EVENT_CACHE_SCAN_OPERATION_FAILED = 1124, - TS_EVENT_CACHE_SCAN_DONE = 1125, - TS_EVENT_CACHE_LOOKUP = 1126, - TS_EVENT_CACHE_READ = 1127, - TS_EVENT_CACHE_DELETE = 1128, - TS_EVENT_CACHE_WRITE = 1129, - TS_EVENT_CACHE_WRITE_HEADER = 1130, - TS_EVENT_CACHE_CLOSE = 1131, - TS_EVENT_CACHE_LOOKUP_READY = 1132, - TS_EVENT_CACHE_LOOKUP_COMPLETE = 1133, - TS_EVENT_CACHE_READ_READY = 1134, - TS_EVENT_CACHE_READ_COMPLETE = 1135, - - TS_EVENT_INTERNAL_1200 = 1200, - - TS_EVENT_SSL_SESSION_GET = 2000, - TS_EVENT_SSL_SESSION_NEW = 2001, - TS_EVENT_SSL_SESSION_REMOVE = 2002, - - TS_EVENT_AIO_DONE = 3900, - - TS_EVENT_HTTP_CONTINUE = 60000, - TS_EVENT_HTTP_ERROR = 60001, - TS_EVENT_HTTP_READ_REQUEST_HDR = 60002, - TS_EVENT_HTTP_OS_DNS = 60003, - TS_EVENT_HTTP_SEND_REQUEST_HDR = 60004, - TS_EVENT_HTTP_READ_CACHE_HDR = 60005, - TS_EVENT_HTTP_READ_RESPONSE_HDR = 60006, - TS_EVENT_HTTP_SEND_RESPONSE_HDR = 60007, - TS_EVENT_HTTP_REQUEST_TRANSFORM = 60008, - TS_EVENT_HTTP_RESPONSE_TRANSFORM = 60009, - TS_EVENT_HTTP_SELECT_ALT = 60010, - TS_EVENT_HTTP_TXN_START = 60011, - TS_EVENT_HTTP_TXN_CLOSE = 60012, - TS_EVENT_HTTP_SSN_START = 60013, - TS_EVENT_HTTP_SSN_CLOSE = 60014, - TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE = 60015, - TS_EVENT_HTTP_PRE_REMAP = 60016, - TS_EVENT_HTTP_POST_REMAP = 60017, - TS_EVENT_HTTP_REQUEST_BUFFER_READ_COMPLETE = 60018, - TS_EVENT_HTTP_RESPONSE_CLIENT = 60019, - TS_EVENT_HTTP_REQUEST_CLIENT = 60020, - - TS_EVENT_LIFECYCLE_PORTS_INITIALIZED = 60100, - TS_EVENT_LIFECYCLE_PORTS_READY = 60101, - TS_EVENT_LIFECYCLE_CACHE_READY = 60102, - TS_EVENT_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED = 60103, - TS_EVENT_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED = 60104, - TS_EVENT_LIFECYCLE_MSG = 60105, - TS_EVENT_LIFECYCLE_TASK_THREADS_READY = 60106, - TS_EVENT_LIFECYCLE_SHUTDOWN = 60107, - - TS_EVENT_INTERNAL_60200 = 60200, - TS_EVENT_INTERNAL_60201 = 60201, - TS_EVENT_INTERNAL_60202 = 60202, - TS_EVENT_SSL_CERT = 60203, - TS_EVENT_SSL_SERVERNAME = 60204, - TS_EVENT_SSL_VERIFY_SERVER = 60205, - TS_EVENT_SSL_VERIFY_CLIENT = 60206, - TS_EVENT_SSL_CLIENT_HELLO = 60207, - TS_EVENT_SSL_SECRET = 60208, - - TS_EVENT_MGMT_UPDATE = 60300 -} TSEvent; -#define TS_EVENT_HTTP_READ_REQUEST_PRE_REMAP TS_EVENT_HTTP_PRE_REMAP /* backwards compat */ + */ + enum TSHttpType { + TS_HTTP_TYPE_UNKNOWN, + TS_HTTP_TYPE_REQUEST, + TS_HTTP_TYPE_RESPONSE, + }; + + /** + This set of enums represents possible return values from + TSHttpHdrStatusGet(), which retrieves the status code from an + HTTP response header (TSHttpHdrStatusGet() retrieves status codes + only from headers of type TS_HTTP_TYPE_RESPONSE). You can also set + the TSHttpStatus of a response header using TSHttpHdrStatusSet(). -/** - This set of enums represents the possible hooks where you can - set up continuation callbacks. The functions used to register a - continuation for a particular hook are: - - TSHttpHookAdd: adds a global hook. You can globally add - any hook except for - - TS_HTTP_REQUEST_TRANSFORM_HOOK - - TS_HTTP_RESPONSE_TRANSFORM_HOOK - - TS_HTTP_RESPONSE_CLIENT_HOOK - - TS_HTTP_REQUEST_CLIENT_HOOK - - The following hooks can ONLY be added globally: - - TS_HTTP_SELECT_ALT_HOOK - - TS_HTTP_SSN_START_HOOK - - TSHttpSsnHookAdd: adds a transaction hook to each transaction - within a session. You can only use transaction hooks with this call: - - TS_HTTP_READ_REQUEST_HDR_HOOK - - TS_HTTP_OS_DNS_HOOK - - TS_HTTP_SEND_REQUEST_HDR_HOOK - - TS_HTTP_READ_CACHE_HDR_HOOK - - TS_HTTP_READ_RESPONSE_HDR_HOOK - - TS_HTTP_SEND_RESPONSE_HDR_HOOK - - TS_HTTP_REQUEST_TRANSFORM_HOOK - - TS_HTTP_RESPONSE_TRANSFORM_HOOK - - TS_HTTP_RESPONSE_CLIENT_HOOK - - TS_HTTP_REQUEST_CLIENT_HOOK - - TS_HTTP_TXN_START_HOOK - - TS_HTTP_TXN_CLOSE_HOOK - - TS_HTTP_SSN_CLOSE_HOOK - - TSHttpTxnHookAdd: adds a callback at a specific point within - an HTTP transaction. The following hooks can be used with this - function: - - TS_HTTP_READ_REQUEST_HDR_HOOK - - TS_HTTP_OS_DNS_HOOK - - TS_HTTP_SEND_REQUEST_HDR_HOOK - - TS_HTTP_READ_CACHE_HDR_HOOK - - TS_HTTP_READ_RESPONSE_HDR_HOOK - - TS_HTTP_SEND_RESPONSE_HDR_HOOK - - TS_HTTP_REQUEST_TRANSFORM_HOOK - - TS_HTTP_RESPONSE_TRANSFORM_HOOK - - TS_HTTP_TXN_CLOSE_HOOK - - The two transform hooks can ONLY be added as transaction hooks. - - TS_VCONN_START_HOOK - called just after the connection is created, - before other activity such as I/O or TLS handshakes No handshake - data has been read or sent (from the proxy) at this point - - TS_HTTP_LAST_HOOK _must_ be the last element. Only right place - to insert a new element is just before TS_HTTP_LAST_HOOK. - - - @note The TS_HTTP hooks below have to be in the same order as their - corresponding TS_EVENT counterparts. We use this in calculating the - corresponding event from a hook ID by summing - TS_EVENT_HTTP_READ_REQUEST_HDR with the hook ID (see the invoke call in - HttpSM::state_api_callout). For example, the following expression must be - true: - - TS_EVENT_HTTP_TXN_CLOSE == TS_EVENT_HTTP_READ_REQUEST_HDR + TS_HTTP_TXN_CLOSE_HOOK + */ + enum TSHttpStatus { + TS_HTTP_STATUS_NONE = 0, + TS_HTTP_STATUS_CONTINUE = 100, + TS_HTTP_STATUS_SWITCHING_PROTOCOL = 101, + TS_HTTP_STATUS_EARLY_HINTS = 103, + TS_HTTP_STATUS_OK = 200, + TS_HTTP_STATUS_CREATED = 201, + TS_HTTP_STATUS_ACCEPTED = 202, + TS_HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203, + TS_HTTP_STATUS_NO_CONTENT = 204, + TS_HTTP_STATUS_RESET_CONTENT = 205, + TS_HTTP_STATUS_PARTIAL_CONTENT = 206, + TS_HTTP_STATUS_MULTI_STATUS = 207, + TS_HTTP_STATUS_ALREADY_REPORTED = 208, + TS_HTTP_STATUS_IM_USED = 211, + TS_HTTP_STATUS_MULTIPLE_CHOICES = 300, + TS_HTTP_STATUS_MOVED_PERMANENTLY = 301, + TS_HTTP_STATUS_MOVED_TEMPORARILY = 302, + TS_HTTP_STATUS_SEE_OTHER = 303, + TS_HTTP_STATUS_NOT_MODIFIED = 304, + TS_HTTP_STATUS_USE_PROXY = 305, + TS_HTTP_STATUS_TEMPORARY_REDIRECT = 307, + TS_HTTP_STATUS_PERMANENT_REDIRECT = 308, + TS_HTTP_STATUS_BAD_REQUEST = 400, + TS_HTTP_STATUS_UNAUTHORIZED = 401, + TS_HTTP_STATUS_PAYMENT_REQUIRED = 402, + TS_HTTP_STATUS_FORBIDDEN = 403, + TS_HTTP_STATUS_NOT_FOUND = 404, + TS_HTTP_STATUS_METHOD_NOT_ALLOWED = 405, + TS_HTTP_STATUS_NOT_ACCEPTABLE = 406, + TS_HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407, + TS_HTTP_STATUS_REQUEST_TIMEOUT = 408, + TS_HTTP_STATUS_CONFLICT = 409, + TS_HTTP_STATUS_GONE = 410, + TS_HTTP_STATUS_LENGTH_REQUIRED = 411, + TS_HTTP_STATUS_PRECONDITION_FAILED = 412, + TS_HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE = 413, + TS_HTTP_STATUS_REQUEST_URI_TOO_LONG = 414, + TS_HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415, + TS_HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416, + TS_HTTP_STATUS_EXPECTATION_FAILED = 417, + TS_HTTP_STATUS_UNPROCESSABLE_ENTITY = 422, + TS_HTTP_STATUS_LOCKED = 423, + TS_HTTP_STATUS_FAILED_DEPENDENCY = 424, + TS_HTTP_STATUS_UPGRADE_REQUIRED = 426, + TS_HTTP_STATUS_PRECONDITION_REQUIRED = 428, + TS_HTTP_STATUS_TOO_MANY_REQUESTS = 429, + TS_HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431, + TS_HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451, + TS_HTTP_STATUS_INTERNAL_SERVER_ERROR = 500, + TS_HTTP_STATUS_NOT_IMPLEMENTED = 501, + TS_HTTP_STATUS_BAD_GATEWAY = 502, + TS_HTTP_STATUS_SERVICE_UNAVAILABLE = 503, + TS_HTTP_STATUS_GATEWAY_TIMEOUT = 504, + TS_HTTP_STATUS_HTTPVER_NOT_SUPPORTED = 505, + TS_HTTP_STATUS_VARIANT_ALSO_NEGOTIATES = 506, + TS_HTTP_STATUS_INSUFFICIENT_STORAGE = 507, + TS_HTTP_STATUS_LOOP_DETECTED = 508, + TS_HTTP_STATUS_NOT_EXTENDED = 510, + TS_HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511 + }; + + /** + TSEvents are sent to continuations when they are called back. + The TSEvent provides the continuation's handler function with + information about the callback. Based on the event it receives, + the handler function can decide what to do. + */ + enum TSEvent { + TS_EVENT_NONE = 0, + TS_EVENT_IMMEDIATE = 1, + TS_EVENT_TIMEOUT = 2, + TS_EVENT_ERROR = 3, + TS_EVENT_CONTINUE = 4, + + TS_EVENT_VCONN_READ_READY = 100, + TS_EVENT_VCONN_WRITE_READY = 101, + TS_EVENT_VCONN_READ_COMPLETE = 102, + TS_EVENT_VCONN_WRITE_COMPLETE = 103, + TS_EVENT_VCONN_EOS = 104, + TS_EVENT_VCONN_INACTIVITY_TIMEOUT = 105, + TS_EVENT_VCONN_ACTIVE_TIMEOUT = 106, + TS_EVENT_VCONN_START = 107, + TS_EVENT_VCONN_CLOSE = 108, + TS_EVENT_VCONN_OUTBOUND_START = 109, + TS_EVENT_VCONN_OUTBOUND_CLOSE = 110, + TS_EVENT_VCONN_PRE_ACCEPT = TS_EVENT_VCONN_START, // Deprecated but still compatible + + TS_EVENT_NET_CONNECT = 200, + TS_EVENT_NET_CONNECT_FAILED = 201, + TS_EVENT_NET_ACCEPT = 202, + TS_EVENT_NET_ACCEPT_FAILED = 204, + + TS_EVENT_INTERNAL_206 = 206, + TS_EVENT_INTERNAL_207 = 207, + TS_EVENT_INTERNAL_208 = 208, + TS_EVENT_INTERNAL_209 = 209, + TS_EVENT_INTERNAL_210 = 210, + TS_EVENT_INTERNAL_211 = 211, + TS_EVENT_INTERNAL_212 = 212, + + TS_EVENT_HOST_LOOKUP = 500, + + TS_EVENT_CACHE_OPEN_READ = 1102, + TS_EVENT_CACHE_OPEN_READ_FAILED = 1103, + TS_EVENT_CACHE_OPEN_WRITE = 1108, + TS_EVENT_CACHE_OPEN_WRITE_FAILED = 1109, + TS_EVENT_CACHE_REMOVE = 1112, + TS_EVENT_CACHE_REMOVE_FAILED = 1113, + TS_EVENT_CACHE_SCAN = 1120, + TS_EVENT_CACHE_SCAN_FAILED = 1121, + TS_EVENT_CACHE_SCAN_OBJECT = 1122, + TS_EVENT_CACHE_SCAN_OPERATION_BLOCKED = 1123, + TS_EVENT_CACHE_SCAN_OPERATION_FAILED = 1124, + TS_EVENT_CACHE_SCAN_DONE = 1125, + TS_EVENT_CACHE_LOOKUP = 1126, + TS_EVENT_CACHE_READ = 1127, + TS_EVENT_CACHE_DELETE = 1128, + TS_EVENT_CACHE_WRITE = 1129, + TS_EVENT_CACHE_WRITE_HEADER = 1130, + TS_EVENT_CACHE_CLOSE = 1131, + TS_EVENT_CACHE_LOOKUP_READY = 1132, + TS_EVENT_CACHE_LOOKUP_COMPLETE = 1133, + TS_EVENT_CACHE_READ_READY = 1134, + TS_EVENT_CACHE_READ_COMPLETE = 1135, + + TS_EVENT_INTERNAL_1200 = 1200, + + TS_EVENT_SSL_SESSION_GET = 2000, + TS_EVENT_SSL_SESSION_NEW = 2001, + TS_EVENT_SSL_SESSION_REMOVE = 2002, + + TS_EVENT_AIO_DONE = 3900, + + TS_EVENT_HTTP_CONTINUE = 60000, + TS_EVENT_HTTP_ERROR = 60001, + TS_EVENT_HTTP_READ_REQUEST_HDR = 60002, + TS_EVENT_HTTP_OS_DNS = 60003, + TS_EVENT_HTTP_SEND_REQUEST_HDR = 60004, + TS_EVENT_HTTP_READ_CACHE_HDR = 60005, + TS_EVENT_HTTP_READ_RESPONSE_HDR = 60006, + TS_EVENT_HTTP_SEND_RESPONSE_HDR = 60007, + TS_EVENT_HTTP_REQUEST_TRANSFORM = 60008, + TS_EVENT_HTTP_RESPONSE_TRANSFORM = 60009, + TS_EVENT_HTTP_SELECT_ALT = 60010, + TS_EVENT_HTTP_TXN_START = 60011, + TS_EVENT_HTTP_TXN_CLOSE = 60012, + TS_EVENT_HTTP_SSN_START = 60013, + TS_EVENT_HTTP_SSN_CLOSE = 60014, + TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE = 60015, + TS_EVENT_HTTP_PRE_REMAP = 60016, + TS_EVENT_HTTP_POST_REMAP = 60017, + TS_EVENT_HTTP_REQUEST_BUFFER_READ_COMPLETE = 60018, + TS_EVENT_HTTP_RESPONSE_CLIENT = 60019, + TS_EVENT_HTTP_REQUEST_CLIENT = 60020, + + TS_EVENT_LIFECYCLE_PORTS_INITIALIZED = 60100, + TS_EVENT_LIFECYCLE_PORTS_READY = 60101, + TS_EVENT_LIFECYCLE_CACHE_READY = 60102, + TS_EVENT_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED = 60103, + TS_EVENT_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED = 60104, + TS_EVENT_LIFECYCLE_MSG = 60105, + TS_EVENT_LIFECYCLE_TASK_THREADS_READY = 60106, + TS_EVENT_LIFECYCLE_SHUTDOWN = 60107, + + TS_EVENT_INTERNAL_60200 = 60200, + TS_EVENT_INTERNAL_60201 = 60201, + TS_EVENT_INTERNAL_60202 = 60202, + TS_EVENT_SSL_CERT = 60203, + TS_EVENT_SSL_SERVERNAME = 60204, + TS_EVENT_SSL_VERIFY_SERVER = 60205, + TS_EVENT_SSL_VERIFY_CLIENT = 60206, + TS_EVENT_SSL_CLIENT_HELLO = 60207, + TS_EVENT_SSL_SECRET = 60208, + + TS_EVENT_MGMT_UPDATE = 60300 + }; + TSEvent const TS_EVENT_HTTP_READ_REQUEST_PRE_REMAP = TS_EVENT_HTTP_PRE_REMAP; /* backwards compat */ + + /** + This set of enums represents the possible hooks where you can + set up continuation callbacks. The functions used to register a + continuation for a particular hook are: + + TSHttpHookAdd: adds a global hook. You can globally add + any hook except for + - TS_HTTP_REQUEST_TRANSFORM_HOOK + - TS_HTTP_RESPONSE_TRANSFORM_HOOK + - TS_HTTP_RESPONSE_CLIENT_HOOK + - TS_HTTP_REQUEST_CLIENT_HOOK + + The following hooks can ONLY be added globally: + - TS_HTTP_SELECT_ALT_HOOK + - TS_HTTP_SSN_START_HOOK + + TSHttpSsnHookAdd: adds a transaction hook to each transaction + within a session. You can only use transaction hooks with this call: + - TS_HTTP_READ_REQUEST_HDR_HOOK + - TS_HTTP_OS_DNS_HOOK + - TS_HTTP_SEND_REQUEST_HDR_HOOK + - TS_HTTP_READ_CACHE_HDR_HOOK + - TS_HTTP_READ_RESPONSE_HDR_HOOK + - TS_HTTP_SEND_RESPONSE_HDR_HOOK + - TS_HTTP_REQUEST_TRANSFORM_HOOK + - TS_HTTP_RESPONSE_TRANSFORM_HOOK + - TS_HTTP_RESPONSE_CLIENT_HOOK + - TS_HTTP_REQUEST_CLIENT_HOOK + - TS_HTTP_TXN_START_HOOK + - TS_HTTP_TXN_CLOSE_HOOK + - TS_HTTP_SSN_CLOSE_HOOK + + TSHttpTxnHookAdd: adds a callback at a specific point within + an HTTP transaction. The following hooks can be used with this + function: + - TS_HTTP_READ_REQUEST_HDR_HOOK + - TS_HTTP_OS_DNS_HOOK + - TS_HTTP_SEND_REQUEST_HDR_HOOK + - TS_HTTP_READ_CACHE_HDR_HOOK + - TS_HTTP_READ_RESPONSE_HDR_HOOK + - TS_HTTP_SEND_RESPONSE_HDR_HOOK + - TS_HTTP_REQUEST_TRANSFORM_HOOK + - TS_HTTP_RESPONSE_TRANSFORM_HOOK + - TS_HTTP_TXN_CLOSE_HOOK + + The two transform hooks can ONLY be added as transaction hooks. + + TS_VCONN_START_HOOK - called just after the connection is created, + before other activity such as I/O or TLS handshakes No handshake + data has been read or sent (from the proxy) at this point + + TS_HTTP_LAST_HOOK _must_ be the last element. Only right place + to insert a new element is just before TS_HTTP_LAST_HOOK. + + + @note The TS_HTTP hooks below have to be in the same order as their + corresponding TS_EVENT counterparts. We use this in calculating the + corresponding event from a hook ID by summing + TS_EVENT_HTTP_READ_REQUEST_HDR with the hook ID (see the invoke call in + HttpSM::state_api_callout). For example, the following expression must be + true: + + TS_EVENT_HTTP_TXN_CLOSE == TS_EVENT_HTTP_READ_REQUEST_HDR + TS_HTTP_TXN_CLOSE_HOOK - */ -typedef enum { + */ + enum TSHttpHookID { /* The following macro helps maintain the relationship between the TS_HTTP hooks and their TS_EVENT_HTTP counterparts as described in the above doxygen comment. */ #define DERIVE_HOOK_VALUE_FROM_EVENT(COMMON) TS_HTTP_##COMMON##_HOOK = TS_EVENT_HTTP_##COMMON - TS_EVENT_HTTP_READ_REQUEST_HDR - DERIVE_HOOK_VALUE_FROM_EVENT(READ_REQUEST_HDR), // TS_HTTP_READ_REQUEST_HDR_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(OS_DNS), // TS_HTTP_OS_DNS_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(SEND_REQUEST_HDR), // TS_HTTP_SEND_REQUEST_HDR_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(READ_CACHE_HDR), // TS_HTTP_READ_CACHE_HDR_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(READ_RESPONSE_HDR), // TS_HTTP_READ_RESPONSE_HDR_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(SEND_RESPONSE_HDR), // TS_HTTP_SEND_RESPONSE_HDR_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(REQUEST_TRANSFORM), // TS_HTTP_REQUEST_TRANSFORM_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(RESPONSE_TRANSFORM), // TS_HTTP_RESPONSE_TRANSFORM_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(SELECT_ALT), // TS_HTTP_SELECT_ALT_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(TXN_START), // TS_HTTP_TXN_START_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(TXN_CLOSE), // TS_HTTP_TXN_CLOSE_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(SSN_START), // TS_HTTP_SSN_START_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(SSN_CLOSE), // TS_HTTP_SSN_CLOSE_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(CACHE_LOOKUP_COMPLETE), // TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(PRE_REMAP), // TS_HTTP_PRE_REMAP_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(POST_REMAP), // TS_HTTP_POST_REMAP_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(REQUEST_BUFFER_READ_COMPLETE), // TS_HTTP_REQUEST_BUFFER_READ_COMPLETE_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(RESPONSE_CLIENT), // TS_HTTP_RESPONSE_CLIENT_HOOK - DERIVE_HOOK_VALUE_FROM_EVENT(REQUEST_CLIENT), // TS_HTTP_REQUEST_CLIENT_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(READ_REQUEST_HDR), // TS_HTTP_READ_REQUEST_HDR_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(OS_DNS), // TS_HTTP_OS_DNS_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(SEND_REQUEST_HDR), // TS_HTTP_SEND_REQUEST_HDR_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(READ_CACHE_HDR), // TS_HTTP_READ_CACHE_HDR_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(READ_RESPONSE_HDR), // TS_HTTP_READ_RESPONSE_HDR_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(SEND_RESPONSE_HDR), // TS_HTTP_SEND_RESPONSE_HDR_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(REQUEST_TRANSFORM), // TS_HTTP_REQUEST_TRANSFORM_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(RESPONSE_TRANSFORM), // TS_HTTP_RESPONSE_TRANSFORM_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(SELECT_ALT), // TS_HTTP_SELECT_ALT_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(TXN_START), // TS_HTTP_TXN_START_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(TXN_CLOSE), // TS_HTTP_TXN_CLOSE_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(SSN_START), // TS_HTTP_SSN_START_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(SSN_CLOSE), // TS_HTTP_SSN_CLOSE_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(CACHE_LOOKUP_COMPLETE), // TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(PRE_REMAP), // TS_HTTP_PRE_REMAP_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(POST_REMAP), // TS_HTTP_POST_REMAP_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(REQUEST_BUFFER_READ_COMPLETE), // TS_HTTP_REQUEST_BUFFER_READ_COMPLETE_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(RESPONSE_CLIENT), // TS_HTTP_RESPONSE_CLIENT_HOOK + DERIVE_HOOK_VALUE_FROM_EVENT(REQUEST_CLIENT), // TS_HTTP_REQUEST_CLIENT_HOOK // NOTE: // If adding any TS_HTTP hooks, be sure to understand the note above in the @@ -479,627 +485,1028 @@ typedef enum { // their corresponding TS_EVENT values. #undef DERIVE_HOOK_VALUE_FROM_EVENT - // Putting the SSL hooks in the same enum space - // So both sets of hooks can be set by the same Hook function - TS_SSL_FIRST_HOOK, - TS_VCONN_START_HOOK = TS_SSL_FIRST_HOOK, - TS_VCONN_PRE_ACCEPT_HOOK = TS_VCONN_START_HOOK, // Deprecated but compatible for now. - TS_VCONN_CLOSE_HOOK, - TS_SSL_CLIENT_HELLO_HOOK, - TS_SSL_SNI_HOOK, - TS_SSL_CERT_HOOK = TS_SSL_SNI_HOOK, - TS_SSL_SERVERNAME_HOOK, - TS_SSL_SERVER_VERIFY_HOOK, - TS_SSL_VERIFY_SERVER_HOOK = TS_SSL_SERVER_VERIFY_HOOK, - TS_SSL_VERIFY_CLIENT_HOOK, - TS_SSL_SESSION_HOOK, - TS_VCONN_OUTBOUND_START_HOOK, - TS_VCONN_OUTBOUND_CLOSE_HOOK, - TS_SSL_LAST_HOOK = TS_VCONN_OUTBOUND_CLOSE_HOOK, - TS_HTTP_LAST_HOOK -} TSHttpHookID; + // Putting the SSL hooks in the same enum space + // So both sets of hooks can be set by the same Hook function + TS_SSL_FIRST_HOOK, + TS_VCONN_START_HOOK = TS_SSL_FIRST_HOOK, + TS_VCONN_PRE_ACCEPT_HOOK = TS_VCONN_START_HOOK, // Deprecated but compatible for now. + TS_VCONN_CLOSE_HOOK, + TS_SSL_CLIENT_HELLO_HOOK, + TS_SSL_SNI_HOOK, + TS_SSL_CERT_HOOK = TS_SSL_SNI_HOOK, + TS_SSL_SERVERNAME_HOOK, + TS_SSL_SERVER_VERIFY_HOOK, + TS_SSL_VERIFY_SERVER_HOOK = TS_SSL_SERVER_VERIFY_HOOK, + TS_SSL_VERIFY_CLIENT_HOOK, + TS_SSL_SESSION_HOOK, + TS_VCONN_OUTBOUND_START_HOOK, + TS_VCONN_OUTBOUND_CLOSE_HOOK, + TS_SSL_LAST_HOOK = TS_VCONN_OUTBOUND_CLOSE_HOOK, + TS_HTTP_LAST_HOOK + }; -/** Plugin lifecycle hooks. + /** Plugin lifecycle hooks. - These are called during lifecycle events of a plugin. They - should be set in the plugin initialization function. The - continuation is invoked with an event ID specified for each hook - and @c NULL for the event data. + These are called during lifecycle events of a plugin. They + should be set in the plugin initialization function. The + continuation is invoked with an event ID specified for each hook + and @c nullptr for the event data. - TS_LIFECYCLE_PORTS_INITIALIZED_HOOK + TS_LIFECYCLE_PORTS_INITIALIZED_HOOK - called once, after the HTTP proxy port data structures have - been initialized. In particular, SSL related calls that depend - on accept endpoints may be invoked. After this hook is - finished, the proxy port sockets are opened and connections - are accepted. + called once, after the HTTP proxy port data structures have + been initialized. In particular, SSL related calls that depend + on accept endpoints may be invoked. After this hook is + finished, the proxy port sockets are opened and connections + are accepted. - Event: TS_EVENT_LIFECYCLE_PORTS_INITIALIZED + Event: TS_EVENT_LIFECYCLE_PORTS_INITIALIZED - TS_LIFECYCLE_PORTS_READY_HOOK + TS_LIFECYCLE_PORTS_READY_HOOK - called once, after the sockets have been opened and the accept - threads have been started. That is, the ports are ready to - accept connections. This is *not* guaranteed to be called - before the first connection is accepted. + called once, after the sockets have been opened and the accept + threads have been started. That is, the ports are ready to + accept connections. This is *not* guaranteed to be called + before the first connection is accepted. - Event: TS_EVENT_LIFECYCLE_PORTS_READY + Event: TS_EVENT_LIFECYCLE_PORTS_READY - TS_LIFECYCLE_CACHE_READY_HOOK + TS_LIFECYCLE_CACHE_READY_HOOK - called once, after the cache has finished its - initialization. It is either online or has failed when this - hook is called. + called once, after the cache has finished its + initialization. It is either online or has failed when this + hook is called. - Event: TS_EVENT_LIFECYCLE_CACHE_READY + Event: TS_EVENT_LIFECYCLE_CACHE_READY - TS_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED_HOOK + TS_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED_HOOK - called every time after a server SSL_CTX has finished the initialization. - It exposes the initialized SSL_CTX pointer. + called every time after a server SSL_CTX has finished the initialization. + It exposes the initialized SSL_CTX pointer. - Event: TS_EVENT_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED + Event: TS_EVENT_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED - TS_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED_HOOK + TS_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED_HOOK - called once, after the client SSL_CTX has finished the initialization. - It exposes the initialized SSL_CTX pointer. + called once, after the client SSL_CTX has finished the initialization. + It exposes the initialized SSL_CTX pointer. - Event: TS_EVENT_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED + Event: TS_EVENT_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED - TS_LIFECYCLE_MSG_HOOK + TS_LIFECYCLE_MSG_HOOK - Called in response to an external agent. The data is a pointer to an instance of TSPluginMsg. + Called in response to an external agent. The data is a pointer to an instance of TSPluginMsg. - Event: TS_EVENT_LIFECYCLE_MSG + Event: TS_EVENT_LIFECYCLE_MSG - TS_LIFECYCLE_TASK_THREADS_READY_HOOK + TS_LIFECYCLE_TASK_THREADS_READY_HOOK - called once, after the task threads have been started. + called once, after the task threads have been started. - Event: TS_EVENT_LIFECYCLE_TASK_THREADS_READY + Event: TS_EVENT_LIFECYCLE_TASK_THREADS_READY - TS_LIFECYCLE_SHUTDOWN_HOOK + TS_LIFECYCLE_SHUTDOWN_HOOK - called once, after receiving a shutdown signal, such as SIGTERM. + called once, after receiving a shutdown signal, such as SIGTERM. - Event: TS_EVENT_LIFECYCLE_SHUTDOWN + Event: TS_EVENT_LIFECYCLE_SHUTDOWN - Ordering guarantees: + Ordering guarantees: - - TS_LIFECYCLE_PORTS_INITIALIZED_HOOK before TS_LIFECYCLE_PORTS_READY_HOOK. + - TS_LIFECYCLE_PORTS_INITIALIZED_HOOK before TS_LIFECYCLE_PORTS_READY_HOOK. - NOTE! ONLY the orderings EXPLICITLY mentioned above are guaranteed. + NOTE! ONLY the orderings EXPLICITLY mentioned above are guaranteed. - */ -typedef enum { - TS_LIFECYCLE_PORTS_INITIALIZED_HOOK, - TS_LIFECYCLE_PORTS_READY_HOOK, - TS_LIFECYCLE_CACHE_READY_HOOK, - TS_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED_HOOK, - TS_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED_HOOK, - TS_LIFECYCLE_MSG_HOOK, - TS_LIFECYCLE_TASK_THREADS_READY_HOOK, - TS_LIFECYCLE_SHUTDOWN_HOOK, - TS_LIFECYCLE_SSL_SECRET_HOOK, - TS_LIFECYCLE_LAST_HOOK -} TSLifecycleHookID; - -typedef enum { - TS_SRVSTATE_STATE_UNDEFINED = 0, - TS_SRVSTATE_ACTIVE_TIMEOUT, - TS_SRVSTATE_BAD_INCOMING_RESPONSE, - TS_SRVSTATE_CONNECTION_ALIVE, - TS_SRVSTATE_CONNECTION_CLOSED, - TS_SRVSTATE_CONNECTION_ERROR, - TS_SRVSTATE_INACTIVE_TIMEOUT, - TS_SRVSTATE_OPEN_RAW_ERROR, - TS_SRVSTATE_PARSE_ERROR, - TS_SRVSTATE_TRANSACTION_COMPLETE, - TS_SRVSTATE_PARENT_RETRY, - TS_SRVSTATE_OUTBOUND_CONGESTION -} TSServerState; - -typedef enum { - TS_LOOKUP_UNDEFINED_LOOKUP, - TS_LOOKUP_PARENT_PROXY, - TS_LOOKUP_ORIGIN_SERVER, - TS_LOOKUP_INCOMING_ROUTER, - TS_LOOKUP_HOST_NONE -} TSLookingUpType; - -typedef enum { - TS_CACHE_LOOKUP_MISS, - TS_CACHE_LOOKUP_HIT_STALE, - TS_CACHE_LOOKUP_HIT_FRESH, - TS_CACHE_LOOKUP_SKIPPED -} TSCacheLookupResult; - -typedef enum { - TS_CACHE_DATA_TYPE_NONE, - TS_CACHE_DATA_TYPE_HTTP, - TS_CACHE_DATA_TYPE_OTHER, -} TSCacheDataType; - -typedef enum { - TS_CACHE_ERROR_NO_DOC = -20400, - TS_CACHE_ERROR_DOC_BUSY = -20401, - TS_CACHE_ERROR_NOT_READY = -20407, -} TSCacheError; - -typedef enum { - TS_CACHE_SCAN_RESULT_DONE = 0, - TS_CACHE_SCAN_RESULT_CONTINUE = 1, - TS_CACHE_SCAN_RESULT_DELETE = 10, - TS_CACHE_SCAN_RESULT_DELETE_ALL_ALTERNATES, - TS_CACHE_SCAN_RESULT_UPDATE, - TS_CACHE_SCAN_RESULT_RETRY -} TSCacheScanResult; - -typedef enum { - TS_TXN_INFO_NONE = -1, - TS_TXN_INFO_CACHE_HIT_RAM, - TS_TXN_INFO_CACHE_COMPRESSED_IN_RAM, - TS_TXN_INFO_CACHE_HIT_RWW, // READ_WHILE_WRITE - TS_TXN_INFO_CACHE_OPEN_READ_TRIES, - TS_TXN_INFO_CACHE_OPEN_WRITE_TRIES, - TS_TXN_INFO_CACHE_VOLUME, - TS_TXN_INFO_LAST_ENTRY -} TSHttpTxnInfoKey; - -typedef enum { - TS_VC_CLOSE_ABORT = -1, - TS_VC_CLOSE_NORMAL = 1, -} TSVConnCloseFlags; - -typedef enum { - TS_IOBUFFER_SIZE_INDEX_128 = 0, - TS_IOBUFFER_SIZE_INDEX_256 = 1, - TS_IOBUFFER_SIZE_INDEX_512 = 2, - TS_IOBUFFER_SIZE_INDEX_1K = 3, - TS_IOBUFFER_SIZE_INDEX_2K = 4, - TS_IOBUFFER_SIZE_INDEX_4K = 5, - TS_IOBUFFER_SIZE_INDEX_8K = 6, - TS_IOBUFFER_SIZE_INDEX_16K = 7, - TS_IOBUFFER_SIZE_INDEX_32K = 8, - TS_IOBUFFER_SIZE_INDEX_64K = 9, - TS_IOBUFFER_SIZE_INDEX_128K = 10, - TS_IOBUFFER_SIZE_INDEX_256K = 11, - TS_IOBUFFER_SIZE_INDEX_512K = 12, - TS_IOBUFFER_SIZE_INDEX_1M = 13, - TS_IOBUFFER_SIZE_INDEX_2M = 14 -} TSIOBufferSizeIndex; - -typedef enum { - TS_IOBUFFER_WATER_MARK_UNDEFINED = -1, - TS_IOBUFFER_WATER_MARK_PLUGIN_VC_DEFAULT = 0, // mirror of DEFAULT_PLUGIN_VC_BUFFER_WATER_MARK - TS_IOBUFFER_WATER_MARK_HTTP_DEFAULT = 32768, // mirror of default_buffer_water_mark -} TSIOBufferWaterMark; - -typedef enum { - TS_ERROR = -1, - TS_SUCCESS = 0, -} TSReturnCode; - -typedef enum { - NO_CALLBACK = 0, - AFTER_HEADER, - AFTER_BODY, -} TSFetchWakeUpOptions; - -/// Values for per server outbound connection tracking group definition. -/// See proxy.config.http.per_server.match -typedef enum { - TS_SERVER_OUTBOUND_MATCH_IP, - TS_SERVER_OUTBOUND_MATCH_PORT, - TS_SERVER_OUTBOUND_MATCH_HOST, - TS_SERVER_OUTBOUND_MATCH_BOTH -} TSOutboundConnectionMatchType; - -/* librecords types */ - -/* The values of this enum must match enum RecT in I_RecDefs.h */ -typedef enum { - TS_RECORDTYPE_NULL = 0x00, - TS_RECORDTYPE_CONFIG = 0x01, - TS_RECORDTYPE_PROCESS = 0x02, - TS_RECORDTYPE_NODE = 0x04, - TS_RECORDTYPE_PLUGIN = 0x20, - TS_RECORDTYPE_ALL = 0x3F -} TSRecordType; - -/* The values of this enum must match enum RecDataT in I_RecDefs.h */ -typedef enum { - TS_RECORDDATATYPE_NULL = 0, - TS_RECORDDATATYPE_INT, - TS_RECORDDATATYPE_FLOAT, - TS_RECORDDATATYPE_STRING, - TS_RECORDDATATYPE_COUNTER, - TS_RECORDDATATYPE_STAT_CONST, - TS_RECORDDATATYPE_STAT_FX, - TS_RECORDDATATYPE_MAX -} TSRecordDataType; - -typedef union { - int64_t rec_int; - float rec_float; - char *rec_string; - int64_t rec_counter; -} TSRecordData; - -/* The values of this enum must match enum RecPersistT in I_RecDefs.h */ -typedef enum { - TS_RECORDP_NULL, - TS_RECORDP_PERSISTENT, - TS_RECORDP_NON_PERSISTENT, -} TSRecordPersistType; - -/* The values of this enum must match enum RecUpdateT in I_RecDefs.h */ -typedef enum { - TS_RECORDUPDATE_NULL, - TS_RECORDUPDATE_DYNAMIC, - TS_RECORDUPDATE_RESTART_TS, - TS_RECORDUPDATE_RESTART_TM, -} TSRecordUpdateType; - -/* The values of this enum must match enum RecCheckT in I_RecDefs.h */ -typedef enum { - TS_RECORDCHECK_NULL, - TS_RECORDCHECK_STR, - TS_RECORDCHECK_INT, - TS_RECORDCHECK_IP, -} TSRecordCheckType; - -/* The values of this enum must match enum RecAccessT in I_RecDefs.h */ -typedef enum { - TS_RECORDACCESS_NULL, - TS_RECORDACCESS_NO_ACCESS, - TS_RECORDACCESS_READ_ONLY, -} TSRecordAccessType; - -typedef enum { - TS_CONFIG_NULL = -1, - TS_CONFIG_URL_REMAP_PRISTINE_HOST_HDR, - TS_CONFIG_HTTP_CHUNKING_ENABLED, - TS_CONFIG_HTTP_NEGATIVE_CACHING_ENABLED, - TS_CONFIG_HTTP_NEGATIVE_CACHING_LIFETIME, - TS_CONFIG_HTTP_CACHE_WHEN_TO_REVALIDATE, - TS_CONFIG_HTTP_KEEP_ALIVE_ENABLED_IN, - TS_CONFIG_HTTP_KEEP_ALIVE_ENABLED_OUT, - TS_CONFIG_HTTP_KEEP_ALIVE_POST_OUT, - TS_CONFIG_HTTP_SERVER_SESSION_SHARING_MATCH, - TS_CONFIG_NET_SOCK_RECV_BUFFER_SIZE_OUT, - TS_CONFIG_NET_SOCK_SEND_BUFFER_SIZE_OUT, - TS_CONFIG_NET_SOCK_OPTION_FLAG_OUT, - TS_CONFIG_HTTP_FORWARD_PROXY_AUTH_TO_PARENT, - TS_CONFIG_HTTP_ANONYMIZE_REMOVE_FROM, - TS_CONFIG_HTTP_ANONYMIZE_REMOVE_REFERER, - TS_CONFIG_HTTP_ANONYMIZE_REMOVE_USER_AGENT, - TS_CONFIG_HTTP_ANONYMIZE_REMOVE_COOKIE, - TS_CONFIG_HTTP_ANONYMIZE_REMOVE_CLIENT_IP, - TS_CONFIG_HTTP_ANONYMIZE_INSERT_CLIENT_IP, - TS_CONFIG_HTTP_RESPONSE_SERVER_ENABLED, - TS_CONFIG_HTTP_INSERT_SQUID_X_FORWARDED_FOR, - TS_CONFIG_HTTP_SEND_HTTP11_REQUESTS, - TS_CONFIG_HTTP_CACHE_HTTP, - TS_CONFIG_HTTP_CACHE_IGNORE_CLIENT_NO_CACHE, - TS_CONFIG_HTTP_CACHE_IGNORE_CLIENT_CC_MAX_AGE, - TS_CONFIG_HTTP_CACHE_IMS_ON_CLIENT_NO_CACHE, - TS_CONFIG_HTTP_CACHE_IGNORE_SERVER_NO_CACHE, - TS_CONFIG_HTTP_CACHE_CACHE_RESPONSES_TO_COOKIES, - TS_CONFIG_HTTP_CACHE_IGNORE_AUTHENTICATION, - TS_CONFIG_HTTP_CACHE_CACHE_URLS_THAT_LOOK_DYNAMIC, - TS_CONFIG_HTTP_CACHE_REQUIRED_HEADERS, - TS_CONFIG_HTTP_INSERT_REQUEST_VIA_STR, - TS_CONFIG_HTTP_INSERT_RESPONSE_VIA_STR, - TS_CONFIG_HTTP_CACHE_HEURISTIC_MIN_LIFETIME, - TS_CONFIG_HTTP_CACHE_HEURISTIC_MAX_LIFETIME, - TS_CONFIG_HTTP_CACHE_GUARANTEED_MIN_LIFETIME, - TS_CONFIG_HTTP_CACHE_GUARANTEED_MAX_LIFETIME, - TS_CONFIG_HTTP_CACHE_MAX_STALE_AGE, - TS_CONFIG_HTTP_KEEP_ALIVE_NO_ACTIVITY_TIMEOUT_IN, - TS_CONFIG_HTTP_KEEP_ALIVE_NO_ACTIVITY_TIMEOUT_OUT, - TS_CONFIG_HTTP_TRANSACTION_NO_ACTIVITY_TIMEOUT_IN, - TS_CONFIG_HTTP_TRANSACTION_NO_ACTIVITY_TIMEOUT_OUT, - TS_CONFIG_HTTP_TRANSACTION_ACTIVE_TIMEOUT_OUT, - TS_CONFIG_HTTP_CONNECT_ATTEMPTS_MAX_RETRIES, - TS_CONFIG_HTTP_CONNECT_ATTEMPTS_MAX_RETRIES_DOWN_SERVER, - TS_CONFIG_HTTP_CONNECT_ATTEMPTS_RR_RETRIES, - TS_CONFIG_HTTP_CONNECT_ATTEMPTS_TIMEOUT, - TS_CONFIG_HTTP_DOWN_SERVER_CACHE_TIME, - TS_CONFIG_HTTP_DOC_IN_CACHE_SKIP_DNS, - TS_CONFIG_HTTP_BACKGROUND_FILL_ACTIVE_TIMEOUT, - TS_CONFIG_HTTP_RESPONSE_SERVER_STR, - TS_CONFIG_HTTP_CACHE_HEURISTIC_LM_FACTOR, - TS_CONFIG_HTTP_BACKGROUND_FILL_COMPLETED_THRESHOLD, - TS_CONFIG_NET_SOCK_PACKET_MARK_OUT, - TS_CONFIG_NET_SOCK_PACKET_TOS_OUT, - TS_CONFIG_HTTP_INSERT_AGE_IN_RESPONSE, - TS_CONFIG_HTTP_CHUNKING_SIZE, - TS_CONFIG_HTTP_FLOW_CONTROL_ENABLED, - TS_CONFIG_HTTP_FLOW_CONTROL_LOW_WATER_MARK, - TS_CONFIG_HTTP_FLOW_CONTROL_HIGH_WATER_MARK, - TS_CONFIG_HTTP_CACHE_RANGE_LOOKUP, - TS_CONFIG_HTTP_DEFAULT_BUFFER_SIZE, - TS_CONFIG_HTTP_DEFAULT_BUFFER_WATER_MARK, - TS_CONFIG_HTTP_REQUEST_HEADER_MAX_SIZE, - TS_CONFIG_HTTP_RESPONSE_HEADER_MAX_SIZE, - TS_CONFIG_HTTP_NEGATIVE_REVALIDATING_ENABLED, - TS_CONFIG_HTTP_NEGATIVE_REVALIDATING_LIFETIME, - TS_CONFIG_SSL_HSTS_MAX_AGE, - TS_CONFIG_SSL_HSTS_INCLUDE_SUBDOMAINS, - TS_CONFIG_HTTP_CACHE_OPEN_READ_RETRY_TIME, - TS_CONFIG_HTTP_CACHE_MAX_OPEN_READ_RETRIES, - TS_CONFIG_HTTP_CACHE_RANGE_WRITE, - TS_CONFIG_HTTP_POST_CHECK_CONTENT_LENGTH_ENABLED, - TS_CONFIG_HTTP_GLOBAL_USER_AGENT_HEADER, - TS_CONFIG_HTTP_AUTH_SERVER_SESSION_PRIVATE, - TS_CONFIG_HTTP_SLOW_LOG_THRESHOLD, - TS_CONFIG_HTTP_CACHE_GENERATION, - TS_CONFIG_BODY_FACTORY_TEMPLATE_BASE, - TS_CONFIG_HTTP_CACHE_OPEN_WRITE_FAIL_ACTION, - TS_CONFIG_HTTP_NUMBER_OF_REDIRECTIONS, - TS_CONFIG_HTTP_CACHE_MAX_OPEN_WRITE_RETRIES, - TS_CONFIG_HTTP_CACHE_MAX_OPEN_WRITE_RETRY_TIMEOUT, - TS_CONFIG_HTTP_REDIRECT_USE_ORIG_CACHE_KEY, - TS_CONFIG_HTTP_ATTACH_SERVER_SESSION_TO_CLIENT, - TS_CONFIG_WEBSOCKET_NO_ACTIVITY_TIMEOUT, - TS_CONFIG_WEBSOCKET_ACTIVE_TIMEOUT, - TS_CONFIG_HTTP_UNCACHEABLE_REQUESTS_BYPASS_PARENT, - TS_CONFIG_HTTP_PARENT_PROXY_TOTAL_CONNECT_ATTEMPTS, - TS_CONFIG_HTTP_TRANSACTION_ACTIVE_TIMEOUT_IN, - TS_CONFIG_SRV_ENABLED, - TS_CONFIG_HTTP_FORWARD_CONNECT_METHOD, - TS_CONFIG_SSL_CERT_FILENAME, - TS_CONFIG_SSL_CLIENT_CERT_FILENAME = TS_CONFIG_SSL_CERT_FILENAME, - TS_CONFIG_SSL_CERT_FILEPATH, - TS_CONFIG_PARENT_FAILURES_UPDATE_HOSTDB, - TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_MISMATCH, - TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_LANGUAGE_MISMATCH, - TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_ENCODING_MISMATCH, - TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_CHARSET_MISMATCH, - TS_CONFIG_HTTP_PARENT_PROXY_FAIL_THRESHOLD, - TS_CONFIG_HTTP_PARENT_PROXY_RETRY_TIME, - TS_CONFIG_HTTP_PER_PARENT_CONNECT_ATTEMPTS, - TS_CONFIG_HTTP_NORMALIZE_AE, - TS_CONFIG_HTTP_INSERT_FORWARDED, - TS_CONFIG_HTTP_PROXY_PROTOCOL_OUT, - TS_CONFIG_HTTP_ALLOW_MULTI_RANGE, - TS_CONFIG_HTTP_REQUEST_BUFFER_ENABLED, - TS_CONFIG_HTTP_ALLOW_HALF_OPEN, - TS_CONFIG_HTTP_SERVER_MIN_KEEP_ALIVE_CONNS, - TS_CONFIG_HTTP_PER_SERVER_CONNECTION_MAX, - TS_CONFIG_HTTP_PER_SERVER_CONNECTION_MATCH, - TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_POLICY, - TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_PROPERTIES, - TS_CONFIG_SSL_CLIENT_SNI_POLICY, - TS_CONFIG_SSL_CLIENT_PRIVATE_KEY_FILENAME, - TS_CONFIG_SSL_CLIENT_CA_CERT_FILENAME, - TS_CONFIG_SSL_CLIENT_ALPN_PROTOCOLS, - TS_CONFIG_HTTP_HOST_RESOLUTION_PREFERENCE, - TS_CONFIG_HTTP_CONNECT_DOWN_POLICY, - TS_CONFIG_HTTP_MAX_PROXY_CYCLES, - TS_CONFIG_PLUGIN_VC_DEFAULT_BUFFER_INDEX, - TS_CONFIG_PLUGIN_VC_DEFAULT_BUFFER_WATER_MARK, - TS_CONFIG_NET_SOCK_NOTSENT_LOWAT, - TS_CONFIG_BODY_FACTORY_RESPONSE_SUPPRESSION_MODE, - TS_CONFIG_HTTP_ENABLE_PARENT_TIMEOUT_MARKDOWNS, - TS_CONFIG_HTTP_DISABLE_PARENT_MARKDOWNS, - TS_CONFIG_NET_DEFAULT_INACTIVITY_TIMEOUT, - TS_CONFIG_HTTP_NO_DNS_JUST_FORWARD_TO_PARENT, - TS_CONFIG_HTTP_CACHE_IGNORE_QUERY, - TS_CONFIG_LAST_ENTRY -} TSOverridableConfigKey; - -/* The TASK pool of threads is the primary method of off-loading continuations from the - net-threads. Configure this with proxy.config.task_threads in records.yaml. */ -typedef enum { - TS_THREAD_POOL_NET, - TS_THREAD_POOL_TASK, - /* unlikely you should use these */ - TS_THREAD_POOL_DNS, - TS_THREAD_POOL_UDP -} TSThreadPool; - -/* TSHRTime stuff, this is a candidate for deprecation in v10.0.0 */ -typedef int64_t TSHRTime; - -#define TS_HRTIME_SECOND (1000 * TS_HRTIME_MSECOND) -#define TS_HRTIME_MSECOND (1000 * TS_HRTIME_USECOND) -#define TS_HRTIME_USECOND (1000 * TS_HRTIME_NSECOND) -#define TS_HRTIME_NSECOND (1LL) - -#define TS_HRTIME_SECONDS(_x) ((_x)*TS_HRTIME_SECOND) -#define TS_HRTIME_MSECONDS(_x) ((_x)*TS_HRTIME_MSECOND) -#define TS_HRTIME_USECONDS(_x) ((_x)*TS_HRTIME_USECOND) -#define TS_HRTIME_NSECONDS(_x) ((_x)*TS_HRTIME_NSECOND) - -/* The TSMilestonesType is an enum defining all the various milestones ("timers") that - we track for a request. */ -typedef enum { - TS_MILESTONE_NULL = -1, - TS_MILESTONE_UA_BEGIN, - TS_MILESTONE_UA_FIRST_READ, - TS_MILESTONE_UA_READ_HEADER_DONE, - TS_MILESTONE_UA_BEGIN_WRITE, - TS_MILESTONE_UA_CLOSE, - TS_MILESTONE_SERVER_FIRST_CONNECT, - TS_MILESTONE_SERVER_CONNECT, - TS_MILESTONE_SERVER_CONNECT_END, - TS_MILESTONE_SERVER_BEGIN_WRITE, - TS_MILESTONE_SERVER_FIRST_READ, - TS_MILESTONE_SERVER_READ_HEADER_DONE, - TS_MILESTONE_SERVER_CLOSE, - TS_MILESTONE_CACHE_OPEN_READ_BEGIN, - TS_MILESTONE_CACHE_OPEN_READ_END, - TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN, - TS_MILESTONE_CACHE_OPEN_WRITE_END, - TS_MILESTONE_DNS_LOOKUP_BEGIN, - TS_MILESTONE_DNS_LOOKUP_END, - TS_MILESTONE_SM_START, - TS_MILESTONE_SM_FINISH, - TS_MILESTONE_PLUGIN_ACTIVE, - TS_MILESTONE_PLUGIN_TOTAL, - TS_MILESTONE_TLS_HANDSHAKE_START, - TS_MILESTONE_TLS_HANDSHAKE_END, - TS_MILESTONE_LAST_ENTRY -} TSMilestonesType; - -/* These typedefs are used with the corresponding TSMgmt*Get functions - for storing the values retrieved by those functions. For example, - TSMgmtCounterGet() retrieves an TSMgmtCounter. */ -typedef int64_t TSMgmtInt; -typedef int64_t TSMgmtCounter; -typedef float TSMgmtFloat; -typedef char *TSMgmtString; - -/// The source of a management value. -typedef enum { - TS_MGMT_SOURCE_NULL, ///< No source / value not found. - TS_MGMT_SOURCE_DEFAULT, ///< Built in core default. - TS_MGMT_SOURCE_PLUGIN, ///< Plugin supplied default. - TS_MGMT_SOURCE_EXPLICIT, ///< Set by administrator (config file, external API, etc.) - TS_MGMT_SOURCE_ENV ///< Process environment variable. -} TSMgmtSource; - -/// The User Arg type, used for Txn/Ssn/VConn user argument slots -typedef enum { - TS_USER_ARGS_TXN, ///< Transaction based. - TS_USER_ARGS_SSN, ///< Session based - TS_USER_ARGS_VCONN, ///< VConnection based - TS_USER_ARGS_GLB, ///< Global based - TS_USER_ARGS_COUNT ///< Fake enum, # of valid entries. -} TSUserArgType; - -/** An enumeration of HTTP version types for the priority functions that behave - * differently across HTTP protocols. */ -typedef enum { - HTTP_PRIORITY_TYPE_HTTP_UNSPECIFIED = 1, - HTTP_PRIORITY_TYPE_HTTP_2, - HTTP_PRIORITY_TYPE_HTTP_3, -} TSHttpPriorityType; - -/** The abstract type of the various HTTP priority implementations. */ -typedef struct { - /** The reference to the concrete HTTP priority implementation. This will be - * a value from TSHttpPriorityType. */ - uint8_t priority_type; - /** The space allocated for the concrete priority implementation. + */ + enum TSLifecycleHookID { + TS_LIFECYCLE_PORTS_INITIALIZED_HOOK, + TS_LIFECYCLE_PORTS_READY_HOOK, + TS_LIFECYCLE_CACHE_READY_HOOK, + TS_LIFECYCLE_SERVER_SSL_CTX_INITIALIZED_HOOK, + TS_LIFECYCLE_CLIENT_SSL_CTX_INITIALIZED_HOOK, + TS_LIFECYCLE_MSG_HOOK, + TS_LIFECYCLE_TASK_THREADS_READY_HOOK, + TS_LIFECYCLE_SHUTDOWN_HOOK, + TS_LIFECYCLE_SSL_SECRET_HOOK, + TS_LIFECYCLE_LAST_HOOK + }; + + enum TSServerState { + TS_SRVSTATE_STATE_UNDEFINED = 0, + TS_SRVSTATE_ACTIVE_TIMEOUT, + TS_SRVSTATE_BAD_INCOMING_RESPONSE, + TS_SRVSTATE_CONNECTION_ALIVE, + TS_SRVSTATE_CONNECTION_CLOSED, + TS_SRVSTATE_CONNECTION_ERROR, + TS_SRVSTATE_INACTIVE_TIMEOUT, + TS_SRVSTATE_OPEN_RAW_ERROR, + TS_SRVSTATE_PARSE_ERROR, + TS_SRVSTATE_TRANSACTION_COMPLETE, + TS_SRVSTATE_PARENT_RETRY, + TS_SRVSTATE_OUTBOUND_CONGESTION + }; + + enum TSLookingUpType { + TS_LOOKUP_UNDEFINED_LOOKUP, + TS_LOOKUP_PARENT_PROXY, + TS_LOOKUP_ORIGIN_SERVER, + TS_LOOKUP_INCOMING_ROUTER, + TS_LOOKUP_HOST_NONE + }; + + enum TSCacheLookupResult { TS_CACHE_LOOKUP_MISS, TS_CACHE_LOOKUP_HIT_STALE, TS_CACHE_LOOKUP_HIT_FRESH, TS_CACHE_LOOKUP_SKIPPED }; + + enum TSCacheDataType { + TS_CACHE_DATA_TYPE_NONE, + TS_CACHE_DATA_TYPE_HTTP, + TS_CACHE_DATA_TYPE_OTHER, + }; + + enum TSCacheError { + TS_CACHE_ERROR_NO_DOC = -20400, + TS_CACHE_ERROR_DOC_BUSY = -20401, + TS_CACHE_ERROR_NOT_READY = -20407, + }; + + enum TSCacheScanResult { + TS_CACHE_SCAN_RESULT_DONE = 0, + TS_CACHE_SCAN_RESULT_CONTINUE = 1, + TS_CACHE_SCAN_RESULT_DELETE = 10, + TS_CACHE_SCAN_RESULT_DELETE_ALL_ALTERNATES, + TS_CACHE_SCAN_RESULT_UPDATE, + TS_CACHE_SCAN_RESULT_RETRY + }; + + enum TSHttpTxnInfoKey { + TS_TXN_INFO_NONE = -1, + TS_TXN_INFO_CACHE_HIT_RAM, + TS_TXN_INFO_CACHE_COMPRESSED_IN_RAM, + TS_TXN_INFO_CACHE_HIT_RWW, // READ_WHILE_WRITE + TS_TXN_INFO_CACHE_OPEN_READ_TRIES, + TS_TXN_INFO_CACHE_OPEN_WRITE_TRIES, + TS_TXN_INFO_CACHE_VOLUME, + TS_TXN_INFO_LAST_ENTRY + }; + + enum TSVConnCloseFlags { + TS_VC_CLOSE_ABORT = -1, + TS_VC_CLOSE_NORMAL = 1, + }; + + enum TSIOBufferSizeIndex { + TS_IOBUFFER_SIZE_INDEX_128 = 0, + TS_IOBUFFER_SIZE_INDEX_256 = 1, + TS_IOBUFFER_SIZE_INDEX_512 = 2, + TS_IOBUFFER_SIZE_INDEX_1K = 3, + TS_IOBUFFER_SIZE_INDEX_2K = 4, + TS_IOBUFFER_SIZE_INDEX_4K = 5, + TS_IOBUFFER_SIZE_INDEX_8K = 6, + TS_IOBUFFER_SIZE_INDEX_16K = 7, + TS_IOBUFFER_SIZE_INDEX_32K = 8, + TS_IOBUFFER_SIZE_INDEX_64K = 9, + TS_IOBUFFER_SIZE_INDEX_128K = 10, + TS_IOBUFFER_SIZE_INDEX_256K = 11, + TS_IOBUFFER_SIZE_INDEX_512K = 12, + TS_IOBUFFER_SIZE_INDEX_1M = 13, + TS_IOBUFFER_SIZE_INDEX_2M = 14 + }; + + enum TSIOBufferWaterMark { + TS_IOBUFFER_WATER_MARK_UNDEFINED = -1, + TS_IOBUFFER_WATER_MARK_PLUGIN_VC_DEFAULT = 0, // mirror of DEFAULT_PLUGIN_VC_BUFFER_WATER_MARK + TS_IOBUFFER_WATER_MARK_HTTP_DEFAULT = 32768, // mirror of default_buffer_water_mark + }; + + enum TSReturnCode { + TS_ERROR = -1, + TS_SUCCESS = 0, + }; + + enum TSFetchWakeUpOptions { + NO_CALLBACK = 0, + AFTER_HEADER, + AFTER_BODY, + }; + + /// Values for per server outbound connection tracking group definition. + /// See proxy.config.http.per_server.match + enum TSOutboundConnectionMatchType { + TS_SERVER_OUTBOUND_MATCH_IP, + TS_SERVER_OUTBOUND_MATCH_PORT, + TS_SERVER_OUTBOUND_MATCH_HOST, + TS_SERVER_OUTBOUND_MATCH_BOTH + }; + + /* librecords types */ + + /* The values of this enum must match enum RecT in I_RecDefs.h */ + enum TSRecordType { + TS_RECORDTYPE_NULL = 0x00, + TS_RECORDTYPE_CONFIG = 0x01, + TS_RECORDTYPE_PROCESS = 0x02, + TS_RECORDTYPE_NODE = 0x04, + TS_RECORDTYPE_PLUGIN = 0x20, + TS_RECORDTYPE_ALL = 0x3F + }; + + /* The values of this enum must match enum RecDataT in I_RecDefs.h */ + enum TSRecordDataType { + TS_RECORDDATATYPE_NULL = 0, + TS_RECORDDATATYPE_INT, + TS_RECORDDATATYPE_FLOAT, + TS_RECORDDATATYPE_STRING, + TS_RECORDDATATYPE_COUNTER, + TS_RECORDDATATYPE_STAT_CONST, + TS_RECORDDATATYPE_STAT_FX, + TS_RECORDDATATYPE_MAX + }; + + union TSRecordData { + int64_t rec_int; + float rec_float; + char *rec_string; + int64_t rec_counter; + }; + + /* The values of this enum must match enum RecPersistT in I_RecDefs.h */ + enum TSRecordPersistType { + TS_RECORDP_NULL, + TS_RECORDP_PERSISTENT, + TS_RECORDP_NON_PERSISTENT, + }; + + /* The values of this enum must match enum RecUpdateT in I_RecDefs.h */ + enum TSRecordUpdateType { + TS_RECORDUPDATE_NULL, + TS_RECORDUPDATE_DYNAMIC, + TS_RECORDUPDATE_RESTART_TS, + TS_RECORDUPDATE_RESTART_TM, + }; + + /* The values of this enum must match enum RecCheckT in I_RecDefs.h */ + enum TSRecordCheckType { + TS_RECORDCHECK_NULL, + TS_RECORDCHECK_STR, + TS_RECORDCHECK_INT, + TS_RECORDCHECK_IP, + }; + + /* The values of this enum must match enum RecAccessT in I_RecDefs.h */ + enum TSRecordAccessType { + TS_RECORDACCESS_NULL, + TS_RECORDACCESS_NO_ACCESS, + TS_RECORDACCESS_READ_ONLY, + }; + + enum TSOverridableConfigKey { + TS_CONFIG_NULL = -1, + TS_CONFIG_URL_REMAP_PRISTINE_HOST_HDR, + TS_CONFIG_HTTP_CHUNKING_ENABLED, + TS_CONFIG_HTTP_NEGATIVE_CACHING_ENABLED, + TS_CONFIG_HTTP_NEGATIVE_CACHING_LIFETIME, + TS_CONFIG_HTTP_CACHE_WHEN_TO_REVALIDATE, + TS_CONFIG_HTTP_KEEP_ALIVE_ENABLED_IN, + TS_CONFIG_HTTP_KEEP_ALIVE_ENABLED_OUT, + TS_CONFIG_HTTP_KEEP_ALIVE_POST_OUT, + TS_CONFIG_HTTP_SERVER_SESSION_SHARING_MATCH, + TS_CONFIG_NET_SOCK_RECV_BUFFER_SIZE_OUT, + TS_CONFIG_NET_SOCK_SEND_BUFFER_SIZE_OUT, + TS_CONFIG_NET_SOCK_OPTION_FLAG_OUT, + TS_CONFIG_HTTP_FORWARD_PROXY_AUTH_TO_PARENT, + TS_CONFIG_HTTP_ANONYMIZE_REMOVE_FROM, + TS_CONFIG_HTTP_ANONYMIZE_REMOVE_REFERER, + TS_CONFIG_HTTP_ANONYMIZE_REMOVE_USER_AGENT, + TS_CONFIG_HTTP_ANONYMIZE_REMOVE_COOKIE, + TS_CONFIG_HTTP_ANONYMIZE_REMOVE_CLIENT_IP, + TS_CONFIG_HTTP_ANONYMIZE_INSERT_CLIENT_IP, + TS_CONFIG_HTTP_RESPONSE_SERVER_ENABLED, + TS_CONFIG_HTTP_INSERT_SQUID_X_FORWARDED_FOR, + TS_CONFIG_HTTP_SEND_HTTP11_REQUESTS, + TS_CONFIG_HTTP_CACHE_HTTP, + TS_CONFIG_HTTP_CACHE_IGNORE_CLIENT_NO_CACHE, + TS_CONFIG_HTTP_CACHE_IGNORE_CLIENT_CC_MAX_AGE, + TS_CONFIG_HTTP_CACHE_IMS_ON_CLIENT_NO_CACHE, + TS_CONFIG_HTTP_CACHE_IGNORE_SERVER_NO_CACHE, + TS_CONFIG_HTTP_CACHE_CACHE_RESPONSES_TO_COOKIES, + TS_CONFIG_HTTP_CACHE_IGNORE_AUTHENTICATION, + TS_CONFIG_HTTP_CACHE_CACHE_URLS_THAT_LOOK_DYNAMIC, + TS_CONFIG_HTTP_CACHE_REQUIRED_HEADERS, + TS_CONFIG_HTTP_INSERT_REQUEST_VIA_STR, + TS_CONFIG_HTTP_INSERT_RESPONSE_VIA_STR, + TS_CONFIG_HTTP_CACHE_HEURISTIC_MIN_LIFETIME, + TS_CONFIG_HTTP_CACHE_HEURISTIC_MAX_LIFETIME, + TS_CONFIG_HTTP_CACHE_GUARANTEED_MIN_LIFETIME, + TS_CONFIG_HTTP_CACHE_GUARANTEED_MAX_LIFETIME, + TS_CONFIG_HTTP_CACHE_MAX_STALE_AGE, + TS_CONFIG_HTTP_KEEP_ALIVE_NO_ACTIVITY_TIMEOUT_IN, + TS_CONFIG_HTTP_KEEP_ALIVE_NO_ACTIVITY_TIMEOUT_OUT, + TS_CONFIG_HTTP_TRANSACTION_NO_ACTIVITY_TIMEOUT_IN, + TS_CONFIG_HTTP_TRANSACTION_NO_ACTIVITY_TIMEOUT_OUT, + TS_CONFIG_HTTP_TRANSACTION_ACTIVE_TIMEOUT_OUT, + TS_CONFIG_HTTP_CONNECT_ATTEMPTS_MAX_RETRIES, + TS_CONFIG_HTTP_CONNECT_ATTEMPTS_MAX_RETRIES_DOWN_SERVER, + TS_CONFIG_HTTP_CONNECT_ATTEMPTS_RR_RETRIES, + TS_CONFIG_HTTP_CONNECT_ATTEMPTS_TIMEOUT, + TS_CONFIG_HTTP_DOWN_SERVER_CACHE_TIME, + TS_CONFIG_HTTP_DOC_IN_CACHE_SKIP_DNS, + TS_CONFIG_HTTP_BACKGROUND_FILL_ACTIVE_TIMEOUT, + TS_CONFIG_HTTP_RESPONSE_SERVER_STR, + TS_CONFIG_HTTP_CACHE_HEURISTIC_LM_FACTOR, + TS_CONFIG_HTTP_BACKGROUND_FILL_COMPLETED_THRESHOLD, + TS_CONFIG_NET_SOCK_PACKET_MARK_OUT, + TS_CONFIG_NET_SOCK_PACKET_TOS_OUT, + TS_CONFIG_HTTP_INSERT_AGE_IN_RESPONSE, + TS_CONFIG_HTTP_CHUNKING_SIZE, + TS_CONFIG_HTTP_FLOW_CONTROL_ENABLED, + TS_CONFIG_HTTP_FLOW_CONTROL_LOW_WATER_MARK, + TS_CONFIG_HTTP_FLOW_CONTROL_HIGH_WATER_MARK, + TS_CONFIG_HTTP_CACHE_RANGE_LOOKUP, + TS_CONFIG_HTTP_DEFAULT_BUFFER_SIZE, + TS_CONFIG_HTTP_DEFAULT_BUFFER_WATER_MARK, + TS_CONFIG_HTTP_REQUEST_HEADER_MAX_SIZE, + TS_CONFIG_HTTP_RESPONSE_HEADER_MAX_SIZE, + TS_CONFIG_HTTP_NEGATIVE_REVALIDATING_ENABLED, + TS_CONFIG_HTTP_NEGATIVE_REVALIDATING_LIFETIME, + TS_CONFIG_SSL_HSTS_MAX_AGE, + TS_CONFIG_SSL_HSTS_INCLUDE_SUBDOMAINS, + TS_CONFIG_HTTP_CACHE_OPEN_READ_RETRY_TIME, + TS_CONFIG_HTTP_CACHE_MAX_OPEN_READ_RETRIES, + TS_CONFIG_HTTP_CACHE_RANGE_WRITE, + TS_CONFIG_HTTP_POST_CHECK_CONTENT_LENGTH_ENABLED, + TS_CONFIG_HTTP_GLOBAL_USER_AGENT_HEADER, + TS_CONFIG_HTTP_AUTH_SERVER_SESSION_PRIVATE, + TS_CONFIG_HTTP_SLOW_LOG_THRESHOLD, + TS_CONFIG_HTTP_CACHE_GENERATION, + TS_CONFIG_BODY_FACTORY_TEMPLATE_BASE, + TS_CONFIG_HTTP_CACHE_OPEN_WRITE_FAIL_ACTION, + TS_CONFIG_HTTP_NUMBER_OF_REDIRECTIONS, + TS_CONFIG_HTTP_CACHE_MAX_OPEN_WRITE_RETRIES, + TS_CONFIG_HTTP_CACHE_MAX_OPEN_WRITE_RETRY_TIMEOUT, + TS_CONFIG_HTTP_REDIRECT_USE_ORIG_CACHE_KEY, + TS_CONFIG_HTTP_ATTACH_SERVER_SESSION_TO_CLIENT, + TS_CONFIG_WEBSOCKET_NO_ACTIVITY_TIMEOUT, + TS_CONFIG_WEBSOCKET_ACTIVE_TIMEOUT, + TS_CONFIG_HTTP_UNCACHEABLE_REQUESTS_BYPASS_PARENT, + TS_CONFIG_HTTP_PARENT_PROXY_TOTAL_CONNECT_ATTEMPTS, + TS_CONFIG_HTTP_TRANSACTION_ACTIVE_TIMEOUT_IN, + TS_CONFIG_SRV_ENABLED, + TS_CONFIG_HTTP_FORWARD_CONNECT_METHOD, + TS_CONFIG_SSL_CERT_FILENAME, + TS_CONFIG_SSL_CLIENT_CERT_FILENAME = TS_CONFIG_SSL_CERT_FILENAME, + TS_CONFIG_SSL_CERT_FILEPATH, + TS_CONFIG_PARENT_FAILURES_UPDATE_HOSTDB, + TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_MISMATCH, + TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_LANGUAGE_MISMATCH, + TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_ENCODING_MISMATCH, + TS_CONFIG_HTTP_CACHE_IGNORE_ACCEPT_CHARSET_MISMATCH, + TS_CONFIG_HTTP_PARENT_PROXY_FAIL_THRESHOLD, + TS_CONFIG_HTTP_PARENT_PROXY_RETRY_TIME, + TS_CONFIG_HTTP_PER_PARENT_CONNECT_ATTEMPTS, + TS_CONFIG_HTTP_NORMALIZE_AE, + TS_CONFIG_HTTP_INSERT_FORWARDED, + TS_CONFIG_HTTP_PROXY_PROTOCOL_OUT, + TS_CONFIG_HTTP_ALLOW_MULTI_RANGE, + TS_CONFIG_HTTP_REQUEST_BUFFER_ENABLED, + TS_CONFIG_HTTP_ALLOW_HALF_OPEN, + TS_CONFIG_HTTP_SERVER_MIN_KEEP_ALIVE_CONNS, + TS_CONFIG_HTTP_PER_SERVER_CONNECTION_MAX, + TS_CONFIG_HTTP_PER_SERVER_CONNECTION_MATCH, + TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_POLICY, + TS_CONFIG_SSL_CLIENT_VERIFY_SERVER_PROPERTIES, + TS_CONFIG_SSL_CLIENT_SNI_POLICY, + TS_CONFIG_SSL_CLIENT_PRIVATE_KEY_FILENAME, + TS_CONFIG_SSL_CLIENT_CA_CERT_FILENAME, + TS_CONFIG_SSL_CLIENT_ALPN_PROTOCOLS, + TS_CONFIG_HTTP_HOST_RESOLUTION_PREFERENCE, + TS_CONFIG_HTTP_CONNECT_DOWN_POLICY, + TS_CONFIG_HTTP_MAX_PROXY_CYCLES, + TS_CONFIG_PLUGIN_VC_DEFAULT_BUFFER_INDEX, + TS_CONFIG_PLUGIN_VC_DEFAULT_BUFFER_WATER_MARK, + TS_CONFIG_NET_SOCK_NOTSENT_LOWAT, + TS_CONFIG_BODY_FACTORY_RESPONSE_SUPPRESSION_MODE, + TS_CONFIG_HTTP_ENABLE_PARENT_TIMEOUT_MARKDOWNS, + TS_CONFIG_HTTP_DISABLE_PARENT_MARKDOWNS, + TS_CONFIG_NET_DEFAULT_INACTIVITY_TIMEOUT, + TS_CONFIG_HTTP_NO_DNS_JUST_FORWARD_TO_PARENT, + TS_CONFIG_HTTP_CACHE_IGNORE_QUERY, + TS_CONFIG_LAST_ENTRY + }; + + /* The TASK pool of threads is the primary method of off-loading continuations from the + net-threads. Configure this with proxy.config.task_threads in records.yaml. */ + enum TSThreadPool { + TS_THREAD_POOL_NET, + TS_THREAD_POOL_TASK, + /* unlikely you should use these */ + TS_THREAD_POOL_DNS, + TS_THREAD_POOL_UDP + }; + + /* TSHRTime stuff, this is a candidate for deprecation in v10.0.0 */ + using TSHRTime = int64_t; + + TSHRTime const TS_HRTIME_NSECOND = 1; + TSHRTime const TS_HRTIME_USECOND = 1000 * TS_HRTIME_NSECOND; + TSHRTime const TS_HRTIME_MSECOND = 1000 * TS_HRTIME_USECOND; + TSHRTime const TS_HRTIME_SECOND = 1000 * TS_HRTIME_MSECOND; + + constexpr TSHRTime + TS_HRTIME_SECONDS(TSHRTime x) + { + return x * TS_HRTIME_SECOND; + } + constexpr TSHRTime + TS_HRTIME_MSECONDS(TSHRTime x) + { + return x * TS_HRTIME_MSECOND; + } + constexpr TSHRTime + TS_HRTIME_USECONDS(TSHRTime x) + { + return x * TS_HRTIME_USECOND; + } + constexpr TSHRTime + TS_HRTIME_NSECONDS(TSHRTime x) + { + return x * TS_HRTIME_NSECOND; + } + + /* The TSMilestonesType is an enum defining all the various milestones ("timers") that + we track for a request. */ + enum TSMilestonesType { + TS_MILESTONE_NULL = -1, + TS_MILESTONE_UA_BEGIN, + TS_MILESTONE_UA_FIRST_READ, + TS_MILESTONE_UA_READ_HEADER_DONE, + TS_MILESTONE_UA_BEGIN_WRITE, + TS_MILESTONE_UA_CLOSE, + TS_MILESTONE_SERVER_FIRST_CONNECT, + TS_MILESTONE_SERVER_CONNECT, + TS_MILESTONE_SERVER_CONNECT_END, + TS_MILESTONE_SERVER_BEGIN_WRITE, + TS_MILESTONE_SERVER_FIRST_READ, + TS_MILESTONE_SERVER_READ_HEADER_DONE, + TS_MILESTONE_SERVER_CLOSE, + TS_MILESTONE_CACHE_OPEN_READ_BEGIN, + TS_MILESTONE_CACHE_OPEN_READ_END, + TS_MILESTONE_CACHE_OPEN_WRITE_BEGIN, + TS_MILESTONE_CACHE_OPEN_WRITE_END, + TS_MILESTONE_DNS_LOOKUP_BEGIN, + TS_MILESTONE_DNS_LOOKUP_END, + TS_MILESTONE_SM_START, + TS_MILESTONE_SM_FINISH, + TS_MILESTONE_PLUGIN_ACTIVE, + TS_MILESTONE_PLUGIN_TOTAL, + TS_MILESTONE_TLS_HANDSHAKE_START, + TS_MILESTONE_TLS_HANDSHAKE_END, + TS_MILESTONE_LAST_ENTRY + }; + + /* These type aliases are used with the corresponding TSMgmt*Get functions + for storing the values retrieved by those functions. For example, + TSMgmtCounterGet() retrieves an TSMgmtCounter. */ + using TSMgmtInt = int64_t; + using TSMgmtCounter = int64_t; + using TSMgmtFloat = float; + using TSMgmtString = char *; + + /// The source of a management value. + enum TSMgmtSource { + TS_MGMT_SOURCE_NULL, ///< No source / value not found. + TS_MGMT_SOURCE_DEFAULT, ///< Built in core default. + TS_MGMT_SOURCE_PLUGIN, ///< Plugin supplied default. + TS_MGMT_SOURCE_EXPLICIT, ///< Set by administrator (config file, external API, etc.) + TS_MGMT_SOURCE_ENV ///< Process environment variable. + }; + + /// The User Arg type, used for Txn/Ssn/VConn user argument slots + enum TSUserArgType { + TS_USER_ARGS_TXN, ///< Transaction based. + TS_USER_ARGS_SSN, ///< Session based + TS_USER_ARGS_VCONN, ///< VConnection based + TS_USER_ARGS_GLB, ///< Global based + TS_USER_ARGS_COUNT ///< Fake enum, # of valid entries. + }; + + /** An enumeration of HTTP version types for the priority functions that behave + * differently across HTTP protocols. */ + enum TSHttpPriorityType { + HTTP_PRIORITY_TYPE_HTTP_UNSPECIFIED = 1, + HTTP_PRIORITY_TYPE_HTTP_2, + HTTP_PRIORITY_TYPE_HTTP_3, + }; + + /** The abstract type of the various HTTP priority implementations. */ + struct TSHttpPriority { + /** The reference to the concrete HTTP priority implementation. This will be + * a value from TSHttpPriorityType. */ + uint8_t priority_type; + /** The space allocated for the concrete priority implementation. + * + * Note that this has to take padding into account. There is a static_assert + * in InkAPI.cc to verify that TSHttpPriority is at least as large as + * TSHttp2Priority. As other structures are added that are represented by + * TSHttpPriority add more static_asserts to verify that TSHttpPriority is as + * large as it needs to be. + */ + uint8_t data[7]; + }; + + /** A structure for HTTP/2 priority. * - * Note that this has to take padding into account. There is a static_assert - * in InkAPI.cc to verify that TSHttpPriority is at least as large as - * TSHttp2Priority. As other structures are added that are represented by - * TSHttpPriority add more static_asserts to verify that TSHttpPriority is as - * large as it needs to be. + * For an explanation of these terms with respect to HTTP/2, see RFC 7540, + * section 5.3. */ - uint8_t data[7]; -} TSHttpPriority; + struct TSHttp2Priority { + uint8_t priority_type; /** HTTP_PROTOCOL_TYPE_HTTP_2 */ + uint8_t weight; + /** The stream dependency. Per spec, see RFC 7540 section 6.2, this is 31 + * bits. We use a signed 32 bit structure to store either a valid dependency + * or -1 if the stream has no dependency. */ + int32_t stream_dependency; + }; + + using TSFile = struct tsapi_file *; + + using TSMLoc = struct tsapi_mloc *; + using TSMBuffer = struct tsapi_mbuffer *; + using TSHttpSsn = struct tsapi_httpssn *; + using TSHttpTxn = struct tsapi_httptxn *; + using TSSslConnection = struct tsapi_ssl_obj *; + using TSSslSession = struct tsapi_ssl_session *; + using TSHttpAltInfo = struct tsapi_httpaltinfo *; + using TSMimeParser = struct tsapi_mimeparser *; + using TSHttpParser = struct tsapi_httpparser *; + using TSCacheKey = struct tsapi_cachekey *; + using TSCacheHttpInfo = struct tsapi_cachehttpinfo *; + using TSCacheTxn = struct tsapi_cachetxn *; + using TSSslVerifyCTX = struct tsapi_x509_store_ctx *; + + using TSPortDescriptor = struct tsapi_port *; + using TSVIO = struct tsapi_vio *; + using TSThread = struct tsapi_thread *; + using TSEventThread = struct tsapi_event_thread *; + using TSSslX509 = struct tsapi_x509 *; + using TSMutex = struct tsapi_mutex *; + using TSConfig = struct tsapi_config *; + using TSCont = struct tsapi_cont *; + using TSVConn = struct tsapi_cont *; /* a VConn is really a specialized TSCont */ + using TSSslContext = struct tsapi_ssl_context *; + using TSAction = struct tsapi_action *; + using TSIOBuffer = struct tsapi_iobuffer *; + using TSIOBufferData = struct tsapi_iobufferdata *; + using TSIOBufferBlock = struct tsapi_bufferblock *; + using TSIOBufferReader = struct tsapi_bufferreader *; + using TSHostLookupResult = struct tsapi_hostlookupresult *; + using TSAIOCallback = struct tsapi_aiocallback *; + using TSAcceptor = struct tsapi_net_accept *; + using TSRemapPluginInfo = struct tsapi_remap_plugin_info *; + + using TSFetchSM = struct tsapi_fetchsm *; + + using TSThreadFunc = void *(*)(void *data); + using TSEventFunc = int (*)(TSCont contp, TSEvent event, void *edata); + using TSConfigDestroyFunc = void (*)(void *data); + + struct TSFetchEvent { + int success_event_id; + int failure_event_id; + int timeout_event_id; + }; + + struct TSFetchUrlParams { + const char *request; + int request_len; + int port; + struct sockaddr_storage ip; + TSCont contp; + TSFetchEvent events; + TSFetchWakeUpOptions options; + struct TSFetchUrlParams *next; + }; + using TSFetchUrlParams_t = TSFetchUrlParams; + + // This is a duplicate of the SSL_MAX_SSL_SESSION_ID_LENGTH constant + // Redefining here so we don't include the openssl/ssl.h file here + const int TS_SSL_MAX_SSL_SESSION_ID_LENGTH = 32; + + // This mirrors the internal data structure SSLSessionID + struct TSSslSessionID { + size_t len; + char bytes[TS_SSL_MAX_SSL_SESSION_ID_LENGTH]; + }; + + struct TSSecretID { + const char *cert_name; + size_t cert_name_len; + const char *key_name; + size_t key_name_len; + }; + + enum TSConnectType { TS_CONNECT_UNDEFINED, TS_CONNECT_PLUGIN, TS_CONNECT_LAST_ENTRY }; + + struct TSHttpConnectOptions { + TSConnectType connect_type; + struct sockaddr const *addr; + const char *tag; + int64_t id; + TSIOBufferSizeIndex buffer_index; + TSIOBufferWaterMark buffer_water_mark; + }; + + struct TSDbgCtl { + char volatile on; // Flag + char const *tag; + }; + + /* -------------------------------------------------------------------------- + URL schemes */ + extern const char *TS_URL_SCHEME_FILE; + extern const char *TS_URL_SCHEME_FTP; + extern const char *TS_URL_SCHEME_GOPHER; + extern const char *TS_URL_SCHEME_HTTP; + extern const char *TS_URL_SCHEME_HTTPS; + extern const char *TS_URL_SCHEME_MAILTO; + extern const char *TS_URL_SCHEME_NEWS; + extern const char *TS_URL_SCHEME_NNTP; + extern const char *TS_URL_SCHEME_PROSPERO; + extern const char *TS_URL_SCHEME_TELNET; + extern const char *TS_URL_SCHEME_TUNNEL; + extern const char *TS_URL_SCHEME_WAIS; + extern const char *TS_URL_SCHEME_PNM; + extern const char *TS_URL_SCHEME_RTSP; + extern const char *TS_URL_SCHEME_RTSPU; + extern const char *TS_URL_SCHEME_MMS; + extern const char *TS_URL_SCHEME_MMSU; + extern const char *TS_URL_SCHEME_MMST; + extern const char *TS_URL_SCHEME_WS; + extern const char *TS_URL_SCHEME_WSS; + + /* -------------------------------------------------------------------------- + URL scheme string lengths */ + extern int TS_URL_LEN_FILE; + extern int TS_URL_LEN_FTP; + extern int TS_URL_LEN_GOPHER; + extern int TS_URL_LEN_HTTP; + extern int TS_URL_LEN_HTTPS; + extern int TS_URL_LEN_MAILTO; + extern int TS_URL_LEN_NEWS; + extern int TS_URL_LEN_NNTP; + extern int TS_URL_LEN_PROSPERO; + extern int TS_URL_LEN_TELNET; + extern int TS_URL_LEN_WAIS; + extern int TS_URL_LEN_WS; + extern int TS_URL_LEN_WSS; + + /* -------------------------------------------------------------------------- + MIME fields */ + extern const char *TS_MIME_FIELD_ACCEPT; + extern const char *TS_MIME_FIELD_ACCEPT_CHARSET; + extern const char *TS_MIME_FIELD_ACCEPT_ENCODING; + extern const char *TS_MIME_FIELD_ACCEPT_LANGUAGE; + extern const char *TS_MIME_FIELD_ACCEPT_RANGES; + extern const char *TS_MIME_FIELD_AGE; + extern const char *TS_MIME_FIELD_ALLOW; + extern const char *TS_MIME_FIELD_APPROVED; + extern const char *TS_MIME_FIELD_AUTHORIZATION; + extern const char *TS_MIME_FIELD_BYTES; + extern const char *TS_MIME_FIELD_CACHE_CONTROL; + extern const char *TS_MIME_FIELD_CLIENT_IP; + extern const char *TS_MIME_FIELD_CONNECTION; + extern const char *TS_MIME_FIELD_CONTENT_BASE; + extern const char *TS_MIME_FIELD_CONTENT_ENCODING; + extern const char *TS_MIME_FIELD_CONTENT_LANGUAGE; + extern const char *TS_MIME_FIELD_CONTENT_LENGTH; + extern const char *TS_MIME_FIELD_CONTENT_LOCATION; + extern const char *TS_MIME_FIELD_CONTENT_MD5; + extern const char *TS_MIME_FIELD_CONTENT_RANGE; + extern const char *TS_MIME_FIELD_CONTENT_TYPE; + extern const char *TS_MIME_FIELD_CONTROL; + extern const char *TS_MIME_FIELD_COOKIE; + extern const char *TS_MIME_FIELD_DATE; + extern const char *TS_MIME_FIELD_DISTRIBUTION; + extern const char *TS_MIME_FIELD_ETAG; + extern const char *TS_MIME_FIELD_EXPECT; + extern const char *TS_MIME_FIELD_EXPIRES; + extern const char *TS_MIME_FIELD_FOLLOWUP_TO; + extern const char *TS_MIME_FIELD_FROM; + extern const char *TS_MIME_FIELD_HOST; + extern const char *TS_MIME_FIELD_IF_MATCH; + extern const char *TS_MIME_FIELD_IF_MODIFIED_SINCE; + extern const char *TS_MIME_FIELD_IF_NONE_MATCH; + extern const char *TS_MIME_FIELD_IF_RANGE; + extern const char *TS_MIME_FIELD_IF_UNMODIFIED_SINCE; + extern const char *TS_MIME_FIELD_KEEP_ALIVE; + extern const char *TS_MIME_FIELD_KEYWORDS; + extern const char *TS_MIME_FIELD_LAST_MODIFIED; + extern const char *TS_MIME_FIELD_LINES; + extern const char *TS_MIME_FIELD_LOCATION; + extern const char *TS_MIME_FIELD_MAX_FORWARDS; + extern const char *TS_MIME_FIELD_MESSAGE_ID; + extern const char *TS_MIME_FIELD_NEWSGROUPS; + extern const char *TS_MIME_FIELD_ORGANIZATION; + extern const char *TS_MIME_FIELD_PATH; + extern const char *TS_MIME_FIELD_PRAGMA; + extern const char *TS_MIME_FIELD_PROXY_AUTHENTICATE; + extern const char *TS_MIME_FIELD_PROXY_AUTHORIZATION; + extern const char *TS_MIME_FIELD_PROXY_CONNECTION; + extern const char *TS_MIME_FIELD_PUBLIC; + extern const char *TS_MIME_FIELD_RANGE; + extern const char *TS_MIME_FIELD_REFERENCES; + extern const char *TS_MIME_FIELD_REFERER; + extern const char *TS_MIME_FIELD_REPLY_TO; + extern const char *TS_MIME_FIELD_RETRY_AFTER; + extern const char *TS_MIME_FIELD_SENDER; + extern const char *TS_MIME_FIELD_SERVER; + extern const char *TS_MIME_FIELD_SET_COOKIE; + extern const char *TS_MIME_FIELD_STRICT_TRANSPORT_SECURITY; + extern const char *TS_MIME_FIELD_SUBJECT; + extern const char *TS_MIME_FIELD_SUMMARY; + extern const char *TS_MIME_FIELD_TE; + extern const char *TS_MIME_FIELD_TRANSFER_ENCODING; + extern const char *TS_MIME_FIELD_UPGRADE; + extern const char *TS_MIME_FIELD_USER_AGENT; + extern const char *TS_MIME_FIELD_VARY; + extern const char *TS_MIME_FIELD_VIA; + extern const char *TS_MIME_FIELD_WARNING; + extern const char *TS_MIME_FIELD_WWW_AUTHENTICATE; + extern const char *TS_MIME_FIELD_XREF; + extern const char *TS_MIME_FIELD_X_FORWARDED_FOR; + extern const char *TS_MIME_FIELD_FORWARDED; + + /* -------------------------------------------------------------------------- + MIME fields string lengths */ + extern int TS_MIME_LEN_ACCEPT; + extern int TS_MIME_LEN_ACCEPT_CHARSET; + extern int TS_MIME_LEN_ACCEPT_ENCODING; + extern int TS_MIME_LEN_ACCEPT_LANGUAGE; + extern int TS_MIME_LEN_ACCEPT_RANGES; + extern int TS_MIME_LEN_AGE; + extern int TS_MIME_LEN_ALLOW; + extern int TS_MIME_LEN_APPROVED; + extern int TS_MIME_LEN_AUTHORIZATION; + extern int TS_MIME_LEN_BYTES; + extern int TS_MIME_LEN_CACHE_CONTROL; + extern int TS_MIME_LEN_CLIENT_IP; + extern int TS_MIME_LEN_CONNECTION; + extern int TS_MIME_LEN_CONTENT_BASE; + extern int TS_MIME_LEN_CONTENT_ENCODING; + extern int TS_MIME_LEN_CONTENT_LANGUAGE; + extern int TS_MIME_LEN_CONTENT_LENGTH; + extern int TS_MIME_LEN_CONTENT_LOCATION; + extern int TS_MIME_LEN_CONTENT_MD5; + extern int TS_MIME_LEN_CONTENT_RANGE; + extern int TS_MIME_LEN_CONTENT_TYPE; + extern int TS_MIME_LEN_CONTROL; + extern int TS_MIME_LEN_COOKIE; + extern int TS_MIME_LEN_DATE; + extern int TS_MIME_LEN_DISTRIBUTION; + extern int TS_MIME_LEN_ETAG; + extern int TS_MIME_LEN_EXPECT; + extern int TS_MIME_LEN_EXPIRES; + extern int TS_MIME_LEN_FOLLOWUP_TO; + extern int TS_MIME_LEN_FROM; + extern int TS_MIME_LEN_HOST; + extern int TS_MIME_LEN_IF_MATCH; + extern int TS_MIME_LEN_IF_MODIFIED_SINCE; + extern int TS_MIME_LEN_IF_NONE_MATCH; + extern int TS_MIME_LEN_IF_RANGE; + extern int TS_MIME_LEN_IF_UNMODIFIED_SINCE; + extern int TS_MIME_LEN_KEEP_ALIVE; + extern int TS_MIME_LEN_KEYWORDS; + extern int TS_MIME_LEN_LAST_MODIFIED; + extern int TS_MIME_LEN_LINES; + extern int TS_MIME_LEN_LOCATION; + extern int TS_MIME_LEN_MAX_FORWARDS; + extern int TS_MIME_LEN_MESSAGE_ID; + extern int TS_MIME_LEN_NEWSGROUPS; + extern int TS_MIME_LEN_ORGANIZATION; + extern int TS_MIME_LEN_PATH; + extern int TS_MIME_LEN_PRAGMA; + extern int TS_MIME_LEN_PROXY_AUTHENTICATE; + extern int TS_MIME_LEN_PROXY_AUTHORIZATION; + extern int TS_MIME_LEN_PROXY_CONNECTION; + extern int TS_MIME_LEN_PUBLIC; + extern int TS_MIME_LEN_RANGE; + extern int TS_MIME_LEN_REFERENCES; + extern int TS_MIME_LEN_REFERER; + extern int TS_MIME_LEN_REPLY_TO; + extern int TS_MIME_LEN_RETRY_AFTER; + extern int TS_MIME_LEN_SENDER; + extern int TS_MIME_LEN_SERVER; + extern int TS_MIME_LEN_SET_COOKIE; + extern int TS_MIME_LEN_STRICT_TRANSPORT_SECURITY; + extern int TS_MIME_LEN_SUBJECT; + extern int TS_MIME_LEN_SUMMARY; + extern int TS_MIME_LEN_TE; + extern int TS_MIME_LEN_TRANSFER_ENCODING; + extern int TS_MIME_LEN_UPGRADE; + extern int TS_MIME_LEN_USER_AGENT; + extern int TS_MIME_LEN_VARY; + extern int TS_MIME_LEN_VIA; + extern int TS_MIME_LEN_WARNING; + extern int TS_MIME_LEN_WWW_AUTHENTICATE; + extern int TS_MIME_LEN_XREF; + extern int TS_MIME_LEN_X_FORWARDED_FOR; + extern int TS_MIME_LEN_FORWARDED; + + /* -------------------------------------------------------------------------- + HTTP values */ + extern const char *TS_HTTP_VALUE_BYTES; + extern const char *TS_HTTP_VALUE_CHUNKED; + extern const char *TS_HTTP_VALUE_CLOSE; + extern const char *TS_HTTP_VALUE_COMPRESS; + extern const char *TS_HTTP_VALUE_DEFLATE; + extern const char *TS_HTTP_VALUE_GZIP; + extern const char *TS_HTTP_VALUE_BROTLI; + extern const char *TS_HTTP_VALUE_IDENTITY; + extern const char *TS_HTTP_VALUE_KEEP_ALIVE; + extern const char *TS_HTTP_VALUE_MAX_AGE; + extern const char *TS_HTTP_VALUE_MAX_STALE; + extern const char *TS_HTTP_VALUE_MIN_FRESH; + extern const char *TS_HTTP_VALUE_MUST_REVALIDATE; + extern const char *TS_HTTP_VALUE_NONE; + extern const char *TS_HTTP_VALUE_NO_CACHE; + extern const char *TS_HTTP_VALUE_NO_STORE; + extern const char *TS_HTTP_VALUE_NO_TRANSFORM; + extern const char *TS_HTTP_VALUE_ONLY_IF_CACHED; + extern const char *TS_HTTP_VALUE_PRIVATE; + extern const char *TS_HTTP_VALUE_PROXY_REVALIDATE; + extern const char *TS_HTTP_VALUE_PUBLIC; + + /* -------------------------------------------------------------------------- + HTTP values string lengths */ + extern int TS_HTTP_LEN_BYTES; + extern int TS_HTTP_LEN_CHUNKED; + extern int TS_HTTP_LEN_CLOSE; + extern int TS_HTTP_LEN_COMPRESS; + extern int TS_HTTP_LEN_DEFLATE; + extern int TS_HTTP_LEN_GZIP; + extern int TS_HTTP_LEN_BROTLI; + extern int TS_HTTP_LEN_IDENTITY; + extern int TS_HTTP_LEN_KEEP_ALIVE; + extern int TS_HTTP_LEN_MAX_AGE; + extern int TS_HTTP_LEN_MAX_STALE; + extern int TS_HTTP_LEN_MIN_FRESH; + extern int TS_HTTP_LEN_MUST_REVALIDATE; + extern int TS_HTTP_LEN_NONE; + extern int TS_HTTP_LEN_NO_CACHE; + extern int TS_HTTP_LEN_NO_STORE; + extern int TS_HTTP_LEN_NO_TRANSFORM; + extern int TS_HTTP_LEN_ONLY_IF_CACHED; + extern int TS_HTTP_LEN_PRIVATE; + extern int TS_HTTP_LEN_PROXY_REVALIDATE; + extern int TS_HTTP_LEN_PUBLIC; + + /* -------------------------------------------------------------------------- + HTTP methods */ + extern const char *TS_HTTP_METHOD_CONNECT; + extern const char *TS_HTTP_METHOD_DELETE; + extern const char *TS_HTTP_METHOD_GET; + extern const char *TS_HTTP_METHOD_HEAD; + extern const char *TS_HTTP_METHOD_OPTIONS; + extern const char *TS_HTTP_METHOD_POST; + extern const char *TS_HTTP_METHOD_PURGE; + extern const char *TS_HTTP_METHOD_PUT; + extern const char *TS_HTTP_METHOD_TRACE; + extern const char *TS_HTTP_METHOD_PUSH; + + /* -------------------------------------------------------------------------- + HTTP methods string lengths */ + extern int TS_HTTP_LEN_CONNECT; + extern int TS_HTTP_LEN_DELETE; + extern int TS_HTTP_LEN_GET; + extern int TS_HTTP_LEN_HEAD; + extern int TS_HTTP_LEN_OPTIONS; + extern int TS_HTTP_LEN_POST; + extern int TS_HTTP_LEN_PURGE; + extern int TS_HTTP_LEN_PUT; + extern int TS_HTTP_LEN_TRACE; + extern int TS_HTTP_LEN_PUSH; + + /* -------------------------------------------------------------------------- + TLS Next Protocol well-known protocol names. */ + + extern const char *const TS_ALPN_PROTOCOL_HTTP_0_9; + extern const char *const TS_ALPN_PROTOCOL_HTTP_1_0; + extern const char *const TS_ALPN_PROTOCOL_HTTP_1_1; + extern const char *const TS_ALPN_PROTOCOL_HTTP_2_0; + extern const char *const TS_ALPN_PROTOCOL_HTTP_3; + extern const char *const TS_ALPN_PROTOCOL_HTTP_3_D29; + extern const char *const TS_ALPN_PROTOCOL_HTTP_QUIC; + extern const char *const TS_ALPN_PROTOCOL_HTTP_QUIC_D29; + + extern int TS_ALPN_PROTOCOL_INDEX_HTTP_0_9; + extern int TS_ALPN_PROTOCOL_INDEX_HTTP_1_0; + extern int TS_ALPN_PROTOCOL_INDEX_HTTP_1_1; + extern int TS_ALPN_PROTOCOL_INDEX_HTTP_2_0; + extern int TS_ALPN_PROTOCOL_INDEX_HTTP_3; + extern int TS_ALPN_PROTOCOL_INDEX_HTTP_QUIC; + + extern const char *const TS_ALPN_PROTOCOL_GROUP_HTTP; + extern const char *const TS_ALPN_PROTOCOL_GROUP_HTTP2; + + extern const char *const TS_PROTO_TAG_HTTP_1_0; + extern const char *const TS_PROTO_TAG_HTTP_1_1; + extern const char *const TS_PROTO_TAG_HTTP_2_0; + extern const char *const TS_PROTO_TAG_HTTP_3; + extern const char *const TS_PROTO_TAG_HTTP_QUIC; + extern const char *const TS_PROTO_TAG_TLS_1_3; + extern const char *const TS_PROTO_TAG_TLS_1_2; + extern const char *const TS_PROTO_TAG_TLS_1_1; + extern const char *const TS_PROTO_TAG_TLS_1_0; + extern const char *const TS_PROTO_TAG_TCP; + extern const char *const TS_PROTO_TAG_UDP; + extern const char *const TS_PROTO_TAG_IPV4; + extern const char *const TS_PROTO_TAG_IPV6; + + /* -------------------------------------------------------------------------- + MLoc Constants */ + /** + Use TS_NULL_MLOC as the parent in calls that require a parent + when an TSMLoc does not have a parent TSMLoc. For example if + the TSMLoc is obtained by a call to TSHttpTxnClientReqGet(), -/** A structure for HTTP/2 priority. - * - * For an explanation of these terms with respect to HTTP/2, see RFC 7540, - * section 5.3. - */ -typedef struct { - uint8_t priority_type; /** HTTP_PROTOCOL_TYPE_HTTP_2 */ - uint8_t weight; - /** The stream dependency. Per spec, see RFC 7540 section 6.2, this is 31 - * bits. We use a signed 32 bit structure to store either a valid dependency - * or -1 if the stream has no dependency. */ - int32_t stream_dependency; -} TSHttp2Priority; - -typedef struct tsapi_file *TSFile; - -typedef struct tsapi_mloc *TSMLoc; -typedef struct tsapi_mbuffer *TSMBuffer; -typedef struct tsapi_httpssn *TSHttpSsn; -typedef struct tsapi_httptxn *TSHttpTxn; -typedef struct tsapi_ssl_obj *TSSslConnection; -typedef struct tsapi_ssl_session *TSSslSession; -typedef struct tsapi_httpaltinfo *TSHttpAltInfo; -typedef struct tsapi_mimeparser *TSMimeParser; -typedef struct tsapi_httpparser *TSHttpParser; -typedef struct tsapi_cachekey *TSCacheKey; -typedef struct tsapi_cachehttpinfo *TSCacheHttpInfo; -typedef struct tsapi_cachetxn *TSCacheTxn; -typedef struct tsapi_x509_store_ctx *TSSslVerifyCTX; - -typedef struct tsapi_port *TSPortDescriptor; -typedef struct tsapi_vio *TSVIO; -typedef struct tsapi_thread *TSThread; -typedef struct tsapi_event_thread *TSEventThread; -typedef struct tsapi_x509 *TSSslX509; -typedef struct tsapi_mutex *TSMutex; -typedef struct tsapi_config *TSConfig; -typedef struct tsapi_cont *TSCont; -typedef struct tsapi_cont *TSVConn; /* a VConn is really a specialized TSCont */ -typedef struct tsapi_ssl_context *TSSslContext; -typedef struct tsapi_action *TSAction; -typedef struct tsapi_iobuffer *TSIOBuffer; -typedef struct tsapi_iobufferdata *TSIOBufferData; -typedef struct tsapi_bufferblock *TSIOBufferBlock; -typedef struct tsapi_bufferreader *TSIOBufferReader; -typedef struct tsapi_hostlookupresult *TSHostLookupResult; -typedef struct tsapi_aiocallback *TSAIOCallback; -typedef struct tsapi_net_accept *TSAcceptor; -typedef struct tsapi_remap_plugin_info *TSRemapPluginInfo; - -typedef struct tsapi_fetchsm *TSFetchSM; - -typedef void *(*TSThreadFunc)(void *data); -typedef int (*TSEventFunc)(TSCont contp, TSEvent event, void *edata); -typedef void (*TSConfigDestroyFunc)(void *data); - -typedef struct { - int success_event_id; - int failure_event_id; - int timeout_event_id; -} TSFetchEvent; - -typedef struct TSFetchUrlParams { - const char *request; - int request_len; - int port; - struct sockaddr_storage ip; - TSCont contp; - TSFetchEvent events; - TSFetchWakeUpOptions options; - struct TSFetchUrlParams *next; -} TSFetchUrlParams_t; - -// This is a duplicate of the SSL_MAX_SSL_SESSION_ID_LENGTH constant -// Redefining here so we don't include the openssl/ssl.h file here -#define TS_SSL_MAX_SSL_SESSION_ID_LENGTH 32 - -// This mirrors the internal data structure SSLSessionID -typedef struct TSSslSessionID_s { - size_t len; - char bytes[TS_SSL_MAX_SSL_SESSION_ID_LENGTH]; -} TSSslSessionID; - -typedef struct TSSecretID_s { - const char *cert_name; - size_t cert_name_len; - const char *key_name; - size_t key_name_len; -} TSSecretID; - -typedef enum { TS_CONNECT_UNDEFINED, TS_CONNECT_PLUGIN, TS_CONNECT_LAST_ENTRY } TSConnectType; - -typedef struct TSHttpConnectOptions_s { - TSConnectType connect_type; - struct sockaddr const *addr; - const char *tag; - int64_t id; - TSIOBufferSizeIndex buffer_index; - TSIOBufferWaterMark buffer_water_mark; -} TSHttpConnectOptions; - -typedef struct TSDbgCtl_s { - char volatile on; // Flag - char const *tag; -} TSDbgCtl; + */ + TSMLoc const TS_NULL_MLOC = nullptr; + + /* -------------------------------------------------------------------------- + HostStatus types */ + + enum TSHostStatus { + TS_HOST_STATUS_INIT, + TS_HOST_STATUS_DOWN, + TS_HOST_STATUS_UP, + }; + + /* MUST match proxy/HostStatus.h Reason. + * If a value is added here, it MUST be added there with the same value. + */ + enum TSHostStatusReason { + TS_HOST_STATUS_ACTIVE = 0x1, + TS_HOST_STATUS_LOCAL = 0x2, + TS_HOST_STATUS_MANUAL = 0x4, + TS_HOST_STATUS_SELF_DETECT = 0x8, + TS_HOST_STATUS_ALL = 0xf, + }; + + /* -------------------------------------------------------------------------- + Interface for the UUID APIs. https://www.ietf.org/rfc/rfc4122.txt. */ + enum TSUuidVersion { + TS_UUID_UNDEFINED = 0, + TS_UUID_V1 = 1, + TS_UUID_V2, + TS_UUID_V3, + TS_UUID_V4, /* At this point, this is the only implemented version (or variant) */ + TS_UUID_V5, + }; + + const int TS_UUID_STRING_LEN = 36; + const int TS_CRUUID_STRING_LEN = TS_UUID_STRING_LEN + 19 + 1; /* UUID-len + len(uint64_t) + '-' */ + using TSUuid = struct tsapi_uuid *; + + /* Various HTTP "control" modes */ + enum TSHttpCntlType { + TS_HTTP_CNTL_LOGGING_MODE, + TS_HTTP_CNTL_INTERCEPT_RETRY_MODE, + TS_HTTP_CNTL_RESPONSE_CACHEABLE, + TS_HTTP_CNTL_REQUEST_CACHEABLE, + TS_HTTP_CNTL_SERVER_NO_STORE, + TS_HTTP_CNTL_TXN_DEBUG, + TS_HTTP_CNTL_SKIP_REMAPPING + }; + + // JSONRPC 2.0 related interface. + using TSRPCProviderHandle = struct tsapi_rpcproviderhandle *; + using TSYaml = struct tsapi_yaml *; + + /// + /// @brief JSON-RPC Handler options + /// + /// This class holds information about how a handler will be managed and delivered when called. The JSON-RPC manager would use + /// this object to perform certain validation. + /// + struct TSRPCHandlerOptions { + struct Auth { + int restricted; ///< Tells the RPC Manager if the call can be delivered or not based on the config rules. + } auth; + }; + + /// Configuration field info related to a parsed YAML node. + /// + /// This contains information about the parsed record field. This will be passed back to the @a TSYAMLRecNodeHandler + /// when you call @a TSRecYAMLConfigParse. This class holds the record name as well as the YAML node in case the caller + /// wants to use this information to manipulate the record. + struct TSYAMLRecCfgFieldData { + const char *field_name; ///< YAML field name. null terminated + const char *record_name; ///< record name. null terminated + TSYaml value_node; ///< YAML::Node pointer. + }; + +} // end namespace c +} // end namespace tsapi + +using namespace ::tsapi::c; /* -------------------------------------------------------------------------- Init */ @@ -1108,7 +1515,8 @@ typedef struct TSDbgCtl_s { This function must be defined by all plugins. Traffic Server calls this initialization routine when it loads the plugin (at startup), and sets argc and argv appropriately based on the values - in plugin.config. + in plugin.config. (Functions linked dynamically, and called using + dlsym() must be undecorated / extern "C".) @param argc the number of initial values specified in plugin.config, plus one. If only the name of your plugin shared object is @@ -1119,399 +1527,9 @@ typedef struct TSDbgCtl_s { plugin.config. */ -extern tsapi void TSPluginInit(int argc, const char *argv[]); - -/* -------------------------------------------------------------------------- - URL schemes */ -extern tsapi const char *TS_URL_SCHEME_FILE; -extern tsapi const char *TS_URL_SCHEME_FTP; -extern tsapi const char *TS_URL_SCHEME_GOPHER; -extern tsapi const char *TS_URL_SCHEME_HTTP; -extern tsapi const char *TS_URL_SCHEME_HTTPS; -extern tsapi const char *TS_URL_SCHEME_MAILTO; -extern tsapi const char *TS_URL_SCHEME_NEWS; -extern tsapi const char *TS_URL_SCHEME_NNTP; -extern tsapi const char *TS_URL_SCHEME_PROSPERO; -extern tsapi const char *TS_URL_SCHEME_TELNET; -extern tsapi const char *TS_URL_SCHEME_TUNNEL; -extern tsapi const char *TS_URL_SCHEME_WAIS; -extern tsapi const char *TS_URL_SCHEME_PNM; -extern tsapi const char *TS_URL_SCHEME_RTSP; -extern tsapi const char *TS_URL_SCHEME_RTSPU; -extern tsapi const char *TS_URL_SCHEME_MMS; -extern tsapi const char *TS_URL_SCHEME_MMSU; -extern tsapi const char *TS_URL_SCHEME_MMST; -extern tsapi const char *TS_URL_SCHEME_WS; -extern tsapi const char *TS_URL_SCHEME_WSS; - -/* -------------------------------------------------------------------------- - URL scheme string lengths */ -extern tsapi int TS_URL_LEN_FILE; -extern tsapi int TS_URL_LEN_FTP; -extern tsapi int TS_URL_LEN_GOPHER; -extern tsapi int TS_URL_LEN_HTTP; -extern tsapi int TS_URL_LEN_HTTPS; -extern tsapi int TS_URL_LEN_MAILTO; -extern tsapi int TS_URL_LEN_NEWS; -extern tsapi int TS_URL_LEN_NNTP; -extern tsapi int TS_URL_LEN_PROSPERO; -extern tsapi int TS_URL_LEN_TELNET; -extern tsapi int TS_URL_LEN_WAIS; -extern tsapi int TS_URL_LEN_WS; -extern tsapi int TS_URL_LEN_WSS; - -/* -------------------------------------------------------------------------- - MIME fields */ -extern tsapi const char *TS_MIME_FIELD_ACCEPT; -extern tsapi const char *TS_MIME_FIELD_ACCEPT_CHARSET; -extern tsapi const char *TS_MIME_FIELD_ACCEPT_ENCODING; -extern tsapi const char *TS_MIME_FIELD_ACCEPT_LANGUAGE; -extern tsapi const char *TS_MIME_FIELD_ACCEPT_RANGES; -extern tsapi const char *TS_MIME_FIELD_AGE; -extern tsapi const char *TS_MIME_FIELD_ALLOW; -extern tsapi const char *TS_MIME_FIELD_APPROVED; -extern tsapi const char *TS_MIME_FIELD_AUTHORIZATION; -extern tsapi const char *TS_MIME_FIELD_BYTES; -extern tsapi const char *TS_MIME_FIELD_CACHE_CONTROL; -extern tsapi const char *TS_MIME_FIELD_CLIENT_IP; -extern tsapi const char *TS_MIME_FIELD_CONNECTION; -extern tsapi const char *TS_MIME_FIELD_CONTENT_BASE; -extern tsapi const char *TS_MIME_FIELD_CONTENT_ENCODING; -extern tsapi const char *TS_MIME_FIELD_CONTENT_LANGUAGE; -extern tsapi const char *TS_MIME_FIELD_CONTENT_LENGTH; -extern tsapi const char *TS_MIME_FIELD_CONTENT_LOCATION; -extern tsapi const char *TS_MIME_FIELD_CONTENT_MD5; -extern tsapi const char *TS_MIME_FIELD_CONTENT_RANGE; -extern tsapi const char *TS_MIME_FIELD_CONTENT_TYPE; -extern tsapi const char *TS_MIME_FIELD_CONTROL; -extern tsapi const char *TS_MIME_FIELD_COOKIE; -extern tsapi const char *TS_MIME_FIELD_DATE; -extern tsapi const char *TS_MIME_FIELD_DISTRIBUTION; -extern tsapi const char *TS_MIME_FIELD_ETAG; -extern tsapi const char *TS_MIME_FIELD_EXPECT; -extern tsapi const char *TS_MIME_FIELD_EXPIRES; -extern tsapi const char *TS_MIME_FIELD_FOLLOWUP_TO; -extern tsapi const char *TS_MIME_FIELD_FROM; -extern tsapi const char *TS_MIME_FIELD_HOST; -extern tsapi const char *TS_MIME_FIELD_IF_MATCH; -extern tsapi const char *TS_MIME_FIELD_IF_MODIFIED_SINCE; -extern tsapi const char *TS_MIME_FIELD_IF_NONE_MATCH; -extern tsapi const char *TS_MIME_FIELD_IF_RANGE; -extern tsapi const char *TS_MIME_FIELD_IF_UNMODIFIED_SINCE; -extern tsapi const char *TS_MIME_FIELD_KEEP_ALIVE; -extern tsapi const char *TS_MIME_FIELD_KEYWORDS; -extern tsapi const char *TS_MIME_FIELD_LAST_MODIFIED; -extern tsapi const char *TS_MIME_FIELD_LINES; -extern tsapi const char *TS_MIME_FIELD_LOCATION; -extern tsapi const char *TS_MIME_FIELD_MAX_FORWARDS; -extern tsapi const char *TS_MIME_FIELD_MESSAGE_ID; -extern tsapi const char *TS_MIME_FIELD_NEWSGROUPS; -extern tsapi const char *TS_MIME_FIELD_ORGANIZATION; -extern tsapi const char *TS_MIME_FIELD_PATH; -extern tsapi const char *TS_MIME_FIELD_PRAGMA; -extern tsapi const char *TS_MIME_FIELD_PROXY_AUTHENTICATE; -extern tsapi const char *TS_MIME_FIELD_PROXY_AUTHORIZATION; -extern tsapi const char *TS_MIME_FIELD_PROXY_CONNECTION; -extern tsapi const char *TS_MIME_FIELD_PUBLIC; -extern tsapi const char *TS_MIME_FIELD_RANGE; -extern tsapi const char *TS_MIME_FIELD_REFERENCES; -extern tsapi const char *TS_MIME_FIELD_REFERER; -extern tsapi const char *TS_MIME_FIELD_REPLY_TO; -extern tsapi const char *TS_MIME_FIELD_RETRY_AFTER; -extern tsapi const char *TS_MIME_FIELD_SENDER; -extern tsapi const char *TS_MIME_FIELD_SERVER; -extern tsapi const char *TS_MIME_FIELD_SET_COOKIE; -extern tsapi const char *TS_MIME_FIELD_STRICT_TRANSPORT_SECURITY; -extern tsapi const char *TS_MIME_FIELD_SUBJECT; -extern tsapi const char *TS_MIME_FIELD_SUMMARY; -extern tsapi const char *TS_MIME_FIELD_TE; -extern tsapi const char *TS_MIME_FIELD_TRANSFER_ENCODING; -extern tsapi const char *TS_MIME_FIELD_UPGRADE; -extern tsapi const char *TS_MIME_FIELD_USER_AGENT; -extern tsapi const char *TS_MIME_FIELD_VARY; -extern tsapi const char *TS_MIME_FIELD_VIA; -extern tsapi const char *TS_MIME_FIELD_WARNING; -extern tsapi const char *TS_MIME_FIELD_WWW_AUTHENTICATE; -extern tsapi const char *TS_MIME_FIELD_XREF; -extern tsapi const char *TS_MIME_FIELD_X_FORWARDED_FOR; -extern tsapi const char *TS_MIME_FIELD_FORWARDED; - -/* -------------------------------------------------------------------------- - MIME fields string lengths */ -extern tsapi int TS_MIME_LEN_ACCEPT; -extern tsapi int TS_MIME_LEN_ACCEPT_CHARSET; -extern tsapi int TS_MIME_LEN_ACCEPT_ENCODING; -extern tsapi int TS_MIME_LEN_ACCEPT_LANGUAGE; -extern tsapi int TS_MIME_LEN_ACCEPT_RANGES; -extern tsapi int TS_MIME_LEN_AGE; -extern tsapi int TS_MIME_LEN_ALLOW; -extern tsapi int TS_MIME_LEN_APPROVED; -extern tsapi int TS_MIME_LEN_AUTHORIZATION; -extern tsapi int TS_MIME_LEN_BYTES; -extern tsapi int TS_MIME_LEN_CACHE_CONTROL; -extern tsapi int TS_MIME_LEN_CLIENT_IP; -extern tsapi int TS_MIME_LEN_CONNECTION; -extern tsapi int TS_MIME_LEN_CONTENT_BASE; -extern tsapi int TS_MIME_LEN_CONTENT_ENCODING; -extern tsapi int TS_MIME_LEN_CONTENT_LANGUAGE; -extern tsapi int TS_MIME_LEN_CONTENT_LENGTH; -extern tsapi int TS_MIME_LEN_CONTENT_LOCATION; -extern tsapi int TS_MIME_LEN_CONTENT_MD5; -extern tsapi int TS_MIME_LEN_CONTENT_RANGE; -extern tsapi int TS_MIME_LEN_CONTENT_TYPE; -extern tsapi int TS_MIME_LEN_CONTROL; -extern tsapi int TS_MIME_LEN_COOKIE; -extern tsapi int TS_MIME_LEN_DATE; -extern tsapi int TS_MIME_LEN_DISTRIBUTION; -extern tsapi int TS_MIME_LEN_ETAG; -extern tsapi int TS_MIME_LEN_EXPECT; -extern tsapi int TS_MIME_LEN_EXPIRES; -extern tsapi int TS_MIME_LEN_FOLLOWUP_TO; -extern tsapi int TS_MIME_LEN_FROM; -extern tsapi int TS_MIME_LEN_HOST; -extern tsapi int TS_MIME_LEN_IF_MATCH; -extern tsapi int TS_MIME_LEN_IF_MODIFIED_SINCE; -extern tsapi int TS_MIME_LEN_IF_NONE_MATCH; -extern tsapi int TS_MIME_LEN_IF_RANGE; -extern tsapi int TS_MIME_LEN_IF_UNMODIFIED_SINCE; -extern tsapi int TS_MIME_LEN_KEEP_ALIVE; -extern tsapi int TS_MIME_LEN_KEYWORDS; -extern tsapi int TS_MIME_LEN_LAST_MODIFIED; -extern tsapi int TS_MIME_LEN_LINES; -extern tsapi int TS_MIME_LEN_LOCATION; -extern tsapi int TS_MIME_LEN_MAX_FORWARDS; -extern tsapi int TS_MIME_LEN_MESSAGE_ID; -extern tsapi int TS_MIME_LEN_NEWSGROUPS; -extern tsapi int TS_MIME_LEN_ORGANIZATION; -extern tsapi int TS_MIME_LEN_PATH; -extern tsapi int TS_MIME_LEN_PRAGMA; -extern tsapi int TS_MIME_LEN_PROXY_AUTHENTICATE; -extern tsapi int TS_MIME_LEN_PROXY_AUTHORIZATION; -extern tsapi int TS_MIME_LEN_PROXY_CONNECTION; -extern tsapi int TS_MIME_LEN_PUBLIC; -extern tsapi int TS_MIME_LEN_RANGE; -extern tsapi int TS_MIME_LEN_REFERENCES; -extern tsapi int TS_MIME_LEN_REFERER; -extern tsapi int TS_MIME_LEN_REPLY_TO; -extern tsapi int TS_MIME_LEN_RETRY_AFTER; -extern tsapi int TS_MIME_LEN_SENDER; -extern tsapi int TS_MIME_LEN_SERVER; -extern tsapi int TS_MIME_LEN_SET_COOKIE; -extern tsapi int TS_MIME_LEN_STRICT_TRANSPORT_SECURITY; -extern tsapi int TS_MIME_LEN_SUBJECT; -extern tsapi int TS_MIME_LEN_SUMMARY; -extern tsapi int TS_MIME_LEN_TE; -extern tsapi int TS_MIME_LEN_TRANSFER_ENCODING; -extern tsapi int TS_MIME_LEN_UPGRADE; -extern tsapi int TS_MIME_LEN_USER_AGENT; -extern tsapi int TS_MIME_LEN_VARY; -extern tsapi int TS_MIME_LEN_VIA; -extern tsapi int TS_MIME_LEN_WARNING; -extern tsapi int TS_MIME_LEN_WWW_AUTHENTICATE; -extern tsapi int TS_MIME_LEN_XREF; -extern tsapi int TS_MIME_LEN_X_FORWARDED_FOR; -extern tsapi int TS_MIME_LEN_FORWARDED; - -/* -------------------------------------------------------------------------- - HTTP values */ -extern tsapi const char *TS_HTTP_VALUE_BYTES; -extern tsapi const char *TS_HTTP_VALUE_CHUNKED; -extern tsapi const char *TS_HTTP_VALUE_CLOSE; -extern tsapi const char *TS_HTTP_VALUE_COMPRESS; -extern tsapi const char *TS_HTTP_VALUE_DEFLATE; -extern tsapi const char *TS_HTTP_VALUE_GZIP; -extern tsapi const char *TS_HTTP_VALUE_BROTLI; -extern tsapi const char *TS_HTTP_VALUE_IDENTITY; -extern tsapi const char *TS_HTTP_VALUE_KEEP_ALIVE; -extern tsapi const char *TS_HTTP_VALUE_MAX_AGE; -extern tsapi const char *TS_HTTP_VALUE_MAX_STALE; -extern tsapi const char *TS_HTTP_VALUE_MIN_FRESH; -extern tsapi const char *TS_HTTP_VALUE_MUST_REVALIDATE; -extern tsapi const char *TS_HTTP_VALUE_NONE; -extern tsapi const char *TS_HTTP_VALUE_NO_CACHE; -extern tsapi const char *TS_HTTP_VALUE_NO_STORE; -extern tsapi const char *TS_HTTP_VALUE_NO_TRANSFORM; -extern tsapi const char *TS_HTTP_VALUE_ONLY_IF_CACHED; -extern tsapi const char *TS_HTTP_VALUE_PRIVATE; -extern tsapi const char *TS_HTTP_VALUE_PROXY_REVALIDATE; -extern tsapi const char *TS_HTTP_VALUE_PUBLIC; - -/* -------------------------------------------------------------------------- - HTTP values string lengths */ -extern tsapi int TS_HTTP_LEN_BYTES; -extern tsapi int TS_HTTP_LEN_CHUNKED; -extern tsapi int TS_HTTP_LEN_CLOSE; -extern tsapi int TS_HTTP_LEN_COMPRESS; -extern tsapi int TS_HTTP_LEN_DEFLATE; -extern tsapi int TS_HTTP_LEN_GZIP; -extern tsapi int TS_HTTP_LEN_BROTLI; -extern tsapi int TS_HTTP_LEN_IDENTITY; -extern tsapi int TS_HTTP_LEN_KEEP_ALIVE; -extern tsapi int TS_HTTP_LEN_MAX_AGE; -extern tsapi int TS_HTTP_LEN_MAX_STALE; -extern tsapi int TS_HTTP_LEN_MIN_FRESH; -extern tsapi int TS_HTTP_LEN_MUST_REVALIDATE; -extern tsapi int TS_HTTP_LEN_NONE; -extern tsapi int TS_HTTP_LEN_NO_CACHE; -extern tsapi int TS_HTTP_LEN_NO_STORE; -extern tsapi int TS_HTTP_LEN_NO_TRANSFORM; -extern tsapi int TS_HTTP_LEN_ONLY_IF_CACHED; -extern tsapi int TS_HTTP_LEN_PRIVATE; -extern tsapi int TS_HTTP_LEN_PROXY_REVALIDATE; -extern tsapi int TS_HTTP_LEN_PUBLIC; - -/* -------------------------------------------------------------------------- - HTTP methods */ -extern tsapi const char *TS_HTTP_METHOD_CONNECT; -extern tsapi const char *TS_HTTP_METHOD_DELETE; -extern tsapi const char *TS_HTTP_METHOD_GET; -extern tsapi const char *TS_HTTP_METHOD_HEAD; -extern tsapi const char *TS_HTTP_METHOD_OPTIONS; -extern tsapi const char *TS_HTTP_METHOD_POST; -extern tsapi const char *TS_HTTP_METHOD_PURGE; -extern tsapi const char *TS_HTTP_METHOD_PUT; -extern tsapi const char *TS_HTTP_METHOD_TRACE; -extern tsapi const char *TS_HTTP_METHOD_PUSH; +extern "C" void TSPluginInit(int argc, const char *argv[]); -/* -------------------------------------------------------------------------- - HTTP methods string lengths */ -extern tsapi int TS_HTTP_LEN_CONNECT; -extern tsapi int TS_HTTP_LEN_DELETE; -extern tsapi int TS_HTTP_LEN_GET; -extern tsapi int TS_HTTP_LEN_HEAD; -extern tsapi int TS_HTTP_LEN_OPTIONS; -extern tsapi int TS_HTTP_LEN_POST; -extern tsapi int TS_HTTP_LEN_PURGE; -extern tsapi int TS_HTTP_LEN_PUT; -extern tsapi int TS_HTTP_LEN_TRACE; -extern tsapi int TS_HTTP_LEN_PUSH; - -/* -------------------------------------------------------------------------- - TLS Next Protocol well-known protocol names. */ - -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_0_9; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_1_0; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_1_1; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_2_0; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_3; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_3_D29; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_QUIC; -extern tsapi const char *const TS_ALPN_PROTOCOL_HTTP_QUIC_D29; - -extern tsapi int TS_ALPN_PROTOCOL_INDEX_HTTP_0_9; -extern tsapi int TS_ALPN_PROTOCOL_INDEX_HTTP_1_0; -extern tsapi int TS_ALPN_PROTOCOL_INDEX_HTTP_1_1; -extern tsapi int TS_ALPN_PROTOCOL_INDEX_HTTP_2_0; -extern tsapi int TS_ALPN_PROTOCOL_INDEX_HTTP_3; -extern tsapi int TS_ALPN_PROTOCOL_INDEX_HTTP_QUIC; - -extern tsapi const char *const TS_ALPN_PROTOCOL_GROUP_HTTP; -extern tsapi const char *const TS_ALPN_PROTOCOL_GROUP_HTTP2; - -extern tsapi const char *const TS_PROTO_TAG_HTTP_1_0; -extern tsapi const char *const TS_PROTO_TAG_HTTP_1_1; -extern tsapi const char *const TS_PROTO_TAG_HTTP_2_0; -extern tsapi const char *const TS_PROTO_TAG_HTTP_3; -extern tsapi const char *const TS_PROTO_TAG_HTTP_QUIC; -extern tsapi const char *const TS_PROTO_TAG_TLS_1_3; -extern tsapi const char *const TS_PROTO_TAG_TLS_1_2; -extern tsapi const char *const TS_PROTO_TAG_TLS_1_1; -extern tsapi const char *const TS_PROTO_TAG_TLS_1_0; -extern tsapi const char *const TS_PROTO_TAG_TCP; -extern tsapi const char *const TS_PROTO_TAG_UDP; -extern tsapi const char *const TS_PROTO_TAG_IPV4; -extern tsapi const char *const TS_PROTO_TAG_IPV6; - -/* -------------------------------------------------------------------------- - MLoc Constants */ -/** - Use TS_NULL_MLOC as the parent in calls that require a parent - when an TSMLoc does not have a parent TSMLoc. For example if - the TSMLoc is obtained by a call to TSHttpTxnClientReqGet(), - - */ -#define TS_NULL_MLOC ((TSMLoc)0) - -/* -------------------------------------------------------------------------- - HostStatus types */ - -typedef enum { - TS_HOST_STATUS_INIT, - TS_HOST_STATUS_DOWN, - TS_HOST_STATUS_UP, -} TSHostStatus; - -/* MUST match proxy/HostStatus.h Reason. - * If a value is added here, it MUST be added there with the same value. - */ -typedef enum { - TS_HOST_STATUS_ACTIVE = 0x1, - TS_HOST_STATUS_LOCAL = 0x2, - TS_HOST_STATUS_MANUAL = 0x4, - TS_HOST_STATUS_SELF_DETECT = 0x8, - TS_HOST_STATUS_ALL = 0xf, -} TSHostStatusReason; - -/* -------------------------------------------------------------------------- - Interface for the UUID APIs. https://www.ietf.org/rfc/rfc4122.txt. */ -typedef enum { - TS_UUID_UNDEFINED = 0, - TS_UUID_V1 = 1, - TS_UUID_V2, - TS_UUID_V3, - TS_UUID_V4, /* At this point, this is the only implemented version (or variant) */ - TS_UUID_V5, -} TSUuidVersion; - -#define TS_UUID_STRING_LEN 36 -#define TS_CRUUID_STRING_LEN (TS_UUID_STRING_LEN + 19 + 1) /* UUID-len + len(uint64_t) + '-' */ -typedef struct tsapi_uuid *TSUuid; - -/* Various HTTP "control" modes */ -typedef enum { - TS_HTTP_CNTL_LOGGING_MODE, - TS_HTTP_CNTL_INTERCEPT_RETRY_MODE, - TS_HTTP_CNTL_RESPONSE_CACHEABLE, - TS_HTTP_CNTL_REQUEST_CACHEABLE, - TS_HTTP_CNTL_SERVER_NO_STORE, - TS_HTTP_CNTL_TXN_DEBUG, - TS_HTTP_CNTL_SKIP_REMAPPING -} TSHttpCntlType; - -#ifdef __cplusplus namespace ts { - static const int NO_FD = -1; ///< No or invalid file descriptor. -} -#endif - -// JSONRPC 2.0 related interface. -typedef struct tsapi_rpcproviderhandle *TSRPCProviderHandle; -typedef struct tsapi_yaml *TSYaml; - -/// -/// @brief JSON-RPC Handler options -/// -/// This class holds information about how a handler will be managed and delivered when called. The JSON-RPC manager would use this -/// object to perform certain validation. -/// -typedef struct TSRPCHandlerOptions_s { - struct Auth { - int restricted; ///< Tells the RPC Manager if the call can be delivered or not based on the config rules. - } auth; -} TSRPCHandlerOptions; - -/// Configuration field info related to a parsed YAML node. -/// -/// This contains information about the parsed record field. This will be passed back to the @a TSYAMLRecNodeHandler -/// when you call @a TSRecYAMLConfigParse. This class holds the record name as well as the YAML node in case the caller -/// wants to use this information to manipulate the record. -typedef struct TSYAMLCfgFieldData_s { - const char *field_name; ///< YAML field name. null terminated - const char *record_name; ///< record name. null terminated - TSYaml value_node; ///< YAML::Node pointer. -} TSYAMLRecCfgFieldData; - -#ifdef __cplusplus +static const int NO_FD = -1; ///< No or invalid file descriptor. } -#endif /* __cplusplus */ diff --git a/include/ts/experimental.h b/include/ts/experimental.h index 759d1768dc0..cdcbbfbe803 100644 --- a/include/ts/experimental.h +++ b/include/ts/experimental.h @@ -31,350 +31,352 @@ #pragma once -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -typedef enum { - TS_FETCH_EVENT_EXT_HEAD_READY = -1, - TS_FETCH_EVENT_EXT_HEAD_DONE = -2, - TS_FETCH_EVENT_EXT_BODY_READY = -3, - TS_FETCH_EVENT_EXT_BODY_DONE = -4 -} TSFetchEventExt; - -typedef enum { - TS_FETCH_FLAGS_NONE = 0, // do nothing - TS_FETCH_FLAGS_STREAM = 1 << 1, // enable stream IO - TS_FETCH_FLAGS_DECHUNK = 1 << 2, // dechunk body content - TS_FETCH_FLAGS_NEWLOCK = 1 << 3, // allocate new lock for fetch sm - TS_FETCH_FLAGS_NOT_INTERNAL_REQUEST = 1 << 4, // Allow this fetch to be created as a non-internal request. - TS_FETCH_FLAGS_SKIP_REMAP = 1 << 5, // Skip remapping and allow requesting arbitary URL -} TSFetchFlags; - -/* Forward declaration of in_addr, any user of these APIs should probably - include net/netinet.h or whatever is appropriate on the platform. */ -struct in_addr; - -/* Cache APIs that are not yet fully supported and/or frozen nor complete. */ -tsapi TSReturnCode TSCacheBufferInfoGet(TSCacheTxn txnp, uint64_t *length, uint64_t *offset); - -tsapi TSCacheHttpInfo TSCacheHttpInfoCreate(); -tsapi void TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj); -tsapi void TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj); -tsapi void TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj); -tsapi void TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj); -tsapi void TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey key); -tsapi void TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size); -tsapi int TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length); -tsapi time_t TSCacheHttpInfoReqSentTimeGet(TSCacheHttpInfo infop); -tsapi time_t TSCacheHttpInfoRespReceivedTimeGet(TSCacheHttpInfo infop); -int64_t TSCacheHttpInfoSizeGet(TSCacheHttpInfo infop); - -/* Do not edit these apis, used internally */ -tsapi int TSMimeHdrFieldEqual(TSMBuffer bufp, TSMLoc hdr_obj, TSMLoc field1, TSMLoc field2); -tsapi TSReturnCode TSHttpTxnHookRegisteredFor(TSHttpTxn txnp, TSHttpHookID id, TSEventFunc funcp); - -/* Protocols APIs */ -tsapi void TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop); - -/* The rest is from the old "froze" private API include, we should consider - moving some of these over to ts/ts.h as well. TODO */ - -/**************************************************************************** - * Test if cache ready to accept request for a specific type of data - ****************************************************************************/ -tsapi TSReturnCode TSCacheDataTypeReady(TSCacheDataType type, int *is_ready); - -/**************************************************************************** - * When reenabling a txn in error, keep the connection open in case - * of keepalive. - ****************************************************************************/ -tsapi void TSHttpTxnClientKeepaliveSet(TSHttpTxn txnp, int set); - -/**************************************************************************** - * Allow to set the body of a POST request. - ****************************************************************************/ -tsapi void TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength); - -tsapi TSReturnCode TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time); - -/* ===== Cache ===== */ -tsapi TSReturnCode TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type); - -/* ===== Utility ===== */ -/**************************************************************************** - * Create a random number - * Return random integer between and - ****************************************************************************/ -tsapi unsigned int TSrandom(void); - -/**************************************************************************** - * Create a random double - * Return random double between and - ****************************************************************************/ -tsapi double TSdrandom(void); - -/* ===== CacheHttpInfo ===== */ - -tsapi TSCacheHttpInfo TSCacheHttpInfoCopy(TSCacheHttpInfo infop); -tsapi void TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *offset); -tsapi void TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *offset); -tsapi void TSCacheHttpInfoDestroy(TSCacheHttpInfo infop); - -/* Get Arbitrary Txn info such as cache lookup details etc as defined in TSHttpTxnInfoKey */ -/** - Return the particular txn info requested. - - @param txnp the transaction pointer - @param key the requested txn info. - @param TSMgmtInt a pointer to a integer where the return value is stored - - @return @c TS_SUCCESS if the requested info is supported, TS_ERROR otherwise - -*/ -tsapi TSReturnCode TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value); - -/**************************************************************************** - * TSHttpTxnCacheLookupCountGet - * Return: TS_SUCCESS/TS_ERROR - ****************************************************************************/ -tsapi TSReturnCode TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count); -tsapi TSReturnCode TSHttpTxnServerRespIgnore(TSHttpTxn txnp); -tsapi TSReturnCode TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event); -tsapi TSReturnCode TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close); - -/**************************************************************************** - * ?? - * Return ?? - ****************************************************************************/ -tsapi int TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp); - -/**************************************************************************** - * ?? - * Return ?? - ****************************************************************************/ -tsapi void TSHttpTxnOverwriteExpireTime(TSHttpTxn txnp, time_t expire_time); - -/**************************************************************************** - * ?? - * Return ?? - ****************************************************************************/ -tsapi TSReturnCode TSHttpTxnUpdateCachedObject(TSHttpTxn txnp); - -/**************************************************************************** - * ?? - * TODO: This returns a LookingUp_t value, we need to SDK'ify it. - ****************************************************************************/ -tsapi int TSHttpTxnLookingUpTypeGet(TSHttpTxn txnp); - -/** - Attempt to attach the contp continuation to sockets that have already been - opened by the traffic Server and defined as belonging to plugins (based on - records.yaml configuration). If a connection is successfully accepted, - the TS_EVENT_NET_ACCEPT is delivered to the continuation. The event - data will be a valid TSVConn bound to the accepted connection. - In order to configure such a socket, add the "plugin" keyword to a port - in proxy.config.http.server_ports like "8082:plugin" - Transparency/IP settings can also be defined, but a port cannot have - both the "ssl" or "plugin" keywords configured. - - Need to update records.yaml comments on proxy.config.http.server_ports - when this option is promoted from experimental. - */ -tsapi TSReturnCode TSPluginDescriptorAccept(TSCont contp); - -/** - Opens a network connection to the host specified by the 'to' sockaddr - spoofing the client addr to equal the 'from' sockaddr. - If the connection is successfully opened, contp - is called back with the event TS_EVENT_NET_CONNECT and the new - network vconnection will be passed in the event data parameter. - If the connection is not successful, contp is called back with - the event TS_EVENT_NET_CONNECT_FAILED. - - Note: It is possible to receive TS_EVENT_NET_CONNECT - even if the connection failed, because of the implementation of - network sockets in the underlying operating system. There is an - exception: if a plugin tries to open a connection to a port on - its own host machine, then TS_EVENT_NET_CONNECT is sent only - if the connection is successfully opened. In general, however, - your plugin needs to look for an TS_EVENT_VCONN_WRITE_READY to - be sure that the connection is successfully opened. - - @return TSAction which allows you to check if the connection is complete, - or cancel the attempt to connect. - - */ -tsapi TSAction TSNetConnectTransparent( - TSCont contp, /**< continuation that is called back when the attempted net connection either succeeds or fails. */ - struct sockaddr const *from, /**< Address to spoof as connection origin */ - struct sockaddr const *to /**< Address to which to connect. */ -); +namespace tsapi +{ +namespace c +{ + + enum TSFetchEventExt { + TS_FETCH_EVENT_EXT_HEAD_READY = -1, + TS_FETCH_EVENT_EXT_HEAD_DONE = -2, + TS_FETCH_EVENT_EXT_BODY_READY = -3, + TS_FETCH_EVENT_EXT_BODY_DONE = -4 + }; + + enum TSFetchFlags { + TS_FETCH_FLAGS_NONE = 0, // do nothing + TS_FETCH_FLAGS_STREAM = 1 << 1, // enable stream IO + TS_FETCH_FLAGS_DECHUNK = 1 << 2, // dechunk body content + TS_FETCH_FLAGS_NEWLOCK = 1 << 3, // allocate new lock for fetch sm + TS_FETCH_FLAGS_NOT_INTERNAL_REQUEST = 1 << 4, // Allow this fetch to be created as a non-internal request. + TS_FETCH_FLAGS_SKIP_REMAP = 1 << 5, // Skip remapping and allow requesting arbitary URL + }; + + /* Forward declaration of in_addr, any user of these APIs should probably + include net/netinet.h or whatever is appropriate on the platform. */ + struct in_addr; + + /* Cache APIs that are not yet fully supported and/or frozen nor complete. */ + TSReturnCode TSCacheBufferInfoGet(TSCacheTxn txnp, uint64_t *length, uint64_t *offset); + + TSCacheHttpInfo TSCacheHttpInfoCreate(); + void TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj); + void TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj); + void TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj); + void TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj); + void TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey key); + void TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size); + int TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length); + time_t TSCacheHttpInfoReqSentTimeGet(TSCacheHttpInfo infop); + time_t TSCacheHttpInfoRespReceivedTimeGet(TSCacheHttpInfo infop); + int64_t TSCacheHttpInfoSizeGet(TSCacheHttpInfo infop); + + /* Do not edit these apis, used internally */ + int TSMimeHdrFieldEqual(TSMBuffer bufp, TSMLoc hdr_obj, TSMLoc field1, TSMLoc field2); + TSReturnCode TSHttpTxnHookRegisteredFor(TSHttpTxn txnp, TSHttpHookID id, TSEventFunc funcp); + + /* Protocols APIs */ + void TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop); + + /* The rest is from the old "froze" private API include, we should consider + moving some of these over to ts/ts.h as well. TODO */ + + /**************************************************************************** + * Test if cache ready to accept request for a specific type of data + ****************************************************************************/ + TSReturnCode TSCacheDataTypeReady(TSCacheDataType type, int *is_ready); + + /**************************************************************************** + * When reenabling a txn in error, keep the connection open in case + * of keepalive. + ****************************************************************************/ + void TSHttpTxnClientKeepaliveSet(TSHttpTxn txnp, int set); + + /**************************************************************************** + * Allow to set the body of a POST request. + ****************************************************************************/ + void TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength); + + TSReturnCode TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time); + + /* ===== Cache ===== */ + TSReturnCode TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type); + + /* ===== Utility ===== */ + /**************************************************************************** + * Create a random number + * Return random integer between and + ****************************************************************************/ + unsigned int TSrandom(void); + + /**************************************************************************** + * Create a random double + * Return random double between and + ****************************************************************************/ + double TSdrandom(void); + + /* ===== CacheHttpInfo ===== */ + + TSCacheHttpInfo TSCacheHttpInfoCopy(TSCacheHttpInfo infop); + void TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *offset); + void TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *offset); + void TSCacheHttpInfoDestroy(TSCacheHttpInfo infop); + + /* Get Arbitrary Txn info such as cache lookup details etc as defined in TSHttpTxnInfoKey */ + /** + Return the particular txn info requested. + + @param txnp the transaction pointer + @param key the requested txn info. + @param TSMgmtInt a pointer to a integer where the return value is stored + + @return @c TS_SUCCESS if the requested info is supported, TS_ERROR otherwise + + */ + TSReturnCode TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value); + + /**************************************************************************** + * TSHttpTxnCacheLookupCountGet + * Return: TS_SUCCESS/TS_ERROR + ****************************************************************************/ + TSReturnCode TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count); + TSReturnCode TSHttpTxnServerRespIgnore(TSHttpTxn txnp); + TSReturnCode TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event); + TSReturnCode TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close); + + /**************************************************************************** + * ?? + * Return ?? + ****************************************************************************/ + int TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp); + + /**************************************************************************** + * ?? + * Return ?? + ****************************************************************************/ + void TSHttpTxnOverwriteExpireTime(TSHttpTxn txnp, time_t expire_time); + + /**************************************************************************** + * ?? + * Return ?? + ****************************************************************************/ + TSReturnCode TSHttpTxnUpdateCachedObject(TSHttpTxn txnp); + + /**************************************************************************** + * ?? + * TODO: This returns a LookingUp_t value, we need to SDK'ify it. + ****************************************************************************/ + int TSHttpTxnLookingUpTypeGet(TSHttpTxn txnp); + + /** + Attempt to attach the contp continuation to sockets that have already been + opened by the traffic Server and defined as belonging to plugins (based on + records.yaml configuration). If a connection is successfully accepted, + the TS_EVENT_NET_ACCEPT is delivered to the continuation. The event + data will be a valid TSVConn bound to the accepted connection. + In order to configure such a socket, add the "plugin" keyword to a port + in proxy.config.http.server_ports like "8082:plugin" + Transparency/IP settings can also be defined, but a port cannot have + both the "ssl" or "plugin" keywords configured. + + Need to update records.yaml comments on proxy.config.http.server_ports + when this option is promoted from experimental. + */ + TSReturnCode TSPluginDescriptorAccept(TSCont contp); + + /** + Opens a network connection to the host specified by the 'to' sockaddr + spoofing the client addr to equal the 'from' sockaddr. + If the connection is successfully opened, contp + is called back with the event TS_EVENT_NET_CONNECT and the new + network vconnection will be passed in the event data parameter. + If the connection is not successful, contp is called back with + the event TS_EVENT_NET_CONNECT_FAILED. + + Note: It is possible to receive TS_EVENT_NET_CONNECT + even if the connection failed, because of the implementation of + network sockets in the underlying operating system. There is an + exception: if a plugin tries to open a connection to a port on + its own host machine, then TS_EVENT_NET_CONNECT is sent only + if the connection is successfully opened. In general, however, + your plugin needs to look for an TS_EVENT_VCONN_WRITE_READY to + be sure that the connection is successfully opened. + + @return TSAction which allows you to check if the connection is complete, + or cancel the attempt to connect. + + */ + TSAction TSNetConnectTransparent( + TSCont contp, /**< continuation that is called back when the attempted net connection either succeeds or fails. */ + struct sockaddr const *from, /**< Address to spoof as connection origin */ + struct sockaddr const *to /**< Address to which to connect. */ + ); /* ===== Matcher Utils ===== */ #define TS_MATCHER_LINE_INVALID 0 -typedef struct tsapi_matcheline *TSMatcherLine; - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi char *TSMatcherReadIntoBuffer(char *file_name, int *file_len); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi char *TSMatcherTokLine(char *buffer, char **last); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi char *TSMatcherExtractIPRange(char *match_str, uint32_t *addr1, uint32_t *addr2); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi TSMatcherLine TSMatcherLineCreate(); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi void TSMatcherLineDestroy(TSMatcherLine ml); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi const char *TSMatcherParseSrcIPConfigLine(char *line, TSMatcherLine ml); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi char *TSMatcherLineName(TSMatcherLine ml, int element); - -/**************************************************************************** - * ?? - * Return - ****************************************************************************/ -tsapi char *TSMatcherLineValue(TSMatcherLine ml, int element); - -tsapi TSReturnCode TSMgmtConfigFileAdd(const char *parent, const char *fileName); -/* ---------------------------------------------------------------------- - * Interfaces used by Wireless group - * ---------------------------------------------------------------------- */ - -#define TS_NET_EVENT_DATAGRAM_READ_COMPLETE TS_EVENT_INTERNAL_206 -#define TS_NET_EVENT_DATAGRAM_READ_ERROR TS_EVENT_INTERNAL_207 -#define TS_NET_EVENT_DATAGRAM_WRITE_COMPLETE TS_EVENT_INTERNAL_208 -#define TS_NET_EVENT_DATAGRAM_WRITE_ERROR TS_EVENT_INTERNAL_209 -#define TS_NET_EVENT_DATAGRAM_READ_READY TS_EVENT_INTERNAL_210 -#define TS_NET_EVENT_DATAGRAM_OPEN TS_EVENT_INTERNAL_211 -#define TS_NET_EVENT_DATAGRAM_ERROR TS_EVENT_INTERNAL_212 - -/** - * Extended FetchSM's AIPs - */ - -/* - * Create FetchSM, this API will enable stream IO automatically. - * - * @param contp: continuation to be callbacked. - * @param method: request method. - * @param url: scheme://host[:port]/path. - * @param version: client http version, eg: "HTTP/1.1". - * @param client_addr: client addr sent to log. - * @param flags: can be bitwise OR of several TSFetchFlags. - * - * return TSFetchSM which should be destroyed by TSFetchDestroy(). - */ -tsapi TSFetchSM TSFetchCreate(TSCont contp, const char *method, const char *url, const char *version, - struct sockaddr const *client_addr, int flags); - -/* - * Set fetch flags to FetchSM Context - * - * @param fetch_sm: returned value of TSFetchCreate(). - * @param flags: can be bitwise OR of several TSFetchFlags. - * - * return void - */ -tsapi void TSFetchFlagSet(TSFetchSM fetch_sm, int flags); - -/* - * Create FetchSM, this API will enable stream IO automatically. - * - * @param fetch_sm: returned value of TSFetchCreate(). - * @param name: name of header. - * @param name_len: len of name. - * @param value: value of header. - * @param name_len: len of value. - * - * return TSFetchSM which should be destroyed by TSFetchDestroy(). - */ -tsapi void TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char *value, int value_len); - -/* - * Write data to FetchSM - * - * @param fetch_sm: returned value of TSFetchCreate(). - * @param data/len: data to be written to fetch sm. - */ -tsapi void TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len); - -/* - * Read up to *len* bytes from FetchSM into *buf*. - * - * @param fetch_sm: returned value of TSFetchCreate(). - * @param buf/len: buffer to contain data from fetch sm. - */ -tsapi ssize_t TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len); - -/* - * Launch FetchSM to do http request, before calling this API, - * you should append http request header into fetch sm through - * TSFetchWriteData() API - * - * @param fetch_sm: comes from returned value of TSFetchCreate(). - */ -tsapi void TSFetchLaunch(TSFetchSM fetch_sm); - -/* - * Destroy FetchSM - * - * @param fetch_sm: returned value of TSFetchCreate(). - */ -tsapi void TSFetchDestroy(TSFetchSM fetch_sm); - -/* - * Set user-defined data in FetchSM - */ -tsapi void TSFetchUserDataSet(TSFetchSM fetch_sm, void *data); - -/* - * Get user-defined data in FetchSM - */ -tsapi void *TSFetchUserDataGet(TSFetchSM fetch_sm); - -/* - * Get client response hdr mbuffer - */ -tsapi TSMBuffer TSFetchRespHdrMBufGet(TSFetchSM fetch_sm); - -/* - * Get client response hdr mloc - */ -tsapi TSMLoc TSFetchRespHdrMLocGet(TSFetchSM fetch_sm); - -/* - * Print as a MIME header date string. - */ -tsapi TSReturnCode TSMimeFormatDate(time_t const value_time, char *const value_str, int *const value_len); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ + using TSMatcherLine = struct tsapi_matcheline *; + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + char *TSMatcherReadIntoBuffer(char *file_name, int *file_len); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + char *TSMatcherTokLine(char *buffer, char **last); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + char *TSMatcherExtractIPRange(char *match_str, uint32_t *addr1, uint32_t *addr2); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + TSMatcherLine TSMatcherLineCreate(); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + void TSMatcherLineDestroy(TSMatcherLine ml); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + const char *TSMatcherParseSrcIPConfigLine(char *line, TSMatcherLine ml); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + char *TSMatcherLineName(TSMatcherLine ml, int element); + + /**************************************************************************** + * ?? + * Return + ****************************************************************************/ + char *TSMatcherLineValue(TSMatcherLine ml, int element); + + TSReturnCode TSMgmtConfigFileAdd(const char *parent, const char *fileName); + /* ---------------------------------------------------------------------- + * Interfaces used by Wireless group + * ---------------------------------------------------------------------- */ + + TSEvent const TS_NET_EVENT_DATAGRAM_READ_COMPLETE = TS_EVENT_INTERNAL_206; + TSEvent const TS_NET_EVENT_DATAGRAM_READ_ERROR = TS_EVENT_INTERNAL_207; + TSEvent const TS_NET_EVENT_DATAGRAM_WRITE_COMPLETE = TS_EVENT_INTERNAL_208; + TSEvent const TS_NET_EVENT_DATAGRAM_WRITE_ERROR = TS_EVENT_INTERNAL_209; + TSEvent const TS_NET_EVENT_DATAGRAM_READ_READY = TS_EVENT_INTERNAL_210; + TSEvent const TS_NET_EVENT_DATAGRAM_OPEN = TS_EVENT_INTERNAL_211; + TSEvent const TS_NET_EVENT_DATAGRAM_ERROR = TS_EVENT_INTERNAL_212; + + /** + * Extended FetchSM's AIPs + */ + + /* + * Create FetchSM, this API will enable stream IO automatically. + * + * @param contp: continuation to be callbacked. + * @param method: request method. + * @param url: scheme://host[:port]/path. + * @param version: client http version, eg: "HTTP/1.1". + * @param client_addr: client addr sent to log. + * @param flags: can be bitwise OR of several TSFetchFlags. + * + * return TSFetchSM which should be destroyed by TSFetchDestroy(). + */ + TSFetchSM TSFetchCreate(TSCont contp, const char *method, const char *url, const char *version, + struct sockaddr const *client_addr, int flags); + + /* + * Set fetch flags to FetchSM Context + * + * @param fetch_sm: returned value of TSFetchCreate(). + * @param flags: can be bitwise OR of several TSFetchFlags. + * + * return void + */ + void TSFetchFlagSet(TSFetchSM fetch_sm, int flags); + + /* + * Create FetchSM, this API will enable stream IO automatically. + * + * @param fetch_sm: returned value of TSFetchCreate(). + * @param name: name of header. + * @param name_len: len of name. + * @param value: value of header. + * @param name_len: len of value. + * + * return TSFetchSM which should be destroyed by TSFetchDestroy(). + */ + void TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char *value, int value_len); + + /* + * Write data to FetchSM + * + * @param fetch_sm: returned value of TSFetchCreate(). + * @param data/len: data to be written to fetch sm. + */ + void TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len); + + /* + * Read up to *len* bytes from FetchSM into *buf*. + * + * @param fetch_sm: returned value of TSFetchCreate(). + * @param buf/len: buffer to contain data from fetch sm. + */ + ssize_t TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len); + + /* + * Launch FetchSM to do http request, before calling this API, + * you should append http request header into fetch sm through + * TSFetchWriteData() API + * + * @param fetch_sm: comes from returned value of TSFetchCreate(). + */ + void TSFetchLaunch(TSFetchSM fetch_sm); + + /* + * Destroy FetchSM + * + * @param fetch_sm: returned value of TSFetchCreate(). + */ + void TSFetchDestroy(TSFetchSM fetch_sm); + + /* + * Set user-defined data in FetchSM + */ + void TSFetchUserDataSet(TSFetchSM fetch_sm, void *data); + + /* + * Get user-defined data in FetchSM + */ + void *TSFetchUserDataGet(TSFetchSM fetch_sm); + + /* + * Get client response hdr mbuffer + */ + TSMBuffer TSFetchRespHdrMBufGet(TSFetchSM fetch_sm); + + /* + * Get client response hdr mloc + */ + TSMLoc TSFetchRespHdrMLocGet(TSFetchSM fetch_sm); + + /* + * Print as a MIME header date string. + */ + TSReturnCode TSMimeFormatDate(time_t const value_time, char *const value_str, int *const value_len); + +} // end namespace c +} // end namespace tsapi + +using namespace ::tsapi::c; diff --git a/include/ts/parentselectdefs.h b/include/ts/parentselectdefs.h index e4ca8b4ed72..d6f7a9d37a1 100644 --- a/include/ts/parentselectdefs.h +++ b/include/ts/parentselectdefs.h @@ -31,31 +31,41 @@ #include #include -// Plugins may set this to indicate how to retry. -// -// If handled is false, then no plugin set it, and Core will proceed to do its own thing. -// -// If handled is true, core will not do any parent processing, markdown, or anything else, -// but will use the values in this for whether to use the existing response or make another request, -// and what that request should look like. -// -// See the API functions which take this for ownership requirements of pointers, like hostname. -// -// hostname is the hostname to use for the next request. It must be null-terminated. -// hostname_len is the length of hostname, not including the terminating null. -// -typedef struct { - // TODO this shouldn't be necessary - plugins should manipulate the response as they see fit, - // core shouldn't "know" if it was a "success" or "failure," only the response or retry data/action. - // But for now, core needs to know, for reasons. - const char *hostname; - size_t hostname_len; - in_port_t port; - bool fail; - bool is_retry; - bool nextHopExists; - bool responseIsRetryable; - bool goDirect; - bool parentIsProxy; - bool no_cache; -} TSResponseAction; +namespace tsapi +{ +namespace c +{ + + // Plugins may set this to indicate how to retry. + // + // If handled is false, then no plugin set it, and Core will proceed to do its own thing. + // + // If handled is true, core will not do any parent processing, markdown, or anything else, + // but will use the values in this for whether to use the existing response or make another request, + // and what that request should look like. + // + // See the API functions which take this for ownership requirements of pointers, like hostname. + // + // hostname is the hostname to use for the next request. It must be null-terminated. + // hostname_len is the length of hostname, not including the terminating null. + // + struct TSResponseAction { + // TODO this shouldn't be necessary - plugins should manipulate the response as they see fit, + // core shouldn't "know" if it was a "success" or "failure," only the response or retry data/action. + // But for now, core needs to know, for reasons. + const char *hostname; + size_t hostname_len; + in_port_t port; + bool fail; + bool is_retry; + bool nextHopExists; + bool responseIsRetryable; + bool goDirect; + bool parentIsProxy; + bool no_cache; + }; + +} // end namespace c +} // end namespace tsapi + +using namespace ::tsapi::c; diff --git a/include/ts/remap.h b/include/ts/remap.h index 2d3d31b8e10..94385859f62 100644 --- a/include/ts/remap.h +++ b/include/ts/remap.h @@ -23,72 +23,76 @@ #pragma once -#ifndef tsapi -#define tsapi -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ +namespace tsapi +{ +namespace c +{ #define TSREMAP_VMAJOR 3 /* major version number */ #define TSREMAP_VMINOR 0 /* minor version number */ #define TSREMAP_VERSION ((TSREMAP_VMAJOR << 16) | TSREMAP_VMINOR) -typedef struct _tsremap_api_info { - unsigned long size; /* in: sizeof(struct _tsremap_api_info) */ - unsigned long tsremap_version; /* in: TS supported version ((major << 16) | minor) */ - TSRemapPluginInfo plugin_info; /* in: Pointer to the internal RemapPluginInst */ -} TSRemapInterface; - -typedef struct _tm_remap_request_info { - /* Important: You should *not* release these buf pointers or TSMLocs from your plugin! */ - - /* these URL mloc's are read only, use normal ts/ts.h APIs for accessing */ - TSMLoc mapFromUrl; - TSMLoc mapToUrl; - - /* the request URL mloc and buffer pointers are read-write. You can read and modify the - requestUrl using normal ts/ts.h APIs, which is how you change the destination URL. */ - TSMLoc requestUrl; - - /* requestBufp and requestHdrp are the equivalent of calling TSHttpTxnClientReqGet(). */ - TSMBuffer requestBufp; - TSMLoc requestHdrp; - - /* 0 - don't redirect, 1 - use the (new)request URL as a redirect */ - int redirect; -} TSRemapRequestInfo; - -/* This is the type returned by the TSRemapDoRemap() callback */ -typedef enum { - TSREMAP_NO_REMAP = 0, /* No remapping was done, continue with next in chain */ - TSREMAP_DID_REMAP = 1, /* Remapping was done, continue with next in chain */ - TSREMAP_NO_REMAP_STOP = 2, /* No remapping was done, and stop plugin chain evaluation */ - TSREMAP_DID_REMAP_STOP = 3, /* Remapping was done, but stop plugin chain evaluation */ - - /* In the future, the following error codes can also be used: - -400 to -499 - -500 to -599 - .... - This would allow a plugin to generate an error page. Right now, - setting the return code to any negative number is equivalent to TSREMAP_NO_REMAP */ - TSREMAP_ERROR = -1 /* Some error, that should generate an error page */ -} TSRemapStatus; - -/* Status code passed to the plugin by TSRemapPostConfigReload() signaling - * (1) if the configuration reload was successful and - * (2) if (1) is successful show if the plugin was part of the new configuration */ -typedef enum { - TSREMAP_CONFIG_RELOAD_FAILURE = 0, /* notify the plugin that configuration parsing failed */ - TSREMAP_CONFIG_RELOAD_SUCCESS_PLUGIN_USED = 1, /* configuration parsing succeeded and plugin was used by the new configuration */ - TSREMAP_CONFIG_RELOAD_SUCCESS_PLUGIN_UNUSED = - 2 /* configuration parsing succeeded but plugin was NOT used by the new configuration */ -} TSRemapReloadStatus; + struct TSRemapInterface { + unsigned long size; /* in: sizeof(struct _tsremap_api_info) */ + unsigned long tsremap_version; /* in: TS supported version ((major << 16) | minor) */ + TSRemapPluginInfo plugin_info; /* in: Pointer to the internal RemapPluginInst */ + }; + + struct TSRemapRequestInfo { + /* Important: You should *not* release these buf pointers or TSMLocs from your plugin! */ + + /* these URL mloc's are read only, use normal ts/ts.h APIs for accessing */ + TSMLoc mapFromUrl; + TSMLoc mapToUrl; + + /* the request URL mloc and buffer pointers are read-write. You can read and modify the + requestUrl using normal ts/ts.h APIs, which is how you change the destination URL. */ + TSMLoc requestUrl; + + /* requestBufp and requestHdrp are the equivalent of calling TSHttpTxnClientReqGet(). */ + TSMBuffer requestBufp; + TSMLoc requestHdrp; + + /* 0 - don't redirect, 1 - use the (new)request URL as a redirect */ + int redirect; + }; + + /* This is the type returned by the TSRemapDoRemap() callback */ + enum TSRemapStatus { + TSREMAP_NO_REMAP = 0, /* No remapping was done, continue with next in chain */ + TSREMAP_DID_REMAP = 1, /* Remapping was done, continue with next in chain */ + TSREMAP_NO_REMAP_STOP = 2, /* No remapping was done, and stop plugin chain evaluation */ + TSREMAP_DID_REMAP_STOP = 3, /* Remapping was done, but stop plugin chain evaluation */ + + /* In the future, the following error codes can also be used: + -400 to -499 + -500 to -599 + .... + This would allow a plugin to generate an error page. Right now, + setting the return code to any negative number is equivalent to TSREMAP_NO_REMAP */ + TSREMAP_ERROR = -1 /* Some error, that should generate an error page */ + }; + + /* Status code passed to the plugin by TSRemapPostConfigReload() signaling + * (1) if the configuration reload was successful and + * (2) if (1) is successful show if the plugin was part of the new configuration */ + enum TSRemapReloadStatus { + TSREMAP_CONFIG_RELOAD_FAILURE = 0, /* notify the plugin that configuration parsing failed */ + TSREMAP_CONFIG_RELOAD_SUCCESS_PLUGIN_USED = + 1, /* configuration parsing succeeded and plugin was used by the new configuration */ + TSREMAP_CONFIG_RELOAD_SUCCESS_PLUGIN_UNUSED = + 2 /* configuration parsing succeeded but plugin was NOT used by the new configuration */ + }; + +} // end namespace c +} // end namespace tsapi + +using namespace ::tsapi::c; /* ---------------------------------------------------------------------------------- These are the entry points a plugin can implement. Note that TSRemapInit() and - TSRemapDoRemap() are both required. + TSRemapDoRemap() are both required. (These functions are called from TS using dlsym(), + so they must be undecorated / extern "C".) ---------------------------------------------------------------------------------- */ @@ -97,7 +101,7 @@ typedef enum { Return: TS_SUCCESS TS_ERROR - error, errbuf can include error message from plugin */ -tsapi TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size); +extern "C" TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size); /* This gets called every time before remap.config is reloaded. This is complementary to TSRemapInit() which gets called when the plugin is first loaded. @@ -107,7 +111,7 @@ tsapi TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int err Params: none Return: none */ -tsapi void TSRemapPreConfigReload(void); +extern "C" void TSRemapPreConfigReload(void); /* This gets called every time afterremap.config is reloaded. This is complementary to TSRemapInit() which gets called when the plugin is first loaded. @@ -119,7 +123,7 @@ tsapi void TSRemapPreConfigReload(void); TS_ERROR - (re)load failed. Return: none */ -tsapi void TSRemapPostConfigReload(TSRemapReloadStatus reloadStatus); +extern "C" void TSRemapPostConfigReload(TSRemapReloadStatus reloadStatus); /* Remap new request Mandatory interface function. @@ -129,11 +133,11 @@ tsapi void TSRemapPostConfigReload(TSRemapReloadStatus reloadStatus); TSREMAP_NO_REMAP_STOP - No remapping was done, and stop plugin chain evaluation TSREMAP_DID_REMAP_STOP - Remapping was done, but stop plugin chain evaluation */ -tsapi TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri); +extern "C" TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri); /* Plugin shutdown, called when plugin is unloaded. Optional function. */ -tsapi void TSRemapDone(void); +extern "C" void TSRemapDone(void); /* Plugin new instance. Create new plugin processing entry for unique remap record. First two arguments in argv vector are - fromURL and toURL from remap record. @@ -141,16 +145,12 @@ tsapi void TSRemapDone(void); Return: TS_SUCCESS TS_ERROR - instance creation error */ -tsapi TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size); -tsapi void TSRemapDeleteInstance(void *); +extern "C" TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size); +extern "C" void TSRemapDeleteInstance(void *); /* Check response code from Origin Server os_response_type -> TSServerState Remap API plugin can use InkAPI function calls inside TSRemapDoRemap() Return: none */ -tsapi void TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ +extern "C" void TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type); diff --git a/include/ts/ts.h b/include/ts/ts.h index 0aaa54a7c64..6e300b5ff51 100644 --- a/include/ts/ts.h +++ b/include/ts/ts.h @@ -29,2169 +29,2197 @@ #pragma once -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* -------------------------------------------------------------------------- - Memory */ -#define TSmalloc(s) _TSmalloc((s), TS_RES_MEM_PATH) -#define TSrealloc(p, s) _TSrealloc((p), (s), TS_RES_MEM_PATH) -#define TSstrdup(p) _TSstrdup((p), -1, TS_RES_MEM_PATH) -#define TSstrndup(p, n) _TSstrdup((p), (n), TS_RES_MEM_PATH) -#define TSstrlcpy(d, s, l) _TSstrlcpy((d), (s), (l)) -#define TSstrlcat(d, s, l) _TSstrlcat((d), (s), (l)) -#define TSfree(p) _TSfree(p) - -tsapi void *_TSmalloc(size_t size, const char *path); -tsapi void *_TSrealloc(void *ptr, size_t size, const char *path); -tsapi char *_TSstrdup(const char *str, int64_t length, const char *path); -tsapi size_t _TSstrlcpy(char *dst, const char *str, size_t siz); -tsapi size_t _TSstrlcat(char *dst, const char *str, size_t siz); -tsapi void _TSfree(void *ptr); - -/* -------------------------------------------------------------------------- - Component object handles */ -/** - Releases the TSMLoc mloc created from the TSMLoc parent. - If there is no parent TSMLoc, use TS_NULL_MLOC. - - @param bufp marshal buffer containing the TSMLoc handle to be - released. - @param parent location of the parent object from which the handle - was created. - @param mloc location of the handle to be released. - - */ -tsapi TSReturnCode TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc); - -/* -------------------------------------------------------------------------- - Install and plugin locations */ -/** - Gets the path of the directory in which Traffic Server is installed. - Use this function to specify the location of files that the - plugin uses. - - @return pointer to Traffic Server install directory. - - */ -tsapi const char *TSInstallDirGet(void); - -/** - Gets the path of the directory of Traffic Server configuration. - - @return pointer to Traffic Server configuration directory. - - */ -tsapi const char *TSConfigDirGet(void); - -/** - Gets the path of the directory of Traffic Server runtime. - - @return pointer to Traffic Server runtime directory. - - */ -tsapi const char *TSRuntimeDirGet(void); - -/** - Gets the path of the plugin directory relative to the Traffic Server - install directory. For example, to open the file "config_ui.txt" in - the plugin directory: - - @code - TSfopen("TSPluginInstallDirGet()/TSPluginDirGet()/config_ui.txt"); - @endcode - - @return pointer to plugin directory relative to Traffic Server install - directory. - - */ -tsapi const char *TSPluginDirGet(void); - -/* -------------------------------------------------------------------------- - Traffic Server Version */ -/** - Gets the version of Traffic Server currently running. Use this - function to make sure that the plugin version and Traffic Server - version are compatible. See the SDK sample code for usage. - - @return pointer to version of Traffic Server running the plugin. - - */ -tsapi const char *TSTrafficServerVersionGet(void); - -/** Get the major version of Traffic Server currently running. - This is the same as the first element of the string - returned by @c TSTrafficServerVersionGet - - @return The major version as an integer. - */ -int TSTrafficServerVersionGetMajor(void); - -/** Get the minor version of Traffic Server currently running. - This is the same as the second element of the string - returned by @c TSTrafficServerVersionGet - - @return The minor version as an integer. - */ -int TSTrafficServerVersionGetMinor(void); - -/** Get the patch version of Traffic Server currently running. - This is the same as the third element of the string - returned by @c TSTrafficServerVersionGet - - @return The patch version as an integer. - */ -int TSTrafficServerVersionGetPatch(void); - -/* -------------------------------------------------------------------------- - Plugin registration */ - -/** - This function registers your plugin with a particular version - of Traffic Server SDK. Use this function to make sure that the - Traffic Server version currently running also supports your plugin. - See the SDK sample code for usage. - - @param plugin_info contains registration information about your - plugin. See TSPluginRegistrationInfo. - @return TS_ERROR if the plugin registration failed. - - */ -tsapi TSReturnCode TSPluginRegister(const TSPluginRegistrationInfo *plugin_info); - -/** - This function provides the ability to enable/disable programmatically - the plugin dynamic reloading when the same Dynamic Shared Object (DSO) - is also used as a remap plugin. This overrides `proxy.config.plugin.dynamic_reload_mode` - configuration variable. - - @param enabled boolean flag. 0/false will disable the reload on the caller plugin. - @return TS_ERROR if the function is not called from within TSPluginInit or if TS is - unable to get the canonical path from the plugin's path. TS_SUCCESS otherwise. - - @note This function should be called from within TSPluginInit - */ -tsapi TSReturnCode TSPluginDSOReloadEnable(int enabled); - -/* -------------------------------------------------------------------------- - Files */ -/** - Opens a file for reading or writing and returns a descriptor for - accessing the file. The current implementation cannot open a file - for both reading or writing. See the SDK Programmer's Guide for - sample code. - - @param filename file to be opened. - @param mode specifies whether to open the file for reading or - writing. If mode is "r" then the file is opened for reading. - If mode is "w" then the file is opened for writing. Currently - "r" and "w" are the only two valid modes for opening a file. - @return descriptor for the file that TSfopen opens. Descriptors of - type TSFile can be greater than 256. - - */ -tsapi TSFile TSfopen(const char *filename, const char *mode); - -/** - Closes the file to which filep points and frees the data structures - and buffers associated with it. If the file was opened for writing, - any pending data is flushed. - - @param filep file to be closed. - - */ -tsapi void TSfclose(TSFile filep); - -/** - Attempts to read length bytes of data from the file pointed to by - filep into the buffer buf. - - @param filep name of the file to read from. - @param buf buffer to read into. - @param length amount of data to read, in bytes. - @return number of bytes read. If end of the file, it returns 0. - If the file was not opened for reading or if an error occurs - while reading the file, it returns -1. - - */ -tsapi ssize_t TSfread(TSFile filep, void *buf, size_t length); - -/** - Attempts to write length bytes of data from the buffer buf - to the file filep. Make sure that filep is open for writing. - You might want to check the number of bytes written (TSfwrite() - returns this value) against the value of length. If it is less, - there might be insufficient space on disk, for example. - - @param filep file to write into. - @param buf buffer containing the data to be written. - @param length amount of data to write to filep, in bytes. - @return number of bytes written to filep. If the file was not - opened for writing, it returns -1. If an error occurs while - writing, it returns the number of bytes successfully written. - - */ -tsapi ssize_t TSfwrite(TSFile filep, const void *buf, size_t length); - -/** - Flushes pending data that has been buffered up in memory from - previous calls to TSfwrite(). - - @param filep file to flush. - - */ -tsapi void TSfflush(TSFile filep); - -/** - Reads a line from the file pointed to by filep into the buffer buf. - Lines are terminated by a line feed character, '\n'. The line - placed in the buffer includes the line feed character and is - terminated with a NULL. If the line is longer than length bytes - then only the first length-minus-1 bytes are placed in buf. - - @param filep file to read from. - @param buf buffer to read into. - @param length size of the buffer to read into. - @return pointer to the string read into the buffer buf. - - */ -tsapi char *TSfgets(TSFile filep, char *buf, size_t length); - -/* -------------------------------------------------------------------------- - Error logging */ -/** - Writes printf-style error messages to the Traffic Server error - log. One advantage of TSError over printf is that each call is - atomically placed into the error log and is not garbled with other - error entries. This is not an issue in single-threaded programs - but is a definite nuisance in multi-threaded programs. - - @param fmt printf format description. - @param ... argument for the printf format description. - - Note: Your log monitoring (e.g. Splunk) needs to alert Ops of log - messages that contain ' ALERT: ' or ' EMERGENCY: ', these require - immediate attention. - -*/ -tsapi void TSStatus(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log information -tsapi void TSNote(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log significant information -tsapi void TSWarning(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log concerning information -tsapi void TSError(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log operational failure, fail CI -tsapi void TSFatal(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log recoverable crash, fail CI, exit & restart -tsapi void TSAlert(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log recoverable crash, fail CI, exit & restart, Ops attention -tsapi void TSEmergency(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log unrecoverable crash, fail CI, exit, Ops attention - -/* -------------------------------------------------------------------------- - Assertions */ -tsapi void _TSReleaseAssert(const char *txt, const char *f, int l) TS_NORETURN; -tsapi int _TSAssert(const char *txt, const char *f, int l); - -#define TSReleaseAssert(EX) ((void)((EX) ? (void)0 : _TSReleaseAssert(#EX, __FILE__, __LINE__))) - -#define TSAssert(EX) (void)((EX) || (_TSAssert(#EX, __FILE__, __LINE__))) - -/* -------------------------------------------------------------------------- - Marshal buffers */ -/** - Creates a new marshal buffer and initializes the reference count - to 1. - - */ -tsapi TSMBuffer TSMBufferCreate(void); - -/** - Ignores the reference count and destroys the marshal buffer bufp. - The internal data buffer associated with the marshal buffer is - also destroyed if the marshal buffer allocated it. - - @param bufp marshal buffer to be destroyed. - - */ -tsapi TSReturnCode TSMBufferDestroy(TSMBuffer bufp); - -/* -------------------------------------------------------------------------- - URLs */ -/** - Creates a new URL within the marshal buffer bufp. Returns a - location for the URL within the marshal buffer. - - @param bufp marshal buffer containing the new URL. - @param locp pointer to a TSMLoc to store the MLoc into. - - */ -tsapi TSReturnCode TSUrlCreate(TSMBuffer bufp, TSMLoc *locp); - -/** - Copies the URL located at src_url within src_bufp to a URL - location within the marshal buffer dest_bufp, and returns the - TSMLoc location of the copied URL. Unlike TSUrlCopy(), you do - not have to create the destination URL before cloning. Release - the returned TSMLoc handle with a call to TSHandleMLocRelease(). - - @param dest_bufp marshal buffer containing the cloned URL. - @param src_bufp marshal buffer containing the URL to be cloned. - @param src_url location of the URL to be cloned, within the marshal - buffer src_bufp. - @param locp pointer to a TSMLoc to store the MLoc into. - - */ -tsapi TSReturnCode TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp); - -/** - Copies the contents of the URL at location src_loc within the - marshal buffer src_bufp to the location dest_loc within the marshal - buffer dest_bufp. TSUrlCopy() works correctly even if src_bufp - and dest_bufp point to different marshal buffers. Important: create - the destination URL before copying into it. Use TSUrlCreate(). - - @param dest_bufp marshal buffer to contain the copied URL. - @param dest_offset location of the URL to be copied. - @param src_bufp marshal buffer containing the source URL. - @param src_offset location of the source URL within src_bufp. - - */ -tsapi TSReturnCode TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset); - -/** - Formats a URL stored in an TSMBuffer into an TSIOBuffer. - - @param bufp marshal buffer contain the URL to be printed. - @param offset location of the URL within bufp. - @param iobufp destination TSIOBuffer for the URL. - - */ -tsapi void TSUrlPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp); - -/** - Parses a URL. The start pointer is both an input and an output - parameter and marks the start of the URL to be parsed. After - a successful parse, the start pointer equals the end pointer. - The end pointer must be one byte after the last character you - want to parse. The URL parsing routine assumes that everything - between start and end is part of the URL. It is up to higher level - parsing routines, such as TSHttpHdrParseReq(), to determine the - actual end of the URL. Returns TS_PARSE_ERROR if an error occurs, - otherwise TS_PARSE_DONE is returned to indicate success. - - @param bufp marshal buffer containing the URL to be parsed. - @param offset location of the URL to be parsed. - @param start points to the start of the URL to be parsed AND at - the end of a successful parse it will equal the end pointer. - @param end must be one byte after the last character. - @return TS_PARSE_ERROR or TS_PARSE_DONE. - - */ -tsapi TSParseResult TSUrlParse(TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); - -/** - Calculates the length of the URL located at url_loc within the - marshal buffer bufp if it were returned as a string. This length - is the same as the length returned by TSUrlStringGet(). - - @param bufp marshal buffer containing the URL whose length you want. - @param offset location of the URL within the marshal buffer bufp. - @return string length of the URL. - - */ -tsapi int TSUrlLengthGet(TSMBuffer bufp, TSMLoc offset); - -/** - Constructs a string representation of the URL located at url_loc - within bufp. TSUrlStringGet() stores the length of the allocated - string in the parameter length. This is the same length that - TSUrlLengthGet() returns. The returned string is allocated by a - call to TSmalloc(). It should be freed by a call to TSfree(). - The length parameter must be present, providing storage for the - URL string length value. - Note: To get the effective URL from a request, use the alternative - TSHttpTxnEffectiveUrlStringGet or - TSHttpHdrEffectiveUrlBufGet APIs. - - @param bufp marshal buffer containing the URL you want to get. - @param offset location of the URL within bufp. - @param length string length of the URL. - @return The URL as a string. - - */ -tsapi char *TSUrlStringGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Retrieves the scheme portion of the URL located at url_loc within - the marshal buffer bufp. TSUrlSchemeGet() places the length of - the string in the length argument. If the length is NULL then no - attempt is made to dereference it. - - @param bufp marshal buffer storing the URL. - @param offset location of the URL within bufp. - @param length length of the returned string. - @return The scheme portion of the URL, as a string. - - */ -tsapi const char *TSUrlRawSchemeGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Retrieves the scheme portion of the URL located at url_loc within - the marshal buffer bufp. TSUrlSchemeGet() places the length of - the string in the length argument. If the length is NULL then no - attempt is made to dereference it. If there is no explicit scheme, - a scheme of http is returned if the URL type is HTTP, and a scheme - of https is returned if the URL type is HTTPS. - - @param bufp marshal buffer storing the URL. - @param offset location of the URL within bufp. - @param length length of the returned string. - @return The scheme portion of the URL, as a string. - - */ -tsapi const char *TSUrlSchemeGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the scheme portion of the URL located at url_loc within - the marshal buffer bufp to the string value. If length is -1 - then TSUrlSchemeSet() assumes that value is null-terminated. - Otherwise, the length of the string value is taken to be length. - TSUrlSchemeSet() copies the string to within bufp, so it is OK - to modify or delete value after calling TSUrlSchemeSet(). - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param value value to set the URL's scheme to. - @param length string stored in value. - - */ -tsapi TSReturnCode TSUrlSchemeSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/* -------------------------------------------------------------------------- - Internet specific URLs */ -/** - Retrieves the user portion of the URL located at url_loc - within bufp. Note: the returned string is not guaranteed to - be null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param length length of the returned string. - @return user portion of the URL. - - */ -tsapi const char *TSUrlUserGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the user portion of the URL located at url_loc within bufp - to the string value. If length is -1 then TSUrlUserSet() assumes - that value is null-terminated. Otherwise, the length of the string - value is taken to be length. TSUrlUserSet() copies the string to - within bufp, so it is OK to modify or delete value after calling - TSUrlUserSet(). - - @param bufp marshal buffer containing the URL. - @param offset location of the URL whose user is to be set. - @param value holds the new user name. - @param length string length of value. - - */ -tsapi TSReturnCode TSUrlUserSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/** - Retrieves the password portion of the URL located at url_loc - within bufp. TSUrlPasswordGet() places the length of the returned - string in the length argument. Note: the returned string is - not guaranteed to be null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset - @param length of the returned password string. - @return password portion of the URL. - - */ -tsapi const char *TSUrlPasswordGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the password portion of the URL located at url_loc within - bufp to the string value. If length is -1 then TSUrlPasswordSet() - assumes that value is null-terminated. Otherwise, the length - of value is taken to be length. TSUrlPasswordSet() copies the - string to within bufp, so it is okay to modify or delete value - after calling TSUrlPasswordSet(). - - @param bufp marshal buffer containing the URL. - @param offset - @param value new password. - @param length of the new password. - - */ -tsapi TSReturnCode TSUrlPasswordSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/** - Retrieves the host portion of the URL located at url_loc - within bufp. Note: the returned string is not guaranteed to be - null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param length of the returned string. - @return Host portion of the URL. - - */ -tsapi const char *TSUrlHostGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the host portion of the URL at url_loc to the string value. - If length is -1 then TSUrlHostSet() assumes that value is - null-terminated. Otherwise, the length of the string value is - taken to be length. The string is copied to within bufp, so you - can modify or delete value after calling TSUrlHostSet(). - - @param bufp marshal buffer containing the URL to modify. - @param offset location of the URL. - @param value new host name for the URL. - @param length string length of the new host name of the URL. - - */ -tsapi TSReturnCode TSUrlHostSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/** - Returns the port portion of the URL located at url_loc if explicitly present, - otherwise the canonical port for the URL. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @return port portion of the URL. - - */ -tsapi int TSUrlPortGet(TSMBuffer bufp, TSMLoc offset); - -/** - Returns the port portion of the URL located at url_loc if explicitly present, - otherwise 0. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @return port portion of the URL. - - */ -tsapi int TSUrlRawPortGet(TSMBuffer bufp, TSMLoc offset); - -/** - Sets the port portion of the URL located at url_loc. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param port new port setting for the URL. - - */ -tsapi TSReturnCode TSUrlPortSet(TSMBuffer bufp, TSMLoc offset, int port); - -/* -------------------------------------------------------------------------- - HTTP specific URLs */ -/** - Retrieves the path portion of the URL located at url_loc within - bufp. TSUrlPathGet() places the length of the returned string in - the length argument. Note: the returned string is not guaranteed to - be null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param length of the returned string. - @return path portion of the URL. - - */ -tsapi const char *TSUrlPathGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the path portion of the URL located at url_loc within bufp - to the string value. If length is -1 then TSUrlPathSet() assumes - that value is null-terminated. Otherwise, the length of the value - is taken to be length. TSUrlPathSet() copies the string into bufp, - so you can modify or delete value after calling TSUrlPathSet(). - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param value new path string for the URL. - @param length of the new path string. - - */ -tsapi TSReturnCode TSUrlPathSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/* -------------------------------------------------------------------------- - FTP specific URLs */ -/** - Retrieves the FTP type of the URL located at url_loc within bufp. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @return FTP type of the URL. - - */ -tsapi int TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc offset); - -/** - Sets the FTP type portion of the URL located at url_loc within - bufp to the value type. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL to modify. - @param type new FTP type for the URL. - - */ -tsapi TSReturnCode TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc offset, int type); - -/* -------------------------------------------------------------------------- - HTTP specific URLs */ -/** - Retrieves the HTTP params portion of the URL located at url_loc - within bufp. The length of the returned string is in the length - argument. Note: the returned string is not guaranteed to be - null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param length of the returned string. - @return HTTP params portion of the URL. - - */ -tsapi const char *TSUrlHttpParamsGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the HTTP params portion of the URL located at url_loc within - bufp to the string value. If length is -1 that TSUrlHttpParamsSet() - assumes that value is null-terminated. Otherwise, the length of - the string value is taken to be length. TSUrlHttpParamsSet() - copies the string to within bufp, so you can modify or delete - value after calling TSUrlHttpParamsSet(). - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param value HTTP params string to set in the URL. - @param length string length of the new HTTP params value. - - */ -tsapi TSReturnCode TSUrlHttpParamsSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/** - Retrieves the HTTP query portion of the URL located at url_loc - within bufp. The length of the returned string is in the length - argument. Note: the returned string is not guaranteed to be - null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param length of the returned string. - @return HTTP query portion of the URL. - - */ -tsapi const char *TSUrlHttpQueryGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the HTTP query portion of the URL located at url_loc within - bufp to value. If length is -1, the string value is assumed to - be null-terminated; otherwise, the length of value is taken to be - length. TSUrlHttpQuerySet() copies the string to within bufp, so - you can modify or delete value after calling TSUrlHttpQuerySet(). - - @param bufp marshal buffer containing the URL. - @param offset location of the URL within bufp. - @param value new HTTP query string for the URL. - @param length of the new HTTP query string. - - */ -tsapi TSReturnCode TSUrlHttpQuerySet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/** - Retrieves the HTTP fragment portion of the URL located at url_loc - within bufp. The length of the returned string is in the length - argument. Note: the returned string is not guaranteed to be - null-terminated. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL. - @param length of the returned string. - @return HTTP fragment portion of the URL. - - */ -tsapi const char *TSUrlHttpFragmentGet(TSMBuffer bufp, TSMLoc offset, int *length); - -/** - Sets the HTTP fragment portion of the URL located at url_loc - within bufp to value. If length is -1, the string value is - assumed to be null-terminated; otherwise, the length of value - is taken to be length. TSUrlHttpFragmentSet() copies the string - to within bufp, so you can modify or delete value after calling - TSUrlHttpFragmentSet(). - - @param bufp marshal buffer containing the URL. - @param offset location of the URL within bufp. - @param value new HTTP fragment string for the URL. - @param length of the new HTTP query string. - - */ -tsapi TSReturnCode TSUrlHttpFragmentSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); - -/** - Perform percent-encoding of the string in the buffer, storing the - new string in the destination buffer. The length parameter will be - set to the new (encoded) string length, or 0 if the encoding failed. - - @param str the string buffer to encode. - @param str_len length of the string buffer. - @param dst destination buffer. - @param dst_size size of the destination buffer. - @param length amount of data written to the destination buffer. - @param map optional (can be NULL) map of characters to encode. - -*/ -tsapi TSReturnCode TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, size_t *length, - const unsigned char *map); - -/** - Similar to TSStringPercentEncode(), but works on a URL object. - - @param bufp marshal buffer containing the URL. - @param offset location of the URL within bufp. - @param dst destination buffer. - @param dst_size size of the destination buffer. - @param length amount of data written to the destination buffer. - @param map optional (can be NULL) map of characters to encode. - -*/ -tsapi TSReturnCode TSUrlPercentEncode(TSMBuffer bufp, TSMLoc offset, char *dst, size_t dst_size, size_t *length, - const unsigned char *map); - -/** - Perform percent-decoding of the string in the buffer, writing - to the output buffer. The source and destination can be the same, - in which case they overwrite. The decoded string is always - guaranteed to be no longer than the source string. - - @param str the string to decode (and possibly write to). - @param str_len length of the input string (or 0). - @param dst output buffer (can be the same as src). - @param dst_len size of the output buffer. - @param length amount of data written to the destination buffer. - -*/ -tsapi TSReturnCode TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length); - -/* -------------------------------------------------------------------------- - MIME headers */ - -/** - Creates a MIME parser. The parser's data structure contains - information about the header being parsed. A single MIME - parser can be used multiple times, though not simultaneously. - Before being used again, the parser must be cleared by calling - TSMimeParserClear(). - - */ -tsapi TSMimeParser TSMimeParserCreate(void); - -/** - Clears the specified MIME parser so that it can be used again. - - @param parser to be cleared. - - */ -tsapi void TSMimeParserClear(TSMimeParser parser); - -/** - Destroys the specified MIME parser and frees the associated memory. - - @param parser to destroy. - */ -tsapi void TSMimeParserDestroy(TSMimeParser parser); - -/** - Parse a MIME header date string. Candidate for deprecation in v10.0.0 - */ -tsapi time_t TSMimeParseDate(char const *const value_str, int const value_len); - -/** - Creates a new MIME header within bufp. Release with a call to - TSHandleMLocRelease(). - - @param bufp marshal buffer to contain the new MIME header. - @param locp buffer pointer to contain the MLoc - - */ -tsapi TSReturnCode TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp); - -/** - Destroys the MIME header located at hdr_loc within bufp. - - @param bufp marshal buffer containing the MIME header to destroy. - @param offset location of the MIME header. - - */ -tsapi TSReturnCode TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc offset); - -/** - Copies a specified MIME header to a specified marshal buffer, - and returns the location of the copied MIME header within the - destination marshal buffer. Unlike TSMimeHdrCopy(), you do not - have to create the destination MIME header before cloning. Release - the returned TSMLoc handle with a call to TSHandleMLocRelease(). - - @param dest_bufp destination marshal buffer. - @param src_bufp source marshal buffer. - @param src_hdr location of the source MIME header. - @param locp where to store the location of the copied MIME header. - - */ -tsapi TSReturnCode TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp); - -/** - Copies the contents of the MIME header located at src_loc - within src_bufp to the MIME header located at dest_loc within - dest_bufp. TSMimeHdrCopy() works correctly even if src_bufp and - dest_bufp point to different marshal buffers. Important: you must - create the destination MIME header before copying into it--use - TSMimeHdrCreate(). - - @param dest_bufp is the destination marshal buffer. - @param dest_offset - @param src_bufp is the source marshal buffer. - @param src_offset - - */ -tsapi TSReturnCode TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset); - -/** - Formats the MIME header located at hdr_loc within bufp into the - TSIOBuffer iobufp. - - @param bufp marshal buffer containing the header to be copied to - an TSIOBuffer. - @param offset - @param iobufp target TSIOBuffer. - - */ -tsapi void TSMimeHdrPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp); - -/** - Parses a MIME header. The MIME header must have already been - allocated and both bufp and hdr_loc must point within that header. - It is possible to parse a MIME header a single byte at a time - using repeated calls to TSMimeHdrParse(). As long as an error - does not occur, TSMimeHdrParse() consumes each single byte and - asks for more. - - @param parser parses the specified MIME header. - @param bufp marshal buffer containing the MIME header to be parsed. - @param offset - @param start both an input and output. On input, the start - argument points to the current position of the buffer being - parsed. On return, start is modified to point past the last - character parsed. - @param end points to one byte after the end of the buffer. - @return One of 3 possible int values: - - TS_PARSE_ERROR if there is a parsing error. - - TS_PARSE_DONE is returned when a "\r\n\r\n" pattern is - encountered, indicating the end of the header. - - TS_PARSE_CONT is returned if parsing of the header stopped - because the end of the buffer was reached. - - */ -tsapi TSParseResult TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); - -/** - Calculates the length of the MIME header located at hdr_loc if it - were returned as a string. This the length of the MIME header in - its unparsed form. - - @param bufp marshal buffer containing the MIME header. - @param offset location of the MIME header. - @return string length of the MIME header located at hdr_loc. - - */ -tsapi int TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc offset); - -/** - Removes and destroys all the MIME fields within the MIME header - located at hdr_loc within the marshal buffer bufp. - - @param bufp marshal buffer containing the MIME header. - @param offset location of the MIME header. - - */ -tsapi TSReturnCode TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc offset); - -/** - Returns a count of the number of MIME fields within the MIME header - located at hdr_loc within the marshal buffer bufp. - - @param bufp marshal buffer containing the MIME header. - @param offset location of the MIME header within bufp. - @return number of MIME fields within the MIME header located - at hdr_loc. - - */ -tsapi int TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc offset); - -/** - Retrieves the location of a specified MIME field within the - MIME header located at hdr_loc within bufp. The idx parameter - specifies which field to retrieve. The fields are numbered from 0 - to TSMimeHdrFieldsCount(bufp, hdr_loc) - 1. If idx does not lie - within that range then TSMimeHdrFieldGet returns 0. Release the - returned handle with a call to TSHandleMLocRelease. - - @param bufp marshal buffer containing the MIME header. - @param hdr location of the MIME header. - @param idx index of the field to get with base at 0. - @return location of the specified MIME field. - - */ -tsapi TSMLoc TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr, int idx); - -/** - Retrieves the TSMLoc location of a specified MIME field from within - the MIME header located at hdr. The name and length parameters - specify which field to retrieve. For each MIME field in the MIME - header, a case insensitive string comparison is done between - the field name and name. If TSMimeHdrFieldFind() cannot find the - requested field, it returns TS_NULL_MLOC. Release the returned - TSMLoc handle with a call to TSHandleMLocRelease(). - - @param bufp marshal buffer containing the MIME header field to find. - @param hdr location of the MIME header containing the field. - @param name of the field to retrieve. - @param length string length of the string name. If length is -1, - then name is assumed to be null-terminated. - @return location of the requested MIME field. If the field could - not be found, returns TS_NULL_MLOC. - - */ -tsapi TSMLoc TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr, const char *name, int length); - -/** - Returns the TSMLoc location of a specified MIME field from within - the MIME header located at hdr. The retrieved_str parameter - specifies which field to retrieve. For each MIME field in the - MIME header, a pointer comparison is done between the field name - and retrieved_str. This is a much quicker retrieval function - than TSMimeHdrFieldFind() since it obviates the need for a - string comparison. However, retrieved_str must be one of the - predefined field names of the form TS_MIME_FIELD_XXX for the - call to succeed. Release the returned TSMLoc handle with a call - to TSHandleMLocRelease(). - - @param bufp marshal buffer containing the MIME field. - @param hdr location of the MIME header containing the field. - @param retrieved_str specifies the field to retrieve. Must be - one of the predefined field names of the form TS_MIME_FIELD_XXX. - @return location of the requested MIME field. If the requested - field cannot be found, returns 0. - - */ -tsapi TSReturnCode TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); - -/** - Removes the MIME field located at field within bufp from the - header located at hdr within bufp. If the specified field cannot - be found in the list of fields associated with the header then - nothing is done. - - Note: removing the field does not destroy the field, it only - detaches the field, hiding it from the printed output. The field - can be reattached with a call to TSMimeHdrFieldAppend(). If you - do not use the detached field you should destroy it with a call to - TSMimeHdrFieldDestroy() and release the handle field with a call - to TSHandleMLocRelease(). - - @param bufp contains the MIME field to remove. - @param hdr location of the header containing the MIME field to - be removed. This header could be an HTTP header or MIME header. - @param field is the location of the field to remove. - - */ -tsapi TSReturnCode TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); - -tsapi TSReturnCode TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc hdr, TSMLoc *locp); - -/**************************************************************************** - * Create a new field and assign it a name all in one call - ****************************************************************************/ -tsapi TSReturnCode TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int name_len, TSMLoc *locp); - -/** - Destroys the MIME field located at field within bufp. You must - release the TSMLoc field with a call to TSHandleMLocRelease(). - - @param bufp contains the MIME field to be destroyed. - @param hdr location of the parent header containing the field - to be destroyed. This could be the location of a MIME header or - HTTP header. - @param field location of the field to be destroyed. - - */ -tsapi TSReturnCode TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); - -tsapi TSReturnCode TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field, - TSMLoc *locp); -tsapi TSReturnCode TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, - TSMLoc src_field); -tsapi TSReturnCode TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, - TSMLoc src_hdr, TSMLoc src_field); -tsapi TSMLoc TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); -tsapi TSMLoc TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); -tsapi int TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); -tsapi const char *TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length); -tsapi TSReturnCode TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name, int length); - -tsapi TSReturnCode TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); -tsapi int TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); - -tsapi const char *TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int *value_len_ptr); -tsapi int TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); -tsapi int64_t TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); -tsapi unsigned int TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); -tsapi time_t TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); -tsapi TSReturnCode TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length); -tsapi TSReturnCode TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value); -tsapi TSReturnCode TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int64_t value); -tsapi TSReturnCode TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value); -tsapi TSReturnCode TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value); - -tsapi TSReturnCode TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length); -/* These Insert() APIs should be considered. Use the corresponding Set() API instead */ -tsapi TSReturnCode TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, - int length); -tsapi TSReturnCode TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value); -tsapi TSReturnCode TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value); -tsapi TSReturnCode TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value); - -tsapi TSReturnCode TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); -tsapi const char *TSMimeHdrStringToWKS(const char *str, int length); - -/* -------------------------------------------------------------------------- - HTTP headers */ -tsapi TSHttpParser TSHttpParserCreate(void); -tsapi void TSHttpParserClear(TSHttpParser parser); -tsapi void TSHttpParserDestroy(TSHttpParser parser); - -/** - Parses an HTTP request header. The HTTP header must have already - been created, and must reside inside the marshal buffer bufp. - The start argument points to the current position of the string - buffer being parsed. The end argument points to one byte after the - end of the buffer to be parsed. On return, TSHttpHdrParseReq() - modifies start to point past the last character parsed. - - It is possible to parse an HTTP request header a single byte at - a time using repeated calls to TSHttpHdrParseReq(). As long as - an error does not occur, the TSHttpHdrParseReq() function will - consume that single byte and ask for more. - - @param parser parses the HTTP header. - @param bufp marshal buffer containing the HTTP header to be parsed. - @param offset location of the HTTP header within bufp. - @param start both an input and output. On input, it points to the - current position of the string buffer being parsed. On return, - start is modified to point past the last character parsed. - @param end points to one byte after the end of the buffer to be parsed. - @return status of the parse: - - TS_PARSE_ERROR means there was a parsing error. - - TS_PARSE_DONE means that the end of the header was reached - (the parser encountered a "\r\n\r\n" pattern). - - TS_PARSE_CONT means that parsing of the header stopped because - the parser reached the end of the buffer (large headers can - span multiple buffers). - - */ -tsapi TSParseResult TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); - -tsapi TSParseResult TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); - -tsapi TSMLoc TSHttpHdrCreate(TSMBuffer bufp); - -/** - Destroys the HTTP header located at hdr_loc within the marshal - buffer bufp. Do not forget to release the handle hdr_loc with a - call to TSHandleMLocRelease(). - - */ -tsapi void TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc offset); - -tsapi TSReturnCode TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp); - -/** - Copies the contents of the HTTP header located at src_loc within - src_bufp to the HTTP header located at dest_loc within dest_bufp. - TSHttpHdrCopy() works correctly even if src_bufp and dest_bufp - point to different marshal buffers. Make sure that you create the - destination HTTP header before copying into it. - - Note: TSHttpHdrCopy() appends the port number to the domain - of the URL portion of the header. For example, a copy of - http://www.example.com appears as http://www.example.com:80 in - the destination buffer. - - @param dest_bufp marshal buffer to contain the copied header. - @param dest_offset location of the copied header. - @param src_bufp marshal buffer containing the source header. - @param src_offset location of the source header. - - */ -tsapi TSReturnCode TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset); - -tsapi void TSHttpHdrPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp); - -tsapi int TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc offset); - -tsapi TSHttpType TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc offset); -tsapi TSReturnCode TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc offset, TSHttpType type); - -tsapi int TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc offset); -tsapi TSReturnCode TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc offset, int ver); - -tsapi const char *TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc offset, int *length); -tsapi TSReturnCode TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); -tsapi const char *TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc offset, int *length); -tsapi TSReturnCode TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc offset, TSMLoc *locp); -tsapi TSReturnCode TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc offset, TSMLoc url); - -tsapi TSHttpStatus TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc offset); -tsapi TSReturnCode TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc offset, TSHttpStatus status); -tsapi const char *TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc offset, int *length); -tsapi TSReturnCode TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); -tsapi const char *TSHttpHdrReasonLookup(TSHttpStatus status); - -/* -------------------------------------------------------------------------- - Threads */ -tsapi TSThread TSThreadCreate(TSThreadFunc func, void *data); -tsapi TSThread TSThreadInit(void); -tsapi void TSThreadDestroy(TSThread thread); -tsapi void TSThreadWait(TSThread thread); -tsapi TSThread TSThreadSelf(void); -tsapi TSEventThread TSEventThreadSelf(void); - -/* -------------------------------------------------------------------------- - Mutexes */ -tsapi TSMutex TSMutexCreate(void); -tsapi void TSMutexDestroy(TSMutex mutexp); -tsapi void TSMutexLock(TSMutex mutexp); -tsapi TSReturnCode TSMutexLockTry(TSMutex mutexp); - -tsapi void TSMutexUnlock(TSMutex mutexp); - -/* -------------------------------------------------------------------------- - cachekey */ -/** - Creates (allocates memory for) a new cache key. - */ -tsapi TSCacheKey TSCacheKeyCreate(void); - -/** - Generates a key for an object to be cached (written to the cache). - - @param key to be associated with the cached object. Before - calling TSCacheKeySetDigest() you must create the key with - TSCacheKeyCreate(). - @param input string that uniquely identifies the object. In most - cases, it is the URL of the object. - @param length of the string input. - - */ -tsapi TSReturnCode TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length); - -tsapi TSReturnCode TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url); - -/** - Associates a host name to the cache key. Use this function if the - cache has been partitioned by hostname. The hostname tells the - cache which volume to use for the object. - - @param key of the cached object. - @param hostname to associate with the cache key. - @param host_len length of the string hostname. - - */ -tsapi TSReturnCode TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len); - -tsapi TSReturnCode TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache); - -/** - Destroys a cache key. You must destroy cache keys when you are - finished with them, i.e. after all reads and writes are completed. - - @param key to be destroyed. - - */ -tsapi TSReturnCode TSCacheKeyDestroy(TSCacheKey key); - -/* -------------------------------------------------------------------------- - cache url */ -tsapi TSReturnCode TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length); - -/* -------------------------------------------------------------------------- - Configuration */ -tsapi unsigned int TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp); -tsapi TSConfig TSConfigGet(unsigned int id); -tsapi void TSConfigRelease(unsigned int id, TSConfig configp); -tsapi void *TSConfigDataGet(TSConfig configp); - -/* -------------------------------------------------------------------------- - Management */ -tsapi void TSMgmtUpdateRegister(TSCont contp, const char *plugin_name); -tsapi TSReturnCode TSMgmtIntGet(const char *var_name, TSMgmtInt *result); -tsapi TSReturnCode TSMgmtCounterGet(const char *var_name, TSMgmtCounter *result); -tsapi TSReturnCode TSMgmtFloatGet(const char *var_name, TSMgmtFloat *result); -tsapi TSReturnCode TSMgmtStringGet(const char *var_name, TSMgmtString *result); -tsapi TSReturnCode TSMgmtSourceGet(const char *var_name, TSMgmtSource *source); -tsapi TSReturnCode TSMgmtConfigFileAdd(const char *parent, const char *fileName); -tsapi TSReturnCode TSMgmtDataTypeGet(const char *var_name, TSRecordDataType *result); - -/* -------------------------------------------------------------------------- - TSHRTime, this is a candidate for deprecation in v10.0.0 */ -tsapi TSHRTime TShrtime(void); - -/* -------------------------------------------------------------------------- - Continuations */ -tsapi TSCont TSContCreate(TSEventFunc funcp, TSMutex mutexp); -tsapi void TSContDestroy(TSCont contp); -tsapi void TSContDataSet(TSCont contp, void *data); -tsapi void *TSContDataGet(TSCont contp); -tsapi TSAction TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp); -tsapi TSAction TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread); -tsapi TSAction TSContScheduleEveryOnPool(TSCont contp, TSHRTime every /* millisecs */, TSThreadPool tp); -tsapi TSAction TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEventThread ethread); -tsapi TSReturnCode TSContThreadAffinitySet(TSCont contp, TSEventThread ethread); -tsapi TSEventThread TSContThreadAffinityGet(TSCont contp); -tsapi void TSContThreadAffinityClear(TSCont contp); -tsapi TSAction TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout); -tsapi int TSContCall(TSCont contp, TSEvent event, void *edata); -tsapi TSMutex TSContMutexGet(TSCont contp); - -/* -------------------------------------------------------------------------- - Plugin lifecycle hooks */ -tsapi void TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp); -/* -------------------------------------------------------------------------- - HTTP hooks */ -tsapi void TSHttpHookAdd(TSHttpHookID id, TSCont contp); - -/* -------------------------------------------------------------------------- - HTTP sessions */ -tsapi void TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp); -tsapi void TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event); -tsapi int TSHttpSsnTransactionCount(TSHttpSsn ssnp); -/* Get the TSVConn from a session. */ -tsapi TSVConn TSHttpSsnClientVConnGet(TSHttpSsn ssnp); -tsapi TSVConn TSHttpSsnServerVConnGet(TSHttpSsn ssnp); -/* Get the TSVConn from a transaction. */ -tsapi TSVConn TSHttpTxnServerVConnGet(TSHttpTxn txnp); - -/* -------------------------------------------------------------------------- - SSL connections */ -/* Re-enable an SSL connection from a hook. - This must be called exactly once before the SSL connection will resume. */ -tsapi void TSVConnReenable(TSVConn sslvcp); -/* Extended version that allows for passing a status event on reenabling - */ -tsapi void TSVConnReenableEx(TSVConn sslvcp, TSEvent event); -/* Set the connection to go into blind tunnel mode */ -tsapi TSReturnCode TSVConnTunnel(TSVConn sslp); -/* Return the SSL object associated with the connection */ -tsapi TSSslConnection TSVConnSslConnectionGet(TSVConn sslp); -/* Return the intermediate X509StoreCTX object that references the certificate being validated */ -tsapi TSSslVerifyCTX TSVConnSslVerifyCTXGet(TSVConn sslp); -/* Fetch a SSL context from the global lookup table */ -tsapi TSSslContext TSSslContextFindByName(const char *name); -tsapi TSSslContext TSSslContextFindByAddr(struct sockaddr const *); -/* Fetch SSL client contexts from the global lookup table */ -tsapi TSReturnCode TSSslClientContextsNamesGet(int n, const char **result, int *actual); -tsapi TSSslContext TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths); - -/* Update SSL certs in internal storage from given path */ -tsapi TSReturnCode TSSslClientCertUpdate(const char *cert_path, const char *key_path); -tsapi TSReturnCode TSSslServerCertUpdate(const char *cert_path, const char *key_path); - -/* Update the transient secret table for SSL_CTX loading */ -tsapi TSReturnCode TSSslSecretSet(const char *secret_name, int secret_name_length, const char *secret_data, int secret_data_length); - -/* Returns secret with given name (not null terminted). If there is no secret with the given name, return value will -** be null and secret_data_lenght will be zero. Calling code must free data buffer by calling TSfree(). */ -tsapi char *TSSslSecretGet(const char *secret_name, int secret_name_length, int *secret_data_length); - -tsapi TSReturnCode TSSslSecretUpdate(const char *secret_name, int secret_name_length); - -/* Create a new SSL context based on the settings in records.yaml */ -tsapi TSSslContext TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_file); -tsapi void TSSslContextDestroy(TSSslContext ctx); -tsapi TSReturnCode TSSslTicketKeyUpdate(char *ticketData, int ticketDataLen); -TSAcceptor TSAcceptorGet(TSVConn sslp); -TSAcceptor TSAcceptorGetbyID(int ID); -int TSAcceptorCount(); -int TSAcceptorIDGet(TSAcceptor acceptor); -TSReturnCode TSVConnProtocolDisable(TSVConn connp, const char *protocol_name); -TSReturnCode TSVConnProtocolEnable(TSVConn connp, const char *protocol_name); - -/* Returns 1 if the sslp argument refers to a SSL connection */ -tsapi int TSVConnIsSsl(TSVConn sslp); -/* Returns 1 if a certificate was provided in the TLS handshake, 0 otherwise. - */ -tsapi int TSVConnProvidedSslCert(TSVConn sslp); -tsapi const char *TSVConnSslSniGet(TSVConn sslp, int *length); - -tsapi TSSslSession TSSslSessionGet(const TSSslSessionID *session_id); -tsapi int TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_ptr); -tsapi TSReturnCode TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, TSSslConnection ssl_conn); -tsapi TSReturnCode TSSslSessionRemove(const TSSslSessionID *session_id); - -/* -------------------------------------------------------------------------- - HTTP transactions */ -tsapi void TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp); -tsapi TSHttpSsn TSHttpTxnSsnGet(TSHttpTxn txnp); - -/* Gets the client request header for a specified HTTP transaction. */ -tsapi TSReturnCode TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -/* Gets the client response header for a specified HTTP transaction. */ -tsapi TSReturnCode TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -/* Gets the server request header from a specified HTTP transaction. */ -tsapi TSReturnCode TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -/* Gets the server response header from a specified HTTP transaction. */ -tsapi TSReturnCode TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -/* Gets the cached request header for a specified HTTP transaction. */ -tsapi TSReturnCode TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -/* Gets the cached response header for a specified HTTP transaction. */ -tsapi TSReturnCode TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); - -tsapi TSReturnCode TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc); - -/** - * @brief Gets the number of transactions between the Traffic Server proxy and the origin server from a single session. - * Any value greater than zero indicates connection reuse. - * - * @param txnp The transaction - * @return int The number of transactions between the Traffic Server proxy and the origin server from a single session - */ -tsapi int TSHttpTxnServerSsnTransactionCount(TSHttpTxn txnp); - -/** Get the effective URL for the transaction. - The effective URL is the URL taking in to account both the explicit - URL in the request and the HOST field. - - A possibly non-null terminated string is returned. - - @note The returned string is allocated and must be freed by the caller - after use with @c TSfree. -*/ -tsapi char *TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length /**< String length return, may be @c NULL. */ -); - -/** Get the effective URL for in the header (if any), with the scheme and host normalized to lower case letter. - The effective URL is the URL taking in to account both the explicit - URL in the request and the HOST field. - - A possibly non-null terminated string is returned. - - @return TS_SUCCESS if successful, TS_ERROR if no URL in header or other error. -*/ -tsapi TSReturnCode TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_t size, int64_t *length); - -tsapi void TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag); -tsapi void TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag); - -/** Set flag indicating whether or not to cache the server response for - given TSHttpTxn - - @note This should be done in the HTTP_READ_RESPONSE_HDR_HOOK or earlier. - - @note If TSHttpTxnRespCacheableSet() is not working the way you expect, - this may be the function you should use instead. - - @param txnp The transaction whose server response you do not want to store. - @param flag Set 0 to allow storing and 1 to disable storing. - - @return TS_SUCCESS. -*/ -tsapi TSReturnCode TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag); - -/** Get flag indicating whether or not to cache the server response for - given TSHttpTxn - @param txnp The transaction whose server response you do not want to store. - - @return TS_SUCCESS. -*/ -tsapi bool TSHttpTxnServerRespNoStoreGet(TSHttpTxn txnp); -tsapi TSReturnCode TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -tsapi char *TSFetchRespGet(TSHttpTxn txnp, int *length); -tsapi TSReturnCode TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status); - -tsapi TSReturnCode TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); - -/** Set the @a port value for the inbound (user agent) connection in the transaction @a txnp. - This is used primarily where the connection is synthetic and therefore does not have a port. - @note @a port is in @b host @b order. -*/ -tsapi void TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port); - -/** Get client address for transaction @a txnp. - Retrieves the socket address of the remote client that has - connected to Traffic Server for transaction @a txnp. The - return structure is the generic socket address storage in - order to be address-family agnostic. The user of this function - can then go on to do the appropriate thing with the type - specified in the ss_family field of the structure whether - that be for IPv4, IPv6, or any other address family. - - @return Client address for connection to client in transaction @a txnp. - - */ -tsapi struct sockaddr const *TSHttpTxnClientAddrGet(TSHttpTxn txnp); -/** Get the incoming address. - - @note The pointer is valid only for the current callback. Clients - that need to keep the value across callbacks must maintain their - own storage. - - @return Local address of the client connection for transaction @a txnp. -*/ -tsapi struct sockaddr const *TSHttpTxnIncomingAddrGet(TSHttpTxn txnp); -/** Get the outgoing address. - - @note The pointer is valid only for the current callback. Clients - that need to keep the value across callbacks must maintain their - own storage. - - @return Local address of the server connection for transaction @a txnp. -*/ -tsapi struct sockaddr const *TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp); -/** Get the origin server address. - * - @note The pointer is valid only for the current callback. Clients - that need to keep the value across callbacks must maintain their - own storage. - - @return The address of the origin server for transaction @a txnp. -*/ -tsapi struct sockaddr const *TSHttpTxnServerAddrGet(TSHttpTxn txnp); -/** Set the origin server address. - - This must be invoked before the origin server address is looked up. - If called no lookup is done, the address @a addr is used instead. - - @return @c TS_SUCCESS if the origin server address is set, @c TS_ERROR otherwise. -*/ -tsapi TSReturnCode TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr /**< Address for origin server. */ -); - -/** Get the next hop address. - * - @note The pointer is valid only for the current callback. Clients - that need to keep the value across callbacks must maintain their - own storage. - - @return The address of the next hop for transaction @a txnp. -*/ -tsapi struct sockaddr const *TSHttpTxnNextHopAddrGet(TSHttpTxn txnp); - -/** Get the next hop name. - * - @note The pointer is valid only for the current callback. Clients - that need to keep the value across callbacks must maintain their - own storage. - - @return The name of the next hop for transaction @a txnp. -*/ -tsapi const char *TSHttpTxnNextHopNameGet(TSHttpTxn txnp); - -/** Get the next hop port. - * - Retrieves the next hop parent port. - Returns -1 if not valid. - - @return The port of the next hop for transaction @a txnp. - - */ -tsapi int TSHttpTxnNextHopPortGet(TSHttpTxn txnp); - -tsapi TSReturnCode TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp); -tsapi TSReturnCode TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, struct sockaddr const *addr); -tsapi TSReturnCode TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag); -tsapi TSReturnCode TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp); - -/* TS-1008: the above TXN calls for the Client conn should work with SSN */ -tsapi struct sockaddr const *TSHttpSsnClientAddrGet(TSHttpSsn ssnp); -tsapi struct sockaddr const *TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp); -tsapi TSReturnCode TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp); -/* TS-1008 END */ - -/** Change packet firewall mark for the client side connection - * - @note The change takes effect immediately - - @return TS_SUCCESS if the client connection was modified -*/ -tsapi TSReturnCode TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark); - -/** Change packet firewall mark for the server side connection - * - @note The change takes effect immediately, if no OS connection has been - made, then this sets the mark that will be used IF an OS connection - is established - - @return TS_SUCCESS if the (future?) server connection was modified -*/ -tsapi TSReturnCode TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark); - -/** Change packet DSCP for the client side connection - * - @note The change takes effect immediately - - @return TS_SUCCESS if the client connection was modified -*/ -tsapi TSReturnCode TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp); - -/** Change packet DSCP for the server side connection - * - - @note The change takes effect immediately, if no OS connection has been - made, then this sets the mark that will be used IF an OS connection - is established - - @return TS_SUCCESS if the (future?) server connection was modified -*/ -tsapi TSReturnCode TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp); - -/** - Sets an error type body to a transaction. Note that both string arguments - must be allocated with TSmalloc() or TSstrdup(). The mimetype argument is - optional, if not provided it defaults to "text/html". Sending an empty - string would prevent setting a content type header (but that is not advised). - - @param txnp HTTP transaction whose parent proxy to get. - @param buf The body message (must be heap allocated). - @param buflength Length of the body message. - @param mimetype The MIME type to set the response to (can be NULL, but must - be heap allocated if non-NULL). -*/ -tsapi void TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetype); - -/** - Retrieves the parent proxy hostname and port, if parent - proxying is enabled. If parent proxying is not enabled, - TSHttpTxnParentProxyGet() sets hostname to NULL and port to -1. - - @param txnp HTTP transaction whose parent proxy to get. - @param hostname of the parent proxy. - @param port parent proxy's port. - - */ -tsapi TSReturnCode TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port); - -/** - Sets the parent proxy name and port. The string hostname is copied - into the TSHttpTxn; you can modify or delete the string after - calling TSHttpTxnParentProxySet(). - - @param txnp HTTP transaction whose parent proxy to set. - @param hostname parent proxy host name string. - @param port parent proxy port to set. - - */ -tsapi void TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port); - -tsapi TSReturnCode TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); -tsapi TSReturnCode TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); - -tsapi void TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on); -tsapi void TSHttpTxnTransformedRespCache(TSHttpTxn txnp, int on); - -/** - Notifies the HTTP transaction txnp that the plugin is - finished processing the current hook. The plugin tells the - transaction to either continue (TS_EVENT_HTTP_CONTINUE) or stop - (TS_EVENT_HTTP_ERROR). - - You must always reenable the HTTP transaction after the processing - of each transaction event. However, never reenable twice. - Reenabling twice is a serious error. - - @param txnp transaction to be reenabled. - @param event tells the transaction how to continue: - - TS_EVENT_HTTP_CONTINUE, which means that the transaction - should continue. - - TS_EVENT_HTTP_ERROR which terminates the transaction - and sends an error to the client if no response has already - been sent. - - */ -tsapi void TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event); -tsapi TSReturnCode TSHttpCacheReenable(TSCacheTxn txnp, const TSEvent event, const void *data, const uint64_t size); - -/* The reserve API should only be use in TSAPI plugins, during plugin initialization! - The lookup methods can be used anytime, but are best used during initialization as well, - or at least "cache" the results for best performance. */ -tsapi TSReturnCode TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *description, int *arg_idx); -tsapi TSReturnCode TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description); -tsapi TSReturnCode TSUserArgIndexLookup(TSUserArgType type, int arg_idx, const char **name, const char **description); -tsapi void TSUserArgSet(void *data, int arg_idx, void *arg); -tsapi void *TSUserArgGet(void *data, int arg_idx); - -tsapi void TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status); -tsapi TSHttpStatus TSHttpTxnStatusGet(TSHttpTxn txnp); - -tsapi void TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout); -tsapi void TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout); -tsapi void TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout); -tsapi void TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout); - -tsapi TSServerState TSHttpTxnServerStateGet(TSHttpTxn txnp); - -/* -------------------------------------------------------------------------- - Transaction specific debugging control */ - -/** - Set the transaction specific debugging flag for this transaction. - When turned on, internal debug messages related to this transaction - will be written even if the debug tag isn't on. - - @param txnp transaction to change. - @param on set to 1 to turn on, 0 to turn off. -*/ -tsapi void TSHttpTxnDebugSet(TSHttpTxn txnp, int on); -/** - Returns the transaction specific debugging flag for this transaction. - - @param txnp transaction to check. - @return 1 if enabled, 0 otherwise. -*/ -tsapi int TSHttpTxnDebugGet(TSHttpTxn txnp); -/** - Set the session specific debugging flag for this client session. - When turned on, internal debug messages related to this session and all transactions - in the session will be written even if the debug tag isn't on. - - @param ssnp Client session to change. - @param on set to 1 to turn on, 0 to turn off. -*/ -tsapi void TSHttpSsnDebugSet(TSHttpSsn ssnp, int on); -/** - Returns the transaction specific debugging flag for this client session. - - @param txnp Client session to check. - @return 1 if enabled, 0 otherwise. -*/ -tsapi int TSHttpSsnDebugGet(TSHttpSsn ssnp, int *on); - -/* -------------------------------------------------------------------------- - Intercepting Http Transactions */ - -/** - Allows a plugin take over the servicing of the request as though - it was the origin server. contp will be sent TS_EVENT_NET_ACCEPT. - The edata passed with TS_NET_EVENT_ACCEPT is an TSVConn just as - it would be for a normal accept. The plugin must act as if it is - an http server and read the http request and body off the TSVConn - and send an http response header and body. - - TSHttpTxnIntercept() must be called be called from only - TS_HTTP_READ_REQUEST_HOOK. Using TSHttpTxnIntercept will - bypass the Traffic Server cache. If response sent by the plugin - should be cached, use TSHttpTxnServerIntercept() instead. - TSHttpTxnIntercept() primary use is allow plugins to serve data - about their functioning directly. - - TSHttpTxnIntercept() must only be called once per transaction. - - @param contp continuation called to handle the interception. - @param txnp transaction to be intercepted. - - */ -tsapi void TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp); - -/** - Allows a plugin take over the servicing of the request as though - it was the origin server. In the event a request needs to be - made to the server for transaction txnp, contp will be sent - TS_EVENT_NET_ACCEPT. The edata passed with TS_NET_EVENT_ACCEPT - is an TSVConn just as it would be for a normal accept. The plugin - must act as if it is an http server and read the http request and - body off the TSVConn and send an http response header and body. - - TSHttpTxnInterceptServer() must be not be called after - the connection to the server has taken place. The last hook - last hook in that TSHttpTxnIntercept() can be called from is - TS_HTTP_READ_CACHE_HDR_HOOK. If a connection to the server is - not necessary, contp is not called. - - The response from the plugin is cached subject to standard - and configured http caching rules. Should the plugin wish the - response not be cached, the plugin must use appropriate http - response headers to prevent caching. The primary purpose of - TSHttpTxnInterceptServer() is allow plugins to provide gateways - to other protocols or to allow to plugin to it's own transport for - the next hop to the server. TSHttpTxnInterceptServer() overrides - parent cache configuration. - - TSHttpTxnInterceptServer() must only be called once per - transaction. - - @param contp continuation called to handle the interception - @param txnp transaction to be intercepted. - - */ -tsapi void TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp); - -/* -------------------------------------------------------------------------- - Initiate Http Connection */ - -/** - Allows the plugin to initiate an http connection. The TSVConn the - plugin receives as the result of successful operates identically to - one created through TSNetConnect. Aside from allowing the plugin - to set the client ip and port for logging, the functionality of - TSHttpConnect() is identical to connecting to localhost on the - proxy port with TSNetConnect(). TSHttpConnect() is more efficient - than TSNetConnect() to localhost since it avoids the overhead of - passing the data through the operating system. - - This returns a VConn that connected to the transaction. - - @param options a TSHttpConnectPluginOptions structure that specifies options. - */ -tsapi TSVConn TSHttpConnectPlugin(TSHttpConnectOptions *options); - -/** Backwards compatible version. - This function calls This provides a @a buffer_index of 8 and a @a buffer_water_mark of 0. - - @param addr Target address of the origin server. - @param tag A logging tag that can be accessed via the pitag field. May be @c NULL. - @param id A logging id that can be access via the piid field. - */ -tsapi TSVConn TSHttpConnectWithPluginId(struct sockaddr const *addr, const char *tag, int64_t id); +#include -/** Backwards compatible version. - This provides a @a tag of "plugin" and an @a id of 0. - */ -tsapi TSVConn TSHttpConnect(struct sockaddr const *addr); - -/** - Get an instance of TSHttpConnectOptions with default values. - */ -tsapi TSHttpConnectOptions TSHttpConnectOptionsGet(TSConnectType connect_type); - -/** - Get the value of proxy.config.plugin.vc.default_buffer_index from the TSHttpTxn - */ -tsapi TSIOBufferSizeIndex TSPluginVCIOBufferIndexGet(TSHttpTxn txnp); - -/** - Get the value of proxy.config.plugin.vc.default_buffer_water_mark from the TSHttpTxn - */ -tsapi TSIOBufferWaterMark TSPluginVCIOBufferWaterMarkGet(TSHttpTxn txnp); - -/* -------------------------------------------------------------------------- - Initiate Transparent Http Connection */ -/** - Allows the plugin to initiate a transparent http connection. This operates - identically to TSHttpConnect except that it is treated as an intercepted - transparent connection by the session and transaction state machines. - - @param client_addr the address that the resulting connection will be seen as - coming from - @param server_addr the address that the resulting connection will be seen as - attempting to connect to when intercepted - @param vc will be set to point to the new TSVConn on success. - - */ -tsapi TSVConn TSHttpConnectTransparent(struct sockaddr const *client_addr, struct sockaddr const *server_addr); - -tsapi TSFetchSM TSFetchUrl(const char *request, int request_len, struct sockaddr const *addr, TSCont contp, - TSFetchWakeUpOptions callback_options, TSFetchEvent event); -tsapi void TSFetchPages(TSFetchUrlParams_t *params); - -/* Check if HTTP State machine is internal or not */ -tsapi int TSHttpTxnIsInternal(TSHttpTxn txnp); -tsapi int TSHttpSsnIsInternal(TSHttpSsn ssnp); - -/* -------------------------------------------------------------------------- - HTTP alternate selection */ -tsapi TSReturnCode TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset); -tsapi TSReturnCode TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset); -tsapi TSReturnCode TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset); -tsapi void TSHttpAltInfoQualitySet(TSHttpAltInfo infop, float quality); - -/* -------------------------------------------------------------------------- - Actions */ -tsapi void TSActionCancel(TSAction actionp); -tsapi int TSActionDone(TSAction actionp); - -/* -------------------------------------------------------------------------- - VConnections */ -tsapi TSVIO TSVConnReadVIOGet(TSVConn connp); -tsapi TSVIO TSVConnWriteVIOGet(TSVConn connp); -tsapi int TSVConnClosedGet(TSVConn connp); - -tsapi TSVIO TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes); -tsapi TSVIO TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbytes); -tsapi void TSVConnClose(TSVConn connp); -tsapi void TSVConnAbort(TSVConn connp, int error); -tsapi void TSVConnShutdown(TSVConn connp, int read, int write); - -/* -------------------------------------------------------------------------- - Cache VConnections */ -tsapi int64_t TSVConnCacheObjectSizeGet(TSVConn connp); - -/* -------------------------------------------------------------------------- - Transformations */ -tsapi TSVConn TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp); -tsapi TSVConn TSTransformOutputVConnGet(TSVConn connp); - -/* -------------------------------------------------------------------------- - Net VConnections */ -tsapi struct sockaddr const *TSNetVConnRemoteAddrGet(TSVConn vc); - -/** - Opens a network connection to the host specified by ip on the port - specified by port. If the connection is successfully opened, contp - is called back with the event TS_EVENT_NET_CONNECT and the new - network vconnection will be passed in the event data parameter. - If the connection is not successful, contp is called back with - the event TS_EVENT_NET_CONNECT_FAILED. - - @return something allows you to check if the connection is complete, - or cancel the attempt to connect. - - */ -tsapi TSAction TSNetConnect( - TSCont contp, /**< continuation that is called back when the attempted net connection either succeeds or fails. */ - struct sockaddr const *to /**< Address to which to connect. */ -); - -/** - * Retrieves the continuation associated with creating the TSVConn - */ -tsapi TSCont TSNetInvokingContGet(TSVConn conn); - -/** - * Retrieves the transaction associated with creating the TSVConn - */ -tsapi TSHttpTxn TSNetInvokingTxnGet(TSVConn conn); - -tsapi TSAction TSNetAccept(TSCont contp, int port, int domain, int accept_threads); - -/** - Listen on all SSL ports for connections for the specified protocol name. - - TSNetAcceptNamedProtocol registers the specified protocol for all - statically configured TLS ports. When a client using the TLS Next Protocol - Negotiation extension negotiates the requested protocol, TrafficServer will - route the request to the given handler. Note that the protocol is not - registered on ports opened by other plugins. - - The event and data provided to the handler are the same as for - TSNetAccept(). If a connection is successfully accepted, the event code - will be TS_EVENT_NET_ACCEPT and the event data will be a valid TSVConn - bound to the accepted connection. - - Neither contp nor protocol are copied. They must remain valid for the - lifetime of the plugin. - - TSNetAcceptNamedProtocol fails if the requested protocol cannot be - registered on all of the configured TLS ports. If it fails, the protocol - will not be registered on any ports (ie.. no partial failure). -*/ -tsapi TSReturnCode TSNetAcceptNamedProtocol(TSCont contp, const char *protocol); - -/** - Create a new port from the string specification used by the - proxy.config.http.server_ports configuration value. - */ -tsapi TSPortDescriptor TSPortDescriptorParse(const char *descriptor); - -/** - Start listening on the given port descriptor. If a connection is - successfully accepted, the TS_EVENT_NET_ACCEPT is delivered to the - continuation. The event data will be a valid TSVConn bound to the accepted - connection. - */ -tsapi TSReturnCode TSPortDescriptorAccept(TSPortDescriptor, TSCont); - -/* -------------------------------------------------------------------------- - DNS Lookups */ -tsapi TSAction TSHostLookup(TSCont contp, const char *hostname, size_t namelen); -/** Retrieve an address from the host lookup. - * - * @param lookup_result Result handle passed to event callback. - * @return A @c sockaddr with the address if successful, a @c nullptr if not. - */ -tsapi struct sockaddr const *TSHostLookupResultAddrGet(TSHostLookupResult lookup_result); - -/* TODO: Eventually, we might want something like this as well, but it requires - support for building the HostDBInfo struct: - tsapi void TSHostLookupResultSet(TSHttpTxn txnp, TSHostLookupResult result); -*/ - -/* -------------------------------------------------------------------------- - Cache VConnections */ -/** - Asks the Traffic Server cache if the object corresponding to key - exists in the cache and can be read. If the object can be read, - the Traffic Server cache calls the continuation contp back with - the event TS_EVENT_CACHE_OPEN_READ. In this case, the cache also - passes contp a cache vconnection and contp can then initiate a - read operation on that vconnection using TSVConnRead. - - If the object cannot be read, the cache calls contp back with - the event TS_EVENT_CACHE_OPEN_READ_FAILED. The user (contp) - has the option to cancel the action returned by TSCacheRead. - Note that reentrant calls are possible, i.e. the cache can call - back the user (contp) in the same call. - - @param contp continuation to be called back if a read operation - is permissible. - @param key cache key corresponding to the object to be read. - @return something allowing the user to cancel or schedule the - cache read. - - */ -tsapi TSAction TSCacheRead(TSCont contp, TSCacheKey key); - -/** - Asks the Traffic Server cache if contp can start writing the - object (corresponding to key) to the cache. If the object - can be written, the cache calls contp back with the event - TS_EVENT_CACHE_OPEN_WRITE. In this case, the cache also passes - contp a cache vconnection and contp can then initiate a write - operation on that vconnection using TSVConnWrite. The object - is not committed to the cache until the vconnection is closed. - When all data has been transferred, the user (contp) must do - an TSVConnClose. In case of any errors, the user MUST do an - TSVConnAbort(contp, 0). - - If the object cannot be written, the cache calls contp back with - the event TS_EVENT_CACHE_OPEN_WRITE_FAILED. This can happen, - for example, if there is another object with the same key being - written to the cache. The user (contp) has the option to cancel - the action returned by TSCacheWrite. - - Note that reentrant calls are possible, i.e. the cache can call - back the user (contp) in the same call. - - @param contp continuation that the cache calls back (telling it - whether the write operation can proceed or not). - @param key cache key corresponding to the object to be cached. - @return something allowing the user to cancel or schedule the - cache write. - - */ -tsapi TSAction TSCacheWrite(TSCont contp, TSCacheKey key); - -/** - Removes the object corresponding to key from the cache. If the - object was removed successfully, the cache calls contp back - with the event TS_EVENT_CACHE_REMOVE. If the object was not - found in the cache, the cache calls contp back with the event - TS_EVENT_CACHE_REMOVE_FAILED. - - In both of these callbacks, the user (contp) does not have to do - anything. The user does not get any vconnection from the cache, - since no data needs to be transferred. When the cache calls - contp back with TS_EVENT_CACHE_REMOVE, the remove has already - been committed. - - @param contp continuation that the cache calls back reporting the - success or failure of the remove. - @param key cache key corresponding to the object to be removed. - @return something allowing the user to cancel or schedule the - remove. - - */ -tsapi TSAction TSCacheRemove(TSCont contp, TSCacheKey key); -tsapi TSReturnCode TSCacheReady(int *is_ready); -tsapi TSAction TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second); - -/* -------------------------------------------------------------------------- - VIOs */ -tsapi void TSVIOReenable(TSVIO viop); -tsapi TSIOBuffer TSVIOBufferGet(TSVIO viop); -tsapi TSIOBufferReader TSVIOReaderGet(TSVIO viop); -tsapi int64_t TSVIONBytesGet(TSVIO viop); -tsapi void TSVIONBytesSet(TSVIO viop, int64_t nbytes); -tsapi int64_t TSVIONDoneGet(TSVIO viop); -tsapi void TSVIONDoneSet(TSVIO viop, int64_t ndone); -tsapi int64_t TSVIONTodoGet(TSVIO viop); -tsapi TSMutex TSVIOMutexGet(TSVIO viop); -tsapi TSCont TSVIOContGet(TSVIO viop); -tsapi TSVConn TSVIOVConnGet(TSVIO viop); - -/* -------------------------------------------------------------------------- - Buffers */ -tsapi TSIOBuffer TSIOBufferCreate(void); - -/** - Creates a new TSIOBuffer of the specified size. With this function, - you can create smaller buffers than the 32K buffer created by - TSIOBufferCreate(). In some situations using smaller buffers can - improve performance. - - @param index size of the new TSIOBuffer to be created. - @param new TSIOBuffer of the specified size. - - */ -tsapi TSIOBuffer TSIOBufferSizedCreate(TSIOBufferSizeIndex index); - -/** - The watermark of an TSIOBuffer is the minimum number of bytes - of data that have to be in the buffer before calling back any - continuation that has initiated a read operation on this buffer. - TSIOBufferWaterMarkGet() will provide the size of the watermark, - in bytes, for a specified TSIOBuffer. - - @param bufp buffer whose watermark the function gets. - - */ -tsapi int64_t TSIOBufferWaterMarkGet(TSIOBuffer bufp); - -/** - The watermark of an TSIOBuffer is the minimum number of bytes - of data that have to be in the buffer before calling back any - continuation that has initiated a read operation on this buffer. - As a writer feeds data into the TSIOBuffer, no readers are called - back until the amount of data reaches the watermark. Setting - a watermark can improve performance because it avoids frequent - callbacks to read small amounts of data. TSIOBufferWaterMarkSet() - assigns a watermark to a particular TSIOBuffer. - - @param bufp buffer whose water mark the function sets. - @param water_mark watermark setting, as a number of bytes. - - */ -tsapi void TSIOBufferWaterMarkSet(TSIOBuffer bufp, int64_t water_mark); - -tsapi void TSIOBufferDestroy(TSIOBuffer bufp); -tsapi TSIOBufferBlock TSIOBufferStart(TSIOBuffer bufp); -tsapi int64_t TSIOBufferCopy(TSIOBuffer bufp, TSIOBufferReader readerp, int64_t length, int64_t offset); - -/** - Writes length bytes of data contained in the string buf to the - TSIOBuffer bufp. Returns the number of bytes of data successfully - written to the TSIOBuffer. - - @param bufp is the TSIOBuffer to write into. - @param buf string to write into the TSIOBuffer. - @param length of the string buf. - @return length of data successfully copied into the buffer, - in bytes. - - */ -tsapi int64_t TSIOBufferWrite(TSIOBuffer bufp, const void *buf, int64_t length); -tsapi void TSIOBufferProduce(TSIOBuffer bufp, int64_t nbytes); - -tsapi TSIOBufferBlock TSIOBufferBlockNext(TSIOBufferBlock blockp); -tsapi const char *TSIOBufferBlockReadStart(TSIOBufferBlock blockp, TSIOBufferReader readerp, int64_t *avail); -tsapi int64_t TSIOBufferBlockReadAvail(TSIOBufferBlock blockp, TSIOBufferReader readerp); -tsapi char *TSIOBufferBlockWriteStart(TSIOBufferBlock blockp, int64_t *avail); -tsapi int64_t TSIOBufferBlockWriteAvail(TSIOBufferBlock blockp); - -tsapi TSIOBufferReader TSIOBufferReaderAlloc(TSIOBuffer bufp); -tsapi TSIOBufferReader TSIOBufferReaderClone(TSIOBufferReader readerp); -tsapi void TSIOBufferReaderFree(TSIOBufferReader readerp); -tsapi TSIOBufferBlock TSIOBufferReaderStart(TSIOBufferReader readerp); -tsapi void TSIOBufferReaderConsume(TSIOBufferReader readerp, int64_t nbytes); -tsapi int64_t TSIOBufferReaderAvail(TSIOBufferReader readerp); -tsapi int64_t TSIOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length); - -tsapi struct sockaddr const *TSNetVConnLocalAddrGet(TSVConn vc); - -/* -------------------------------------------------------------------------- - Stats and configs based on librecords raw stats (this is preferred API until we - rewrite stats). - - This is available as of Apache TS v2.2.*/ -typedef enum { - TS_STAT_PERSISTENT = 1, - TS_STAT_NON_PERSISTENT, -} TSStatPersistence; - -typedef enum { - TS_STAT_SYNC_SUM = 0, - TS_STAT_SYNC_COUNT, - TS_STAT_SYNC_AVG, - TS_STAT_SYNC_TIMEAVG, -} TSStatSync; - -/* APIs to create new records.yaml configurations */ -tsapi TSReturnCode TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString data_default, - TSRecordUpdateType update_type, TSRecordCheckType check_type, const char *check_regex, - TSRecordAccessType access_type); -tsapi TSReturnCode TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, TSRecordUpdateType update_type, - TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type); - -/* Note that only TS_RECORDDATATYPE_INT is supported at this point. */ -tsapi int TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence persist, TSStatSync sync); - -tsapi void TSStatIntIncrement(int the_stat, TSMgmtInt amount); -tsapi void TSStatIntDecrement(int the_stat, TSMgmtInt amount); -/* Currently not supported. */ -/* tsapi void TSStatFloatIncrement(int the_stat, float amount); */ -/* tsapi void TSStatFloatDecrement(int the_stat, float amount); */ - -tsapi TSMgmtInt TSStatIntGet(int the_stat); -tsapi void TSStatIntSet(int the_stat, TSMgmtInt value); -/* Currently not supported. */ -/* tsapi TSReturnCode TSStatFloatGet(int the_stat, float* value); */ -/* tsapi TSReturnCode TSStatFloatSet(int the_stat, float value); */ - -tsapi TSReturnCode TSStatFindName(const char *name, int *idp); - -/** - Records.yaml file handling API. - - If you need to parse a records.yaml file and need to handle each node separately then - this API should be used, an example of this would be the conf_remap plugin. - - TSYAMLRecNodeHandler +#include +#include - Callback function for the caller to deal with each parsed node. ``cfg`` holds - the details of the parsed field. `data` can be used to pass information along. -*/ -typedef TSReturnCode (*TSYAMLRecNodeHandler)(const TSYAMLRecCfgFieldData *cfg, void *data); -/** - Parse a YAML node following the record structure internals. On every scalar node - the @a handler callback will be invoked with the appropriate parsed fields. @a data - can be used to pass information along to every callback, this could be handy when - you need to read/set data inside the @c TSYAMLRecNodeHandler to be read at a later stage. +class DiagsConfigState; + +namespace tsapi +{ +namespace c +{ + + /* -------------------------------------------------------------------------- + Memory */ + void *_TSmalloc(size_t size, const char *path); + void *_TSrealloc(void *ptr, size_t size, const char *path); + char *_TSstrdup(const char *str, int64_t length, const char *path); + size_t TSstrlcpy(char *dst, const char *str, size_t siz); + size_t TSstrlcat(char *dst, const char *str, size_t siz); + void TSfree(void *ptr); + + inline void * + TSmalloc(size_t s) + { + return _TSmalloc(s, TS_RES_MEM_PATH); + } + inline void * + TSrealloc(void *p, size_t s) + { + return _TSrealloc(p, s, TS_RES_MEM_PATH); + } + inline char * + TSstrdup(const char *p) + { + return _TSstrdup(p, -1, TS_RES_MEM_PATH); + } + inline char * + TSstrndup(const char *p, int64_t n) + { + return _TSstrdup(p, n, TS_RES_MEM_PATH); + } + + /* -------------------------------------------------------------------------- + Component object handles */ + /** + Releases the TSMLoc mloc created from the TSMLoc parent. + If there is no parent TSMLoc, use TS_NULL_MLOC. + + @param bufp marshal buffer containing the TSMLoc handle to be + released. + @param parent location of the parent object from which the handle + was created. + @param mloc location of the handle to be released. + + */ + TSReturnCode TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc); + + /* -------------------------------------------------------------------------- + Install and plugin locations */ + /** + Gets the path of the directory in which Traffic Server is installed. + Use this function to specify the location of files that the + plugin uses. + + @return pointer to Traffic Server install directory. + + */ + const char *TSInstallDirGet(void); + + /** + Gets the path of the directory of Traffic Server configuration. + + @return pointer to Traffic Server configuration directory. + + */ + const char *TSConfigDirGet(void); + + /** + Gets the path of the directory of Traffic Server runtime. + + @return pointer to Traffic Server runtime directory. + + */ + const char *TSRuntimeDirGet(void); + + /** + Gets the path of the plugin directory relative to the Traffic Server + install directory. For example, to open the file "config_ui.txt" in + the plugin directory: + + @code + TSfopen("TSPluginInstallDirGet()/TSPluginDirGet()/config_ui.txt"); + @endcode + + @return pointer to plugin directory relative to Traffic Server install + directory. + + */ + const char *TSPluginDirGet(void); + + /* -------------------------------------------------------------------------- + Traffic Server Version */ + /** + Gets the version of Traffic Server currently running. Use this + function to make sure that the plugin version and Traffic Server + version are compatible. See the SDK sample code for usage. + + @return pointer to version of Traffic Server running the plugin. + + */ + const char *TSTrafficServerVersionGet(void); + + /** Get the major version of Traffic Server currently running. + This is the same as the first element of the string + returned by @c TSTrafficServerVersionGet + + @return The major version as an integer. + */ + int TSTrafficServerVersionGetMajor(void); + + /** Get the minor version of Traffic Server currently running. + This is the same as the second element of the string + returned by @c TSTrafficServerVersionGet + + @return The minor version as an integer. + */ + int TSTrafficServerVersionGetMinor(void); + + /** Get the patch version of Traffic Server currently running. + This is the same as the third element of the string + returned by @c TSTrafficServerVersionGet + + @return The patch version as an integer. + */ + int TSTrafficServerVersionGetPatch(void); + + /* -------------------------------------------------------------------------- + Plugin registration */ + + /** + This function registers your plugin with a particular version + of Traffic Server SDK. Use this function to make sure that the + Traffic Server version currently running also supports your plugin. + See the SDK sample code for usage. + + @param plugin_info contains registration information about your + plugin. See TSPluginRegistrationInfo. + @return TS_ERROR if the plugin registration failed. + + */ + TSReturnCode TSPluginRegister(const TSPluginRegistrationInfo *plugin_info); + + /** + This function provides the ability to enable/disable programmatically + the plugin dynamic reloading when the same Dynamic Shared Object (DSO) + is also used as a remap plugin. This overrides `proxy.config.plugin.dynamic_reload_mode` + configuration variable. + + @param enabled boolean flag. 0/false will disable the reload on the caller plugin. + @return TS_ERROR if the function is not called from within TSPluginInit or if TS is + unable to get the canonical path from the plugin's path. TS_SUCCESS otherwise. + + @note This function should be called from within TSPluginInit + */ + TSReturnCode TSPluginDSOReloadEnable(int enabled); + + /* -------------------------------------------------------------------------- + Files */ + /** + Opens a file for reading or writing and returns a descriptor for + accessing the file. The current implementation cannot open a file + for both reading or writing. See the SDK Programmer's Guide for + sample code. + + @param filename file to be opened. + @param mode specifies whether to open the file for reading or + writing. If mode is "r" then the file is opened for reading. + If mode is "w" then the file is opened for writing. Currently + "r" and "w" are the only two valid modes for opening a file. + @return descriptor for the file that TSfopen opens. Descriptors of + type TSFile can be greater than 256. + + */ + TSFile TSfopen(const char *filename, const char *mode); + + /** + Closes the file to which filep points and frees the data structures + and buffers associated with it. If the file was opened for writing, + any pending data is flushed. + + @param filep file to be closed. + + */ + void TSfclose(TSFile filep); + + /** + Attempts to read length bytes of data from the file pointed to by + filep into the buffer buf. + + @param filep name of the file to read from. + @param buf buffer to read into. + @param length amount of data to read, in bytes. + @return number of bytes read. If end of the file, it returns 0. + If the file was not opened for reading or if an error occurs + while reading the file, it returns -1. + + */ + ssize_t TSfread(TSFile filep, void *buf, size_t length); + + /** + Attempts to write length bytes of data from the buffer buf + to the file filep. Make sure that filep is open for writing. + You might want to check the number of bytes written (TSfwrite() + returns this value) against the value of length. If it is less, + there might be insufficient space on disk, for example. + + @param filep file to write into. + @param buf buffer containing the data to be written. + @param length amount of data to write to filep, in bytes. + @return number of bytes written to filep. If the file was not + opened for writing, it returns -1. If an error occurs while + writing, it returns the number of bytes successfully written. + + */ + ssize_t TSfwrite(TSFile filep, const void *buf, size_t length); + + /** + Flushes pending data that has been buffered up in memory from + previous calls to TSfwrite(). + + @param filep file to flush. + + */ + void TSfflush(TSFile filep); + + /** + Reads a line from the file pointed to by filep into the buffer buf. + Lines are terminated by a line feed character, '\n'. The line + placed in the buffer includes the line feed character and is + terminated with a null. If the line is longer than length bytes + then only the first length-minus-1 bytes are placed in buf. + + @param filep file to read from. + @param buf buffer to read into. + @param length size of the buffer to read into. + @return pointer to the string read into the buffer buf. + + */ + char *TSfgets(TSFile filep, char *buf, size_t length); + + /* -------------------------------------------------------------------------- + Error logging */ + /** + Writes printf-style error messages to the Traffic Server error + log. One advantage of TSError over printf is that each call is + atomically placed into the error log and is not garbled with other + error entries. This is not an issue in single-threaded programs + but is a definite nuisance in multi-threaded programs. + + @param fmt printf format description. + @param ... argument for the printf format description. + + Note: Your log monitoring (e.g. Splunk) needs to alert Ops of log + messages that contain ' ALERT: ' or ' EMERGENCY: ', these require + immediate attention. + + */ + void TSStatus(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log information + void TSNote(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log significant information + void TSWarning(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log concerning information + void TSError(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log operational failure, fail CI + void TSFatal(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log recoverable crash, fail CI, exit & restart + void TSAlert(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log recoverable crash, fail CI, exit & restart, Ops attention + void TSEmergency(const char *fmt, ...) TS_PRINTFLIKE(1, 2); // Log unrecoverable crash, fail CI, exit, Ops attention + + /* -------------------------------------------------------------------------- + Assertions */ + void _TSReleaseAssert(const char *txt, const char *f, int l) TS_NORETURN; + int _TSAssert(const char *txt, const char *f, int l); - This will return TS_ERROR if there was an issue while parsing the file. Particular node errors - should be handled by the @c TSYAMLRecNodeHandler implementation. -*/ -tsapi TSReturnCode TSRecYAMLConfigParse(TSYaml node, TSYAMLRecNodeHandler handler, void *data); +#define TSReleaseAssert(EX) ((void)((EX) ? (void)0 : _TSReleaseAssert(#EX, __FILE__, __LINE__))) -/* -------------------------------------------------------------------------- - tracing api */ +#define TSAssert(EX) (void)((EX) || (_TSAssert(#EX, __FILE__, __LINE__))) -tsapi int TSIsDebugTagSet(const char *t); -tsapi void TSDebug(const char *tag, const char *format_str, ...) TS_PRINTFLIKE(2, 3); -/** - Output a debug line even if the debug tag is turned off, as long as - debugging is enabled. Could be used as follows: - @code - TSDebugSpecific(TSHttpTxnDebugGet(txn), "plugin_tag" , "Hello World from transaction %p", txn); - @endcode - will be printed if the plugin_tag is enabled or the transaction specific - debugging is turned on for txn. - - @param debug_flag boolean flag. - @param tag Debug tag for the line. - @param format Format string. - @param ... Format arguments. - */ -tsapi void TSDebugSpecific(int debug_flag, const char *tag, const char *format_str, ...) TS_PRINTFLIKE(3, 4); -extern int diags_on_for_plugins; /* Do not use directly. */ + /* -------------------------------------------------------------------------- + Marshal buffers */ + /** + Creates a new marshal buffer and initializes the reference count + to 1. + + */ + TSMBuffer TSMBufferCreate(void); + + /** + Ignores the reference count and destroys the marshal buffer bufp. + The internal data buffer associated with the marshal buffer is + also destroyed if the marshal buffer allocated it. + + @param bufp marshal buffer to be destroyed. + + */ + TSReturnCode TSMBufferDestroy(TSMBuffer bufp); + + /* -------------------------------------------------------------------------- + URLs */ + /** + Creates a new URL within the marshal buffer bufp. Returns a + location for the URL within the marshal buffer. + + @param bufp marshal buffer containing the new URL. + @param locp pointer to a TSMLoc to store the MLoc into. + + */ + TSReturnCode TSUrlCreate(TSMBuffer bufp, TSMLoc *locp); + + /** + Copies the URL located at src_url within src_bufp to a URL + location within the marshal buffer dest_bufp, and returns the + TSMLoc location of the copied URL. Unlike TSUrlCopy(), you do + not have to create the destination URL before cloning. Release + the returned TSMLoc handle with a call to TSHandleMLocRelease(). + + @param dest_bufp marshal buffer containing the cloned URL. + @param src_bufp marshal buffer containing the URL to be cloned. + @param src_url location of the URL to be cloned, within the marshal + buffer src_bufp. + @param locp pointer to a TSMLoc to store the MLoc into. + + */ + TSReturnCode TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp); + + /** + Copies the contents of the URL at location src_loc within the + marshal buffer src_bufp to the location dest_loc within the marshal + buffer dest_bufp. TSUrlCopy() works correctly even if src_bufp + and dest_bufp point to different marshal buffers. Important: create + the destination URL before copying into it. Use TSUrlCreate(). + + @param dest_bufp marshal buffer to contain the copied URL. + @param dest_offset location of the URL to be copied. + @param src_bufp marshal buffer containing the source URL. + @param src_offset location of the source URL within src_bufp. + + */ + TSReturnCode TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset); + + /** + Formats a URL stored in an TSMBuffer into an TSIOBuffer. + + @param bufp marshal buffer contain the URL to be printed. + @param offset location of the URL within bufp. + @param iobufp destination TSIOBuffer for the URL. + + */ + void TSUrlPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp); + + /** + Parses a URL. The start pointer is both an input and an output + parameter and marks the start of the URL to be parsed. After + a successful parse, the start pointer equals the end pointer. + The end pointer must be one byte after the last character you + want to parse. The URL parsing routine assumes that everything + between start and end is part of the URL. It is up to higher level + parsing routines, such as TSHttpHdrParseReq(), to determine the + actual end of the URL. Returns TS_PARSE_ERROR if an error occurs, + otherwise TS_PARSE_DONE is returned to indicate success. + + @param bufp marshal buffer containing the URL to be parsed. + @param offset location of the URL to be parsed. + @param start points to the start of the URL to be parsed AND at + the end of a successful parse it will equal the end pointer. + @param end must be one byte after the last character. + @return TS_PARSE_ERROR or TS_PARSE_DONE. + + */ + TSParseResult TSUrlParse(TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); + + /** + Calculates the length of the URL located at url_loc within the + marshal buffer bufp if it were returned as a string. This length + is the same as the length returned by TSUrlStringGet(). + + @param bufp marshal buffer containing the URL whose length you want. + @param offset location of the URL within the marshal buffer bufp. + @return string length of the URL. + + */ + int TSUrlLengthGet(TSMBuffer bufp, TSMLoc offset); + + /** + Constructs a string representation of the URL located at url_loc + within bufp. TSUrlStringGet() stores the length of the allocated + string in the parameter length. This is the same length that + TSUrlLengthGet() returns. The returned string is allocated by a + call to TSmalloc(). It should be freed by a call to TSfree(). + The length parameter must be present, providing storage for the + URL string length value. + Note: To get the effective URL from a request, use the alternative + TSHttpTxnEffectiveUrlStringGet or + TSHttpHdrEffectiveUrlBufGet APIs. + + @param bufp marshal buffer containing the URL you want to get. + @param offset location of the URL within bufp. + @param length string length of the URL. + @return The URL as a string. + + */ + char *TSUrlStringGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Retrieves the scheme portion of the URL located at url_loc within + the marshal buffer bufp. TSUrlSchemeGet() places the length of + the string in the length argument. If the length is null then no + attempt is made to dereference it. + + @param bufp marshal buffer storing the URL. + @param offset location of the URL within bufp. + @param length length of the returned string. + @return The scheme portion of the URL, as a string. + + */ + const char *TSUrlRawSchemeGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Retrieves the scheme portion of the URL located at url_loc within + the marshal buffer bufp. TSUrlSchemeGet() places the length of + the string in the length argument. If the length is null then no + attempt is made to dereference it. If there is no explicit scheme, + a scheme of http is returned if the URL type is HTTP, and a scheme + of https is returned if the URL type is HTTPS. + + @param bufp marshal buffer storing the URL. + @param offset location of the URL within bufp. + @param length length of the returned string. + @return The scheme portion of the URL, as a string. + + */ + const char *TSUrlSchemeGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the scheme portion of the URL located at url_loc within + the marshal buffer bufp to the string value. If length is -1 + then TSUrlSchemeSet() assumes that value is null-terminated. + Otherwise, the length of the string value is taken to be length. + TSUrlSchemeSet() copies the string to within bufp, so it is OK + to modify or delete value after calling TSUrlSchemeSet(). + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param value value to set the URL's scheme to. + @param length string stored in value. + + */ + TSReturnCode TSUrlSchemeSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /* -------------------------------------------------------------------------- + Internet specific URLs */ + /** + Retrieves the user portion of the URL located at url_loc + within bufp. Note: the returned string is not guaranteed to + be null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param length length of the returned string. + @return user portion of the URL. + + */ + const char *TSUrlUserGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the user portion of the URL located at url_loc within bufp + to the string value. If length is -1 then TSUrlUserSet() assumes + that value is null-terminated. Otherwise, the length of the string + value is taken to be length. TSUrlUserSet() copies the string to + within bufp, so it is OK to modify or delete value after calling + TSUrlUserSet(). + + @param bufp marshal buffer containing the URL. + @param offset location of the URL whose user is to be set. + @param value holds the new user name. + @param length string length of value. + + */ + TSReturnCode TSUrlUserSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /** + Retrieves the password portion of the URL located at url_loc + within bufp. TSUrlPasswordGet() places the length of the returned + string in the length argument. Note: the returned string is + not guaranteed to be null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset + @param length of the returned password string. + @return password portion of the URL. + + */ + const char *TSUrlPasswordGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the password portion of the URL located at url_loc within + bufp to the string value. If length is -1 then TSUrlPasswordSet() + assumes that value is null-terminated. Otherwise, the length + of value is taken to be length. TSUrlPasswordSet() copies the + string to within bufp, so it is okay to modify or delete value + after calling TSUrlPasswordSet(). + + @param bufp marshal buffer containing the URL. + @param offset + @param value new password. + @param length of the new password. + + */ + TSReturnCode TSUrlPasswordSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /** + Retrieves the host portion of the URL located at url_loc + within bufp. Note: the returned string is not guaranteed to be + null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param length of the returned string. + @return Host portion of the URL. + + */ + const char *TSUrlHostGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the host portion of the URL at url_loc to the string value. + If length is -1 then TSUrlHostSet() assumes that value is + null-terminated. Otherwise, the length of the string value is + taken to be length. The string is copied to within bufp, so you + can modify or delete value after calling TSUrlHostSet(). + + @param bufp marshal buffer containing the URL to modify. + @param offset location of the URL. + @param value new host name for the URL. + @param length string length of the new host name of the URL. + + */ + TSReturnCode TSUrlHostSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /** + Returns the port portion of the URL located at url_loc if explicitly present, + otherwise the canonical port for the URL. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @return port portion of the URL. + + */ + int TSUrlPortGet(TSMBuffer bufp, TSMLoc offset); + + /** + Returns the port portion of the URL located at url_loc if explicitly present, + otherwise 0. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @return port portion of the URL. + + */ + int TSUrlRawPortGet(TSMBuffer bufp, TSMLoc offset); + + /** + Sets the port portion of the URL located at url_loc. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param port new port setting for the URL. + + */ + TSReturnCode TSUrlPortSet(TSMBuffer bufp, TSMLoc offset, int port); + + /* -------------------------------------------------------------------------- + HTTP specific URLs */ + /** + Retrieves the path portion of the URL located at url_loc within + bufp. TSUrlPathGet() places the length of the returned string in + the length argument. Note: the returned string is not guaranteed to + be null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param length of the returned string. + @return path portion of the URL. + + */ + const char *TSUrlPathGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the path portion of the URL located at url_loc within bufp + to the string value. If length is -1 then TSUrlPathSet() assumes + that value is null-terminated. Otherwise, the length of the value + is taken to be length. TSUrlPathSet() copies the string into bufp, + so you can modify or delete value after calling TSUrlPathSet(). + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param value new path string for the URL. + @param length of the new path string. + + */ + TSReturnCode TSUrlPathSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /* -------------------------------------------------------------------------- + FTP specific URLs */ + /** + Retrieves the FTP type of the URL located at url_loc within bufp. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @return FTP type of the URL. + + */ + int TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc offset); + + /** + Sets the FTP type portion of the URL located at url_loc within + bufp to the value type. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL to modify. + @param type new FTP type for the URL. + + */ + TSReturnCode TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc offset, int type); + + /* -------------------------------------------------------------------------- + HTTP specific URLs */ + /** + Retrieves the HTTP params portion of the URL located at url_loc + within bufp. The length of the returned string is in the length + argument. Note: the returned string is not guaranteed to be + null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param length of the returned string. + @return HTTP params portion of the URL. + + */ + const char *TSUrlHttpParamsGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the HTTP params portion of the URL located at url_loc within + bufp to the string value. If length is -1 that TSUrlHttpParamsSet() + assumes that value is null-terminated. Otherwise, the length of + the string value is taken to be length. TSUrlHttpParamsSet() + copies the string to within bufp, so you can modify or delete + value after calling TSUrlHttpParamsSet(). + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param value HTTP params string to set in the URL. + @param length string length of the new HTTP params value. + + */ + TSReturnCode TSUrlHttpParamsSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /** + Retrieves the HTTP query portion of the URL located at url_loc + within bufp. The length of the returned string is in the length + argument. Note: the returned string is not guaranteed to be + null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param length of the returned string. + @return HTTP query portion of the URL. + + */ + const char *TSUrlHttpQueryGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the HTTP query portion of the URL located at url_loc within + bufp to value. If length is -1, the string value is assumed to + be null-terminated; otherwise, the length of value is taken to be + length. TSUrlHttpQuerySet() copies the string to within bufp, so + you can modify or delete value after calling TSUrlHttpQuerySet(). + + @param bufp marshal buffer containing the URL. + @param offset location of the URL within bufp. + @param value new HTTP query string for the URL. + @param length of the new HTTP query string. + + */ + TSReturnCode TSUrlHttpQuerySet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /** + Retrieves the HTTP fragment portion of the URL located at url_loc + within bufp. The length of the returned string is in the length + argument. Note: the returned string is not guaranteed to be + null-terminated. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL. + @param length of the returned string. + @return HTTP fragment portion of the URL. + + */ + const char *TSUrlHttpFragmentGet(TSMBuffer bufp, TSMLoc offset, int *length); + + /** + Sets the HTTP fragment portion of the URL located at url_loc + within bufp to value. If length is -1, the string value is + assumed to be null-terminated; otherwise, the length of value + is taken to be length. TSUrlHttpFragmentSet() copies the string + to within bufp, so you can modify or delete value after calling + TSUrlHttpFragmentSet(). + + @param bufp marshal buffer containing the URL. + @param offset location of the URL within bufp. + @param value new HTTP fragment string for the URL. + @param length of the new HTTP query string. + + */ + TSReturnCode TSUrlHttpFragmentSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + + /** + Perform percent-encoding of the string in the buffer, storing the + new string in the destination buffer. The length parameter will be + set to the new (encoded) string length, or 0 if the encoding failed. + + @param str the string buffer to encode. + @param str_len length of the string buffer. + @param dst destination buffer. + @param dst_size size of the destination buffer. + @param length amount of data written to the destination buffer. + @param map optional (can be null) map of characters to encode. + + */ + TSReturnCode TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, size_t *length, + const unsigned char *map); + + /** + Similar to TSStringPercentEncode(), but works on a URL object. + + @param bufp marshal buffer containing the URL. + @param offset location of the URL within bufp. + @param dst destination buffer. + @param dst_size size of the destination buffer. + @param length amount of data written to the destination buffer. + @param map optional (can be null) map of characters to encode. + + */ + TSReturnCode TSUrlPercentEncode(TSMBuffer bufp, TSMLoc offset, char *dst, size_t dst_size, size_t *length, + const unsigned char *map); + + /** + Perform percent-decoding of the string in the buffer, writing + to the output buffer. The source and destination can be the same, + in which case they overwrite. The decoded string is always + guaranteed to be no longer than the source string. + + @param str the string to decode (and possibly write to). + @param str_len length of the input string (or 0). + @param dst output buffer (can be the same as src). + @param dst_len size of the output buffer. + @param length amount of data written to the destination buffer. + + */ + TSReturnCode TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length); + + /* -------------------------------------------------------------------------- + MIME headers */ + + /** + Creates a MIME parser. The parser's data structure contains + information about the header being parsed. A single MIME + parser can be used multiple times, though not simultaneously. + Before being used again, the parser must be cleared by calling + TSMimeParserClear(). + + */ + TSMimeParser TSMimeParserCreate(void); + + /** + Clears the specified MIME parser so that it can be used again. + + @param parser to be cleared. + + */ + void TSMimeParserClear(TSMimeParser parser); + + /** + Destroys the specified MIME parser and frees the associated memory. + + @param parser to destroy. + */ + void TSMimeParserDestroy(TSMimeParser parser); + + /** + Parse a MIME header date string. Candidate for deprecation in v10.0.0 + */ + time_t TSMimeParseDate(char const *const value_str, int const value_len); + + /** + Creates a new MIME header within bufp. Release with a call to + TSHandleMLocRelease(). + + @param bufp marshal buffer to contain the new MIME header. + @param locp buffer pointer to contain the MLoc + + */ + TSReturnCode TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp); + + /** + Destroys the MIME header located at hdr_loc within bufp. + + @param bufp marshal buffer containing the MIME header to destroy. + @param offset location of the MIME header. + + */ + TSReturnCode TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc offset); + + /** + Copies a specified MIME header to a specified marshal buffer, + and returns the location of the copied MIME header within the + destination marshal buffer. Unlike TSMimeHdrCopy(), you do not + have to create the destination MIME header before cloning. Release + the returned TSMLoc handle with a call to TSHandleMLocRelease(). + + @param dest_bufp destination marshal buffer. + @param src_bufp source marshal buffer. + @param src_hdr location of the source MIME header. + @param locp where to store the location of the copied MIME header. + + */ + TSReturnCode TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp); + + /** + Copies the contents of the MIME header located at src_loc + within src_bufp to the MIME header located at dest_loc within + dest_bufp. TSMimeHdrCopy() works correctly even if src_bufp and + dest_bufp point to different marshal buffers. Important: you must + create the destination MIME header before copying into it--use + TSMimeHdrCreate(). + + @param dest_bufp is the destination marshal buffer. + @param dest_offset + @param src_bufp is the source marshal buffer. + @param src_offset + + */ + TSReturnCode TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset); + + /** + Formats the MIME header located at hdr_loc within bufp into the + TSIOBuffer iobufp. + + @param bufp marshal buffer containing the header to be copied to + an TSIOBuffer. + @param offset + @param iobufp target TSIOBuffer. + + */ + void TSMimeHdrPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp); + + /** + Parses a MIME header. The MIME header must have already been + allocated and both bufp and hdr_loc must point within that header. + It is possible to parse a MIME header a single byte at a time + using repeated calls to TSMimeHdrParse(). As long as an error + does not occur, TSMimeHdrParse() consumes each single byte and + asks for more. + + @param parser parses the specified MIME header. + @param bufp marshal buffer containing the MIME header to be parsed. + @param offset + @param start both an input and output. On input, the start + argument points to the current position of the buffer being + parsed. On return, start is modified to point past the last + character parsed. + @param end points to one byte after the end of the buffer. + @return One of 3 possible int values: + - TS_PARSE_ERROR if there is a parsing error. + - TS_PARSE_DONE is returned when a "\r\n\r\n" pattern is + encountered, indicating the end of the header. + - TS_PARSE_CONT is returned if parsing of the header stopped + because the end of the buffer was reached. + + */ + TSParseResult TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); + + /** + Calculates the length of the MIME header located at hdr_loc if it + were returned as a string. This the length of the MIME header in + its unparsed form. + + @param bufp marshal buffer containing the MIME header. + @param offset location of the MIME header. + @return string length of the MIME header located at hdr_loc. + + */ + int TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc offset); + + /** + Removes and destroys all the MIME fields within the MIME header + located at hdr_loc within the marshal buffer bufp. + + @param bufp marshal buffer containing the MIME header. + @param offset location of the MIME header. + + */ + TSReturnCode TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc offset); + + /** + Returns a count of the number of MIME fields within the MIME header + located at hdr_loc within the marshal buffer bufp. + + @param bufp marshal buffer containing the MIME header. + @param offset location of the MIME header within bufp. + @return number of MIME fields within the MIME header located + at hdr_loc. + + */ + int TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc offset); + + /** + Retrieves the location of a specified MIME field within the + MIME header located at hdr_loc within bufp. The idx parameter + specifies which field to retrieve. The fields are numbered from 0 + to TSMimeHdrFieldsCount(bufp, hdr_loc) - 1. If idx does not lie + within that range then TSMimeHdrFieldGet returns 0. Release the + returned handle with a call to TSHandleMLocRelease. + + @param bufp marshal buffer containing the MIME header. + @param hdr location of the MIME header. + @param idx index of the field to get with base at 0. + @return location of the specified MIME field. + + */ + TSMLoc TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr, int idx); + + /** + Retrieves the TSMLoc location of a specified MIME field from within + the MIME header located at hdr. The name and length parameters + specify which field to retrieve. For each MIME field in the MIME + header, a case insensitive string comparison is done between + the field name and name. If TSMimeHdrFieldFind() cannot find the + requested field, it returns TS_NULL_MLOC. Release the returned + TSMLoc handle with a call to TSHandleMLocRelease(). + + @param bufp marshal buffer containing the MIME header field to find. + @param hdr location of the MIME header containing the field. + @param name of the field to retrieve. + @param length string length of the string name. If length is -1, + then name is assumed to be null-terminated. + @return location of the requested MIME field. If the field could + not be found, returns TS_NULL_MLOC. + + */ + TSMLoc TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr, const char *name, int length); + + /** + Returns the TSMLoc location of a specified MIME field from within + the MIME header located at hdr. The retrieved_str parameter + specifies which field to retrieve. For each MIME field in the + MIME header, a pointer comparison is done between the field name + and retrieved_str. This is a much quicker retrieval function + than TSMimeHdrFieldFind() since it obviates the need for a + string comparison. However, retrieved_str must be one of the + predefined field names of the form TS_MIME_FIELD_XXX for the + call to succeed. Release the returned TSMLoc handle with a call + to TSHandleMLocRelease(). + + @param bufp marshal buffer containing the MIME field. + @param hdr location of the MIME header containing the field. + @param retrieved_str specifies the field to retrieve. Must be + one of the predefined field names of the form TS_MIME_FIELD_XXX. + @return location of the requested MIME field. If the requested + field cannot be found, returns 0. + + */ + TSReturnCode TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + + /** + Removes the MIME field located at field within bufp from the + header located at hdr within bufp. If the specified field cannot + be found in the list of fields associated with the header then + nothing is done. + + Note: removing the field does not destroy the field, it only + detaches the field, hiding it from the printed output. The field + can be reattached with a call to TSMimeHdrFieldAppend(). If you + do not use the detached field you should destroy it with a call to + TSMimeHdrFieldDestroy() and release the handle field with a call + to TSHandleMLocRelease(). + + @param bufp contains the MIME field to remove. + @param hdr location of the header containing the MIME field to + be removed. This header could be an HTTP header or MIME header. + @param field is the location of the field to remove. + + */ + TSReturnCode TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + + TSReturnCode TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc hdr, TSMLoc *locp); + + /**************************************************************************** + * Create a new field and assign it a name all in one call + ****************************************************************************/ + TSReturnCode TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int name_len, TSMLoc *locp); + + /** + Destroys the MIME field located at field within bufp. You must + release the TSMLoc field with a call to TSHandleMLocRelease(). + + @param bufp contains the MIME field to be destroyed. + @param hdr location of the parent header containing the field + to be destroyed. This could be the location of a MIME header or + HTTP header. + @param field location of the field to be destroyed. + + */ + TSReturnCode TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + + TSReturnCode TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field, + TSMLoc *locp); + TSReturnCode TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, + TSMLoc src_field); + TSReturnCode TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, + TSMLoc src_field); + TSMLoc TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + TSMLoc TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + int TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + const char *TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length); + TSReturnCode TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name, int length); + + TSReturnCode TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + int TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + + const char *TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int *value_len_ptr); + int TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); + int64_t TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); + unsigned int TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); + time_t TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field); + TSReturnCode TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length); + TSReturnCode TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value); + TSReturnCode TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int64_t value); + TSReturnCode TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value); + TSReturnCode TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value); + + TSReturnCode TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length); + /* These Insert() APIs should be considered. Use the corresponding Set() API instead */ + TSReturnCode TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length); + TSReturnCode TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value); + TSReturnCode TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value); + TSReturnCode TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value); + + TSReturnCode TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx); + const char *TSMimeHdrStringToWKS(const char *str, int length); + + /* -------------------------------------------------------------------------- + HTTP headers */ + TSHttpParser TSHttpParserCreate(void); + void TSHttpParserClear(TSHttpParser parser); + void TSHttpParserDestroy(TSHttpParser parser); + + /** + Parses an HTTP request header. The HTTP header must have already + been created, and must reside inside the marshal buffer bufp. + The start argument points to the current position of the string + buffer being parsed. The end argument points to one byte after the + end of the buffer to be parsed. On return, TSHttpHdrParseReq() + modifies start to point past the last character parsed. + + It is possible to parse an HTTP request header a single byte at + a time using repeated calls to TSHttpHdrParseReq(). As long as + an error does not occur, the TSHttpHdrParseReq() function will + consume that single byte and ask for more. + + @param parser parses the HTTP header. + @param bufp marshal buffer containing the HTTP header to be parsed. + @param offset location of the HTTP header within bufp. + @param start both an input and output. On input, it points to the + current position of the string buffer being parsed. On return, + start is modified to point past the last character parsed. + @param end points to one byte after the end of the buffer to be parsed. + @return status of the parse: + - TS_PARSE_ERROR means there was a parsing error. + - TS_PARSE_DONE means that the end of the header was reached + (the parser encountered a "\r\n\r\n" pattern). + - TS_PARSE_CONT means that parsing of the header stopped because + the parser reached the end of the buffer (large headers can + span multiple buffers). + + */ + TSParseResult TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); + + TSParseResult TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc offset, const char **start, const char *end); + + TSMLoc TSHttpHdrCreate(TSMBuffer bufp); + + /** + Destroys the HTTP header located at hdr_loc within the marshal + buffer bufp. Do not forget to release the handle hdr_loc with a + call to TSHandleMLocRelease(). + + */ + void TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc offset); + + TSReturnCode TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp); + + /** + Copies the contents of the HTTP header located at src_loc within + src_bufp to the HTTP header located at dest_loc within dest_bufp. + TSHttpHdrCopy() works correctly even if src_bufp and dest_bufp + point to different marshal buffers. Make sure that you create the + destination HTTP header before copying into it. + + Note: TSHttpHdrCopy() appends the port number to the domain + of the URL portion of the header. For example, a copy of + http://www.example.com appears as http://www.example.com:80 in + the destination buffer. + + @param dest_bufp marshal buffer to contain the copied header. + @param dest_offset location of the copied header. + @param src_bufp marshal buffer containing the source header. + @param src_offset location of the source header. + + */ + TSReturnCode TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_offset, TSMBuffer src_bufp, TSMLoc src_offset); + + void TSHttpHdrPrint(TSMBuffer bufp, TSMLoc offset, TSIOBuffer iobufp); + + int TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc offset); + + TSHttpType TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc offset); + TSReturnCode TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc offset, TSHttpType type); + + int TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc offset); + TSReturnCode TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc offset, int ver); + + const char *TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc offset, int *length); + TSReturnCode TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + const char *TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc offset, int *length); + TSReturnCode TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc offset, TSMLoc *locp); + TSReturnCode TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc offset, TSMLoc url); + + TSHttpStatus TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc offset); + TSReturnCode TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc offset, TSHttpStatus status); + const char *TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc offset, int *length); + TSReturnCode TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc offset, const char *value, int length); + const char *TSHttpHdrReasonLookup(TSHttpStatus status); + + /* -------------------------------------------------------------------------- + Threads */ + TSThread TSThreadCreate(TSThreadFunc func, void *data); + TSThread TSThreadInit(void); + void TSThreadDestroy(TSThread thread); + void TSThreadWait(TSThread thread); + TSThread TSThreadSelf(void); + TSEventThread TSEventThreadSelf(void); + + /* -------------------------------------------------------------------------- + Mutexes */ + TSMutex TSMutexCreate(void); + void TSMutexDestroy(TSMutex mutexp); + void TSMutexLock(TSMutex mutexp); + TSReturnCode TSMutexLockTry(TSMutex mutexp); + + void TSMutexUnlock(TSMutex mutexp); + + /* -------------------------------------------------------------------------- + cachekey */ + /** + Creates (allocates memory for) a new cache key. + */ + TSCacheKey TSCacheKeyCreate(void); + + /** + Generates a key for an object to be cached (written to the cache). + + @param key to be associated with the cached object. Before + calling TSCacheKeySetDigest() you must create the key with + TSCacheKeyCreate(). + @param input string that uniquely identifies the object. In most + cases, it is the URL of the object. + @param length of the string input. + + */ + TSReturnCode TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length); + + TSReturnCode TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url); + + /** + Associates a host name to the cache key. Use this function if the + cache has been partitioned by hostname. The hostname tells the + cache which volume to use for the object. + + @param key of the cached object. + @param hostname to associate with the cache key. + @param host_len length of the string hostname. + + */ + TSReturnCode TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len); + + TSReturnCode TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache); + + /** + Destroys a cache key. You must destroy cache keys when you are + finished with them, i.e. after all reads and writes are completed. + + @param key to be destroyed. + + */ + TSReturnCode TSCacheKeyDestroy(TSCacheKey key); + + /* -------------------------------------------------------------------------- + cache url */ + TSReturnCode TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length); + + /* -------------------------------------------------------------------------- + Configuration */ + unsigned int TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp); + TSConfig TSConfigGet(unsigned int id); + void TSConfigRelease(unsigned int id, TSConfig configp); + void *TSConfigDataGet(TSConfig configp); + + /* -------------------------------------------------------------------------- + Management */ + void TSMgmtUpdateRegister(TSCont contp, const char *plugin_name); + TSReturnCode TSMgmtIntGet(const char *var_name, TSMgmtInt *result); + TSReturnCode TSMgmtCounterGet(const char *var_name, TSMgmtCounter *result); + TSReturnCode TSMgmtFloatGet(const char *var_name, TSMgmtFloat *result); + TSReturnCode TSMgmtStringGet(const char *var_name, TSMgmtString *result); + TSReturnCode TSMgmtSourceGet(const char *var_name, TSMgmtSource *source); + TSReturnCode TSMgmtConfigFileAdd(const char *parent, const char *fileName); + TSReturnCode TSMgmtDataTypeGet(const char *var_name, TSRecordDataType *result); + + /* -------------------------------------------------------------------------- + TSHRTime, this is a candidate for deprecation in v10.0.0 */ + TSHRTime TShrtime(void); + + /* -------------------------------------------------------------------------- + Continuations */ + TSCont TSContCreate(TSEventFunc funcp, TSMutex mutexp); + void TSContDestroy(TSCont contp); + void TSContDataSet(TSCont contp, void *data); + void *TSContDataGet(TSCont contp); + TSAction TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp); + TSAction TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread); + TSAction TSContScheduleEveryOnPool(TSCont contp, TSHRTime every /* millisecs */, TSThreadPool tp); + TSAction TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEventThread ethread); + TSReturnCode TSContThreadAffinitySet(TSCont contp, TSEventThread ethread); + TSEventThread TSContThreadAffinityGet(TSCont contp); + void TSContThreadAffinityClear(TSCont contp); + TSAction TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout); + int TSContCall(TSCont contp, TSEvent event, void *edata); + TSMutex TSContMutexGet(TSCont contp); + + /* -------------------------------------------------------------------------- + Plugin lifecycle hooks */ + void TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp); + /* -------------------------------------------------------------------------- + HTTP hooks */ + void TSHttpHookAdd(TSHttpHookID id, TSCont contp); + + /* -------------------------------------------------------------------------- + HTTP sessions */ + void TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp); + void TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event); + int TSHttpSsnTransactionCount(TSHttpSsn ssnp); + /* Get the TSVConn from a session. */ + TSVConn TSHttpSsnClientVConnGet(TSHttpSsn ssnp); + TSVConn TSHttpSsnServerVConnGet(TSHttpSsn ssnp); + /* Get the TSVConn from a transaction. */ + TSVConn TSHttpTxnServerVConnGet(TSHttpTxn txnp); + + /* -------------------------------------------------------------------------- + SSL connections */ + /* Re-enable an SSL connection from a hook. + This must be called exactly once before the SSL connection will resume. */ + void TSVConnReenable(TSVConn sslvcp); + /* Extended version that allows for passing a status event on reenabling + */ + void TSVConnReenableEx(TSVConn sslvcp, TSEvent event); + /* Set the connection to go into blind tunnel mode */ + TSReturnCode TSVConnTunnel(TSVConn sslp); + /* Return the SSL object associated with the connection */ + TSSslConnection TSVConnSslConnectionGet(TSVConn sslp); + /* Return the intermediate X509StoreCTX object that references the certificate being validated */ + TSSslVerifyCTX TSVConnSslVerifyCTXGet(TSVConn sslp); + /* Fetch a SSL context from the global lookup table */ + TSSslContext TSSslContextFindByName(const char *name); + TSSslContext TSSslContextFindByAddr(struct sockaddr const *); + /* Fetch SSL client contexts from the global lookup table */ + TSReturnCode TSSslClientContextsNamesGet(int n, const char **result, int *actual); + TSSslContext TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths); + + /* Update SSL certs in internal storage from given path */ + TSReturnCode TSSslClientCertUpdate(const char *cert_path, const char *key_path); + TSReturnCode TSSslServerCertUpdate(const char *cert_path, const char *key_path); + + /* Update the transient secret table for SSL_CTX loading */ + TSReturnCode TSSslSecretSet(const char *secret_name, int secret_name_length, const char *secret_data, int secret_data_length); + + /* Returns secret with given name (not null terminted). If there is no secret with the given name, return value will + ** be null and secret_data_lenght will be zero. Calling code must free data buffer by calling TSfree(). */ + char *TSSslSecretGet(const char *secret_name, int secret_name_length, int *secret_data_length); + + TSReturnCode TSSslSecretUpdate(const char *secret_name, int secret_name_length); + + /* Create a new SSL context based on the settings in records.yaml */ + TSSslContext TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_file); + void TSSslContextDestroy(TSSslContext ctx); + TSReturnCode TSSslTicketKeyUpdate(char *ticketData, int ticketDataLen); + TSAcceptor TSAcceptorGet(TSVConn sslp); + TSAcceptor TSAcceptorGetbyID(int ID); + int TSAcceptorCount(); + int TSAcceptorIDGet(TSAcceptor acceptor); + TSReturnCode TSVConnProtocolDisable(TSVConn connp, const char *protocol_name); + TSReturnCode TSVConnProtocolEnable(TSVConn connp, const char *protocol_name); + + /* Returns 1 if the sslp argument refers to a SSL connection */ + int TSVConnIsSsl(TSVConn sslp); + /* Returns 1 if a certificate was provided in the TLS handshake, 0 otherwise. + */ + int TSVConnProvidedSslCert(TSVConn sslp); + const char *TSVConnSslSniGet(TSVConn sslp, int *length); + + TSSslSession TSSslSessionGet(const TSSslSessionID *session_id); + int TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_ptr); + TSReturnCode TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, TSSslConnection ssl_conn); + TSReturnCode TSSslSessionRemove(const TSSslSessionID *session_id); + + /* -------------------------------------------------------------------------- + HTTP transactions */ + void TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp); + TSHttpSsn TSHttpTxnSsnGet(TSHttpTxn txnp); + + /* Gets the client request header for a specified HTTP transaction. */ + TSReturnCode TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + /* Gets the client response header for a specified HTTP transaction. */ + TSReturnCode TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + /* Gets the server request header from a specified HTTP transaction. */ + TSReturnCode TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + /* Gets the server response header from a specified HTTP transaction. */ + TSReturnCode TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + /* Gets the cached request header for a specified HTTP transaction. */ + TSReturnCode TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + /* Gets the cached response header for a specified HTTP transaction. */ + TSReturnCode TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + + TSReturnCode TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc); + + /** + * @brief Gets the number of transactions between the Traffic Server proxy and the origin server from a single session. + * Any value greater than zero indicates connection reuse. + * + * @param txnp The transaction + * @return int The number of transactions between the Traffic Server proxy and the origin server from a single session + */ + int TSHttpTxnServerSsnTransactionCount(TSHttpTxn txnp); + + /** Get the effective URL for the transaction. + The effective URL is the URL taking in to account both the explicit + URL in the request and the HOST field. + + A possibly non-null terminated string is returned. + + @note The returned string is allocated and must be freed by the caller + after use with @c TSfree. + */ + char *TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length /**< String length return, may be @c nullptr. */ + ); + + /** Get the effective URL for in the header (if any), with the scheme and host normalized to lower case letter. + The effective URL is the URL taking in to account both the explicit + URL in the request and the HOST field. + + A possibly non-null terminated string is returned. + + @return TS_SUCCESS if successful, TS_ERROR if no URL in header or other error. + */ + TSReturnCode TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_t size, int64_t *length); + + void TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag); + void TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag); + + /** Set flag indicating whether or not to cache the server response for + given TSHttpTxn + + @note This should be done in the HTTP_READ_RESPONSE_HDR_HOOK or earlier. + + @note If TSHttpTxnRespCacheableSet() is not working the way you expect, + this may be the function you should use instead. + + @param txnp The transaction whose server response you do not want to store. + @param flag Set 0 to allow storing and 1 to disable storing. + + @return TS_SUCCESS. + */ + TSReturnCode TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag); + + /** Get flag indicating whether or not to cache the server response for + given TSHttpTxn + @param txnp The transaction whose server response you do not want to store. + + @return TS_SUCCESS. + */ + bool TSHttpTxnServerRespNoStoreGet(TSHttpTxn txnp); + TSReturnCode TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + char *TSFetchRespGet(TSHttpTxn txnp, int *length); + TSReturnCode TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status); + + TSReturnCode TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + + /** Set the @a port value for the inbound (user agent) connection in the transaction @a txnp. + This is used primarily where the connection is synthetic and therefore does not have a port. + @note @a port is in @b host @b order. + */ + void TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port); + + /** Get client address for transaction @a txnp. + Retrieves the socket address of the remote client that has + connected to Traffic Server for transaction @a txnp. The + return structure is the generic socket address storage in + order to be address-family agnostic. The user of this function + can then go on to do the appropriate thing with the type + specified in the ss_family field of the structure whether + that be for IPv4, IPv6, or any other address family. + + @return Client address for connection to client in transaction @a txnp. + + */ + struct sockaddr const *TSHttpTxnClientAddrGet(TSHttpTxn txnp); + /** Get the incoming address. + + @note The pointer is valid only for the current callback. Clients + that need to keep the value across callbacks must maintain their + own storage. + + @return Local address of the client connection for transaction @a txnp. + */ + struct sockaddr const *TSHttpTxnIncomingAddrGet(TSHttpTxn txnp); + /** Get the outgoing address. + + @note The pointer is valid only for the current callback. Clients + that need to keep the value across callbacks must maintain their + own storage. + + @return Local address of the server connection for transaction @a txnp. + */ + struct sockaddr const *TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp); + /** Get the origin server address. + * + @note The pointer is valid only for the current callback. Clients + that need to keep the value across callbacks must maintain their + own storage. + + @return The address of the origin server for transaction @a txnp. + */ + struct sockaddr const *TSHttpTxnServerAddrGet(TSHttpTxn txnp); + /** Set the origin server address. + + This must be invoked before the origin server address is looked up. + If called no lookup is done, the address @a addr is used instead. + + @return @c TS_SUCCESS if the origin server address is set, @c TS_ERROR otherwise. + */ + TSReturnCode TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr /**< Address for origin server. */ + ); + + /** Get the next hop address. + * + @note The pointer is valid only for the current callback. Clients + that need to keep the value across callbacks must maintain their + own storage. + + @return The address of the next hop for transaction @a txnp. + */ + struct sockaddr const *TSHttpTxnNextHopAddrGet(TSHttpTxn txnp); + + /** Get the next hop name. + * + @note The pointer is valid only for the current callback. Clients + that need to keep the value across callbacks must maintain their + own storage. + + @return The name of the next hop for transaction @a txnp. + */ + const char *TSHttpTxnNextHopNameGet(TSHttpTxn txnp); + + /** Get the next hop port. + * + Retrieves the next hop parent port. + Returns -1 if not valid. + + @return The port of the next hop for transaction @a txnp. + + */ + int TSHttpTxnNextHopPortGet(TSHttpTxn txnp); + + TSReturnCode TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp); + TSReturnCode TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, struct sockaddr const *addr); + TSReturnCode TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag); + TSReturnCode TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp); + + /* TS-1008: the above TXN calls for the Client conn should work with SSN */ + struct sockaddr const *TSHttpSsnClientAddrGet(TSHttpSsn ssnp); + struct sockaddr const *TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp); + TSReturnCode TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp); + /* TS-1008 END */ + + /** Change packet firewall mark for the client side connection + * + @note The change takes effect immediately + + @return TS_SUCCESS if the client connection was modified + */ + TSReturnCode TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark); + + /** Change packet firewall mark for the server side connection + * + @note The change takes effect immediately, if no OS connection has been + made, then this sets the mark that will be used IF an OS connection + is established + + @return TS_SUCCESS if the (future?) server connection was modified + */ + TSReturnCode TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark); + + /** Change packet DSCP for the client side connection + * + @note The change takes effect immediately + + @return TS_SUCCESS if the client connection was modified + */ + TSReturnCode TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp); + + /** Change packet DSCP for the server side connection + * + + @note The change takes effect immediately, if no OS connection has been + made, then this sets the mark that will be used IF an OS connection + is established + + @return TS_SUCCESS if the (future?) server connection was modified + */ + TSReturnCode TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp); + + /** + Sets an error type body to a transaction. Note that both string arguments + must be allocated with TSmalloc() or TSstrdup(). The mimetype argument is + optional, if not provided it defaults to "text/html". Sending an empty + string would prevent setting a content type header (but that is not advised). + + @param txnp HTTP transaction whose parent proxy to get. + @param buf The body message (must be heap allocated). + @param buflength Length of the body message. + @param mimetype The MIME type to set the response to (can be null, but must + be heap allocated if non-null). + */ + void TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetype); + + /** + Retrieves the parent proxy hostname and port, if parent + proxying is enabled. If parent proxying is not enabled, + TSHttpTxnParentProxyGet() sets hostname to nullptr and port to -1. + + @param txnp HTTP transaction whose parent proxy to get. + @param hostname of the parent proxy. + @param port parent proxy's port. + + */ + TSReturnCode TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port); + + /** + Sets the parent proxy name and port. The string hostname is copied + into the TSHttpTxn; you can modify or delete the string after + calling TSHttpTxnParentProxySet(). + + @param txnp HTTP transaction whose parent proxy to set. + @param hostname parent proxy host name string. + @param port parent proxy port to set. + + */ + void TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port); + + TSReturnCode TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); + TSReturnCode TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); + + void TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on); + void TSHttpTxnTransformedRespCache(TSHttpTxn txnp, int on); + + /** + Notifies the HTTP transaction txnp that the plugin is + finished processing the current hook. The plugin tells the + transaction to either continue (TS_EVENT_HTTP_CONTINUE) or stop + (TS_EVENT_HTTP_ERROR). + + You must always reenable the HTTP transaction after the processing + of each transaction event. However, never reenable twice. + Reenabling twice is a serious error. + + @param txnp transaction to be reenabled. + @param event tells the transaction how to continue: + - TS_EVENT_HTTP_CONTINUE, which means that the transaction + should continue. + - TS_EVENT_HTTP_ERROR which terminates the transaction + and sends an error to the client if no response has already + been sent. + + */ + void TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event); + TSReturnCode TSHttpCacheReenable(TSCacheTxn txnp, const TSEvent event, const void *data, const uint64_t size); + + /* The reserve API should only be use in TSAPI plugins, during plugin initialization! + The lookup methods can be used anytime, but are best used during initialization as well, + or at least "cache" the results for best performance. */ + TSReturnCode TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *description, int *arg_idx); + TSReturnCode TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description); + TSReturnCode TSUserArgIndexLookup(TSUserArgType type, int arg_idx, const char **name, const char **description); + void TSUserArgSet(void *data, int arg_idx, void *arg); + void *TSUserArgGet(void *data, int arg_idx); + + void TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status); + TSHttpStatus TSHttpTxnStatusGet(TSHttpTxn txnp); + + void TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout); + void TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout); + void TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout); + void TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout); + + TSServerState TSHttpTxnServerStateGet(TSHttpTxn txnp); + + /* -------------------------------------------------------------------------- + Transaction specific debugging control */ + + /** + Set the transaction specific debugging flag for this transaction. + When turned on, internal debug messages related to this transaction + will be written even if the debug tag isn't on. + + @param txnp transaction to change. + @param on set to 1 to turn on, 0 to turn off. + */ + void TSHttpTxnDebugSet(TSHttpTxn txnp, int on); + /** + Returns the transaction specific debugging flag for this transaction. + + @param txnp transaction to check. + @return 1 if enabled, 0 otherwise. + */ + int TSHttpTxnDebugGet(TSHttpTxn txnp); + /** + Set the session specific debugging flag for this client session. + When turned on, internal debug messages related to this session and all transactions + in the session will be written even if the debug tag isn't on. + + @param ssnp Client session to change. + @param on set to 1 to turn on, 0 to turn off. + */ + void TSHttpSsnDebugSet(TSHttpSsn ssnp, int on); + /** + Returns the transaction specific debugging flag for this client session. + + @param txnp Client session to check. + @return 1 if enabled, 0 otherwise. + */ + int TSHttpSsnDebugGet(TSHttpSsn ssnp, int *on); + + /* -------------------------------------------------------------------------- + Intercepting Http Transactions */ + + /** + Allows a plugin take over the servicing of the request as though + it was the origin server. contp will be sent TS_EVENT_NET_ACCEPT. + The edata passed with TS_NET_EVENT_ACCEPT is an TSVConn just as + it would be for a normal accept. The plugin must act as if it is + an http server and read the http request and body off the TSVConn + and send an http response header and body. + + TSHttpTxnIntercept() must be called be called from only + TS_HTTP_READ_REQUEST_HOOK. Using TSHttpTxnIntercept will + bypass the Traffic Server cache. If response sent by the plugin + should be cached, use TSHttpTxnServerIntercept() instead. + TSHttpTxnIntercept() primary use is allow plugins to serve data + about their functioning directly. + + TSHttpTxnIntercept() must only be called once per transaction. + + @param contp continuation called to handle the interception. + @param txnp transaction to be intercepted. + + */ + void TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp); + + /** + Allows a plugin take over the servicing of the request as though + it was the origin server. In the event a request needs to be + made to the server for transaction txnp, contp will be sent + TS_EVENT_NET_ACCEPT. The edata passed with TS_NET_EVENT_ACCEPT + is an TSVConn just as it would be for a normal accept. The plugin + must act as if it is an http server and read the http request and + body off the TSVConn and send an http response header and body. + + TSHttpTxnInterceptServer() must be not be called after + the connection to the server has taken place. The last hook + last hook in that TSHttpTxnIntercept() can be called from is + TS_HTTP_READ_CACHE_HDR_HOOK. If a connection to the server is + not necessary, contp is not called. + + The response from the plugin is cached subject to standard + and configured http caching rules. Should the plugin wish the + response not be cached, the plugin must use appropriate http + response headers to prevent caching. The primary purpose of + TSHttpTxnInterceptServer() is allow plugins to provide gateways + to other protocols or to allow to plugin to it's own transport for + the next hop to the server. TSHttpTxnInterceptServer() overrides + parent cache configuration. + + TSHttpTxnInterceptServer() must only be called once per + transaction. + + @param contp continuation called to handle the interception + @param txnp transaction to be intercepted. + + */ + void TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp); + + /* -------------------------------------------------------------------------- + Initiate Http Connection */ + + /** + Allows the plugin to initiate an http connection. The TSVConn the + plugin receives as the result of successful operates identically to + one created through TSNetConnect. Aside from allowing the plugin + to set the client ip and port for logging, the functionality of + TSHttpConnect() is identical to connecting to localhost on the + proxy port with TSNetConnect(). TSHttpConnect() is more efficient + than TSNetConnect() to localhost since it avoids the overhead of + passing the data through the operating system. + + This returns a VConn that connected to the transaction. + + @param options a TSHttpConnectPluginOptions structure that specifies options. + */ + TSVConn TSHttpConnectPlugin(TSHttpConnectOptions *options); + + /** Backwards compatible version. + This function calls This provides a @a buffer_index of 8 and a @a buffer_water_mark of 0. + + @param addr Target address of the origin server. + @param tag A logging tag that can be accessed via the pitag field. May be @c nullptr. + @param id A logging id that can be access via the piid field. + */ + TSVConn TSHttpConnectWithPluginId(struct sockaddr const *addr, const char *tag, int64_t id); + + /** Backwards compatible version. + This provides a @a tag of "plugin" and an @a id of 0. + */ + TSVConn TSHttpConnect(struct sockaddr const *addr); + + /** + Get an instance of TSHttpConnectOptions with default values. + */ + TSHttpConnectOptions TSHttpConnectOptionsGet(TSConnectType connect_type); + + /** + Get the value of proxy.config.plugin.vc.default_buffer_index from the TSHttpTxn + */ + TSIOBufferSizeIndex TSPluginVCIOBufferIndexGet(TSHttpTxn txnp); + + /** + Get the value of proxy.config.plugin.vc.default_buffer_water_mark from the TSHttpTxn + */ + TSIOBufferWaterMark TSPluginVCIOBufferWaterMarkGet(TSHttpTxn txnp); + + /* -------------------------------------------------------------------------- + Initiate Transparent Http Connection */ + /** + Allows the plugin to initiate a transparent http connection. This operates + identically to TSHttpConnect except that it is treated as an intercepted + transparent connection by the session and transaction state machines. + + @param client_addr the address that the resulting connection will be seen as + coming from + @param server_addr the address that the resulting connection will be seen as + attempting to connect to when intercepted + @param vc will be set to point to the new TSVConn on success. + + */ + TSVConn TSHttpConnectTransparent(struct sockaddr const *client_addr, struct sockaddr const *server_addr); + + TSFetchSM TSFetchUrl(const char *request, int request_len, struct sockaddr const *addr, TSCont contp, + TSFetchWakeUpOptions callback_options, TSFetchEvent event); + void TSFetchPages(TSFetchUrlParams_t *params); + + /* Check if HTTP State machine is internal or not */ + int TSHttpTxnIsInternal(TSHttpTxn txnp); + int TSHttpSsnIsInternal(TSHttpSsn ssnp); + + /* -------------------------------------------------------------------------- + HTTP alternate selection */ + TSReturnCode TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset); + TSReturnCode TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset); + TSReturnCode TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *offset); + void TSHttpAltInfoQualitySet(TSHttpAltInfo infop, float quality); + + /* -------------------------------------------------------------------------- + Actions */ + void TSActionCancel(TSAction actionp); + int TSActionDone(TSAction actionp); + + /* -------------------------------------------------------------------------- + VConnections */ + TSVIO TSVConnReadVIOGet(TSVConn connp); + TSVIO TSVConnWriteVIOGet(TSVConn connp); + int TSVConnClosedGet(TSVConn connp); + + TSVIO TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes); + TSVIO TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbytes); + void TSVConnClose(TSVConn connp); + void TSVConnAbort(TSVConn connp, int error); + void TSVConnShutdown(TSVConn connp, int read, int write); + + /* -------------------------------------------------------------------------- + Cache VConnections */ + int64_t TSVConnCacheObjectSizeGet(TSVConn connp); + + /* -------------------------------------------------------------------------- + Transformations */ + TSVConn TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp); + TSVConn TSTransformOutputVConnGet(TSVConn connp); + + /* -------------------------------------------------------------------------- + Net VConnections */ + struct sockaddr const *TSNetVConnRemoteAddrGet(TSVConn vc); + + /** + Opens a network connection to the host specified by ip on the port + specified by port. If the connection is successfully opened, contp + is called back with the event TS_EVENT_NET_CONNECT and the new + network vconnection will be passed in the event data parameter. + If the connection is not successful, contp is called back with + the event TS_EVENT_NET_CONNECT_FAILED. + + @return something allows you to check if the connection is complete, + or cancel the attempt to connect. + + */ + TSAction TSNetConnect( + TSCont contp, /**< continuation that is called back when the attempted net connection either succeeds or fails. */ + struct sockaddr const *to /**< Address to which to connect. */ + ); + + /** + * Retrieves the continuation associated with creating the TSVConn + */ + TSCont TSNetInvokingContGet(TSVConn conn); + + /** + * Retrieves the transaction associated with creating the TSVConn + */ + TSHttpTxn TSNetInvokingTxnGet(TSVConn conn); + + TSAction TSNetAccept(TSCont contp, int port, int domain, int accept_threads); + + /** + Listen on all SSL ports for connections for the specified protocol name. + + TSNetAcceptNamedProtocol registers the specified protocol for all + statically configured TLS ports. When a client using the TLS Next Protocol + Negotiation extension negotiates the requested protocol, TrafficServer will + route the request to the given handler. Note that the protocol is not + registered on ports opened by other plugins. + + The event and data provided to the handler are the same as for + TSNetAccept(). If a connection is successfully accepted, the event code + will be TS_EVENT_NET_ACCEPT and the event data will be a valid TSVConn + bound to the accepted connection. + + Neither contp nor protocol are copied. They must remain valid for the + lifetime of the plugin. + + TSNetAcceptNamedProtocol fails if the requested protocol cannot be + registered on all of the configured TLS ports. If it fails, the protocol + will not be registered on any ports (ie.. no partial failure). + */ + TSReturnCode TSNetAcceptNamedProtocol(TSCont contp, const char *protocol); + + /** + Create a new port from the string specification used by the + proxy.config.http.server_ports configuration value. + */ + TSPortDescriptor TSPortDescriptorParse(const char *descriptor); + + /** + Start listening on the given port descriptor. If a connection is + successfully accepted, the TS_EVENT_NET_ACCEPT is delivered to the + continuation. The event data will be a valid TSVConn bound to the accepted + connection. + */ + TSReturnCode TSPortDescriptorAccept(TSPortDescriptor, TSCont); + + /* -------------------------------------------------------------------------- + DNS Lookups */ + TSAction TSHostLookup(TSCont contp, const char *hostname, size_t namelen); + /** Retrieve an address from the host lookup. + * + * @param lookup_result Result handle passed to event callback. + * @return A @c sockaddr with the address if successful, a @c nullptr if not. + */ + struct sockaddr const *TSHostLookupResultAddrGet(TSHostLookupResult lookup_result); + + /* TODO: Eventually, we might want something like this as well, but it requires + support for building the HostDBInfo struct: + void TSHostLookupResultSet(TSHttpTxn txnp, TSHostLookupResult result); + */ + + /* -------------------------------------------------------------------------- + Cache VConnections */ + /** + Asks the Traffic Server cache if the object corresponding to key + exists in the cache and can be read. If the object can be read, + the Traffic Server cache calls the continuation contp back with + the event TS_EVENT_CACHE_OPEN_READ. In this case, the cache also + passes contp a cache vconnection and contp can then initiate a + read operation on that vconnection using TSVConnRead. + + If the object cannot be read, the cache calls contp back with + the event TS_EVENT_CACHE_OPEN_READ_FAILED. The user (contp) + has the option to cancel the action returned by TSCacheRead. + Note that reentrant calls are possible, i.e. the cache can call + back the user (contp) in the same call. + + @param contp continuation to be called back if a read operation + is permissible. + @param key cache key corresponding to the object to be read. + @return something allowing the user to cancel or schedule the + cache read. + + */ + TSAction TSCacheRead(TSCont contp, TSCacheKey key); + + /** + Asks the Traffic Server cache if contp can start writing the + object (corresponding to key) to the cache. If the object + can be written, the cache calls contp back with the event + TS_EVENT_CACHE_OPEN_WRITE. In this case, the cache also passes + contp a cache vconnection and contp can then initiate a write + operation on that vconnection using TSVConnWrite. The object + is not committed to the cache until the vconnection is closed. + When all data has been transferred, the user (contp) must do + an TSVConnClose. In case of any errors, the user MUST do an + TSVConnAbort(contp, 0). + + If the object cannot be written, the cache calls contp back with + the event TS_EVENT_CACHE_OPEN_WRITE_FAILED. This can happen, + for example, if there is another object with the same key being + written to the cache. The user (contp) has the option to cancel + the action returned by TSCacheWrite. + + Note that reentrant calls are possible, i.e. the cache can call + back the user (contp) in the same call. + + @param contp continuation that the cache calls back (telling it + whether the write operation can proceed or not). + @param key cache key corresponding to the object to be cached. + @return something allowing the user to cancel or schedule the + cache write. + + */ + TSAction TSCacheWrite(TSCont contp, TSCacheKey key); + + /** + Removes the object corresponding to key from the cache. If the + object was removed successfully, the cache calls contp back + with the event TS_EVENT_CACHE_REMOVE. If the object was not + found in the cache, the cache calls contp back with the event + TS_EVENT_CACHE_REMOVE_FAILED. + + In both of these callbacks, the user (contp) does not have to do + anything. The user does not get any vconnection from the cache, + since no data needs to be transferred. When the cache calls + contp back with TS_EVENT_CACHE_REMOVE, the remove has already + been committed. + + @param contp continuation that the cache calls back reporting the + success or failure of the remove. + @param key cache key corresponding to the object to be removed. + @return something allowing the user to cancel or schedule the + remove. + + */ + TSAction TSCacheRemove(TSCont contp, TSCacheKey key); + TSReturnCode TSCacheReady(int *is_ready); + TSAction TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second); + + /* -------------------------------------------------------------------------- + VIOs */ + void TSVIOReenable(TSVIO viop); + TSIOBuffer TSVIOBufferGet(TSVIO viop); + TSIOBufferReader TSVIOReaderGet(TSVIO viop); + int64_t TSVIONBytesGet(TSVIO viop); + void TSVIONBytesSet(TSVIO viop, int64_t nbytes); + int64_t TSVIONDoneGet(TSVIO viop); + void TSVIONDoneSet(TSVIO viop, int64_t ndone); + int64_t TSVIONTodoGet(TSVIO viop); + TSMutex TSVIOMutexGet(TSVIO viop); + TSCont TSVIOContGet(TSVIO viop); + TSVConn TSVIOVConnGet(TSVIO viop); + + /* -------------------------------------------------------------------------- + Buffers */ + TSIOBuffer TSIOBufferCreate(void); + + /** + Creates a new TSIOBuffer of the specified size. With this function, + you can create smaller buffers than the 32K buffer created by + TSIOBufferCreate(). In some situations using smaller buffers can + improve performance. + + @param index size of the new TSIOBuffer to be created. + @param new TSIOBuffer of the specified size. + + */ + TSIOBuffer TSIOBufferSizedCreate(TSIOBufferSizeIndex index); + + /** + The watermark of an TSIOBuffer is the minimum number of bytes + of data that have to be in the buffer before calling back any + continuation that has initiated a read operation on this buffer. + TSIOBufferWaterMarkGet() will provide the size of the watermark, + in bytes, for a specified TSIOBuffer. + + @param bufp buffer whose watermark the function gets. + + */ + int64_t TSIOBufferWaterMarkGet(TSIOBuffer bufp); + + /** + The watermark of an TSIOBuffer is the minimum number of bytes + of data that have to be in the buffer before calling back any + continuation that has initiated a read operation on this buffer. + As a writer feeds data into the TSIOBuffer, no readers are called + back until the amount of data reaches the watermark. Setting + a watermark can improve performance because it avoids frequent + callbacks to read small amounts of data. TSIOBufferWaterMarkSet() + assigns a watermark to a particular TSIOBuffer. + + @param bufp buffer whose water mark the function sets. + @param water_mark watermark setting, as a number of bytes. + + */ + void TSIOBufferWaterMarkSet(TSIOBuffer bufp, int64_t water_mark); + + void TSIOBufferDestroy(TSIOBuffer bufp); + TSIOBufferBlock TSIOBufferStart(TSIOBuffer bufp); + int64_t TSIOBufferCopy(TSIOBuffer bufp, TSIOBufferReader readerp, int64_t length, int64_t offset); + + /** + Writes length bytes of data contained in the string buf to the + TSIOBuffer bufp. Returns the number of bytes of data successfully + written to the TSIOBuffer. + + @param bufp is the TSIOBuffer to write into. + @param buf string to write into the TSIOBuffer. + @param length of the string buf. + @return length of data successfully copied into the buffer, + in bytes. + + */ + int64_t TSIOBufferWrite(TSIOBuffer bufp, const void *buf, int64_t length); + void TSIOBufferProduce(TSIOBuffer bufp, int64_t nbytes); + + TSIOBufferBlock TSIOBufferBlockNext(TSIOBufferBlock blockp); + const char *TSIOBufferBlockReadStart(TSIOBufferBlock blockp, TSIOBufferReader readerp, int64_t *avail); + int64_t TSIOBufferBlockReadAvail(TSIOBufferBlock blockp, TSIOBufferReader readerp); + char *TSIOBufferBlockWriteStart(TSIOBufferBlock blockp, int64_t *avail); + int64_t TSIOBufferBlockWriteAvail(TSIOBufferBlock blockp); + + TSIOBufferReader TSIOBufferReaderAlloc(TSIOBuffer bufp); + TSIOBufferReader TSIOBufferReaderClone(TSIOBufferReader readerp); + void TSIOBufferReaderFree(TSIOBufferReader readerp); + TSIOBufferBlock TSIOBufferReaderStart(TSIOBufferReader readerp); + void TSIOBufferReaderConsume(TSIOBufferReader readerp, int64_t nbytes); + int64_t TSIOBufferReaderAvail(TSIOBufferReader readerp); + int64_t TSIOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length); + + struct sockaddr const *TSNetVConnLocalAddrGet(TSVConn vc); + + /* -------------------------------------------------------------------------- + Stats and configs based on librecords raw stats (this is preferred API until we + rewrite stats). + + This is available as of Apache TS v2.2.*/ + enum TSStatPersistence { + TS_STAT_PERSISTENT = 1, + TS_STAT_NON_PERSISTENT, + }; + + enum TSStatSync { + TS_STAT_SYNC_SUM = 0, + TS_STAT_SYNC_COUNT, + TS_STAT_SYNC_AVG, + TS_STAT_SYNC_TIMEAVG, + }; + + /* APIs to create new records.yaml configurations */ + TSReturnCode TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString data_default, + TSRecordUpdateType update_type, TSRecordCheckType check_type, const char *check_regex, + TSRecordAccessType access_type); + TSReturnCode TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, TSRecordUpdateType update_type, + TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type); + + /* Note that only TS_RECORDDATATYPE_INT is supported at this point. */ + int TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence persist, TSStatSync sync); + + void TSStatIntIncrement(int the_stat, TSMgmtInt amount); + void TSStatIntDecrement(int the_stat, TSMgmtInt amount); + /* Currently not supported. */ + /* void TSStatFloatIncrement(int the_stat, float amount); */ + /* void TSStatFloatDecrement(int the_stat, float amount); */ + + TSMgmtInt TSStatIntGet(int the_stat); + void TSStatIntSet(int the_stat, TSMgmtInt value); + /* Currently not supported. */ + /* TSReturnCode TSStatFloatGet(int the_stat, float* value); */ + /* TSReturnCode TSStatFloatSet(int the_stat, float value); */ + + TSReturnCode TSStatFindName(const char *name, int *idp); + + /** + Records.yaml file handling API. + + If you need to parse a records.yaml file and need to handle each node separately then + this API should be used, an example of this would be the conf_remap plugin. + + TSYAMLRecNodeHandler + + Callback function for the caller to deal with each parsed node. ``cfg`` holds + the details of the parsed field. `data` can be used to pass information along. + */ + using TSYAMLRecNodeHandler = TSReturnCode (*)(const TSYAMLRecCfgFieldData *cfg, void *data); + /** + Parse a YAML node following the record structure internals. On every scalar node + the @a handler callback will be invoked with the appropriate parsed fields. @a data + can be used to pass information along to every callback, this could be handy when + you need to read/set data inside the @c TSYAMLRecNodeHandler to be read at a later stage. + + This will return TS_ERROR if there was an issue while parsing the file. Particular node errors + should be handled by the @c TSYAMLRecNodeHandler implementation. + */ + TSReturnCode TSRecYAMLConfigParse(TSYaml node, TSYAMLRecNodeHandler handler, void *data); + + /* -------------------------------------------------------------------------- + tracing api */ + + int TSIsDebugTagSet(const char *t); + void TSDebug(const char *tag, const char *format_str, ...) TS_PRINTFLIKE(2, 3); + /** + Output a debug line even if the debug tag is turned off, as long as + debugging is enabled. Could be used as follows: + @code + TSDebugSpecific(TSHttpTxnDebugGet(txn), "plugin_tag" , "Hello World from transaction %p", txn); + @endcode + will be printed if the plugin_tag is enabled or the transaction specific + debugging is turned on for txn. + + @param debug_flag boolean flag. + @param tag Debug tag for the line. + @param format Format string. + @param ... Format arguments. + */ + void TSDebugSpecific(int debug_flag, const char *tag, const char *format_str, ...) TS_PRINTFLIKE(3, 4); + extern int diags_on_for_plugins; /* Do not use directly. */ #define TSDEBUG \ if (diags_on_for_plugins) \ TSDebug -extern char ts_new_debug_on_flag_; /* Do not use directly. */ + class TSDbgCtlDetail + { + friend bool TSIsDbgCtlSet(TSDbgCtl const *ctlp); -#define TSIsDbgCtlSet(ctlp__) (ts_new_debug_on_flag_ && ctlp__->on) + static bool debug_on; + + friend class ::DiagsConfigState; + }; + + inline bool + TSIsDbgCtlSet(TSDbgCtl const *ctlp) + { + return (TSDbgCtlDetail::debug_on && ctlp->on); + } /** Output a debug line if the debug output control is turned on. @@ -2206,667 +2234,676 @@ extern char ts_new_debug_on_flag_; /* Do not use directly. */ } \ } while (0) -/** - Return a pointer for use with TSDbg(). For good performance, - this should be called in TSPluginInit() or TSRemapInit(), or in - static initialization in C++ (with the result stored in a - static pointer). - - @param tag Debug tag for the control. - */ -tsapi TSDbgCtl const *TSDbgCtlCreate(char const *tag); - -/** - Destroy (dereference) a debug control object previously created - with TSDbgCtlCreate(). - - @param dbg_ctl pointer to debug control object. - */ -tsapi void TSDbgCtlDestroy(TSDbgCtl const *dbg_ctl); - -void _TSDbg(const char *tag, const char *format_str, ...) TS_PRINTFLIKE(2, 3); /* Not for direct use. */ - -/* -------------------------------------------------------------------------- - logging api */ - -/** - The following enum values are flags, so they should be powers - of two. With the exception of TS_LOG_MODE_INVALID_FLAG, they - are all used to configure the creation of an TSTextLogObject - through the mode argument to TSTextLogObjectCreate(). - TS_LOG_MODE_INVALID_FLAG is used internally to check the validity - of this argument. Insert new flags before TS_LOG_MODE_INVALID_FLAG, - and set TS_LOG_MODE_INVALID_FLAG to the largest power of two of - the enum. - - */ -enum { - TS_LOG_MODE_ADD_TIMESTAMP = 1, - TS_LOG_MODE_DO_NOT_RENAME = 2, - TS_LOG_MODE_INVALID_FLAG = 4, -}; - -/** - This type represents a custom log file that you create with - TSTextLogObjectCreate(). Your plugin writes entries into this - log file using TSTextLogObjectWrite(). - - */ -typedef struct tsapi_textlogobject *TSTextLogObject; - -typedef void (*TSRecordDumpCb)(TSRecordType rec_type, void *edata, int registered, const char *name, TSRecordDataType data_type, - TSRecordData *datum); - -tsapi void TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata); - -/** - - Creates a new custom log file that your plugin can write to. You - can design the fields and inputs to the log file using the - TSTextLogObjectWrite() function. The logs you create are treated - like ordinary logs; they are rolled if log rolling is enabled. - - @param filename new log file being created. The new log file - is created in the logs directory. You can specify a path to a - subdirectory within the log directory, e.g. subdir/filename, - but make sure you create the subdirectory first. If you do - not specify a file name extension, the extension ".log" is - automatically added. - @param mode is one (or both) of the following: - - TS_LOG_MODE_ADD_TIMESTAMP Whenever the plugin makes a log - entry using TSTextLogObjectWrite (see below), it prepends - the entry with a timestamp. - - TS_LOG_MODE_DO_NOT_RENAME This means that if there is a - filename conflict, Traffic Server should not attempt to rename - the custom log. The consequence of a name conflict is that the - custom log will simply not be created, e.g. suppose you call: - @code - log = TSTextLogObjectCreate("squid" , mode, NULL, &error); - @endcode - If mode is TS_LOG_MODE_DO_NOT_RENAME, you will NOT get a new - log (you'll get a null pointer) if squid.log already exists. - If mode is not TS_LOG_MODE_DO_NOT_RENAME, Traffic Server - tries to rename the log to a new name (it will try squid_1.log). - @param new_log_obj new custom log file. - @return error code: - - TS_LOG_ERROR_NO_ERROR No error; the log object has been - created successfully. - - TS_LOG_ERROR_OBJECT_CREATION Log object not created. This - error is rare and would most likely be caused by the system - running out of memory. - - TS_LOG_ERROR_FILENAME_CONFLICTS You get this error if mode = - TS_LOG_MODE_DO_NOT_RENAME, and if there is a naming conflict. - The log object is not created. - - TS_LOG_ERROR_FILE_ACCESS Log object not created because of - a file access problem (for example, no write permission to the - logging directory, or a specified subdirectory for the log file - does not exist). - - */ -tsapi TSReturnCode TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_log_obj); - -/** - Writes a printf-style formatted statement to an TSTextLogObject - (a plugin custom log). - - @param the_object log object to write to. You must first create - this object with TSTextLogObjectCreate(). - @param format printf-style formatted statement to be printed. - @param ... parameters in the formatted statement. A newline is - automatically added to the end. - @return one of the following errors: - - TS_LOG_ERROR_NO_ERROR Means that the write was successful. - - TS_LOG_ERROR_LOG_SPACE_EXHAUSTED Means that Traffic Server - ran out of disk space for logs. If you see this error you might - want to roll logs more often. - - TS_LOG_ERROR_INTERNAL_ERROR Indicates some internal problem - with a log entry (such as an entry larger than the size of the - log write buffer). This error is very unusual. - - */ -tsapi TSReturnCode TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...) TS_PRINTFLIKE(2, 3); - -/** - This immediately flushes the contents of the log write buffer for - the_object to disk. Use this call only if you want to make sure that - log entries are flushed immediately. This call has a performance - cost. Traffic Server flushes the log buffer automatically about - every 1 second. - - @param the_object custom log file whose write buffer is to be - flushed. - - */ -tsapi void TSTextLogObjectFlush(TSTextLogObject the_object); - -/** - Destroys a log object and releases the memory allocated to it. - Use this call if you are done with the log. - - @param the_object custom log to be destroyed. - - */ -tsapi TSReturnCode TSTextLogObjectDestroy(TSTextLogObject the_object); - -/** - Set log header. - - */ -tsapi void TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header); - -/** - Enable/disable rolling. - - @param rolling_enabled a valid proxy.config.log.rolling_enabled value. - - */ -tsapi TSReturnCode TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled); - -/** - Set the rolling interval. - - */ -tsapi void TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_interval_sec); - -/** - Set the rolling offset. rolling_offset_hr specifies the hour (between 0 and 23) when log rolling - should take place. - - */ -tsapi void TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset_hr); - -/** - Set the rolling size. rolling_size_mb specifies the size in MB when log rolling - should take place. - - */ -tsapi void TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb); - -/** - Async disk IO read - - @return TS_SUCCESS or TS_ERROR. - */ -tsapi TSReturnCode TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp); - -/** - Async disk IO buffer get - - @return char* to the buffer - */ -tsapi char *TSAIOBufGet(TSAIOCallback data); - -/** - Async disk IO get number of bytes - - @return the number of bytes - */ -tsapi int TSAIONBytesGet(TSAIOCallback data); - -/** - Async disk IO write - - @return TS_SUCCESS or TS_ERROR. - */ -tsapi TSReturnCode TSAIOWrite(int fd, off_t offset, char *buf, size_t bufSize, TSCont contp); - -/** - Async disk IO set number of threads - - @return TS_SUCCESS or TS_ERROR. - */ -tsapi TSReturnCode TSAIOThreadNumSet(int thread_num); - -/** - Check if transaction was aborted (due client/server errors etc.) - Client_abort is set as True, in case the abort was caused by the Client. - - @return 1 if transaction was aborted -*/ -tsapi TSReturnCode TSHttpTxnAborted(TSHttpTxn txnp, bool *client_abort); - -tsapi TSVConn TSVConnCreate(TSEventFunc event_funcp, TSMutex mutexp); -tsapi TSVConn TSVConnFdCreate(int fd); - -/* api functions to access stats */ -/* ClientResp APIs exist as well and are exposed in PrivateFrozen */ -tsapi int TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp); -tsapi int64_t TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp); -tsapi int TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp); -tsapi int64_t TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp); -tsapi int TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp); -tsapi int64_t TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp); -tsapi int TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp); -tsapi int64_t TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp); -tsapi int TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp); -tsapi int64_t TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp); -tsapi int TSVConnIsSslReused(TSVConn sslp); - -/** - Return the current (if set) SSL Cipher. This is still owned by the - core, and must not be free'd. - - @param sslp The connection pointer - - @return the SSL Cipher -*/ -tsapi const char *TSVConnSslCipherGet(TSVConn sslp); - -/** - Return the current (if set) SSL Protocol. This is still owned by the - core, and must not be free'd. - - @param sslp The connection pointer - - @return the SSL Protocol -*/ -tsapi const char *TSVConnSslProtocolGet(TSVConn sslp); - -/** - Return the current (if set) SSL Curve. This is still owned by the - core, and must not be free'd. - - @param txnp the transaction pointer - - @return the SSL Curve -*/ -tsapi const char *TSVConnSslCurveGet(TSVConn sslp); - -/* NetVC timeout APIs. */ -tsapi void TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout); -tsapi void TSVConnInactivityTimeoutCancel(TSVConn connp); -tsapi void TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout); -tsapi void TSVConnActiveTimeoutCancel(TSVConn connp); - -/* - ability to skip the remap phase of the State Machine - this only really makes sense in TS_HTTP_READ_REQUEST_HDR_HOOK -*/ -tsapi void TSSkipRemappingSet(TSHttpTxn txnp, int flag); - -/* - Set or get various overridable configurations, for a transaction. This should - probably be done as early as possible, e.g. TS_HTTP_READ_REQUEST_HDR_HOOK. -*/ -tsapi TSReturnCode TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt value); -tsapi TSReturnCode TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *value); -tsapi TSReturnCode TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat value); -tsapi TSReturnCode TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat *value); -tsapi TSReturnCode TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char *value, int length); -tsapi TSReturnCode TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char **value, int *length); - -tsapi TSReturnCode TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, TSRecordDataType *type); - -/** - This is a generalization of the old TSHttpTxnFollowRedirect(), but gives finer - control over the behavior. Instead of using the Location: header for the new - destination, this API takes the new URL as a parameter. Calling this API - transfers the ownership of the URL from the plugin to the core, so you must - make sure it is heap allocated, and that you do not free it. - - Calling this API implicitly also enables the "Follow Redirect" feature, so - there is no need to set that overridable configuration as well. - - @param txnp the transaction pointer - @param url a heap allocated string with the URL - @param url_len the length of the URL -*/ -tsapi void TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len); - -/** - Return the current (if set) redirection URL string. This is still owned by the - core, and must not be free'd. - - @param txnp the transaction pointer - @param url_len_ptr a pointer to where the URL length is to be stored - - @return the url string -*/ -tsapi const char *TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr); - -/** - Return the number of redirection retries we have done. This starts off - at zero, and can be used to select different URLs based on which attempt this - is. This can be useful for example when providing a list of URLs to try, and - do so in order until one succeeds. - - @param txnp the transaction pointer - - @return the redirect try count -*/ -tsapi int TSHttpTxnRedirectRetries(TSHttpTxn txnp); - -/* Get current HTTP connection stats */ -tsapi int TSHttpCurrentClientConnectionsGet(void); -tsapi int TSHttpCurrentActiveClientConnectionsGet(void); -tsapi int TSHttpCurrentIdleClientConnectionsGet(void); -tsapi int TSHttpCurrentCacheConnectionsGet(void); -tsapi int TSHttpCurrentServerConnectionsGet(void); - -/* ===== Http Transactions ===== */ -tsapi TSReturnCode TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); -tsapi TSReturnCode TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup); -tsapi TSReturnCode TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); -tsapi TSReturnCode TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); -tsapi TSReturnCode TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session); -tsapi const char *TSHttpTxnCacheDiskPathGet(TSHttpTxn txnp, int *length); -tsapi int TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp); -tsapi int TSHttpTxnIsWebsocket(TSHttpTxn txnp); - -/* Get the Txn's (HttpSM's) unique identifier, which is a sequence number since server start) */ -tsapi uint64_t TSHttpTxnIdGet(TSHttpTxn txnp); - -/* Get the Ssn's unique identifier */ -tsapi int64_t TSHttpSsnIdGet(TSHttpSsn ssnp); - -/* Expose internal Base64 Encoding / Decoding */ -tsapi TSReturnCode TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_size, size_t *length); -tsapi TSReturnCode TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length); - -/* Get milestone timers, useful for measuring where we are spending time in the transaction processing */ -/** - Return the particular milestone timer for the transaction. If 0 is returned, it means - the transaction has not yet reached that milestone. Asking for an "unknown" milestone is - an error. - - @param txnp the transaction pointer - @param milestone the requested milestone timer - was created. - @param time a pointer to a TSHRTime where we will store the timer - - @return @c TS_SUCCESS if the milestone is supported, TS_ERROR otherwise - -*/ -tsapi TSReturnCode TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, TSHRTime *time); - -/** - Test whether a request / response header pair would be cacheable under the current - configuration. This would typically be used in TS_HTTP_READ_RESPONSE_HDR_HOOK, when - you have both the client request and server response ready. - - @param txnp the transaction pointer - @param request the client request header. If NULL, use the transactions client request. - @param response the server response header. If NULL, use the transactions origin response. - - @return 1 if the request / response is cacheable, 0 otherwise -*/ -tsapi int TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response); - -/** - Get the maximum age in seconds as indicated by the origin server. - This would typically be used in TS_HTTP_READ_RESPONSE_HDR_HOOK, when you have - the server response ready. - - @param txnp the transaction pointer - @param response the server response header. If NULL, use the transactions origin response. - - @return the age in seconds if specified by Cache-Control, -1 otherwise -*/ -tsapi int TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response); - -/** - Return a string representation for a TSServerState value. This is useful for plugin debugging. - - @param state the value of this TSServerState - - @return the string representation of the state -*/ -tsapi const char *TSHttpServerStateNameLookup(TSServerState state); - -/** - Return a string representation for a TSHttpHookID value. This is useful for plugin debugging. - - @param hook the value of this TSHttpHookID - - @return the string representation of the hook ID -*/ -tsapi const char *TSHttpHookNameLookup(TSHttpHookID hook); - -/** - Return a string representation for a TSEvent value. This is useful for plugin debugging. - - @param event the value of this TSHttpHookID - - @return the string representation of the event -*/ -tsapi const char *TSHttpEventNameLookup(TSEvent event); - -/* APIs for dealing with UUIDs, either self made, or the system wide process UUID. See - https://docs.trafficserver.apache.org/en/latest/developer-guide/api/functions/TSUuidCreate.en.html -*/ -tsapi TSUuid TSUuidCreate(void); -tsapi TSReturnCode TSUuidInitialize(TSUuid uuid, TSUuidVersion v); -tsapi void TSUuidDestroy(TSUuid uuid); -tsapi TSReturnCode TSUuidCopy(TSUuid dest, const TSUuid src); -tsapi const char *TSUuidStringGet(const TSUuid uuid); -tsapi TSUuidVersion TSUuidVersionGet(const TSUuid uuid); -tsapi TSReturnCode TSUuidStringParse(TSUuid uuid, const char *uuid_str); -tsapi TSReturnCode TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str); - -/* Get the process global UUID, resets on every startup */ -tsapi TSUuid TSProcessUuidGet(void); - -/** - Returns the plugin_tag. -*/ -tsapi const char *TSHttpTxnPluginTagGet(TSHttpTxn txnp); - -/* - * Return information about the client protocols. - */ -tsapi TSReturnCode TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual); -tsapi TSReturnCode TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int count, const char **result, int *actual); -tsapi const char *TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, char const *tag); -tsapi const char *TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, char const *tag); -tsapi const char *TSNormalizedProtocolTag(char const *tag); -tsapi const char *TSRegisterProtocolTag(char const *tag); - -/* - * Return information about the server protocols. - */ -tsapi TSReturnCode TSHttpTxnServerProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual); -tsapi const char *TSHttpTxnServerProtocolStackContains(TSHttpTxn txnp, char const *tag); - -// If, for the given transaction, the URL has been remapped, this function puts the memory location of the "from" URL object in -// the variable pointed to by urlLocp, and returns TS_SUCCESS. (The URL object will be within memory allocated to the -// transaction object.) Otherwise, the function returns TS_ERROR. -// -tsapi TSReturnCode TSRemapFromUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp); - -// If, for the given transaction, the URL has been remapped, this function puts the memory location of the "to" URL object in the -// variable pointed to by urlLocp, and returns TS_SUCCESS. (The URL object will be within memory allocated to the transaction -// object.) Otherwise, the function returns TS_ERROR. -// -tsapi TSReturnCode TSRemapToUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp); - -// Get some plugin details from the TSRemapPluginInfo -tsapi void *TSRemapDLHandleGet(TSRemapPluginInfo plugin_info); - -// Override response behavior, and hard-set the state machine for whether to succeed or fail, and how. -tsapi void TSHttpTxnResponseActionSet(TSHttpTxn txnp, TSResponseAction *action); - -// Get the overridden response behavior set by previously called plugins. -tsapi void TSHttpTxnResponseActionGet(TSHttpTxn txnp, TSResponseAction *action); - -/* - * Get a TSIOBufferReader to read the buffered body. The return value needs to be freed. - */ -tsapi TSIOBufferReader TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp); - -/** - * Initiate an HTTP/2 Server Push preload request. - * Use this api to register a URL that you want to preload with HTTP/2 Server Push. - * - * @param url the URL string to preload. - * @param url_len the length of the URL string. - */ -tsapi TSReturnCode TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len); - -/** Retrieve the client side stream id for the stream of which the - * provided transaction is a part. - * - * @param[in] txnp The Transaction for which the stream id should be retrieved. - * @param[out] stream_id The stream id for this transaction. - * - * @return TS_ERROR if a stream id cannot be retrieved for the given - * transaction given its protocol. For instance, if txnp is an HTTP/1.1 - * transaction, then a TS_ERROR will be returned because HTTP/1.1 does not - * implement streams. - */ -tsapi TSReturnCode TSHttpTxnClientStreamIdGet(TSHttpTxn txnp, uint64_t *stream_id); - -/** Retrieve the client side priority for the stream of which the - * provided transaction is a part. - * - * @param[in] txnp The Transaction for which the stream id should be retrieved. - * @param[out] priority The priority for the stream in this transaction. - * - * @return TS_ERROR if a priority cannot be retrieved for the given - * transaction given its protocol. For instance, if txnp is an HTTP/1.1 - * transaction, then a TS_ERROR will be returned because HTTP/1.1 does not - * implement stream priorities. - */ -tsapi TSReturnCode TSHttpTxnClientStreamPriorityGet(TSHttpTxn txnp, TSHttpPriority *priority); - -/* - * Returns TS_SUCCESS if hostname is this machine, as used for parent and remap self-detection. - * Returns TS_ERROR if hostname is not this machine. - */ -tsapi TSReturnCode TSHostnameIsSelf(const char *hostname, size_t hostname_len); - -/* - * Gets the status of hostname in the outparam status, and the status reason in the outparam reason. - * The reason is a logical-or combination of the reasons in TSHostStatusReason. - * If either outparam is null, it will not be set and no error will be returned. - * Returns TS_SUCCESS if the hostname was a parent and existed in the HostStatus, else TS_ERROR. - */ -tsapi TSReturnCode TSHostStatusGet(const char *hostname, const size_t hostname_len, TSHostStatus *status, unsigned int *reason); - -/* - * Sets the status of hostname in status, down_time, and reason. - * The reason is a logical-or combination of the reasons in TSHostStatusReason. - */ -tsapi void TSHostStatusSet(const char *hostname, const size_t hostname_len, TSHostStatus status, const unsigned int down_time, - const unsigned int reason); - -/* - * Set or get various HTTP Transaction control settings. - */ -tsapi bool TSHttpTxnCntlGet(TSHttpTxn txnp, TSHttpCntlType ctrl); -tsapi TSReturnCode TSHttpTxnCntlSet(TSHttpTxn txnp, TSHttpCntlType ctrl, bool data); - -/** - * JSONRPC callback signature for method calls. - */ -typedef void (*TSRPCMethodCb)(const char *id, TSYaml params); -/** - * JSONRPC callback signature for notification calls - */ -typedef void (*TSRPCNotificationCb)(TSYaml params); + /** + Return a pointer for use with TSDbg(). For good performance, + this should be called in TSPluginInit() or TSRemapInit(), or in + static initialization in C++ (with the result stored in a + static pointer). + + @param tag Debug tag for the control. + */ + TSDbgCtl const *TSDbgCtlCreate(char const *tag); + + /** + Destroy (dereference) a debug control object previously created + with TSDbgCtlCreate(). + + @param dbg_ctl pointer to debug control object. + */ + void TSDbgCtlDestroy(TSDbgCtl const *dbg_ctl); + + void _TSDbg(const char *tag, const char *format_str, ...) TS_PRINTFLIKE(2, 3); /* Not for direct use. */ + + /* -------------------------------------------------------------------------- + logging api */ + + /** + The following enum values are flags, so they should be powers + of two. With the exception of TS_LOG_MODE_INVALID_FLAG, they + are all used to configure the creation of an TSTextLogObject + through the mode argument to TSTextLogObjectCreate(). + TS_LOG_MODE_INVALID_FLAG is used internally to check the validity + of this argument. Insert new flags before TS_LOG_MODE_INVALID_FLAG, + and set TS_LOG_MODE_INVALID_FLAG to the largest power of two of + the enum. + + */ + enum { + TS_LOG_MODE_ADD_TIMESTAMP = 1, + TS_LOG_MODE_DO_NOT_RENAME = 2, + TS_LOG_MODE_INVALID_FLAG = 4, + }; + + /** + This type represents a custom log file that you create with + TSTextLogObjectCreate(). Your plugin writes entries into this + log file using TSTextLogObjectWrite(). + + */ + using TSTextLogObject = struct tsapi_textlogobject *; + + using TSRecordDumpCb = void (*)(TSRecordType rec_type, void *edata, int registered, const char *name, TSRecordDataType data_type, + TSRecordData *datum); + + void TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata); + + /** + + Creates a new custom log file that your plugin can write to. You + can design the fields and inputs to the log file using the + TSTextLogObjectWrite() function. The logs you create are treated + like ordinary logs; they are rolled if log rolling is enabled. + + @param filename new log file being created. The new log file + is created in the logs directory. You can specify a path to a + subdirectory within the log directory, e.g. subdir/filename, + but make sure you create the subdirectory first. If you do + not specify a file name extension, the extension ".log" is + automatically added. + @param mode is one (or both) of the following: + - TS_LOG_MODE_ADD_TIMESTAMP Whenever the plugin makes a log + entry using TSTextLogObjectWrite (see below), it prepends + the entry with a timestamp. + - TS_LOG_MODE_DO_NOT_RENAME This means that if there is a + filename conflict, Traffic Server should not attempt to rename + the custom log. The consequence of a name conflict is that the + custom log will simply not be created, e.g. suppose you call: + @code + log = TSTextLogObjectCreate("squid" , mode, nullptr, &error); + @endcode + If mode is TS_LOG_MODE_DO_NOT_RENAME, you will NOT get a new + log (you'll get a null pointer) if squid.log already exists. + If mode is not TS_LOG_MODE_DO_NOT_RENAME, Traffic Server + tries to rename the log to a new name (it will try squid_1.log). + @param new_log_obj new custom log file. + @return error code: + - TS_LOG_ERROR_NO_ERROR No error; the log object has been + created successfully. + - TS_LOG_ERROR_OBJECT_CREATION Log object not created. This + error is rare and would most likely be caused by the system + running out of memory. + - TS_LOG_ERROR_FILENAME_CONFLICTS You get this error if mode = + TS_LOG_MODE_DO_NOT_RENAME, and if there is a naming conflict. + The log object is not created. + - TS_LOG_ERROR_FILE_ACCESS Log object not created because of + a file access problem (for example, no write permission to the + logging directory, or a specified subdirectory for the log file + does not exist). + + */ + TSReturnCode TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_log_obj); + + /** + Writes a printf-style formatted statement to an TSTextLogObject + (a plugin custom log). + + @param the_object log object to write to. You must first create + this object with TSTextLogObjectCreate(). + @param format printf-style formatted statement to be printed. + @param ... parameters in the formatted statement. A newline is + automatically added to the end. + @return one of the following errors: + - TS_LOG_ERROR_NO_ERROR Means that the write was successful. + - TS_LOG_ERROR_LOG_SPACE_EXHAUSTED Means that Traffic Server + ran out of disk space for logs. If you see this error you might + want to roll logs more often. + - TS_LOG_ERROR_INTERNAL_ERROR Indicates some internal problem + with a log entry (such as an entry larger than the size of the + log write buffer). This error is very unusual. + + */ + TSReturnCode TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...) TS_PRINTFLIKE(2, 3); + + /** + This immediately flushes the contents of the log write buffer for + the_object to disk. Use this call only if you want to make sure that + log entries are flushed immediately. This call has a performance + cost. Traffic Server flushes the log buffer automatically about + every 1 second. + + @param the_object custom log file whose write buffer is to be + flushed. + + */ + void TSTextLogObjectFlush(TSTextLogObject the_object); + + /** + Destroys a log object and releases the memory allocated to it. + Use this call if you are done with the log. + + @param the_object custom log to be destroyed. + + */ + TSReturnCode TSTextLogObjectDestroy(TSTextLogObject the_object); + + /** + Set log header. + + */ + void TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header); + + /** + Enable/disable rolling. + + @param rolling_enabled a valid proxy.config.log.rolling_enabled value. + + */ + TSReturnCode TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled); + + /** + Set the rolling interval. + + */ + void TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_interval_sec); + + /** + Set the rolling offset. rolling_offset_hr specifies the hour (between 0 and 23) when log rolling + should take place. + + */ + void TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset_hr); + + /** + Set the rolling size. rolling_size_mb specifies the size in MB when log rolling + should take place. + + */ + void TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb); + + /** + Async disk IO read + + @return TS_SUCCESS or TS_ERROR. + */ + TSReturnCode TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp); + + /** + Async disk IO buffer get + + @return char* to the buffer + */ + char *TSAIOBufGet(TSAIOCallback data); + + /** + Async disk IO get number of bytes + + @return the number of bytes + */ + int TSAIONBytesGet(TSAIOCallback data); + + /** + Async disk IO write + + @return TS_SUCCESS or TS_ERROR. + */ + TSReturnCode TSAIOWrite(int fd, off_t offset, char *buf, size_t bufSize, TSCont contp); + + /** + Async disk IO set number of threads + + @return TS_SUCCESS or TS_ERROR. + */ + TSReturnCode TSAIOThreadNumSet(int thread_num); -/** - * @brief Method to perform a registration and validation when a plugin is expected to handle JSONRPC calls. - * - * @note YAMLCPP The JSONRPC library will only provide binary compatibility within the life-span of a major release. Plugins must - * check-in if they intent to handle RPC commands, passing their yamlcpp library version this function will validate it against the - * one used internally in TS. - * - * @param provider_name The name of the provider. - * @param provider_len The length of the provider string. - * @param yamlcpp_lib_version a string with the yamlcpp library version. - * @param yamlcpp_lib_len The length of the yamlcpp_lib_len string. - * @return A new TSRPCProviderHandle, nullptr if the yamlcpp_lib_version was not set, or the yamlcpp version does not match with - * the one used internally in TS. The returned TSRPCProviderHandle will be set with the provider's name. The caller should pass the - * returned TSRPCProviderHandle object to each subsequent TSRPCRegisterMethod/Notification* call. - */ -tsapi TSRPCProviderHandle TSRPCRegister(const char *provider_name, size_t provider_len, const char *yamlcpp_lib_version, - size_t yamlcpp_lib_len); + /** + Check if transaction was aborted (due client/server errors etc.) + Client_abort is set as True, in case the abort was caused by the Client. -/** - * @brief Add new registered method handler to the JSON RPC engine. - * - * @param name Call name to be exposed by the RPC Engine, this should match the incoming request. i.e: If you register 'get_stats' - * then the incoming jsonrpc call should have this very same name in the 'method' field. .. {...'method': - * 'get_stats'...} . - * @param name_len The length of the name string. - * @param callback The function to be registered. See @c TSRPCMethodCb - * @param info TSRPCProviderHandle pointer, this will be used to provide more context information about this call. This object - * ideally should be the one returned by the TSRPCRegister API. - * @param opt Pointer to @c TSRPCHandlerOptions object. This will be used to store specifics about a particular call, the rpc - * manager will use this object to perform certain actions. A copy of this object wil be stored by the rpc manager. - * - * @return TS_SUCCESS if the handler was successfully registered, TS_ERROR if the handler is already registered. - */ -tsapi TSReturnCode TSRPCRegisterMethodHandler(const char *name, size_t name_len, TSRPCMethodCb callback, TSRPCProviderHandle info, - const TSRPCHandlerOptions *opt); + @return 1 if transaction was aborted + */ + TSReturnCode TSHttpTxnAborted(TSHttpTxn txnp, bool *client_abort); -/** - * @brief Add new registered notification handler to the JSON RPC engine. - * - * @param name Call name to be exposed by the RPC Engine, this should match the incoming request. i.e: If you register 'get_stats' - * then the incoming jsonrpc call should have this very same name in the 'method' field. .. {...'method': - * 'get_stats'...} . - * @param name_len The length of the name string. - * @param callback The function to be registered. See @c TSRPCNotificationCb - * @param info TSRPCProviderHandle pointer, this will be used to provide more description for instance, when logging before or after - * a call. This object ideally should be the one returned by the TSRPCRegister API. - * @param opt Pointer to @c TSRPCHandlerOptions object. This will be used to store specifics about a particular call, the rpc - * manager will use this object to perform certain actions. A copy of this object wil be stored by the rpc manager. - * @return TS_SUCCESS if the handler was successfully registered, TS_ERROR if the handler is already registered. - */ -tsapi TSReturnCode TSRPCRegisterNotificationHandler(const char *name, size_t name_len, TSRPCNotificationCb callback, - TSRPCProviderHandle info, const TSRPCHandlerOptions *opt); + TSVConn TSVConnCreate(TSEventFunc event_funcp, TSMutex mutexp); + TSVConn TSVConnFdCreate(int fd); -/** - * @brief Function to notify the JSONRPC engine that the current handler is done working. - * - * This function must be used when implementing a 'method' rpc handler. Once the work is done and the response is ready to be sent - * back to the client, this function should be called. Is expected to set the YAML node as response. If the response is empty a - * 'success' message will be added to the client's response. - * - * @note This should not be used if you registered your handler as a notification: @c TSRPCNotificationCb - * @param resp The YAML node that contains the call response. - * @return TS_SUCCESS if no issues. TS_ERROR otherwise. - */ -tsapi TSReturnCode TSRPCHandlerDone(TSYaml resp); + /* api functions to access stats */ + /* ClientResp APIs exist as well and are exposed in PrivateFrozen */ + int TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp); + int64_t TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp); + int TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp); + int64_t TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp); + int TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp); + int64_t TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp); + int TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp); + int64_t TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp); + int TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp); + int64_t TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp); + int TSVConnIsSslReused(TSVConn sslp); -/** - * @brief Function to notify the JSONRPC engine that the current handler is done working and an error has arisen. - * - * @note This should not be used if you registered your handler as a notification: @c TSRPCNotificationCb - * call. - * @param code Error code. - * @param descr A text with a description of the error. - * @param descr_len The length of the description string. - * @note The @c code and @c descr will be part of the @c 'data' field in the jsonrpc error response. - * @return TS_SUCCESS if no issues. TS_ERROR otherwise. - */ -tsapi TSReturnCode TSRPCHandlerError(int code, const char *descr, size_t descr_len); - -/** Do another cache lookup with a different cache key. - * - * @param txnp Transaction. - * @param url URL to use for cache key. - * @param length Length of the string in @a url - * - * @return @c TS_SUCCESS on success, @c TS_ERROR if the @a txnp is invalid or the @a url is - * not a valid URL. - * - * If @a length is negative, @c strlen will be used to determine the length of @a url. - * - * @a url must be syntactically a URL, but otherwise it is just a string and does not need to - * be retrievable. - * - * This can only be called in a @c TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK callback. To set the cache - * key for the first lookup, use @c TSCacheUrlSet. - * - * @see TSCacheUrlSet - */ -tsapi TSReturnCode TSHttpTxnRedoCacheLookup(TSHttpTxn txnp, const char *url, int length); + /** + Return the current (if set) SSL Cipher. This is still owned by the + core, and must not be free'd. + + @param sslp The connection pointer + + @return the SSL Cipher + */ + const char *TSVConnSslCipherGet(TSVConn sslp); + + /** + Return the current (if set) SSL Protocol. This is still owned by the + core, and must not be free'd. + + @param sslp The connection pointer + + @return the SSL Protocol + */ + const char *TSVConnSslProtocolGet(TSVConn sslp); + + /** + Return the current (if set) SSL Curve. This is still owned by the + core, and must not be free'd. + + @param txnp the transaction pointer + + @return the SSL Curve + */ + const char *TSVConnSslCurveGet(TSVConn sslp); + + /* NetVC timeout APIs. */ + void TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout); + void TSVConnInactivityTimeoutCancel(TSVConn connp); + void TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout); + void TSVConnActiveTimeoutCancel(TSVConn connp); + + /* + ability to skip the remap phase of the State Machine + this only really makes sense in TS_HTTP_READ_REQUEST_HDR_HOOK + */ + void TSSkipRemappingSet(TSHttpTxn txnp, int flag); + + /* + Set or get various overridable configurations, for a transaction. This should + probably be done as early as possible, e.g. TS_HTTP_READ_REQUEST_HDR_HOOK. + */ + TSReturnCode TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt value); + TSReturnCode TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *value); + TSReturnCode TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat value); + TSReturnCode TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat *value); + TSReturnCode TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char *value, int length); + TSReturnCode TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char **value, int *length); + + TSReturnCode TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, TSRecordDataType *type); + + /** + This is a generalization of the old TSHttpTxnFollowRedirect(), but gives finer + control over the behavior. Instead of using the Location: header for the new + destination, this API takes the new URL as a parameter. Calling this API + transfers the ownership of the URL from the plugin to the core, so you must + make sure it is heap allocated, and that you do not free it. + + Calling this API implicitly also enables the "Follow Redirect" feature, so + there is no need to set that overridable configuration as well. + + @param txnp the transaction pointer + @param url a heap allocated string with the URL + @param url_len the length of the URL + */ + void TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len); + + /** + Return the current (if set) redirection URL string. This is still owned by the + core, and must not be free'd. + + @param txnp the transaction pointer + @param url_len_ptr a pointer to where the URL length is to be stored + + @return the url string + */ + const char *TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr); + + /** + Return the number of redirection retries we have done. This starts off + at zero, and can be used to select different URLs based on which attempt this + is. This can be useful for example when providing a list of URLs to try, and + do so in order until one succeeds. + + @param txnp the transaction pointer + + @return the redirect try count + */ + int TSHttpTxnRedirectRetries(TSHttpTxn txnp); + + /* Get current HTTP connection stats */ + int TSHttpCurrentClientConnectionsGet(void); + int TSHttpCurrentActiveClientConnectionsGet(void); + int TSHttpCurrentIdleClientConnectionsGet(void); + int TSHttpCurrentCacheConnectionsGet(void); + int TSHttpCurrentServerConnectionsGet(void); + + /* ===== Http Transactions ===== */ + TSReturnCode TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *offset); + TSReturnCode TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup); + TSReturnCode TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); + TSReturnCode TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj); + TSReturnCode TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session); + const char *TSHttpTxnCacheDiskPathGet(TSHttpTxn txnp, int *length); + int TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp); + int TSHttpTxnIsWebsocket(TSHttpTxn txnp); + + /* Get the Txn's (HttpSM's) unique identifier, which is a sequence number since server start) */ + uint64_t TSHttpTxnIdGet(TSHttpTxn txnp); + + /* Get the Ssn's unique identifier */ + int64_t TSHttpSsnIdGet(TSHttpSsn ssnp); + + /* Expose internal Base64 Encoding / Decoding */ + TSReturnCode TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_size, size_t *length); + TSReturnCode TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length); + + /* Get milestone timers, useful for measuring where we are spending time in the transaction processing */ + /** + Return the particular milestone timer for the transaction. If 0 is returned, it means + the transaction has not yet reached that milestone. Asking for an "unknown" milestone is + an error. + + @param txnp the transaction pointer + @param milestone the requested milestone timer + was created. + @param time a pointer to a TSHRTime where we will store the timer + + @return @c TS_SUCCESS if the milestone is supported, TS_ERROR otherwise + + */ + TSReturnCode TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, TSHRTime *time); + + /** + Test whether a request / response header pair would be cacheable under the current + configuration. This would typically be used in TS_HTTP_READ_RESPONSE_HDR_HOOK, when + you have both the client request and server response ready. + + @param txnp the transaction pointer + @param request the client request header. If null, use the transactions client request. + @param response the server response header. If null, use the transactions origin response. + + @return 1 if the request / response is cacheable, 0 otherwise + */ + int TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response); + + /** + Get the maximum age in seconds as indicated by the origin server. + This would typically be used in TS_HTTP_READ_RESPONSE_HDR_HOOK, when you have + the server response ready. + + @param txnp the transaction pointer + @param response the server response header. If null, use the transactions origin response. + + @return the age in seconds if specified by Cache-Control, -1 otherwise + */ + int TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response); + + /** + Return a string representation for a TSServerState value. This is useful for plugin debugging. + + @param state the value of this TSServerState + + @return the string representation of the state + */ + const char *TSHttpServerStateNameLookup(TSServerState state); + + /** + Return a string representation for a TSHttpHookID value. This is useful for plugin debugging. + + @param hook the value of this TSHttpHookID + + @return the string representation of the hook ID + */ + const char *TSHttpHookNameLookup(TSHttpHookID hook); + + /** + Return a string representation for a TSEvent value. This is useful for plugin debugging. + + @param event the value of this TSHttpHookID + + @return the string representation of the event + */ + const char *TSHttpEventNameLookup(TSEvent event); + + /* APIs for dealing with UUIDs, either self made, or the system wide process UUID. See + https://docs.trafficserver.apache.org/en/latest/developer-guide/api/functions/TSUuidCreate.en.html + */ + TSUuid TSUuidCreate(void); + TSReturnCode TSUuidInitialize(TSUuid uuid, TSUuidVersion v); + void TSUuidDestroy(TSUuid uuid); + TSReturnCode TSUuidCopy(TSUuid dest, const TSUuid src); + const char *TSUuidStringGet(const TSUuid uuid); + TSUuidVersion TSUuidVersionGet(const TSUuid uuid); + TSReturnCode TSUuidStringParse(TSUuid uuid, const char *uuid_str); + TSReturnCode TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str); + + /* Get the process global UUID, resets on every startup */ + TSUuid TSProcessUuidGet(void); + + /** + Returns the plugin_tag. + */ + const char *TSHttpTxnPluginTagGet(TSHttpTxn txnp); + + /* + * Return information about the client protocols. + */ + TSReturnCode TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual); + TSReturnCode TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int count, const char **result, int *actual); + const char *TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, char const *tag); + const char *TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, char const *tag); + const char *TSNormalizedProtocolTag(char const *tag); + const char *TSRegisterProtocolTag(char const *tag); + + /* + * Return information about the server protocols. + */ + TSReturnCode TSHttpTxnServerProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual); + const char *TSHttpTxnServerProtocolStackContains(TSHttpTxn txnp, char const *tag); + + // If, for the given transaction, the URL has been remapped, this function puts the memory location of the "from" URL object in + // the variable pointed to by urlLocp, and returns TS_SUCCESS. (The URL object will be within memory allocated to the + // transaction object.) Otherwise, the function returns TS_ERROR. + // + TSReturnCode TSRemapFromUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp); + + // If, for the given transaction, the URL has been remapped, this function puts the memory location of the "to" URL object in the + // variable pointed to by urlLocp, and returns TS_SUCCESS. (The URL object will be within memory allocated to the transaction + // object.) Otherwise, the function returns TS_ERROR. + // + TSReturnCode TSRemapToUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp); + + // Get some plugin details from the TSRemapPluginInfo + void *TSRemapDLHandleGet(TSRemapPluginInfo plugin_info); + + // Override response behavior, and hard-set the state machine for whether to succeed or fail, and how. + void TSHttpTxnResponseActionSet(TSHttpTxn txnp, TSResponseAction *action); + + // Get the overridden response behavior set by previously called plugins. + void TSHttpTxnResponseActionGet(TSHttpTxn txnp, TSResponseAction *action); + + /* + * Get a TSIOBufferReader to read the buffered body. The return value needs to be freed. + */ + TSIOBufferReader TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp); + + /** + * Initiate an HTTP/2 Server Push preload request. + * Use this api to register a URL that you want to preload with HTTP/2 Server Push. + * + * @param url the URL string to preload. + * @param url_len the length of the URL string. + */ + TSReturnCode TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len); + + /** Retrieve the client side stream id for the stream of which the + * provided transaction is a part. + * + * @param[in] txnp The Transaction for which the stream id should be retrieved. + * @param[out] stream_id The stream id for this transaction. + * + * @return TS_ERROR if a stream id cannot be retrieved for the given + * transaction given its protocol. For instance, if txnp is an HTTP/1.1 + * transaction, then a TS_ERROR will be returned because HTTP/1.1 does not + * implement streams. + */ + TSReturnCode TSHttpTxnClientStreamIdGet(TSHttpTxn txnp, uint64_t *stream_id); + + /** Retrieve the client side priority for the stream of which the + * provided transaction is a part. + * + * @param[in] txnp The Transaction for which the stream id should be retrieved. + * @param[out] priority The priority for the stream in this transaction. + * + * @return TS_ERROR if a priority cannot be retrieved for the given + * transaction given its protocol. For instance, if txnp is an HTTP/1.1 + * transaction, then a TS_ERROR will be returned because HTTP/1.1 does not + * implement stream priorities. + */ + TSReturnCode TSHttpTxnClientStreamPriorityGet(TSHttpTxn txnp, TSHttpPriority *priority); + + /* + * Returns TS_SUCCESS if hostname is this machine, as used for parent and remap self-detection. + * Returns TS_ERROR if hostname is not this machine. + */ + TSReturnCode TSHostnameIsSelf(const char *hostname, size_t hostname_len); + + /* + * Gets the status of hostname in the outparam status, and the status reason in the outparam reason. + * The reason is a logical-or combination of the reasons in TSHostStatusReason. + * If either outparam is null, it will not be set and no error will be returned. + * Returns TS_SUCCESS if the hostname was a parent and existed in the HostStatus, else TS_ERROR. + */ + TSReturnCode TSHostStatusGet(const char *hostname, const size_t hostname_len, TSHostStatus *status, unsigned int *reason); + + /* + * Sets the status of hostname in status, down_time, and reason. + * The reason is a logical-or combination of the reasons in TSHostStatusReason. + */ + void TSHostStatusSet(const char *hostname, const size_t hostname_len, TSHostStatus status, const unsigned int down_time, + const unsigned int reason); + + /* + * Set or get various HTTP Transaction control settings. + */ + bool TSHttpTxnCntlGet(TSHttpTxn txnp, TSHttpCntlType ctrl); + TSReturnCode TSHttpTxnCntlSet(TSHttpTxn txnp, TSHttpCntlType ctrl, bool data); + + /** + * JSONRPC callback signature for method calls. + */ + using TSRPCMethodCb = void (*)(const char *id, TSYaml params); + /** + * JSONRPC callback signature for notification calls + */ + using TSRPCNotificationCb = void (*)(TSYaml params); + + /** + * @brief Method to perform a registration and validation when a plugin is expected to handle JSONRPC calls. + * + * @note YAMLCPP The JSONRPC library will only provide binary compatibility within the life-span of a major release. Plugins must + * check-in if they intent to handle RPC commands, passing their yamlcpp library version this function will validate it against + * the one used internally in TS. + * + * @param provider_name The name of the provider. + * @param provider_len The length of the provider string. + * @param yamlcpp_lib_version a string with the yamlcpp library version. + * @param yamlcpp_lib_len The length of the yamlcpp_lib_len string. + * @return A new TSRPCProviderHandle, nullptr if the yamlcpp_lib_version was not set, or the yamlcpp version does not match with + * the one used internally in TS. The returned TSRPCProviderHandle will be set with the provider's name. The caller should pass + * the returned TSRPCProviderHandle object to each subsequent TSRPCRegisterMethod/Notification* call. + */ + TSRPCProviderHandle TSRPCRegister(const char *provider_name, size_t provider_len, const char *yamlcpp_lib_version, + size_t yamlcpp_lib_len); + + /** + * @brief Add new registered method handler to the JSON RPC engine. + * + * @param name Call name to be exposed by the RPC Engine, this should match the incoming request. i.e: If you register 'get_stats' + * then the incoming jsonrpc call should have this very same name in the 'method' field. .. {...'method': + * 'get_stats'...} . + * @param name_len The length of the name string. + * @param callback The function to be registered. See @c TSRPCMethodCb + * @param info TSRPCProviderHandle pointer, this will be used to provide more context information about this call. This object + * ideally should be the one returned by the TSRPCRegister API. + * @param opt Pointer to @c TSRPCHandlerOptions object. This will be used to store specifics about a particular call, the rpc + * manager will use this object to perform certain actions. A copy of this object wil be stored by the rpc manager. + * + * @return TS_SUCCESS if the handler was successfully registered, TS_ERROR if the handler is already registered. + */ + TSReturnCode TSRPCRegisterMethodHandler(const char *name, size_t name_len, TSRPCMethodCb callback, TSRPCProviderHandle info, + const TSRPCHandlerOptions *opt); + + /** + * @brief Add new registered notification handler to the JSON RPC engine. + * + * @param name Call name to be exposed by the RPC Engine, this should match the incoming request. i.e: If you register 'get_stats' + * then the incoming jsonrpc call should have this very same name in the 'method' field. .. {...'method': + * 'get_stats'...} . + * @param name_len The length of the name string. + * @param callback The function to be registered. See @c TSRPCNotificationCb + * @param info TSRPCProviderHandle pointer, this will be used to provide more description for instance, when logging before or + * after a call. This object ideally should be the one returned by the TSRPCRegister API. + * @param opt Pointer to @c TSRPCHandlerOptions object. This will be used to store specifics about a particular call, the rpc + * manager will use this object to perform certain actions. A copy of this object wil be stored by the rpc manager. + * @return TS_SUCCESS if the handler was successfully registered, TS_ERROR if the handler is already registered. + */ + TSReturnCode TSRPCRegisterNotificationHandler(const char *name, size_t name_len, TSRPCNotificationCb callback, + TSRPCProviderHandle info, const TSRPCHandlerOptions *opt); + + /** + * @brief Function to notify the JSONRPC engine that the current handler is done working. + * + * This function must be used when implementing a 'method' rpc handler. Once the work is done and the response is ready to be sent + * back to the client, this function should be called. Is expected to set the YAML node as response. If the response is empty a + * 'success' message will be added to the client's response. + * + * @note This should not be used if you registered your handler as a notification: @c TSRPCNotificationCb + * @param resp The YAML node that contains the call response. + * @return TS_SUCCESS if no issues. TS_ERROR otherwise. + */ + TSReturnCode TSRPCHandlerDone(TSYaml resp); + + /** + * @brief Function to notify the JSONRPC engine that the current handler is done working and an error has arisen. + * + * @note This should not be used if you registered your handler as a notification: @c TSRPCNotificationCb + * call. + * @param code Error code. + * @param descr A text with a description of the error. + * @param descr_len The length of the description string. + * @note The @c code and @c descr will be part of the @c 'data' field in the jsonrpc error response. + * @return TS_SUCCESS if no issues. TS_ERROR otherwise. + */ + TSReturnCode TSRPCHandlerError(int code, const char *descr, size_t descr_len); + + /** Do another cache lookup with a different cache key. + * + * @param txnp Transaction. + * @param url URL to use for cache key. + * @param length Length of the string in @a url + * + * @return @c TS_SUCCESS on success, @c TS_ERROR if the @a txnp is invalid or the @a url is + * not a valid URL. + * + * If @a length is negative, @c strlen will be used to determine the length of @a url. + * + * @a url must be syntactically a URL, but otherwise it is just a string and does not need to + * be retrievable. + * + * This can only be called in a @c TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK callback. To set the cache + * key for the first lookup, use @c TSCacheUrlSet. + * + * @see TSCacheUrlSet + */ + TSReturnCode TSHttpTxnRedoCacheLookup(TSHttpTxn txnp, const char *url, int length); + + /* IP addr parsing. This is a candidate for deprecation in v10.0.0, in favor of libswoc */ + TSReturnCode TSIpStringToAddr(const char *str, size_t str_len, struct sockaddr *addr); + +} // end namespace c + +template +T * +malloc(size_t count = 1) +{ + return static_cast *>(c::TSmalloc(count * sizeof(T))); +} -/* IP addr parsing. This is a candidate for deprecation in v10.0.0, in favor of libswoc */ -tsapi TSReturnCode TSIpStringToAddr(const char *str, size_t str_len, struct sockaddr *addr); +} // end namespace tsapi -#ifdef __cplusplus -} -#endif /* __cplusplus */ +using namespace tsapi::c; diff --git a/include/tscore/DbgCtl.h b/include/tscore/DbgCtl.h index f7b2f59ad3f..72f8df6e0d5 100644 --- a/include/tscore/DbgCtl.h +++ b/include/tscore/DbgCtl.h @@ -56,7 +56,7 @@ class DbgCtl class _RegistryAccessor; - friend TSDbgCtl const *TSDbgCtlCreate(char const *tag); + friend TSDbgCtl const *tsapi::c::TSDbgCtlCreate(char const *tag); - friend void TSDbgCtlDestroy(TSDbgCtl const *dbg_ctl); + friend void tsapi::c::TSDbgCtlDestroy(TSDbgCtl const *dbg_ctl); }; diff --git a/include/tscore/ink_assert.h b/include/tscore/ink_assert.h index 2b83751b471..473b295f822 100644 --- a/include/tscore/ink_assert.h +++ b/include/tscore/ink_assert.h @@ -29,10 +29,6 @@ Assertions #include "tscore/ink_apidefs.h" -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - /* don't use assert, no really DON'T use assert */ #undef assert #define assert __DONT_USE_BARE_assert_USE_ink_assert__ @@ -51,9 +47,6 @@ void _ink_assert(const char *a, const char *f, int l) TS_NORETURN; #define ink_release_assert(EX) ((void)(__builtin_expect(!!(EX), 0) ? (void)0 : _ink_assert(#EX, __FILE__, __LINE__))) -#ifdef __cplusplus -} - /* Use cast_to_derived() to cast a pointer/reference to a dynamic base class into a pointer/reference to a class that inherits directly or indirectly from the base class. Uses checked dynamic_cast in debug builds, and @@ -99,5 +92,3 @@ cast_to_derived(Base &b) #endif } - -#endif /* __cplusplus */ diff --git a/include/tscore/ink_memory.h b/include/tscore/ink_memory.h index b083e80b48b..3dbac7b75a4 100644 --- a/include/tscore/ink_memory.h +++ b/include/tscore/ink_memory.h @@ -76,10 +76,6 @@ #define MADV_DONTNEED 4 #endif -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - struct IOVec : public iovec { IOVec() { @@ -134,12 +130,6 @@ char *_xstrdup(const char *str, int length, const char *path); #define ats_strndup(p, n) _xstrdup((p), n, nullptr) -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus - #include // this is to help with migration to a std::string issue with older code that @@ -622,5 +612,3 @@ struct ats_unique_buf_deleter { }; using ats_unique_buf = std::unique_ptr; ats_unique_buf ats_unique_malloc(size_t size); - -#endif /* __cplusplus */ diff --git a/include/tscore/ink_queue.h b/include/tscore/ink_queue.h index 53ce721f69b..edf31e378c1 100644 --- a/include/tscore/ink_queue.h +++ b/include/tscore/ink_queue.h @@ -56,10 +56,6 @@ #endif */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - void ink_queue_load_64(void *dst, void *src); #ifdef __x86_64__ @@ -248,7 +244,3 @@ void *ink_atomiclist_popall(InkAtomicList *l); * WARNING WARNING WARNING WARNING WARNING WARNING WARNING */ void *ink_atomiclist_remove(InkAtomicList *l, void *item); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/include/tscore/ink_stack_trace.h b/include/tscore/ink_stack_trace.h index ff759b8b802..4ec4e6d11e1 100644 --- a/include/tscore/ink_stack_trace.h +++ b/include/tscore/ink_stack_trace.h @@ -26,10 +26,6 @@ // The max number of levels in the stack trace #define INK_STACK_TRACE_MAX_LEVELS 100 -#ifdef __cplusplus -extern "C" { -#endif - /* dumps the current back trace to stderr */ void ink_stack_trace_dump(); @@ -37,7 +33,3 @@ void ink_stack_trace_dump(); Get symbol of @n-th frame */ const void *ink_backtrace(const int n); - -#ifdef __cplusplus -} -#endif diff --git a/include/tscpp/api/Logger.h b/include/tscpp/api/Logger.h index be849de2df1..159345741a4 100644 --- a/include/tscpp/api/Logger.h +++ b/include/tscpp/api/Logger.h @@ -78,23 +78,30 @@ (log).logError("[%s:%d, %s()] " fmt, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \ } while (false) -/** - * We forward declare this because if we didn't we end up writing our - * own version to do the vsnprintf just to call TSDebug and have it do - * an unnecessary vsnprintf. - * - * @private - */ -extern "C" void TSDebug(const char *tag, const char *fmt, ...) ATSCPPAPI_PRINTFLIKE(2, 3); +namespace tsapi +{ +namespace c +{ + /** + * We forward declare this because if we didn't we end up writing our + * own version to do the vsnprintf just to call TSDebug and have it do + * an unnecessary vsnprintf. + * + * @private + */ + void TSDebug(const char *tag, const char *fmt, ...) ATSCPPAPI_PRINTFLIKE(2, 3); -/** - * We forward declare this because if we didn't we end up writing our - * own version to do the vsnprintf just to call TSError and have it do - * an unnecessary vsnprintf. - * - * @private - */ -extern "C" void TSError(const char *fmt, ...) ATSCPPAPI_PRINTFLIKE(1, 2); + /** + * We forward declare this because if we didn't we end up writing our + * own version to do the vsnprintf just to call TSError and have it do + * an unnecessary vsnprintf. + * + * @private + */ + void TSError(const char *fmt, ...) ATSCPPAPI_PRINTFLIKE(1, 2); + +} // end namespace c +} // end namespace tsapi // This is weird, but see the following: // http://stackoverflow.com/questions/5641427/how-to-make-preprocessor-generate-a-string-for-line-keyword diff --git a/include/tscpp/api/PluginInit.h b/include/tscpp/api/PluginInit.h index 626f99b6289..acd8bea2986 100644 --- a/include/tscpp/api/PluginInit.h +++ b/include/tscpp/api/PluginInit.h @@ -23,7 +23,6 @@ #pragma once #include #include "tscpp/api/utils.h" -extern "C" { /** * Invoked for "general" plugins - listed in plugin.config. The arguments in the @@ -44,4 +43,3 @@ void TSPluginInit(int argc, const char *argv[]); * @param errbuf_size Not used */ TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **instance_handle, char *errbuf, int errbuf_size); -} diff --git a/iocore/eventsystem/I_VConnection.h b/iocore/eventsystem/I_VConnection.h index c60915e78af..e39f4dff5c2 100644 --- a/iocore/eventsystem/I_VConnection.h +++ b/iocore/eventsystem/I_VConnection.h @@ -130,9 +130,7 @@ enum TSApiDataType { TS_API_DATA_LAST ///< Used by other classes to extend the enum values. }; -extern "C" { typedef struct tsapi_vio *TSVIO; -} /** Base class for the connection classes that provide IO capabilities. diff --git a/lib/fastlz/fastlz.h b/lib/fastlz/fastlz.h index 42fccde5744..fd41e961e04 100644 --- a/lib/fastlz/fastlz.h +++ b/lib/fastlz/fastlz.h @@ -32,10 +32,6 @@ #define FASTLZ_VERSION_STRING "0.5.0" -#if defined(__cplusplus) -extern "C" { -#endif - /** Compress a block of data in the input buffer and returns the size of compressed block. The size of input buffer is specified by length. The @@ -90,8 +86,4 @@ int fastlz_decompress(const void *input, int length, void *output, int maxout); int fastlz_compress(const void *input, int length, void *output); -#if defined(__cplusplus) -} -#endif - #endif /* FASTLZ_H */ diff --git a/plugins/esi/lib/IncludeHandlerFactory.h b/plugins/esi/lib/IncludeHandlerFactory.h index 2b64906c688..ab8cb5ba7d8 100644 --- a/plugins/esi/lib/IncludeHandlerFactory.h +++ b/plugins/esi/lib/IncludeHandlerFactory.h @@ -26,17 +26,9 @@ #include #include "SpecialIncludeHandler.h" -#ifdef __cplusplus -extern "C" { -#endif - EsiLib::SpecialIncludeHandler *createSpecialIncludeHandler(EsiLib::Variables &esi_vars, EsiLib::Expression &esi_expr, HttpDataFetcher &fetcher, const std::string &id); -#ifdef __cplusplus -} -#endif - namespace EsiLib { using SpecialIncludeHandlerCreator = SpecialIncludeHandler *(*)(Variables &, Expression &, HttpDataFetcher &, const std::string &); diff --git a/plugins/experimental/cache_key_genid/Makefile.inc b/plugins/experimental/cache_key_genid/Makefile.inc index b3a34b35379..442cfae98f6 100644 --- a/plugins/experimental/cache_key_genid/Makefile.inc +++ b/plugins/experimental/cache_key_genid/Makefile.inc @@ -17,7 +17,7 @@ pkglib_LTLIBRARIES += experimental/cache_key_genid/cache_key_genid.la experimental_cache_key_genid_cache_key_genid_la_SOURCES = \ - experimental/cache_key_genid/cache_key_genid.c + experimental/cache_key_genid/cache_key_genid.cc experimental_cache_key_genid_cache_key_genid_la_LDFLAGS = \ $(AM_LDFLAGS) $(LIB_KYOTOCABINET) diff --git a/plugins/experimental/cache_key_genid/cache_key_genid.c b/plugins/experimental/cache_key_genid/cache_key_genid.cc similarity index 97% rename from plugins/experimental/cache_key_genid/cache_key_genid.c rename to plugins/experimental/cache_key_genid/cache_key_genid.cc index 5435b43a134..cb4db03b64d 100644 --- a/plugins/experimental/cache_key_genid/cache_key_genid.c +++ b/plugins/experimental/cache_key_genid/cache_key_genid.cc @@ -75,7 +75,7 @@ get_genid(char *host) if (vbuf) { TSDebug(PLUGIN_NAME, "kcdbget(%s) = %s", host, vbuf); - answer = (int)strtol(vbuf, NULL, 10); + answer = (int)strtol(vbuf, nullptr, 10); kcfree(vbuf); } else { host_size = strlen(host); @@ -96,7 +96,7 @@ static int handle_hook(TSCont *contp, TSEvent event, void *edata) { TSHttpTxn txnp = (TSHttpTxn)edata; - char *url = NULL, *host = NULL; + char *url = nullptr, *host = nullptr; int url_length; int gen_id; int ok = 1; @@ -172,5 +172,5 @@ TSPluginInit(int argc, const char *argv[]) return; } - TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate((TSEventFunc)handle_hook, NULL)); + TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate((TSEventFunc)handle_hook, nullptr)); } diff --git a/plugins/experimental/cookie_remap/Makefile.inc b/plugins/experimental/cookie_remap/Makefile.inc index 919eb282df0..ddf84afb6ce 100644 --- a/plugins/experimental/cookie_remap/Makefile.inc +++ b/plugins/experimental/cookie_remap/Makefile.inc @@ -18,7 +18,7 @@ pkglib_LTLIBRARIES += experimental/cookie_remap/cookie_remap.la experimental_cookie_remap_cookie_remap_la_SOURCES = \ experimental/cookie_remap/cookie_remap.cc \ - experimental/cookie_remap/hash.c \ + experimental/cookie_remap/hash.cc \ experimental/cookie_remap/strip.cc \ experimental/cookie_remap/cookiejar.cc diff --git a/plugins/experimental/cookie_remap/hash.c b/plugins/experimental/cookie_remap/hash.cc similarity index 100% rename from plugins/experimental/cookie_remap/hash.c rename to plugins/experimental/cookie_remap/hash.cc diff --git a/plugins/experimental/cookie_remap/hash.h b/plugins/experimental/cookie_remap/hash.h index 18375b3ecb9..b05992bfd2d 100644 --- a/plugins/experimental/cookie_remap/hash.h +++ b/plugins/experimental/cookie_remap/hash.h @@ -22,10 +22,6 @@ #include #include // NOLINT(modernize-deprecated-headers) -#ifdef __cplusplus -extern "C" { -#endif - /** * 32-bit Fowler / Noll / Vo (FNV) Hash. * @@ -45,7 +41,3 @@ uint32_t hash_fnv32_buf(const char *buf, size_t len); * if num_buckets is a power of two. */ uint32_t hash_fnv32_buckets(const char *buf, size_t len, uint32_t num_buckets); - -#ifdef __cplusplus -} -#endif diff --git a/plugins/experimental/cookie_remap/strip.h b/plugins/experimental/cookie_remap/strip.h index 9a0a739ed61..12572576076 100644 --- a/plugins/experimental/cookie_remap/strip.h +++ b/plugins/experimental/cookie_remap/strip.h @@ -20,10 +20,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* return codes */ #define STRIP_RESULT_OK 0 /**< success */ #define STRIP_RESULT_BAD_PARAM -1 /**< one or more invalid arguments */ @@ -75,7 +71,7 @@ extern "C" { * - STRIP_FLAG_UNSAFE_QUOTES - Leave apos and quote in place. * - STRIP_FLAG_UNSAFE_SLASHES - Leave backslashes in place. * - STRIP_FLAG_UNSAFE_SPACES - Leave spaces in place. - * @param[in] charset NULL or the charset used to treat the input + * @param[in] charset null or the charset used to treat the input * * @return * IV_RESULT_OK(0) on success. Non-zero on failure. @@ -114,7 +110,7 @@ extern "C" { * - the input buffer does not need to be null-terminated * * - the output is always null-terminated (except when it is - * not possible -- out==NULL || *out_len==0) + * not possible -- out==nullptr || *out_len==0) * * - no context is retained between calls * @@ -129,7 +125,7 @@ extern "C" { * required length in out_len and out set to the empty * string * - * - can be called with out_len == 0 and out == NULL to + * - can be called with out_len == 0 and out == nullptr to * compute sufficient storage size, which is returned * in out_len * @@ -137,7 +133,3 @@ extern "C" { * NUL-terminated */ int get_stripped(const char *in, ssize_t in_len, char *out, int *out_len, unsigned int flags); - -#ifdef __cplusplus -} -#endif diff --git a/plugins/experimental/fq_pacing/CMakeLists.txt b/plugins/experimental/fq_pacing/CMakeLists.txt index 457e69ae607..18d02d9fbf3 100644 --- a/plugins/experimental/fq_pacing/CMakeLists.txt +++ b/plugins/experimental/fq_pacing/CMakeLists.txt @@ -15,4 +15,4 @@ # ####################### -add_atsplugin(fq_pacing fq_pacing.c) +add_atsplugin(fq_pacing fq_pacing.cc) diff --git a/plugins/experimental/fq_pacing/Makefile.inc b/plugins/experimental/fq_pacing/Makefile.inc index 00e5b455696..5fda9b6ac3e 100644 --- a/plugins/experimental/fq_pacing/Makefile.inc +++ b/plugins/experimental/fq_pacing/Makefile.inc @@ -17,4 +17,4 @@ pkglib_LTLIBRARIES += experimental/fq_pacing/fq_pacing.la experimental_fq_pacing_fq_pacing_la_SOURCES = \ - experimental/fq_pacing/fq_pacing.c + experimental/fq_pacing/fq_pacing.cc diff --git a/plugins/experimental/fq_pacing/fq_pacing.c b/plugins/experimental/fq_pacing/fq_pacing.cc similarity index 91% rename from plugins/experimental/fq_pacing/fq_pacing.c rename to plugins/experimental/fq_pacing/fq_pacing.cc index c86ee858379..4cc916808b0 100644 --- a/plugins/experimental/fq_pacing/fq_pacing.c +++ b/plugins/experimental/fq_pacing/fq_pacing.cc @@ -125,7 +125,7 @@ TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size) { - fq_pacing_cfg_t *cfg = NULL; + fq_pacing_cfg_t *cfg = nullptr; unsigned long pacing_rate = 0; TSDebug(PLUGIN_NAME, "Instantiating a new remap.config plugin rule"); @@ -133,17 +133,17 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s if (argc > 1) { int c; static const struct option longopts[] = { - {"rate", required_argument, NULL, 'r'}, - {NULL, 0, NULL, 0 } + {"rate", required_argument, nullptr, 'r'}, + {nullptr, 0, nullptr, 0 } }; // The "-" in optstring is required to prevent permutation of argv, which // makes the plugin loader crashy - while ((c = getopt_long(argc, (char *const *)argv, "-r:", longopts, NULL)) != -1) { + while ((c = getopt_long(argc, (char *const *)argv, "-r:", longopts, nullptr)) != -1) { switch (c) { case 'r': errno = 0; - pacing_rate = strtoul(optarg, NULL, 0); + pacing_rate = strtoul(optarg, nullptr, 0); if (errno != 0) { snprintf(errbuf, errbuf_size - 1, "[TsRemapNewInstance] input pacing value is not a valid positive integer"); return TS_ERROR; @@ -160,10 +160,10 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s return TS_ERROR; } - cfg = TSmalloc(sizeof(fq_pacing_cfg_t)); + cfg = tsapi::malloc(); memset(cfg, 0, sizeof(*cfg)); cfg->pacing_rate = pacing_rate; - *ih = (void *)cfg; + *ih = cfg; TSDebug(PLUGIN_NAME, "Setting pacing rate to %lu", pacing_rate); return TS_SUCCESS; @@ -174,7 +174,7 @@ TSRemapDeleteInstance(void *instance) { TSError("[fq_pacing] Cleaning up..."); - if (instance != NULL) { + if (instance != nullptr) { TSfree((fq_pacing_cfg_t *)instance); } } @@ -182,8 +182,8 @@ TSRemapDeleteInstance(void *instance) static int reset_pacing_cont(TSCont contp, TSEvent event, void *edata) { - TSHttpTxn txnp = (TSHttpTxn)edata; - fq_pacing_cont_t *txn_data = TSContDataGet(contp); + TSHttpTxn txnp = (TSHttpTxn)edata; + auto txn_data = static_cast(TSContDataGet(contp)); #ifdef SO_MAX_PACING_RATE unsigned int pacing_off = ~0U; @@ -207,7 +207,7 @@ reset_pacing_cont(TSCont contp, TSEvent event, void *edata) TSRemapStatus TSRemapDoRemap(void *instance, TSHttpTxn txnp, TSRemapRequestInfo *rri) { - if (TSHttpTxnClientProtocolStackContains(txnp, TS_PROTO_TAG_HTTP_2_0) != NULL) { + if (TSHttpTxnClientProtocolStackContains(txnp, TS_PROTO_TAG_HTTP_2_0) != nullptr) { TSDebug(PLUGIN_NAME, "Skipping plugin execution for HTTP/2 requests"); return TSREMAP_NO_REMAP; } @@ -230,10 +230,10 @@ TSRemapDoRemap(void *instance, TSHttpTxn txnp, TSRemapRequestInfo *rri) // Reset pacing at end of transaction in case session is // reused for another delivery service w/o pacing - TSCont cont = TSContCreate(reset_pacing_cont, NULL); + TSCont cont = TSContCreate(reset_pacing_cont, nullptr); - fq_pacing_cont_t *txn_data = TSmalloc(sizeof(fq_pacing_cont_t)); - txn_data->client_fd = client_fd; + auto txn_data = tsapi::malloc(); + txn_data->client_fd = client_fd; TSContDataSet(cont, txn_data); TSHttpTxnHookAdd(txnp, TS_HTTP_TXN_CLOSE_HOOK, cont); diff --git a/plugins/experimental/memcache/protocol_binary.h b/plugins/experimental/memcache/protocol_binary.h index 8ca18ff98b6..62aecfcfd6b 100644 --- a/plugins/experimental/memcache/protocol_binary.h +++ b/plugins/experimental/memcache/protocol_binary.h @@ -40,9 +40,6 @@ * to convert each multibyte field to / from network byte order to / from * host order. */ -#ifdef __cplusplus -extern "C" { -#endif /** * Definition of the legal "magic" values used in a packet. @@ -407,7 +404,3 @@ typedef protocol_binary_request_rangeop protocol_binary_request_rincr; typedef protocol_binary_request_rangeop protocol_binary_request_rincrq; typedef protocol_binary_request_rangeop protocol_binary_request_rdecr; typedef protocol_binary_request_rangeop protocol_binary_request_rdecrq; - -#ifdef __cplusplus -} -#endif diff --git a/plugins/experimental/parent_select/parent_select.cc b/plugins/experimental/parent_select/parent_select.cc index 6ed8f5b783d..10b9a6d064c 100644 --- a/plugins/experimental/parent_select/parent_select.cc +++ b/plugins/experimental/parent_select/parent_select.cc @@ -319,7 +319,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuff, int errbuff return TS_SUCCESS; } -extern "C" tsapi TSRemapStatus +TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) { TSDebug(PLUGIN_NAME, "TSRemapDoRemap calling"); @@ -368,7 +368,7 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) return TSREMAP_NO_REMAP; } -extern "C" tsapi void +void TSRemapDeleteInstance(void *ih) { TSDebug(PLUGIN_NAME, "TSRemapDeleteInstance calling"); diff --git a/plugins/experimental/slice/slice.cc b/plugins/experimental/slice/slice.cc index 09d2847383f..87854c5ed53 100644 --- a/plugins/experimental/slice/slice.cc +++ b/plugins/experimental/slice/slice.cc @@ -210,7 +210,6 @@ global_read_request_hook(TSCont // contp ///// remap plugin engine -SLICE_EXPORT TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) { @@ -224,13 +223,11 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) } ///// remap plugin setup and teardown -SLICE_EXPORT void TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type) { } -SLICE_EXPORT TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */) { @@ -240,7 +237,6 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int / return TS_SUCCESS; } -SLICE_EXPORT void TSRemapDeleteInstance(void *ih) { @@ -250,7 +246,6 @@ TSRemapDeleteInstance(void *ih) } } -SLICE_EXPORT TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbug, int errbuf_size) { @@ -259,7 +254,6 @@ TSRemapInit(TSRemapInterface *api_info, char *errbug, int errbuf_size) } ///// global plugin -SLICE_EXPORT void TSPluginInit(int argc, char const *argv[]) { diff --git a/plugins/experimental/slice/slice.h b/plugins/experimental/slice/slice.h index 541a37bd2c9..6fe04601172 100644 --- a/plugins/experimental/slice/slice.h +++ b/plugins/experimental/slice/slice.h @@ -23,10 +23,6 @@ #include #include -#ifndef SLICE_EXPORT -#define SLICE_EXPORT extern "C" tsapi -#endif - #ifndef PLUGIN_NAME #define PLUGIN_NAME "slice" #endif diff --git a/plugins/experimental/sslheaders/sslheaders.h b/plugins/experimental/sslheaders/sslheaders.h index dc506aab2da..ba8fd5ad32a 100644 --- a/plugins/experimental/sslheaders/sslheaders.h +++ b/plugins/experimental/sslheaders/sslheaders.h @@ -24,10 +24,8 @@ #include #include -extern "C" { using X509 = struct x509_st; using BIO = struct bio_st; -} #define PLUGIN_NAME "sslheaders" diff --git a/plugins/experimental/sslheaders/unit_tests/test_sslheaders.cc b/plugins/experimental/sslheaders/unit_tests/test_sslheaders.cc index 59a7fa64260..6ff8fed6167 100644 --- a/plugins/experimental/sslheaders/unit_tests/test_sslheaders.cc +++ b/plugins/experimental/sslheaders/unit_tests/test_sslheaders.cc @@ -27,22 +27,6 @@ // Mock TS API functions. -char * -_TSstrdup(const char *str, int64_t length, const char *) -{ - if (length == -1) { - return strdup(str); - } else { - return strndup(str, length); - } -} - -void -_TSfree(void *ptr) -{ - free(ptr); -} - void TSDebug(const char *tag, const char *fmt, ...) { @@ -56,7 +40,7 @@ TSDebug(const char *tag, const char *fmt, ...) } void -TSError(const char *fmt, ...) +tsapi::c::TSError(const char *fmt, ...) { va_list args; diff --git a/plugins/experimental/stream_editor/stream_editor.cc b/plugins/experimental/stream_editor/stream_editor.cc index 453ff8e83c3..cba92518093 100644 --- a/plugins/experimental/stream_editor/stream_editor.cc +++ b/plugins/experimental/stream_editor/stream_editor.cc @@ -827,7 +827,7 @@ read_conf(const char *filename, ruleset_t *&in, ruleset_t *&out) fclose(file); } -extern "C" void +void TSPluginInit(int argc, const char *argv[]) { TSPluginRegistrationInfo info; diff --git a/plugins/experimental/uri_signing/Makefile.inc b/plugins/experimental/uri_signing/Makefile.inc index 4a44445eb09..828fa7f1d37 100644 --- a/plugins/experimental/uri_signing/Makefile.inc +++ b/plugins/experimental/uri_signing/Makefile.inc @@ -17,14 +17,14 @@ pkglib_LTLIBRARIES += experimental/uri_signing/uri_signing.la experimental_uri_signing_uri_signing_la_SOURCES = \ - experimental/uri_signing/uri_signing.c \ - experimental/uri_signing/config.c \ - experimental/uri_signing/cookie.c \ - experimental/uri_signing/jwt.c \ - experimental/uri_signing/match.c \ - experimental/uri_signing/parse.c \ - experimental/uri_signing/normalize.c \ - experimental/uri_signing/timing.c + experimental/uri_signing/uri_signing.cc \ + experimental/uri_signing/config.cc \ + experimental/uri_signing/cookie.cc \ + experimental/uri_signing/jwt.cc \ + experimental/uri_signing/match.cc \ + experimental/uri_signing/parse.cc \ + experimental/uri_signing/normalize.cc \ + experimental/uri_signing/timing.cc experimental_uri_signing_uri_signing_la_LIBADD = @LIBJANSSON@ @LIBCJOSE@ @LIBPCRE@ -lm -lcrypto @@ -38,12 +38,12 @@ experimental_uri_signing_test_uri_signing_CPPFLAGS = \ experimental_uri_signing_test_uri_signing_LDADD = @LIBJANSSON@ @LIBCJOSE@ @LIBPCRE@ -lm -lcrypto experimental_uri_signing_test_uri_signing_SOURCES = \ - experimental/uri_signing/unit_tests/uri_signing_test.cc \ - experimental/uri_signing/jwt.c \ - experimental/uri_signing/common.c \ - experimental/uri_signing/parse.c \ - experimental/uri_signing/cookie.c \ - experimental/uri_signing/config.c \ - experimental/uri_signing/timing.c \ - experimental/uri_signing/normalize.c \ - experimental/uri_signing/match.c + experimental/uri_signing/unit_tests/uri_signing_test.cc \ + experimental/uri_signing/jwt.cc \ + experimental/uri_signing/common.cc \ + experimental/uri_signing/parse.cc \ + experimental/uri_signing/cookie.cc \ + experimental/uri_signing/config.cc \ + experimental/uri_signing/timing.cc \ + experimental/uri_signing/normalize.cc \ + experimental/uri_signing/match.cc diff --git a/plugins/experimental/uri_signing/common.c b/plugins/experimental/uri_signing/common.cc similarity index 100% rename from plugins/experimental/uri_signing/common.c rename to plugins/experimental/uri_signing/common.cc diff --git a/plugins/experimental/uri_signing/config.c b/plugins/experimental/uri_signing/config.c deleted file mode 100644 index 64deda64c92..00000000000 --- a/plugins/experimental/uri_signing/config.c +++ /dev/null @@ -1,399 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "common.h" -#include "config.h" -#include "timing.h" -#include "jwt.h" - -#include -#include - -#include -#include -#include - -#define JSONError(err) PluginError("json-err: %s:%d:%d: %s", (err).source, (err).line, (err).column, (err).text) - -#define AUTH_DENY 0 -#define AUTH_ALLOW 1 -struct auth_directive { - char auth; - char *container; -}; - -struct config { - struct hsearch_data *issuers; - cjose_jwk_t ***jwkis; - char **issuer_names; - struct signer signer; - struct auth_directive *auth_directives; - char *id; - bool strip_token; -}; - -cjose_jwk_t ** -find_keys(struct config *cfg, const char *issuer) -{ - ENTRY *entry; - if (!hsearch_r((ENTRY){.key = (char *)issuer}, FIND, &entry, cfg->issuers) || !entry) { - PluginDebug("Unable to locate any keys at %p for issuer %s in %p->%p", entry, issuer, cfg, cfg->issuers); - return NULL; - } - - int n = 0; - for (cjose_jwk_t **jwks = entry->data; *jwks; ++jwks, ++n) { - ; - } - PluginDebug("Located %d keys for issuer %s in %p->%p", n, issuer, cfg, cfg->issuers); - return entry->data; -} - -cjose_jwk_t * -find_key_by_kid(struct config *cfg, const char *issuer, const char *kid) -{ - const char *this_kid; - cjose_jwk_t **jwkis = find_keys(cfg, issuer); - if (!jwkis) { - return NULL; - } - for (cjose_jwk_t **jwks = jwkis; *jwks; ++jwks) { - if ((this_kid = cjose_jwk_get_kid(*jwks, NULL)) && !strcmp(this_kid, kid)) { - return *jwks; - } - } - return NULL; -} - -const char * -config_get_id(struct config *cfg) -{ - return cfg->id; -} - -bool -config_strip_token(struct config *cfg) -{ - return cfg->strip_token; -} - -struct config * -config_new(size_t n) -{ - PluginDebug("Creating new config object with size %ld", n); - struct config *cfg = malloc(sizeof *cfg); - - cfg->issuers = calloc(1, sizeof *cfg->issuers); - if (!hcreate_r(n * 2, cfg->issuers)) { - PluginError("Unable to create config table (%d)!", errno); - free(cfg); - return NULL; - } - PluginDebug("Created table with size %d", cfg->issuers->size); - - cfg->jwkis = malloc((n + 1) * sizeof *cfg->jwkis); - cfg->jwkis[n] = NULL; - - cfg->issuer_names = malloc((n + 1) * sizeof *cfg->issuer_names); - cfg->issuer_names[n] = NULL; - - cfg->signer.issuer = NULL; - cfg->signer.jwk = NULL; - cfg->signer.alg = NULL; - - cfg->auth_directives = NULL; - cfg->id = NULL; - - cfg->strip_token = false; - - PluginDebug("New config object created at %p", cfg); - return cfg; -} - -void -config_delete(struct config *cfg) -{ - if (!cfg) { - return; - } - hdestroy_r(cfg->issuers); - free(cfg->issuers); - - for (cjose_jwk_t ***jwkis = cfg->jwkis; *jwkis; ++jwkis) { - for (cjose_jwk_t **jwks = *jwkis; *jwks; ++jwks) { - cjose_jwk_release(*jwks); - } - free(*jwkis); - } - free(cfg->jwkis); - - if (cfg->id) { - free(cfg->id); - } - - for (char **name = cfg->issuer_names; *name; ++name) { - free(*name); - } - free(cfg->issuer_names); - - if (cfg->signer.alg) { - free(cfg->signer.alg); - } - - if (cfg->auth_directives) { - for (struct auth_directive *ad = cfg->auth_directives; ad->container; ++ad) { - free(ad->container); - } - free(cfg->auth_directives); - } - free(cfg); -} - -cjose_jwk_t * -load_jwk(json_t *obj, cjose_err *err) -{ - char *s = json_dumps(obj, JSON_COMPACT); - if (!s) { - PluginError("Failed to re-serialize JSON sub-object."); - return NULL; - } - - cjose_jwk_t *jwk = cjose_jwk_import(s, strlen(s), err); - free(s); - return jwk; -} - -static struct config * -read_config_from_json(json_t *const issuer_json) -{ - if (!json_is_object(issuer_json)) { - PluginError("Config file is not a valid JSON object"); - goto issuer_fail; - } - - size_t issuers_ct = json_object_size(issuer_json); - if (!issuers_ct) { - PluginError("Config file contains no issuers."); - goto issuer_fail; - } - - struct config *cfg = config_new(issuers_ct); - if (!cfg) { - PluginError("Unable to allocate config."); - goto issuer_fail; - } - - cjose_jwk_t ***jwkis = cfg->jwkis; - char **issuer = cfg->issuer_names; - const char *json_issuer; - json_t *jwks; - json_object_foreach(issuer_json, json_issuer, jwks) - { - *issuer = strdup(json_issuer); - - json_t *ad_json = json_object_get(jwks, "auth_directives"); - if (ad_json) { - PluginDebug("Loading auth_directives."); - size_t ad_ct = json_array_size(ad_json); - if (ad_ct) { - PluginDebug("Loading %d new auth_directives.", (int)ad_ct); - struct auth_directive *ad = cfg->auth_directives; - if (cfg->auth_directives) { - /* We've already got directives, so extend them. */ - PluginDebug("Extending existing auth_directives."); - size_t ad_old_ct = 0; - while (ad->container) { - ++ad; - ++ad_old_ct; - } - cfg->auth_directives = realloc(cfg->auth_directives, (ad_ct + ad_old_ct + 1) * sizeof *cfg->auth_directives); - ad = cfg->auth_directives + ad_old_ct; - } else { - ad = cfg->auth_directives = malloc((ad_ct + 1) * sizeof *cfg->auth_directives); - } - json_t *ad_obj; - for (size_t idx = 0; (idx < ad_ct) && (ad_obj = json_array_get(ad_json, idx)); ++idx, ++ad) { - json_t *uri_json = json_object_get(ad_obj, "uri"); - json_t *auth_json = json_object_get(ad_obj, "auth"); - if (uri_json) { - const char *uri = json_string_value(uri_json); - ad->container = strdup(uri ? uri : ""); - ad->auth = AUTH_DENY; - if (auth_json) { - const char *auth = json_string_value(auth_json); - if (!auth) { - auth = ""; - } - if (!strcmp(auth, "allow")) { - ad->auth = AUTH_ALLOW; - } else if (!strcmp(auth, "deny")) { - ad->auth = AUTH_DENY; - } else { - PluginError("auth_directive has unknown auth parameter '%s', defaulting to deny: %s", auth, uri); - } - } else { - PluginError("auth_directive is missing auth parameter, defaulting to deny: %s", uri); - } - PluginDebug("Adding auth_directive %d for %s.", (int)ad->auth, ad->container); - } - } - ad->container = NULL; - } - } else { - PluginDebug("No auth_directives to load for %s.", *issuer); - } - - json_t *key_ary = json_object_get(jwks, "keys"); - if (!key_ary) { - PluginError("Failed to get keys member from jwk for issuer %s", *issuer); - *jwkis = NULL; - goto cfg_fail; - } - PluginDebug("Created table with size %d", cfg->issuers->size); - - const char *renewal_kid = NULL; - json_t *renewal_kid_json = json_object_get(jwks, "renewal_kid"); - if (renewal_kid_json) { - renewal_kid = json_string_value(renewal_kid_json); - } - - json_t *id_json = json_object_get(jwks, "id"); - const char *id; - if (id_json) { - id = json_string_value(id_json); - if (id) { - cfg->id = malloc(strlen(id) + 1); - strcpy(cfg->id, id); - PluginDebug("Found Id in the config: %s", cfg->id); - } - } - - json_t *strip_json = json_object_get(jwks, "strip_token"); - if (strip_json) { - cfg->strip_token = json_boolean_value(strip_json); - } - - size_t jwks_ct = json_array_size(key_ary); - cjose_jwk_t **jwks = (*jwkis++ = malloc((jwks_ct + 1) * sizeof *jwks)); - PluginDebug("Created table with size %d", cfg->issuers->size); - if (!hsearch_r(((ENTRY){*issuer, jwks}), ENTER, &(ENTRY *){0}, cfg->issuers)) { - PluginDebug("Failed to store keys for issuer %s", *issuer); - } else { - PluginDebug("Stored keys for %s at %16p", *issuer, jwks); - } - - json_t *jwk_obj; - cjose_err jwk_err; - memset(&jwk_err, 0, sizeof(cjose_err)); - for (size_t idx = 0; (idx < jwks_ct) && (jwk_obj = json_array_get(key_ary, idx)); ++idx, ++jwks) { - if ((*jwks = load_jwk(jwk_obj, &jwk_err))) { - const char *kid = cjose_jwk_get_kid(*jwks, NULL); - PluginDebug("Stored jwk %ld for issuer %s, kid %s, cfg %p->%p", idx, *issuer, kid ? kid : "", cfg, cfg->issuers); - if (renewal_kid && kid && !strcmp(kid, renewal_kid)) { - if (cfg->signer.issuer) { - PluginError("Cannot load multiple renewal keys for a single remap. iss:\"%s\", kid:\"%s\"; iss:\"%s\", kid:\"%s\"", - cfg->signer.issuer, cjose_jwk_get_kid(cfg->signer.jwk, NULL), *issuer, kid); - goto cfg_fail; - } else { - cfg->signer.issuer = *issuer; - cfg->signer.jwk = *jwks; - - const char *jwk_alg = json_string_value(json_object_get(jwk_obj, "alg")); - if (!jwk_alg) { - PluginError("Cannot load JWK algorithm for renewal key."); - goto cfg_fail; - } - cfg->signer.alg = strdup(jwk_alg); - } - } - } else { - PluginError("Failed to load jwk %ld for issuer %s: %s", idx, *issuer, jwk_err.message); - goto cfg_fail; - } - } - *jwks = NULL; - ++issuer; - } - if (!cfg->signer.issuer) { - PluginError("Cannot load remap without signing key."); - goto cfg_fail; - } - json_decref(issuer_json); - PluginDebug("Loaded config file successfully."); - return cfg; -cfg_fail: - config_delete(cfg); -issuer_fail: - json_decref(issuer_json); - return NULL; -} - -struct config * -read_config_from_path(char const *const path) -{ - json_error_t err; - memset(&err, 0, sizeof(json_error_t)); - json_t *issuer_json = json_load_file(path, 0, &err); - if (!issuer_json) { - JSONError(err); - return NULL; - } - return read_config_from_json(issuer_json); -} - -struct config * -read_config_from_string(char const *const buffer) -{ - json_error_t err; - memset(&err, 0, sizeof(json_error_t)); - json_t *issuer_json = json_loads(buffer, 0, &err); - if (!issuer_json) { - JSONError(err); - return NULL; - } - return read_config_from_json(issuer_json); -} - -struct signer * -config_signer(struct config *cfg) -{ - if (!cfg) { - return NULL; - } - return &cfg->signer; -} - -bool -uri_matches_auth_directive(struct config *cfg, const char *uri, size_t uri_ct) -{ - if (!cfg || !cfg->auth_directives || !uri) { - return false; - } - - char *uri_s = malloc(uri_ct + 1); - memcpy(uri_s, uri, uri_ct); - uri_s[uri_ct] = 0; - for (const struct auth_directive *ad = cfg->auth_directives; ad->container; ++ad) { - if (jwt_check_uri(ad->container, uri_s)) { - free(uri_s); - return (ad->auth == AUTH_ALLOW); - } - } - free(uri_s); - return false; -} diff --git a/plugins/experimental/uri_signing/config.cc b/plugins/experimental/uri_signing/config.cc new file mode 100644 index 00000000000..70efa1ffb04 --- /dev/null +++ b/plugins/experimental/uri_signing/config.cc @@ -0,0 +1,406 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "common.h" +#include "config.h" +#include "timing.h" +#include "jwt.h" + +#include +#include + +#include +#include +#include + +#define JSONError(err) PluginError("json-err: %s:%d:%d: %s", (err).source, (err).line, (err).column, (err).text) + +#define AUTH_DENY 0 +#define AUTH_ALLOW 1 +struct auth_directive { + char auth; + char *container; +}; + +struct config { + struct hsearch_data *issuers; + cjose_jwk_t ***jwkis; + char **issuer_names; + struct signer signer; + struct auth_directive *auth_directives; + char *id; + bool strip_token; +}; + +cjose_jwk_t ** +find_keys(struct config *cfg, const char *issuer) +{ + ENTRY *entry; + if (!hsearch_r((ENTRY){.key = (char *)issuer, .data = nullptr}, FIND, &entry, cfg->issuers) || !entry) { + PluginDebug("Unable to locate any keys at %p for issuer %s in %p->%p", entry, issuer, cfg, cfg->issuers); + return nullptr; + } + + int n = 0; + for (auto jwks = static_cast(entry->data); *jwks; ++jwks, ++n) { + ; + } + PluginDebug("Located %d keys for issuer %s in %p->%p", n, issuer, cfg, cfg->issuers); + return static_cast(entry->data); +} + +cjose_jwk_t * +find_key_by_kid(struct config *cfg, const char *issuer, const char *kid) +{ + const char *this_kid; + cjose_jwk_t **jwkis = find_keys(cfg, issuer); + if (!jwkis) { + return nullptr; + } + for (cjose_jwk_t **jwks = jwkis; *jwks; ++jwks) { + if ((this_kid = cjose_jwk_get_kid(*jwks, nullptr)) && !strcmp(this_kid, kid)) { + return *jwks; + } + } + return nullptr; +} + +const char * +config_get_id(struct config *cfg) +{ + return cfg->id; +} + +bool +config_strip_token(struct config *cfg) +{ + return cfg->strip_token; +} + +struct config * +config_new(size_t n) +{ + PluginDebug("Creating new config object with size %ld", n); + config *cfg = static_cast(malloc(sizeof *cfg)); + + cfg->issuers = static_cast(calloc(1, sizeof *cfg->issuers)); + if (!hcreate_r(n * 2, cfg->issuers)) { + PluginError("Unable to create config table (%d)!", errno); + free(cfg); + return nullptr; + } + PluginDebug("Created table with size %d", cfg->issuers->size); + + cfg->jwkis = static_cast(malloc((n + 1) * sizeof *cfg->jwkis)); + cfg->jwkis[n] = nullptr; + + cfg->issuer_names = static_cast(malloc((n + 1) * sizeof *cfg->issuer_names)); + cfg->issuer_names[n] = nullptr; + + cfg->signer.issuer = nullptr; + cfg->signer.jwk = nullptr; + cfg->signer.alg = nullptr; + + cfg->auth_directives = nullptr; + cfg->id = nullptr; + + cfg->strip_token = false; + + PluginDebug("New config object created at %p", cfg); + return cfg; +} + +void +config_delete(struct config *cfg) +{ + if (!cfg) { + return; + } + hdestroy_r(cfg->issuers); + free(cfg->issuers); + + for (cjose_jwk_t ***jwkis = cfg->jwkis; *jwkis; ++jwkis) { + for (cjose_jwk_t **jwks = *jwkis; *jwks; ++jwks) { + cjose_jwk_release(*jwks); + } + free(*jwkis); + } + free(cfg->jwkis); + + if (cfg->id) { + free(cfg->id); + } + + for (char **name = cfg->issuer_names; *name; ++name) { + free(*name); + } + free(cfg->issuer_names); + + if (cfg->signer.alg) { + free(cfg->signer.alg); + } + + if (cfg->auth_directives) { + for (struct auth_directive *ad = cfg->auth_directives; ad->container; ++ad) { + free(ad->container); + } + free(cfg->auth_directives); + } + free(cfg); +} + +cjose_jwk_t * +load_jwk(json_t *obj, cjose_err *err) +{ + char *s = json_dumps(obj, JSON_COMPACT); + if (!s) { + PluginError("Failed to re-serialize JSON sub-object."); + return nullptr; + } + + cjose_jwk_t *jwk = cjose_jwk_import(s, strlen(s), err); + free(s); + return jwk; +} + +static struct config * +read_config_from_json(json_t *const issuer_json) +{ + struct config *cfg = nullptr; + size_t issuers_ct = 0; + + if (!json_is_object(issuer_json)) { + PluginError("Config file is not a valid JSON object"); + goto issuer_fail; + } + + issuers_ct = json_object_size(issuer_json); + if (!issuers_ct) { + PluginError("Config file contains no issuers."); + goto issuer_fail; + } + + { + cfg = config_new(issuers_ct); + if (!cfg) { + PluginError("Unable to allocate config."); + goto issuer_fail; + } + + cjose_jwk_t ***jwkis = cfg->jwkis; + char **issuer = cfg->issuer_names; + const char *json_issuer; + json_t *jwks; + json_object_foreach(issuer_json, json_issuer, jwks) + { + *issuer = strdup(json_issuer); + + json_t *ad_json = json_object_get(jwks, "auth_directives"); + if (ad_json) { + PluginDebug("Loading auth_directives."); + size_t ad_ct = json_array_size(ad_json); + if (ad_ct) { + PluginDebug("Loading %d new auth_directives.", (int)ad_ct); + struct auth_directive *ad = cfg->auth_directives; + if (cfg->auth_directives) { + /* We've already got directives, so extend them. */ + PluginDebug("Extending existing auth_directives."); + size_t ad_old_ct = 0; + while (ad->container) { + ++ad; + ++ad_old_ct; + } + cfg->auth_directives = + static_cast(realloc(cfg->auth_directives, (ad_ct + ad_old_ct + 1) * sizeof *cfg->auth_directives)); + ad = cfg->auth_directives + ad_old_ct; + } else { + ad = cfg->auth_directives = static_cast(malloc((ad_ct + 1) * sizeof *cfg->auth_directives)); + } + json_t *ad_obj; + for (size_t idx = 0; (idx < ad_ct) && (ad_obj = json_array_get(ad_json, idx)); ++idx, ++ad) { + json_t *uri_json = json_object_get(ad_obj, "uri"); + json_t *auth_json = json_object_get(ad_obj, "auth"); + if (uri_json) { + const char *uri = json_string_value(uri_json); + ad->container = strdup(uri ? uri : ""); + ad->auth = AUTH_DENY; + if (auth_json) { + const char *auth = json_string_value(auth_json); + if (!auth) { + auth = ""; + } + if (!strcmp(auth, "allow")) { + ad->auth = AUTH_ALLOW; + } else if (!strcmp(auth, "deny")) { + ad->auth = AUTH_DENY; + } else { + PluginError("auth_directive has unknown auth parameter '%s', defaulting to deny: %s", auth, uri); + } + } else { + PluginError("auth_directive is missing auth parameter, defaulting to deny: %s", uri); + } + PluginDebug("Adding auth_directive %d for %s.", (int)ad->auth, ad->container); + } + } + ad->container = nullptr; + } + } else { + PluginDebug("No auth_directives to load for %s.", *issuer); + } + + json_t *key_ary = json_object_get(jwks, "keys"); + if (!key_ary) { + PluginError("Failed to get keys member from jwk for issuer %s", *issuer); + *jwkis = nullptr; + goto cfg_fail; + } + PluginDebug("Created table with size %d", cfg->issuers->size); + + const char *renewal_kid = nullptr; + json_t *renewal_kid_json = json_object_get(jwks, "renewal_kid"); + if (renewal_kid_json) { + renewal_kid = json_string_value(renewal_kid_json); + } + + json_t *id_json = json_object_get(jwks, "id"); + const char *id; + if (id_json) { + id = json_string_value(id_json); + if (id) { + cfg->id = static_cast(malloc(strlen(id) + 1)); + strcpy(cfg->id, id); + PluginDebug("Found Id in the config: %s", cfg->id); + } + } + + json_t *strip_json = json_object_get(jwks, "strip_token"); + if (strip_json) { + cfg->strip_token = json_boolean_value(strip_json); + } + + size_t jwks_ct = json_array_size(key_ary); + cjose_jwk_t **jwks = *jwkis++ = static_cast(malloc((jwks_ct + 1) * sizeof *jwks)); + PluginDebug("Created table with size %d", cfg->issuers->size); + ENTRY *dummy; + if (!hsearch_r(((ENTRY){*issuer, jwks}), ENTER, &dummy, cfg->issuers)) { + PluginDebug("Failed to store keys for issuer %s", *issuer); + } else { + PluginDebug("Stored keys for %s at %16p", *issuer, jwks); + } + + json_t *jwk_obj; + cjose_err jwk_err; + memset(&jwk_err, 0, sizeof(cjose_err)); + for (size_t idx = 0; (idx < jwks_ct) && (jwk_obj = json_array_get(key_ary, idx)); ++idx, ++jwks) { + if ((*jwks = load_jwk(jwk_obj, &jwk_err))) { + const char *kid = cjose_jwk_get_kid(*jwks, nullptr); + PluginDebug("Stored jwk %ld for issuer %s, kid %s, cfg %p->%p", idx, *issuer, kid ? kid : "", cfg, cfg->issuers); + if (renewal_kid && kid && !strcmp(kid, renewal_kid)) { + if (cfg->signer.issuer) { + PluginError("Cannot load multiple renewal keys for a single remap. iss:\"%s\", kid:\"%s\"; iss:\"%s\", kid:\"%s\"", + cfg->signer.issuer, cjose_jwk_get_kid(cfg->signer.jwk, nullptr), *issuer, kid); + goto cfg_fail; + } else { + cfg->signer.issuer = *issuer; + cfg->signer.jwk = *jwks; + + const char *jwk_alg = json_string_value(json_object_get(jwk_obj, "alg")); + if (!jwk_alg) { + PluginError("Cannot load JWK algorithm for renewal key."); + goto cfg_fail; + } + cfg->signer.alg = strdup(jwk_alg); + } + } + } else { + PluginError("Failed to load jwk %ld for issuer %s: %s", idx, *issuer, jwk_err.message); + goto cfg_fail; + } + } + *jwks = nullptr; + ++issuer; + } + if (!cfg->signer.issuer) { + PluginError("Cannot load remap without signing key."); + goto cfg_fail; + } + json_decref(issuer_json); + PluginDebug("Loaded config file successfully."); + return cfg; + } +cfg_fail: + config_delete(cfg); +issuer_fail: + json_decref(issuer_json); + return nullptr; +} + +struct config * +read_config_from_path(char const *const path) +{ + json_error_t err; + memset(&err, 0, sizeof(json_error_t)); + json_t *issuer_json = json_load_file(path, 0, &err); + if (!issuer_json) { + JSONError(err); + return nullptr; + } + return read_config_from_json(issuer_json); +} + +struct config * +read_config_from_string(char const *const buffer) +{ + json_error_t err; + memset(&err, 0, sizeof(json_error_t)); + json_t *issuer_json = json_loads(buffer, 0, &err); + if (!issuer_json) { + JSONError(err); + return nullptr; + } + return read_config_from_json(issuer_json); +} + +struct signer * +config_signer(struct config *cfg) +{ + if (!cfg) { + return nullptr; + } + return &cfg->signer; +} + +bool +uri_matches_auth_directive(struct config *cfg, const char *uri, size_t uri_ct) +{ + if (!cfg || !cfg->auth_directives || !uri) { + return false; + } + + char *uri_s = static_cast(malloc(uri_ct + 1)); + memcpy(uri_s, uri, uri_ct); + uri_s[uri_ct] = 0; + for (const struct auth_directive *ad = cfg->auth_directives; ad->container; ++ad) { + if (jwt_check_uri(ad->container, uri_s)) { + free(uri_s); + return (ad->auth == AUTH_ALLOW); + } + } + free(uri_s); + return false; +} diff --git a/plugins/experimental/uri_signing/cookie.c b/plugins/experimental/uri_signing/cookie.cc similarity index 97% rename from plugins/experimental/uri_signing/cookie.c rename to plugins/experimental/uri_signing/cookie.cc index 1e9fc7f9a30..d494268e5ff 100644 --- a/plugins/experimental/uri_signing/cookie.c +++ b/plugins/experimental/uri_signing/cookie.cc @@ -24,7 +24,7 @@ const char * next_cookie(const char *cookie, size_t *cookie_ct, const char **k, size_t *k_ct, const char **v, size_t *v_ct) { if (!k || !k_ct || !v || !v_ct || !cookie_ct || !*cookie_ct) { - return NULL; + return nullptr; } const char *end = cookie + *cookie_ct; @@ -42,7 +42,7 @@ next_cookie(const char *cookie, size_t *cookie_ct, const char **k, size_t *k_ct, /* Cookies that don't have an equal are treated as values, not keys. */ *v = *k; *v_ct = cookie - *v; - *k = NULL; + *k = nullptr; *k_ct = 0; goto done; } @@ -82,5 +82,5 @@ get_cookie_value(const char **cookie, size_t *cookie_ct, const char *key, size_t } } *ct = 0; - return NULL; + return nullptr; } diff --git a/plugins/experimental/uri_signing/jwt.c b/plugins/experimental/uri_signing/jwt.cc similarity index 53% rename from plugins/experimental/uri_signing/jwt.c rename to plugins/experimental/uri_signing/jwt.cc index 81f6e32cbab..841c3e6e86f 100644 --- a/plugins/experimental/uri_signing/jwt.c +++ b/plugins/experimental/uri_signing/jwt.cc @@ -48,10 +48,10 @@ struct jwt * parse_jwt(json_t *raw) { if (!raw) { - return NULL; + return nullptr; } - struct jwt *jwt = malloc(sizeof *jwt); + struct jwt *jwt = static_cast(malloc(sizeof *jwt)); jwt->raw = raw; jwt->iss = json_string_value(json_object_get(raw, "iss")); jwt->sub = json_string_value(json_object_get(raw, "sub")); @@ -102,7 +102,7 @@ bool jwt_validate(struct jwt *jwt) { if (!jwt) { - PluginDebug("Initial JWT Failure: NULL argument"); + PluginDebug("Initial JWT Failure: null argument"); return false; } @@ -218,39 +218,40 @@ jwt_check_uri(const char *cdniuc, const char *uri) if (err) { goto fail_jwt; } - - const char *kind = cdniuc, *container = cdniuc; - while (*container && *container != ':') { - ++container; - } - if (!*container) { - goto fail_jwt; - } - ++container; - - size_t len = container - kind; - bool status; - PluginDebug("Comparing with match kind \"%.*s\" on \"%s\" to normalized URI \"%s\"", (int)len - 1, kind, container, normal_uri); - switch (len) { - case sizeof CONT_URI_HASH_STR: - if (!strncmp(CONT_URI_HASH_STR, kind, len - 1)) { - status = match_hash(container, normal_uri); - TSfree(normal_uri); - return status; + // Block ending at fail_jwt label. + { + const char *kind = cdniuc, *container = cdniuc; + while (*container && *container != ':') { + ++container; } - PluginDebug("Expected kind %s, but did not find it in \"%.*s\"", CONT_URI_HASH_STR, (int)len - 1, kind); - break; - case sizeof CONT_URI_REGEX_STR: - if (!strncmp(CONT_URI_REGEX_STR, kind, len - 1)) { - status = match_regex(container, normal_uri); - TSfree(normal_uri); - return status; + if (!*container) { + goto fail_jwt; } - PluginDebug("Expected kind %s, but did not find it in \"%.*s\"", CONT_URI_REGEX_STR, (int)len - 1, kind); - break; - } - PluginDebug("Unknown match kind \"%.*s\"", (int)len - 1, kind); + ++container; + size_t len = container - kind; + bool status; + PluginDebug("Comparing with match kind \"%.*s\" on \"%s\" to normalized URI \"%s\"", (int)len - 1, kind, container, normal_uri); + switch (len) { + case sizeof CONT_URI_HASH_STR: + if (!strncmp(CONT_URI_HASH_STR, kind, len - 1)) { + status = match_hash(container, normal_uri); + TSfree(normal_uri); + return status; + } + PluginDebug("Expected kind %s, but did not find it in \"%.*s\"", CONT_URI_HASH_STR, (int)len - 1, kind); + break; + case sizeof CONT_URI_REGEX_STR: + if (!strncmp(CONT_URI_REGEX_STR, kind, len - 1)) { + status = match_regex(container, normal_uri); + TSfree(normal_uri); + return status; + } + PluginDebug("Expected kind %s, but did not find it in \"%.*s\"", CONT_URI_REGEX_STR, (int)len - 1, kind); + break; + } + PluginDebug("Unknown match kind \"%.*s\"", (int)len - 1, kind); + } fail_jwt: TSfree(normal_uri); return false; @@ -290,15 +291,15 @@ renew_copy_integer(json_t *new_json, const char *name, double old) char * renew(struct jwt *jwt, const char *iss, cjose_jwk_t *jwk, const char *alg, const char *package, const char *uri, size_t uri_ct) { - char *s = NULL; + char *s = nullptr; if (jwt->cdnistt != 1) { PluginDebug("Not renewing jwt, cdnistt != 1"); - return NULL; + return nullptr; } if (jwt->cdniets == 0) { PluginDebug("Not renewing jwt, cdniets == 0"); - return NULL; + return nullptr; } int buff_ct = uri_ct + 2; @@ -307,125 +308,127 @@ renew(struct jwt *jwt, const char *iss, cjose_jwk_t *jwk, const char *alg, const memset(normal_uri, 0, buff_ct); normal_err = normalize_uri(uri, uri_ct, normal_uri, buff_ct); - - if (normal_err) { - goto fail_normal; - } - - /* Determine Path String Based on cdnistd claim */ - size_t normal_size = strlen(normal_uri); - const char *path_start = normal_uri; - const char *path_end = NULL; - const char *uri_end = normal_uri + normal_size; - char *path_string = NULL; - size_t path_size = normal_size + 1; - - path_string = (char *)TSmalloc(path_size); - memset(path_string, 0, path_size); - PluginDebug("Renewing JWT. Stripped URI: %s", uri); - - if (jwt->cdnistd == 0) { - PluginDebug("STD is 0 - Setting Cookie Path to Path=/"); - snprintf(path_string, 2, "%s", "/"); - } else { - PluginDebug("STD is greater than 0. Calculating Path"); - int slash_count = 0; - /* Search for 3rd '/' to mark start of path */ - while (path_start != uri_end && slash_count < 3) { - ++path_start; - if (*path_start == '/') { - slash_count++; + if (!normal_err) { + /* Determine Path String Based on cdnistd claim */ + size_t normal_size = strlen(normal_uri); + const char *path_start = normal_uri; + const char *path_end = nullptr; + const char *uri_end = normal_uri + normal_size; + char *path_string = nullptr; + size_t path_size = normal_size + 1; + + path_string = (char *)TSmalloc(path_size); + memset(path_string, 0, path_size); + PluginDebug("Renewing JWT. Stripped URI: %s", uri); + + if (jwt->cdnistd == 0) { + PluginDebug("STD is 0 - Setting Cookie Path to Path=/"); + snprintf(path_string, 2, "%s", "/"); + } else { + PluginDebug("STD is greater than 0. Calculating Path"); + int slash_count = 0; + /* Search for 3rd '/' to mark start of path */ + while (path_start != uri_end && slash_count < 3) { + ++path_start; + if (*path_start == '/') { + slash_count++; + } } - } - if (path_start == uri_end) { - PluginDebug("STD is greater than number of path segments. Cannot Renew Token!"); - goto fail_path; - } - PluginDebug("Searching through path: %s", path_start); - /* Now search through path for cdnistd number of segments */ - slash_count = 0; - path_end = path_start + 1; - while (path_end != uri_end && slash_count < jwt->cdnistd) { - ++path_end; - if (*path_end == '/') { - slash_count++; + if (path_start == uri_end) { + PluginDebug("STD is greater than number of path segments. Cannot Renew Token!"); + goto fail_path; + } + PluginDebug("Searching through path: %s", path_start); + /* Now search through path for cdnistd number of segments */ + slash_count = 0; + path_end = path_start + 1; + while (path_end != uri_end && slash_count < jwt->cdnistd) { + ++path_end; + if (*path_end == '/') { + slash_count++; + } } + if (path_end == uri_end) { + PluginDebug("STD is greater than number of path segments. Cannot Renew Token!"); + goto fail_path; + } + path_size = path_end - path_start + 1; + snprintf(path_string, path_size, "%s", path_start); + PluginDebug("Setting Cookie Path to %s", path_string); } - if (path_end == uri_end) { - PluginDebug("STD is greater than number of path segments. Cannot Renew Token!"); - goto fail_path; + // Block ending at fail_path label. + { + json_t *new_json = json_object(); + renew_copy_string(new_json, "iss", iss); /* use issuer of new signing key */ + renew_copy_string(new_json, "sub", jwt->sub); + renew_copy_raw(new_json, "aud", jwt->aud); + renew_copy_real(new_json, "exp", now() + jwt->cdniets); /* expire ets seconds hence */ + renew_copy_real(new_json, "nbf", jwt->nbf); + renew_copy_real(new_json, "iat", now()); /* issued now */ + renew_copy_string(new_json, "jti", jwt->jti); + renew_copy_string(new_json, "cdniuc", jwt->cdniuc); + renew_copy_integer(new_json, "cdniv", jwt->cdniv); + renew_copy_integer(new_json, "cdniets", jwt->cdniets); + renew_copy_integer(new_json, "cdnistt", jwt->cdnistt); + renew_copy_integer(new_json, "cdnistd", jwt->cdnistd); + + char *pt = json_dumps(new_json, JSON_COMPACT); + json_decref(new_json); + + cjose_header_t *hdr = cjose_header_new(nullptr); + if (!hdr) { + PluginDebug("Unable to create new jose header."); + goto fail_json; + } + // Block ending at fail_json label. + { + cjose_err err; + const char *kid = cjose_jwk_get_kid(jwk, &err); + if (!kid) { + PluginDebug("Unable to get kid from signing key: %s", err.message); + goto fail_hdr; + } + if (!cjose_header_set(hdr, CJOSE_HDR_KID, kid, &err)) { + PluginDebug("Unable to set kid of jose header to %s: %s", kid, err.message); + goto fail_hdr; + } + if (!cjose_header_set(hdr, "alg", alg, &err)) { + PluginDebug("Unable to set alg of jose header to %s: %s", alg, err.message); + goto fail_hdr; + } + // Block fail_hdr label. + { + cjose_jws_t *jws = cjose_jws_sign(jwk, hdr, (uint8_t *)pt, strlen(pt), &err); + if (!jws) { + char *hdr_str = json_dumps((json_t *)hdr, JSON_COMPACT); + PluginDebug("Unable to sign new key: %s. {%p(%s), \"%s\", \"%s\"}", err.message, jwk, kid, hdr_str, pt); + free(hdr_str); + goto fail_hdr; + } + { + const char *jws_str; + if (!cjose_jws_export(jws, &jws_str, &err)) { + PluginDebug("Unable to export jws: %s", err.message); + + } else { + const char *fmt = "%s=%s; Path=%s"; + size_t s_ct; + s = static_cast(malloc(s_ct = (1 + snprintf(nullptr, 0, fmt, package, jws_str, path_string)))); + snprintf(s, s_ct, fmt, package, jws_str, path_string); + PluginDebug("Cookie returned from renew function: %s", s); + } + } + cjose_jws_release(jws); + } + fail_hdr: + cjose_header_release(hdr); + } + fail_json: + free(pt); } - path_size = path_end - path_start + 1; - snprintf(path_string, path_size, "%s", path_start); - PluginDebug("Setting Cookie Path to %s", path_string); - } - - json_t *new_json = json_object(); - renew_copy_string(new_json, "iss", iss); /* use issuer of new signing key */ - renew_copy_string(new_json, "sub", jwt->sub); - renew_copy_raw(new_json, "aud", jwt->aud); - renew_copy_real(new_json, "exp", now() + jwt->cdniets); /* expire ets seconds hence */ - renew_copy_real(new_json, "nbf", jwt->nbf); - renew_copy_real(new_json, "iat", now()); /* issued now */ - renew_copy_string(new_json, "jti", jwt->jti); - renew_copy_string(new_json, "cdniuc", jwt->cdniuc); - renew_copy_integer(new_json, "cdniv", jwt->cdniv); - renew_copy_integer(new_json, "cdniets", jwt->cdniets); - renew_copy_integer(new_json, "cdnistt", jwt->cdnistt); - renew_copy_integer(new_json, "cdnistd", jwt->cdnistd); - - char *pt = json_dumps(new_json, JSON_COMPACT); - json_decref(new_json); - - cjose_header_t *hdr = cjose_header_new(NULL); - if (!hdr) { - PluginDebug("Unable to create new jose header."); - goto fail_json; + fail_path: + TSfree(path_string); } - - cjose_err err; - const char *kid = cjose_jwk_get_kid(jwk, &err); - if (!kid) { - PluginDebug("Unable to get kid from signing key: %s", err.message); - goto fail_hdr; - } - if (!cjose_header_set(hdr, CJOSE_HDR_KID, kid, &err)) { - PluginDebug("Unable to set kid of jose header to %s: %s", kid, err.message); - goto fail_hdr; - } - if (!cjose_header_set(hdr, "alg", alg, &err)) { - PluginDebug("Unable to set alg of jose header to %s: %s", alg, err.message); - goto fail_hdr; - } - - cjose_jws_t *jws = cjose_jws_sign(jwk, hdr, (uint8_t *)pt, strlen(pt), &err); - if (!jws) { - char *hdr_str = json_dumps((json_t *)hdr, JSON_COMPACT); - PluginDebug("Unable to sign new key: %s. {%p(%s), \"%s\", \"%s\"}", err.message, jwk, kid, hdr_str, pt); - free(hdr_str); - goto fail_hdr; - } - - const char *jws_str; - if (!cjose_jws_export(jws, &jws_str, &err)) { - PluginDebug("Unable to export jws: %s", err.message); - goto fail_jws; - } - - const char *fmt = "%s=%s; Path=%s"; - size_t s_ct; - s = malloc(s_ct = (1 + snprintf(NULL, 0, fmt, package, jws_str, path_string))); - snprintf(s, s_ct, fmt, package, jws_str, path_string); - PluginDebug("Cookie returned from renew function: %s", s); -fail_jws: - cjose_jws_release(jws); -fail_hdr: - cjose_header_release(hdr); -fail_json: - free(pt); -fail_path: - TSfree(path_string); -fail_normal: TSfree(normal_uri); return s; } diff --git a/plugins/experimental/uri_signing/match.c b/plugins/experimental/uri_signing/match.cc similarity index 100% rename from plugins/experimental/uri_signing/match.c rename to plugins/experimental/uri_signing/match.cc diff --git a/plugins/experimental/uri_signing/normalize.c b/plugins/experimental/uri_signing/normalize.cc similarity index 99% rename from plugins/experimental/uri_signing/normalize.c rename to plugins/experimental/uri_signing/normalize.cc index cd475868e2e..98b4b049645 100644 --- a/plugins/experimental/uri_signing/normalize.c +++ b/plugins/experimental/uri_signing/normalize.cc @@ -218,7 +218,7 @@ normalize_uri(const char *uri, int uri_ct, char *normal_uri, int normal_ct) const char *uri_end = uri + uri_ct; const char *buff_end = normal_uri + normal_ct; - if ((normal_uri == NULL) || (normal_uri && normal_ct < uri_ct + 1)) { + if ((normal_uri == nullptr) || (normal_uri && normal_ct < uri_ct + 1)) { PluginDebug("Buffer to Normalize URI not large enough."); return -1; } @@ -242,6 +242,9 @@ normalize_uri(const char *uri, int uri_ct, char *normal_uri, int normal_ct) write_buffer++; } + /* Set comp start/end to contain authority component */ + bool userInfo = false; + if (comp_end == uri_end) { PluginDebug("Reached End of String prematurely"); goto normalize_failure; @@ -279,8 +282,6 @@ normalize_uri(const char *uri, int uri_ct, char *normal_uri, int normal_ct) int comp_ct; comp_start = comp_end; - /* Set comp start/end to contain authority component */ - bool userInfo = false; while (comp_end != uri_end && *comp_end != '/' && *comp_end != '?' && *comp_end != '#') { /* If we encounter userinfo, decode it without altering case and set comp_start/end to only include hostname/port */ if (*comp_end == '@' && userInfo == false) { diff --git a/plugins/experimental/uri_signing/parse.c b/plugins/experimental/uri_signing/parse.cc similarity index 93% rename from plugins/experimental/uri_signing/parse.c rename to plugins/experimental/uri_signing/parse.cc index fdeec321307..ddc665fb8d3 100644 --- a/plugins/experimental/uri_signing/parse.c +++ b/plugins/experimental/uri_signing/parse.cc @@ -26,6 +26,7 @@ #include #include #include +#include cjose_jws_t * get_jws_from_uri(const char *uri, size_t uri_ct, const char *paramName, char *strip_uri, size_t buff_ct, size_t *strip_ct) @@ -42,7 +43,7 @@ get_jws_from_uri(const char *uri, size_t uri_ct, const char *paramName, char *st if (param_ct <= 0) { PluginDebug("URI signing package name cannot be empty"); - return NULL; + return nullptr; } if (strchr(reserved_string, paramName[param_ct - 1])) { @@ -61,7 +62,7 @@ get_jws_from_uri(const char *uri, size_t uri_ct, const char *paramName, char *st for (;;) { /* Search the URI for a reserved character. */ - while (param != end && strchr(reserved_string, *param) == NULL) { + while (param != end && strchr(reserved_string, *param) == nullptr) { ++param; } if (param == end) { @@ -84,7 +85,7 @@ get_jws_from_uri(const char *uri, size_t uri_ct, const char *paramName, char *st /* If the Parameter key is our target parameter name, attempt to import a JWS from the value. */ if ((size_t)(key_end - key) == termination_ct && !strncmp(paramName, key, (size_t)(key_end - key))) { value_end = ++value; - while (value_end != end && strchr(reserved_string, *value_end) == NULL) { + while (value_end != end && strchr(reserved_string, *value_end) == nullptr) { ++value_end; } PluginDebug("Decoding JWS: %.*s", (int)(key_end - key), key); @@ -101,7 +102,7 @@ get_jws_from_uri(const char *uri, size_t uri_ct, const char *paramName, char *st *strip_ct = ((key - uri) + (end - value_end)); if (buff_ct <= *strip_ct) { PluginDebug("Strip URI buffer is not large enough"); - return NULL; + return nullptr; } if (value_end != end && strchr(sub_delim_string, *value_end)) { @@ -123,7 +124,7 @@ get_jws_from_uri(const char *uri, size_t uri_ct, const char *paramName, char *st } } PluginDebug("Unable to locate signing key in uri: %.*s", (int)uri_ct, uri); - return NULL; + return nullptr; } cjose_jws_t * @@ -134,7 +135,7 @@ get_jws_from_cookie(const char **cookie, size_t *cookie_ct, const char *paramNam const char *value = get_cookie_value(cookie, cookie_ct, paramName, &value_ct); PluginDebug("Got jws string: (%p) %.*s", value, (int)value_ct, value); if (!value || !value_ct) { - return NULL; + return nullptr; } cjose_err err; memset(&err, 0, sizeof(cjose_err)); @@ -168,7 +169,7 @@ validate_jws(cjose_jws_t *jws, struct config *cfg, const char *uri, size_t uri_c char const *pt; if (!cjose_jws_get_plaintext(jws, (uint8_t **)&pt, &pt_ct, &cerr)) { PluginDebug("Cannot get plaintext for %16p", jws); - return false; + return nullptr; } TimerDebug("getting jws plaintext"); @@ -182,19 +183,21 @@ validate_jws(cjose_jws_t *jws, struct config *cfg, const char *uri, size_t uri_c } else { PluginDebug("Cannot load json for %16p: %.*s", jws, (int)pt_ct, pt); } - return false; + return nullptr; } - struct jwt *jwt = parse_jwt(jwk_json); + struct jwt *const jwt = parse_jwt(jwk_json); TimerDebug("parsing jwt"); if (!jwt) { json_decref(jwk_json); - return NULL; + return nullptr; } + ts::PostScript ps([&jwt]() -> void { jwt_delete(jwt); }); + if (!jwt_validate(jwt)) { PluginDebug("Initial validation of JWT failed for %16p", jws); - goto jwt_fail; + return nullptr; } TimerDebug("initial validation of jwt"); @@ -202,23 +205,23 @@ validate_jws(cjose_jws_t *jws, struct config *cfg, const char *uri, size_t uri_c TimerDebug("getting header of jws"); if (!hdr) { PluginDebug("Cannot get protected header for %16p", jws); - goto jwt_fail; + return nullptr; } - const char *kid = cjose_header_get(hdr, "kid", NULL); + const char *kid = cjose_header_get(hdr, "kid", nullptr); TimerDebug("getting kid of jws header"); if (kid) { cjose_jwk_t *jwk = find_key_by_kid(cfg, jwt->iss, kid); TimerDebug("finding key for jwt"); if (!jwk) { PluginDebug("Cannot find key %s for issuer %s for %16p", kid, jwt->iss, jws); - goto jwt_fail; + return nullptr; } cjose_err err; memset(&err, 0, sizeof(cjose_err)); if (!cjose_jws_verify(jws, jwk, &err)) { PluginDebug("Key %s for issuer %s for %16p does not validate: '%s'", kid, jwt->iss, jws, (err.message ? err.message : "")); - goto jwt_fail; + return nullptr; } TimerDebug("checking crypto signature for jwt"); } else { @@ -240,23 +243,21 @@ validate_jws(cjose_jws_t *jws, struct config *cfg, const char *uri, size_t uri_c } else { PluginDebug("No valid key for issuer %s found for %16p", jwt->iss, jws); } - goto jwt_fail; + return nullptr; } } if (!jwt_check_aud(jwt->aud, config_get_id(cfg))) { PluginDebug("Valid key for %16p that does not match aud.", jws); - goto jwt_fail; + return nullptr; } if (!jwt_check_uri(jwt->cdniuc, uri)) { PluginDebug("Valid key for %16p that does not match uri.", jws); - goto jwt_fail; + return nullptr; } TimerDebug("verifying sub claim"); + ps.release(); return jwt; -jwt_fail: - jwt_delete(jwt); - return NULL; } diff --git a/plugins/experimental/uri_signing/timing.c b/plugins/experimental/uri_signing/timing.cc similarity index 100% rename from plugins/experimental/uri_signing/timing.c rename to plugins/experimental/uri_signing/timing.cc diff --git a/plugins/experimental/uri_signing/unit_tests/uri_signing_test.cc b/plugins/experimental/uri_signing/unit_tests/uri_signing_test.cc index d57136f4cb5..036c23aa14a 100644 --- a/plugins/experimental/uri_signing/unit_tests/uri_signing_test.cc +++ b/plugins/experimental/uri_signing/unit_tests/uri_signing_test.cc @@ -26,12 +26,13 @@ extern "C" { #include #include +} + #include "../jwt.h" #include "../normalize.h" #include "../parse.h" #include "../match.h" #include "../config.h" -} static char const *const testConfig = R"( @@ -296,7 +297,7 @@ TEST_CASE("2", "[JWSFromURLTest]") "www.foo.com/hellothere/" "URISigningPackag=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", - "URISigningPackage", NULL)); + "URISigningPackage", nullptr)); } SECTION("Token in middle of the URL") @@ -318,12 +319,12 @@ TEST_CASE("2", "[JWSFromURLTest]") SECTION("Pass empty path parameter at end") { - REQUIRE(!jws_parsing_helper("www.foobar.com/hellothere/URISigningPackage=", "URISigningPackage", NULL)); + REQUIRE(!jws_parsing_helper("www.foobar.com/hellothere/URISigningPackage=", "URISigningPackage", nullptr)); } SECTION("Pass empty path parameter in the middle of URL") { - REQUIRE(!jws_parsing_helper("www.foobar.com/hellothere/URISigningPackage=/Something/Else", "URISigningPackage", NULL)); + REQUIRE(!jws_parsing_helper("www.foobar.com/hellothere/URISigningPackage=/Something/Else", "URISigningPackage", nullptr)); } SECTION("Partial package name in previous path parameter") @@ -359,12 +360,12 @@ TEST_CASE("2", "[JWSFromURLTest]") "URISigningPackage=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ." "SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c/Something/Else", - "URISigningPackage", NULL)); + "URISigningPackage", nullptr)); } SECTION("Empty string as URL") { - REQUIRE(!jws_parsing_helper("", "URISigningPackage", NULL)); + REQUIRE(!jws_parsing_helper("", "URISigningPackage", nullptr)); } SECTION("Empty package name to parser") @@ -373,7 +374,7 @@ TEST_CASE("2", "[JWSFromURLTest]") "www.foobar.com/" "URISigningPackage=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", - "", NULL)); + "", nullptr)); } SECTION("Custom package name with a reserved character - at the end of the URI") @@ -533,22 +534,22 @@ TEST_CASE("4", "[NormalizeTest]") SECTION("Testing passing too small of a URI to normalize") { - REQUIRE(!normalize_uri_helper("ht", NULL)); + REQUIRE(!normalize_uri_helper("ht", nullptr)); } SECTION("Testing passing non http/https protocol") { - REQUIRE(!normalize_uri_helper("ht:", NULL)); + REQUIRE(!normalize_uri_helper("ht:", nullptr)); } SECTION("Passing a uri with half encoded value at end") { - REQUIRE(!normalize_uri_helper("http://www.foobar.co%4", NULL)); + REQUIRE(!normalize_uri_helper("http://www.foobar.co%4", nullptr)); } SECTION("Passing a uri with half encoded value in the middle") { - REQUIRE(!normalize_uri_helper("http://www.foobar.co%4psomethin/Path", NULL)); + REQUIRE(!normalize_uri_helper("http://www.foobar.co%4psomethin/Path", nullptr)); } SECTION("Passing a uri with an empty path parameter") @@ -623,22 +624,22 @@ TEST_CASE("4", "[NormalizeTest]") SECTION("Testing empty hostname with userinfon") { - REQUIRE(!normalize_uri_helper("https://foo:something@", NULL)); + REQUIRE(!normalize_uri_helper("https://foo:something@", nullptr)); } SECTION("Testing empty uri after http://") { - REQUIRE(!normalize_uri_helper("http://", NULL)); + REQUIRE(!normalize_uri_helper("http://", nullptr)); } SECTION("Testing http:///////") { - REQUIRE(!normalize_uri_helper("http:///////", NULL)); + REQUIRE(!normalize_uri_helper("http:///////", nullptr)); } SECTION("Testing empty uri after http://?/") { - REQUIRE(!normalize_uri_helper("http://?/", NULL)); + REQUIRE(!normalize_uri_helper("http://?/", nullptr)); } fprintf(stderr, "\n"); } @@ -686,7 +687,7 @@ TEST_CASE("6", "[AudTests]") { INFO("TEST 6, Test Aud Matching"); - json_error_t *err = NULL; + json_error_t *err = nullptr; SECTION("Standard aud string match") { json_t *raw = json_loads("{\"aud\": \"tester\"}", 0, err); @@ -764,7 +765,7 @@ TEST_CASE("7", "[TestsConfig]") SECTION("Config Loading ID Field") { struct config *cfg = read_config_from_string(testConfig); - REQUIRE(cfg != NULL); + REQUIRE(cfg != nullptr); REQUIRE(strcmp(config_get_id(cfg), "tester") == 0); config_delete(cfg); } diff --git a/plugins/experimental/uri_signing/uri_signing.c b/plugins/experimental/uri_signing/uri_signing.cc similarity index 66% rename from plugins/experimental/uri_signing/uri_signing.c rename to plugins/experimental/uri_signing/uri_signing.cc index 5eb3be7cdc7..aab4aa24744 100644 --- a/plugins/experimental/uri_signing/uri_signing.c +++ b/plugins/experimental/uri_signing/uri_signing.cc @@ -69,14 +69,14 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s return TS_ERROR; } - char *config_file = NULL; + char *config_file = nullptr; if ('/' == fname[0]) { config_file = strdup(fname); } else { char const *const config_dir = TSConfigDirGet(); - size_t const config_file_ct = snprintf(NULL, 0, "%s/%s", config_dir, fname); - config_file = malloc(config_file_ct + 1); - (void)snprintf(config_file, config_file_ct + 1, "%s/%s", config_dir, fname); + size_t const config_file_ct = snprintf(nullptr, 0, "%s/%s", config_dir, fname); + config_file = static_cast(malloc(config_file_ct + 1)); + static_cast(snprintf(config_file, config_file_ct + 1, "%s/%s", config_dir, fname)); } TSDebug(PLUGIN_NAME, "config file name: %s", config_file); @@ -96,7 +96,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s void TSRemapDeleteInstance(void *ih) { - config_delete(ih); + config_delete(static_cast(ih)); } int @@ -106,7 +106,7 @@ add_cookie(TSCont cont, TSEvent event, void *edata) start_timer(&t); TSHttpTxn txn = (TSHttpTxn)edata; - char *cookie = TSContDataGet(cont); + char *cookie = static_cast(TSContDataGet(cont)); TSMBuffer buffer; TSMLoc hdr; TSMLoc field; @@ -148,11 +148,11 @@ add_cookie(TSCont cont, TSEvent event, void *edata) TSCont cont_new(char *cookie) { - TSCont cont = TSContCreate(add_cookie, NULL); + TSCont cont = TSContCreate(add_cookie, nullptr); if (!cont) { PluginError("Cannot create continuation!"); free(cookie); /* Nobody else is going to do it at this point. */ - return NULL; + return nullptr; } TSContDataSet(cont, cookie); return cont; @@ -162,19 +162,73 @@ cont_new(char *cookie) TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) { + static char const *const package = "URISigningPackage"; + struct timer t; start_timer(&t); - const int max_cpi = 20; - int64_t checkpoints[20] = {0}; - int cpi = 0; - int url_ct = 0; - const char *url = NULL; - char *strip_uri = NULL; - TSRemapStatus status = TSREMAP_NO_REMAP; - bool checked_auth = false; + const int max_cpi = 20; + int64_t checkpoints[20] = {0}; + int cpi = 0; + int url_ct = 0; + const char *url = nullptr; + char *strip_uri = nullptr; + TSRemapStatus status = TSREMAP_NO_REMAP; + bool checked_auth = false; + struct jwt *jwt = nullptr; + int checked_cookies = 0; + size_t client_cookie_sz_ct = 0; + const char *client_cookie = nullptr; + int client_cookie_ct = 0; + int strip_size = 0; + size_t strip_ct = 0; + cjose_jws_t *jws = nullptr; + + auto check_cookies = [&](bool more) -> bool { + if (!more) { + /* There is no valid token in the url */ + strncpy(strip_uri, url, url_ct); + strip_ct = url_ct; + ++checked_cookies; + + TSMLoc field; + TSMBuffer buffer; + TSMLoc hdr; + + if (TSHttpTxnClientReqGet(txnp, &buffer, &hdr) == TS_ERROR) { + return false; + } - static char const *const package = "URISigningPackage"; + field = TSMimeHdrFieldFind(buffer, hdr, "Cookie", 6); + if (field == TS_NULL_MLOC) { + TSHandleMLocRelease(buffer, TS_NULL_MLOC, hdr); + if (!checked_auth) { + return true; + } else { + return false; + } + } + + client_cookie = TSMimeHdrFieldValueStringGet(buffer, hdr, field, 0, &client_cookie_ct); + + TSHandleMLocRelease(buffer, hdr, field); + TSHandleMLocRelease(buffer, TS_NULL_MLOC, hdr); + + if (!client_cookie || !client_cookie_ct) { + if (!checked_auth) { + return true; + } else { + return false; + } + } + client_cookie_sz_ct = client_cookie_ct; + } + if (cpi < max_cpi) { + checkpoints[cpi++] = mark_timer(&t); + } + jws = get_jws_from_cookie(&client_cookie, &client_cookie_sz_ct, package); + return true; + }; TSMBuffer mbuf; TSMLoc ul; @@ -190,69 +244,25 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) PluginDebug("Processing request for %.*s.", url_ct, url); checkpoints[cpi++] = mark_timer(&t); - int strip_size = url_ct + 1; - strip_uri = (char *)TSmalloc(strip_size); + strip_size = url_ct + 1; + strip_uri = (char *)TSmalloc(strip_size); memset(strip_uri, 0, strip_size); - size_t strip_ct; - cjose_jws_t *jws = get_jws_from_uri(url, url_ct, package, strip_uri, strip_size, &strip_ct); + jws = get_jws_from_uri(url, url_ct, package, strip_uri, strip_size, &strip_ct); checkpoints[cpi++] = mark_timer(&t); - - int checked_cookies = 0; if (!jws) { - check_cookies: - /* There is no valid token in the url */ - strncpy(strip_uri, url, url_ct); - strip_ct = url_ct; - ++checked_cookies; - - TSMLoc field; - TSMBuffer buffer; - TSMLoc hdr; - - if (TSHttpTxnClientReqGet(txnp, &buffer, &hdr) == TS_ERROR) { + if (!check_cookies(false)) { goto fail; } - - field = TSMimeHdrFieldFind(buffer, hdr, "Cookie", 6); - if (field == TS_NULL_MLOC) { - TSHandleMLocRelease(buffer, TS_NULL_MLOC, hdr); - if (!checked_auth) { - goto check_auth; - } else { - goto fail; - } - } - - const char *client_cookie; - int client_cookie_ct; - client_cookie = TSMimeHdrFieldValueStringGet(buffer, hdr, field, 0, &client_cookie_ct); - - TSHandleMLocRelease(buffer, hdr, field); - TSHandleMLocRelease(buffer, TS_NULL_MLOC, hdr); - - if (!client_cookie || !client_cookie_ct) { - if (!checked_auth) { - goto check_auth; - } else { - goto fail; - } - } - size_t client_cookie_sz_ct = client_cookie_ct; - check_more_cookies: - if (cpi < max_cpi) { - checkpoints[cpi++] = mark_timer(&t); - } - jws = get_jws_from_cookie(&client_cookie, &client_cookie_sz_ct, package); } else { /* There has been a JWS found in the url */ /* Strip the token from the URL for upstream if configured to do so */ if (config_strip_token((struct config *)ih)) { if ((int)strip_ct != url_ct) { int map_url_ct = 0; - char *map_url = NULL; - char *map_strip_uri = NULL; + char *map_url = nullptr; + char *map_strip_uri = nullptr; map_url = TSUrlStringGet(rri->requestBufp, rri->requestUrl, &map_url_ct); PluginDebug("Stripping Token from requestUrl: %s", map_url); @@ -274,10 +284,10 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) PluginDebug("Stripping token from upstream url to: %.*s", (int)mlen, strip_uri_start); TSParseResult parse_rc = TSUrlParse(rri->requestBufp, rri->requestUrl, &strip_uri_start, strip_uri_end); - if (map_url != NULL) { + if (map_url != nullptr) { TSfree(map_url); } - if (map_strip_uri != NULL) { + if (map_strip_uri != nullptr) { TSfree(map_strip_uri); } @@ -289,14 +299,13 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) } } } -check_auth: /* Check auth_dir and pass through if configured */ if (uri_matches_auth_directive((struct config *)ih, url, url_ct)) { PluginDebug("Auth directive matched for %.*s", url_ct, url); - if (url != NULL) { + if (url != nullptr) { TSfree((void *)url); } - if (strip_uri != NULL) { + if (strip_uri != nullptr) { TSfree(strip_uri); } return TSREMAP_NO_REMAP; @@ -311,57 +320,51 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) checkpoints[cpi++] = mark_timer(&t); } - struct jwt *jwt = validate_jws(jws, (struct config *)ih, strip_uri, strip_ct); + jwt = validate_jws(jws, (struct config *)ih, strip_uri, strip_ct); cjose_jws_release(jws); if (cpi < max_cpi) { checkpoints[cpi++] = mark_timer(&t); } - if (!jwt) { - if (!checked_cookies) { - goto check_cookies; - } else { - goto check_more_cookies; - } - } + if (jwt || check_cookies(checked_cookies)) { + /* There has been a validated JWT found in either the cookie or url */ - /* There has been a validated JWT found in either the cookie or url */ + struct signer *signer = config_signer((struct config *)ih); + char *cookie = renew(jwt, signer->issuer, signer->jwk, signer->alg, package, strip_uri, strip_ct); + jwt_delete(jwt); - struct signer *signer = config_signer((struct config *)ih); - char *cookie = renew(jwt, signer->issuer, signer->jwk, signer->alg, package, strip_uri, strip_ct); - jwt_delete(jwt); - - if (cpi < max_cpi) { - checkpoints[cpi++] = mark_timer(&t); - } - if (cookie) { - PluginDebug("Scheduling cookie callback for %.*s", url_ct, url); - TSCont cont = cont_new(cookie); - TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont); - } else { - PluginDebug("No cookie scheduled for %.*s", url_ct, url); - } + if (cpi < max_cpi) { + checkpoints[cpi++] = mark_timer(&t); + } + if (cookie) { + PluginDebug("Scheduling cookie callback for %.*s", url_ct, url); + TSCont cont = cont_new(cookie); + TSHttpTxnHookAdd(txnp, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont); + } else { + PluginDebug("No cookie scheduled for %.*s", url_ct, url); + } - int64_t last_mark = 0; - for (int i = 0; i < cpi; ++i) { - PluginDebug("Spent %" PRId64 " ns in checkpoint %d.", checkpoints[i] - last_mark, i); - last_mark = checkpoints[i]; - } - PluginDebug("Spent %" PRId64 " ns uri_signing verification of %.*s.", mark_timer(&t), url_ct, url); + int64_t last_mark = 0; + for (int i = 0; i < cpi; ++i) { + PluginDebug("Spent %" PRId64 " ns in checkpoint %d.", checkpoints[i] - last_mark, i); + last_mark = checkpoints[i]; + } + PluginDebug("Spent %" PRId64 " ns uri_signing verification of %.*s.", mark_timer(&t), url_ct, url); - TSfree((void *)url); - if (strip_uri != NULL) { - TSfree(strip_uri); + TSfree((void *)url); + if (strip_uri != nullptr) { + TSfree(strip_uri); + } + return status; } - return status; fail: TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_FORBIDDEN); - if (url != NULL) { + if (url != nullptr) { PluginDebug("Invalid JWT for %.*s", url_ct, url); PluginDebug("Spent %" PRId64 " ns uri_signing verification of %.*s.", mark_timer(&t), url_ct, url); TSfree((void *)url); } - if (strip_uri != NULL) { + if (strip_uri != nullptr) { TSfree(strip_uri); } diff --git a/plugins/experimental/url_sig/Makefile.inc b/plugins/experimental/url_sig/Makefile.inc index 73a5c6df416..1af6ede11c4 100644 --- a/plugins/experimental/url_sig/Makefile.inc +++ b/plugins/experimental/url_sig/Makefile.inc @@ -17,4 +17,4 @@ pkglib_LTLIBRARIES += experimental/url_sig/url_sig.la experimental_url_sig_url_sig_la_SOURCES = \ - experimental/url_sig/url_sig.c + experimental/url_sig/url_sig.cc diff --git a/plugins/experimental/url_sig/Makefile.tsxs b/plugins/experimental/url_sig/Makefile.tsxs index e3ee96ecc8e..71bffef67e9 100644 --- a/plugins/experimental/url_sig/Makefile.tsxs +++ b/plugins/experimental/url_sig/Makefile.tsxs @@ -16,7 +16,7 @@ TSXS?=tsxs -all: url_sig.c +all: url_sig.cc $(TSXS) -v -o url_sig.so $? install: diff --git a/plugins/experimental/url_sig/url_sig.c b/plugins/experimental/url_sig/url_sig.cc similarity index 63% rename from plugins/experimental/url_sig/url_sig.c rename to plugins/experimental/url_sig/url_sig.cc index 4e0e2fec276..bc5a31dcf1e 100644 --- a/plugins/experimental/url_sig/url_sig.c +++ b/plugins/experimental/url_sig/url_sig.cc @@ -127,7 +127,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s } TSDebug(PLUGIN_NAME, "config file name: %s", config_file); FILE *file = fopen(config_file, "r"); - if (file == NULL) { + if (file == nullptr) { snprintf(errbuf, errbuf_size, "[TSRemapNewInstance] - Error opening file %s", config_file); return TS_ERROR; } @@ -137,10 +137,10 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s int keynum; bool eat_comment = false; - cfg = TSmalloc(sizeof(struct config)); + cfg = tsapi::malloc(); memset(cfg, 0, sizeof(struct config)); - while (fgets(line, sizeof(line), file) != NULL) { + while (fgets(line, sizeof(line), file) != nullptr) { TSDebug(PLUGIN_NAME, "LINE: %s (%d)", line, (int)strlen(line)); line_no++; @@ -159,7 +159,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s continue; } char *pos = strchr(line, '='); - if (pos == NULL) { + if (pos == nullptr) { TSError("[url_sig] Error parsing line %d of file %s (%s)", line_no, config_file, line); continue; } @@ -169,10 +169,10 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s value++; } pos = strchr(value, '\n'); // remove the new line, terminate the string - if (pos != NULL) { + if (pos != nullptr) { *pos = '\0'; } - if (pos == NULL || strlen(value) >= MAX_KEY_LEN) { + if (pos == nullptr || strlen(value) >= MAX_KEY_LEN) { snprintf(errbuf, errbuf_size, "[TSRemapNewInstance] - Maximum key length (%d) exceeded on line %d", MAX_KEY_LEN - 1, line_no); fclose(file); free_cfg(cfg); @@ -198,7 +198,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s snprintf(&cfg->keys[keynum][0], MAX_KEY_LEN, "%s", value); } else if (strncmp(line, "error_url", 9) == 0) { if (atoi(value)) { - cfg->err_status = atoi(value); + cfg->err_status = TSHttpStatus(atoi(value)); } value += 3; while (isspace(*value)) { @@ -207,7 +207,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s if (cfg->err_status == TS_HTTP_STATUS_MOVED_TEMPORARILY) { cfg->err_url = TSstrndup(value, strlen(value)); } else { - cfg->err_url = NULL; + cfg->err_url = nullptr; } } else if (strncmp(line, "sig_anchor", 10) == 0) { cfg->sig_anchor = TSstrndup(value, strlen(value)); @@ -221,8 +221,8 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s continue; } - cfg->regex = pcre_compile(value, options, &errptr, &erroffset, NULL); - if (cfg->regex == NULL) { + cfg->regex = pcre_compile(value, options, &errptr, &erroffset, nullptr); + if (cfg->regex == nullptr) { TSDebug(PLUGIN_NAME, "Regex compilation failed with error (%s) at character %d", errptr, erroffset); } else { #ifdef PCRE_STUDY_JIT_COMPILE @@ -262,15 +262,15 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s switch (cfg->err_status) { case TS_HTTP_STATUS_MOVED_TEMPORARILY: - if (cfg->err_url == NULL) { - snprintf(errbuf, errbuf_size, "[TSRemapNewInstance] - Invalid config, err_status == 302, but err_url == NULL"); + if (cfg->err_url == nullptr) { + snprintf(errbuf, errbuf_size, "[TSRemapNewInstance] - Invalid config, err_status == 302, but err_url == nullptr"); free_cfg(cfg); return TS_ERROR; } break; case TS_HTTP_STATUS_FORBIDDEN: - if (cfg->err_url != NULL) { - snprintf(errbuf, errbuf_size, "[TSRemapNewInstance] - Invalid config, err_status == 403, but err_url != NULL"); + if (cfg->err_url != nullptr) { + snprintf(errbuf, errbuf_size, "[TSRemapNewInstance] - Invalid config, err_status == 403, but err_url != nullptr"); free_cfg(cfg); return TS_ERROR; } @@ -313,7 +313,7 @@ getAppQueryString(const char *query_string, int query_length) if (query_length > MAX_QUERY_LEN) { TSDebug(PLUGIN_NAME, "Cannot process the query string as the length exceeds %d bytes", MAX_QUERY_LEN); - return NULL; + return nullptr; } memset(buf, 0, sizeof(buf)); memcpy(buf, query_string, query_length); @@ -338,7 +338,7 @@ getAppQueryString(const char *query_string, int query_length) break; default: p = strchr(p, '&'); - if (p == NULL) { + if (p == nullptr) { done = 1; } else { p++; @@ -351,7 +351,7 @@ getAppQueryString(const char *query_string, int query_length) p = TSstrdup(buf); return p; } else { - return NULL; + return nullptr; } } @@ -381,7 +381,7 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat char url[8192] = {'\0'}; unsigned char decoded_string[2048] = {'\0'}; char new_url[8192]; /* new_url is not null_terminated */ - char *p = NULL, *sig_anchor = NULL, *saveptr = NULL; + char *p = nullptr, *sig_anchor = nullptr, *saveptr = nullptr; int i = 0, numtoks = 0, sig_anchor_seg = 0; size_t decoded_len = 0; @@ -395,29 +395,29 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat char *skip = strchr(url, ':'); if (!skip || skip[1] != '/' || skip[2] != '/') { - return NULL; + return nullptr; } skip += 3; // preserve the scheme in the new_url. if (!fixedBufferWrite(&new_url_end, &new_url_len_left, url, skip - url)) { TSError("insufficient space to copy schema into new_path_seg buffer."); - return NULL; + return nullptr; } TSDebug(PLUGIN_NAME, "%s:%d - new_url: %.*s\n", __FILE__, __LINE__, (int)(new_url_end - new_url), new_url); // parse the url. - if ((p = strtok_r(skip, "/", &saveptr)) != NULL) { + if ((p = strtok_r(skip, "/", &saveptr)) != nullptr) { segment[numtoks++] = p; do { - p = strtok_r(NULL, "/", &saveptr); - if (p != NULL) { + p = strtok_r(nullptr, "/", &saveptr); + if (p != nullptr) { segment[numtoks] = p; - if (anchor != NULL && sig_anchor_seg == 0) { + if (anchor != nullptr && sig_anchor_seg == 0) { // look for the signed anchor string. - if ((sig_anchor = strcasestr(segment[numtoks], anchor)) != NULL) { + if ((sig_anchor = strcasestr(segment[numtoks], anchor)) != nullptr) { // null terminate this segment just before he signing anchor, this should be a ';'. *(sig_anchor - 1) = '\0'; - if ((sig_anchor = strstr(sig_anchor, "=")) != NULL) { + if ((sig_anchor = strstr(sig_anchor, "=")) != nullptr) { *sig_anchor = '\0'; sig_anchor++; sig_anchor_seg = numtoks; @@ -426,12 +426,12 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat } numtoks++; } - } while (p != NULL && numtoks < MAX_SEGMENTS); + } while (p != nullptr && numtoks < MAX_SEGMENTS); } else { - return NULL; + return nullptr; } if ((numtoks >= MAX_SEGMENTS) || (numtoks < 3)) { - return NULL; + return nullptr; } // create a new path string for later use when dealing with query parameters. @@ -439,19 +439,19 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat // starting with segment 1. for (i = 1; i < numtoks; i++) { // if no signing anchor is found, skip the signed parameters segment. - if (sig_anchor == NULL && i == numtoks - 2) { + if (sig_anchor == nullptr && i == numtoks - 2) { // the signing parameters when no signature anchor is found, should be in the // last path segment so skip them. continue; } if (!fixedBufferWrite(&new_path_seg_end, &new_path_seg_len_left, segment[i], strlen(segment[i]))) { TSError("insufficient space to copy into new_path_seg buffer."); - return NULL; + return nullptr; } if (i != numtoks - 1) { if (!fixedBufferWrite(&new_path_seg_end, &new_path_seg_len_left, "/", 1)) { TSError("insufficient space to copy into new_path_seg buffer."); - return NULL; + return nullptr; } } } @@ -459,7 +459,7 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat TSDebug(PLUGIN_NAME, "new_path_seg: %s", new_path_seg); // save the encoded signing parameter data - if (sig_anchor != NULL) { // a signature anchor string was found. + if (sig_anchor != nullptr) { // a signature anchor string was found. if (strlen(sig_anchor) < signed_seg_len) { memcpy(signed_seg, sig_anchor, strlen(sig_anchor)); } else { @@ -470,14 +470,14 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat memcpy(signed_seg, segment[numtoks - 2], strlen(segment[numtoks - 2])); } else { TSError("insufficient space to copy into new_path_seg buffer."); - return NULL; + return nullptr; } } TSDebug(PLUGIN_NAME, "signed_seg: %s", signed_seg); // no signature anchor was found so decode and save the signing parameters assumed // to be in the last path segment. - if (sig_anchor == NULL) { + if (sig_anchor == nullptr) { if (TSBase64Decode(segment[numtoks - 2], strlen(segment[numtoks - 2]), decoded_string, sizeof(decoded_string), &decoded_len) != TS_SUCCESS) { TSDebug(PLUGIN_NAME, "Unable to decode the path parameter string."); @@ -494,7 +494,7 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat for (i = 0; i < numtoks; i++) { // cp the base64 decoded string. - if (i == sig_anchor_seg && sig_anchor != NULL) { + if (i == sig_anchor_seg && sig_anchor != nullptr) { if (!fixedBufferWrite(&new_url_end, &new_url_len_left, segment[i], strlen(segment[i]))) { oob = 1; break; @@ -509,7 +509,7 @@ urlParse(char const *const url_in, char *anchor, char *new_path_seg, int new_pat } continue; - } else if (i == numtoks - 2 && sig_anchor == NULL) { + } else if (i == numtoks - 2 && sig_anchor == nullptr) { if (!fixedBufferWrite(&new_url_end, &new_url_len_left, (char *)decoded_string, strlen((char *)decoded_string))) { oob = 1; break; @@ -606,238 +606,255 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) } } - const char *query = strchr(url, '?'); + // Block needed due to goto. + { + const char *query = strchr(url, '?'); - // check for path params. - if (query == NULL || strstr(query, "E=") == NULL) { - char *const parsed = urlParse(url, cfg->sig_anchor, new_path, 8192, path_params, 8192); - if (parsed == NULL) { - err_log(url, "Unable to parse/decode new url path parameters"); - goto deny; - } + // check for path params. + if (query == nullptr || strstr(query, "E=") == nullptr) { + char *const parsed = urlParse(url, cfg->sig_anchor, new_path, 8192, path_params, 8192); + if (parsed == nullptr) { + err_log(url, "Unable to parse/decode new url path parameters"); + goto deny; + } - has_path_params = true; - query = strstr(parsed, ";"); + has_path_params = true; + query = strstr(parsed, ";"); - if (query == NULL) { - err_log(url, "Has no signing query string or signing path parameters."); - TSfree(parsed); - goto deny; - } + if (query == nullptr) { + err_log(url, "Has no signing query string or signing path parameters."); + TSfree(parsed); + goto deny; + } - if (url != current_url) { - TSfree(url); - } + if (url != current_url) { + TSfree(url); + } - url = parsed; - } + url = parsed; + } - /* first, parse the query string */ - if (!has_path_params) { - query++; /* get rid of the ? */ - } - TSDebug(PLUGIN_NAME, "Query string is:%s", query); + /* first, parse the query string */ + if (!has_path_params) { + query++; /* get rid of the ? */ + } + TSDebug(PLUGIN_NAME, "Query string is:%s", query); - // Client IP - this one is optional - const char *cp = strstr(query, CIP_QSTRING "="); - const char *pp = NULL; - if (cp != NULL) { - cp += (strlen(CIP_QSTRING) + 1); - struct sockaddr const *ip = TSHttpTxnClientAddrGet(txnp); - if (ip == NULL) { - TSError("Can't get client ip address."); - goto deny; - } else { - switch (ip->sa_family) { - case AF_INET: - TSDebug(PLUGIN_NAME, "ip->sa_family: AF_INET"); - has_path_params == false ? (pp = strstr(cp, "&")) : (pp = strstr(cp, ";")); - if ((pp - cp) > INET_ADDRSTRLEN - 1 || (pp - cp) < 4) { - err_log(url, "IP address string too long or short."); - goto deny; - } - strncpy(client_ip, cp, (pp - cp)); - client_ip[pp - cp] = '\0'; - TSDebug(PLUGIN_NAME, "CIP: -%s-", client_ip); - inet_ntop(AF_INET, &(((struct sockaddr_in *)ip)->sin_addr), ipstr, sizeof ipstr); - TSDebug(PLUGIN_NAME, "Peer address: -%s-", ipstr); - if (strcmp(ipstr, client_ip) != 0) { - err_log(url, "Client IP doesn't match signature."); + // Block needed due to goto. + { + // Client IP - this one is optional + const char *cp = strstr(query, CIP_QSTRING "="); + const char *pp = nullptr; + if (cp != nullptr) { + cp += (strlen(CIP_QSTRING) + 1); + struct sockaddr const *ip = TSHttpTxnClientAddrGet(txnp); + if (ip == nullptr) { + TSError("Can't get client ip address."); goto deny; + } else { + switch (ip->sa_family) { + case AF_INET: + TSDebug(PLUGIN_NAME, "ip->sa_family: AF_INET"); + has_path_params == false ? (pp = strstr(cp, "&")) : (pp = strstr(cp, ";")); + if ((pp - cp) > INET_ADDRSTRLEN - 1 || (pp - cp) < 4) { + err_log(url, "IP address string too long or short."); + goto deny; + } + strncpy(client_ip, cp, (pp - cp)); + client_ip[pp - cp] = '\0'; + TSDebug(PLUGIN_NAME, "CIP: -%s-", client_ip); + inet_ntop(AF_INET, &(((struct sockaddr_in *)ip)->sin_addr), ipstr, sizeof ipstr); + TSDebug(PLUGIN_NAME, "Peer address: -%s-", ipstr); + if (strcmp(ipstr, client_ip) != 0) { + err_log(url, "Client IP doesn't match signature."); + goto deny; + } + break; + case AF_INET6: + TSDebug(PLUGIN_NAME, "ip->sa_family: AF_INET6"); + has_path_params == false ? (pp = strstr(cp, "&")) : (pp = strstr(cp, ";")); + if ((pp - cp) > INET6_ADDRSTRLEN - 1 || (pp - cp) < 4) { + err_log(url, "IP address string too long or short."); + goto deny; + } + strncpy(client_ip, cp, (pp - cp)); + client_ip[pp - cp] = '\0'; + TSDebug(PLUGIN_NAME, "CIP: -%s-", client_ip); + inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)ip)->sin6_addr), ipstr, sizeof ipstr); + TSDebug(PLUGIN_NAME, "Peer address: -%s-", ipstr); + if (strcmp(ipstr, client_ip) != 0) { + err_log(url, "Client IP doesn't match signature."); + goto deny; + } + break; + default: + TSError("%s: Unknown address family %d", PLUGIN_NAME, ip->sa_family); + goto deny; + break; + } } - break; - case AF_INET6: - TSDebug(PLUGIN_NAME, "ip->sa_family: AF_INET6"); - has_path_params == false ? (pp = strstr(cp, "&")) : (pp = strstr(cp, ";")); - if ((pp - cp) > INET6_ADDRSTRLEN - 1 || (pp - cp) < 4) { - err_log(url, "IP address string too long or short."); + } + + // Expiration + if (!cfg->ignore_expiry) { + cp = strstr(query, EXP_QSTRING "="); + if (cp != nullptr) { + cp += strlen(EXP_QSTRING) + 1; + if (sscanf(cp, "%" SCNu64, &expiration) != 1 || (time_t)expiration < time(nullptr)) { + err_log(url, "Invalid expiration, or expired"); + goto deny; + } + TSDebug(PLUGIN_NAME, "Exp: %" PRIu64, expiration); + } else { + err_log(url, "Expiration query string not found"); goto deny; } - strncpy(client_ip, cp, (pp - cp)); - client_ip[pp - cp] = '\0'; - TSDebug(PLUGIN_NAME, "CIP: -%s-", client_ip); - inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)ip)->sin6_addr), ipstr, sizeof ipstr); - TSDebug(PLUGIN_NAME, "Peer address: -%s-", ipstr); - if (strcmp(ipstr, client_ip) != 0) { - err_log(url, "Client IP doesn't match signature."); + } + // Algorithm + cp = strstr(query, ALG_QSTRING "="); + if (cp != nullptr) { + cp += strlen(ALG_QSTRING) + 1; + algorithm = atoi(cp); + // The check for a valid algorithm is later. + TSDebug(PLUGIN_NAME, "Algorithm: %d", algorithm); + } else { + err_log(url, "Algorithm query string not found"); + goto deny; + } + // Key index + cp = strstr(query, KIN_QSTRING "="); + if (cp != nullptr) { + cp += strlen(KIN_QSTRING) + 1; + keyindex = atoi(cp); + if (keyindex < 0 || keyindex >= MAX_KEY_NUM || 0 == cfg->keys[keyindex][0]) { + err_log(url, "Invalid key index"); goto deny; } - break; - default: - TSError("%s: Unknown address family %d", PLUGIN_NAME, ip->sa_family); + TSDebug(PLUGIN_NAME, "Key Index: %d", keyindex); + } else { + err_log(url, "KeyIndex query string not found"); goto deny; - break; } - } - } + // Block needed due to goto. + { + // Parts + const char *parts = nullptr; + cp = strstr(query, PAR_QSTRING "="); + if (cp != nullptr) { + cp += strlen(PAR_QSTRING) + 1; + parts = cp; // NOTE parts is not null terminated it is terminated by "&" of next param + has_path_params == false ? (cp = strstr(parts, "&")) : (cp = strstr(parts, ";")); + if (cp) { + TSDebug(PLUGIN_NAME, "Parts: %.*s", (int)(cp - parts), parts); + } else { + TSDebug(PLUGIN_NAME, "Parts: %s", parts); + } + } else { + err_log(url, "PartsSigned query string not found"); + goto deny; + } - // Expiration - if (!cfg->ignore_expiry) { - cp = strstr(query, EXP_QSTRING "="); - if (cp != NULL) { - cp += strlen(EXP_QSTRING) + 1; - if (sscanf(cp, "%" SCNu64, &expiration) != 1 || (time_t)expiration < time(NULL)) { - err_log(url, "Invalid expiration, or expired"); - goto deny; - } - TSDebug(PLUGIN_NAME, "Exp: %" PRIu64, expiration); - } else { - err_log(url, "Expiration query string not found"); - goto deny; - } - } - // Algorithm - cp = strstr(query, ALG_QSTRING "="); - if (cp != NULL) { - cp += strlen(ALG_QSTRING) + 1; - algorithm = atoi(cp); - // The check for a valid algorithm is later. - TSDebug(PLUGIN_NAME, "Algorithm: %d", algorithm); - } else { - err_log(url, "Algorithm query string not found"); - goto deny; - } - // Key index - cp = strstr(query, KIN_QSTRING "="); - if (cp != NULL) { - cp += strlen(KIN_QSTRING) + 1; - keyindex = atoi(cp); - if (keyindex < 0 || keyindex >= MAX_KEY_NUM || 0 == cfg->keys[keyindex][0]) { - err_log(url, "Invalid key index"); - goto deny; - } - TSDebug(PLUGIN_NAME, "Key Index: %d", keyindex); - } else { - err_log(url, "KeyIndex query string not found"); - goto deny; - } - // Parts - const char *parts = NULL; - cp = strstr(query, PAR_QSTRING "="); - if (cp != NULL) { - cp += strlen(PAR_QSTRING) + 1; - parts = cp; // NOTE parts is not NULL terminated it is terminated by "&" of next param - has_path_params == false ? (cp = strstr(parts, "&")) : (cp = strstr(parts, ";")); - if (cp) { - TSDebug(PLUGIN_NAME, "Parts: %.*s", (int)(cp - parts), parts); - } else { - TSDebug(PLUGIN_NAME, "Parts: %s", parts); - } - } else { - err_log(url, "PartsSigned query string not found"); - goto deny; - } - // And finally, the sig (has to be last) - const char *signature = NULL; - cp = strstr(query, SIG_QSTRING "="); - if (cp != NULL) { - cp += strlen(SIG_QSTRING) + 1; - signature = cp; - if ((algorithm == USIG_HMAC_SHA1 && strlen(signature) < SHA1_SIG_SIZE) || - (algorithm == USIG_HMAC_MD5 && strlen(signature) < MD5_SIG_SIZE)) { - err_log(url, "Signature query string too short (< 20)"); - goto deny; - } - } else { - err_log(url, "Signature query string not found"); - goto deny; - } + // Block needed due to goto. + { + // And finally, the sig (has to be last) + const char *signature = nullptr; + cp = strstr(query, SIG_QSTRING "="); + if (cp != nullptr) { + cp += strlen(SIG_QSTRING) + 1; + signature = cp; + if ((algorithm == USIG_HMAC_SHA1 && strlen(signature) < SHA1_SIG_SIZE) || + (algorithm == USIG_HMAC_MD5 && strlen(signature) < MD5_SIG_SIZE)) { + err_log(url, "Signature query string too short (< 20)"); + goto deny; + } + } else { + err_log(url, "Signature query string not found"); + goto deny; + } - /* have the query string, and parameters passed initial checks */ - TSDebug(PLUGIN_NAME, "Found all needed parameters: C=%s E=%" PRIu64 " A=%d K=%d P=%s S=%s", client_ip, expiration, algorithm, - keyindex, parts, signature); + /* have the query string, and parameters passed initial checks */ + TSDebug(PLUGIN_NAME, "Found all needed parameters: C=%s E=%" PRIu64 " A=%d K=%d P=%s S=%s", client_ip, expiration, + algorithm, keyindex, parts, signature); - /* find the string that was signed - cycle through the parts letters, adding the part of the fqdn/path if it is 1 */ - has_path_params == false ? (cp = strchr(url, '?')) : (cp = strchr(url, ';')); - // Skip scheme and initial forward slashes. - const char *skip = strchr(url, ':'); - if (!skip || skip[1] != '/' || skip[2] != '/') { - goto deny; - } - skip += 3; - memcpy(urltokstr, skip, cp - skip); - char *strtok_r_p; - const char *part = strtok_r(urltokstr, "/", &strtok_r_p); - while (part != NULL) { - if (parts[j] == '1') { - strncat(signed_part, part, sizeof(signed_part) - strlen(signed_part) - 1); - strncat(signed_part, "/", sizeof(signed_part) - strlen(signed_part) - 1); - } - if (parts[j + 1] == '0' || - parts[j + 1] == '1') { // This remembers the last part, meaning, if there are no more valid letters in parts - j++; // will keep repeating the value of the last one - } - part = strtok_r(NULL, "/", &strtok_r_p); - } + /* find the string that was signed - cycle through the parts letters, adding the part of the fqdn/path if it is 1 */ + has_path_params == false ? (cp = strchr(url, '?')) : (cp = strchr(url, ';')); + // Skip scheme and initial forward slashes. + const char *skip = strchr(url, ':'); + if (!skip || skip[1] != '/' || skip[2] != '/') { + goto deny; + } + skip += 3; + memcpy(urltokstr, skip, cp - skip); + + // Block needed due to goto. + { + char *strtok_r_p; + const char *part = strtok_r(urltokstr, "/", &strtok_r_p); + while (part != nullptr) { + if (parts[j] == '1') { + strncat(signed_part, part, sizeof(signed_part) - strlen(signed_part) - 1); + strncat(signed_part, "/", sizeof(signed_part) - strlen(signed_part) - 1); + } + if (parts[j + 1] == '0' || + parts[j + 1] == '1') { // This remembers the last part, meaning, if there are no more valid letters in parts + j++; // will keep repeating the value of the last one + } + part = strtok_r(nullptr, "/", &strtok_r_p); + } - // chop off the last /, replace with '?' or ';' as appropriate. - has_path_params == false ? (signed_part[strlen(signed_part) - 1] = '?') : (signed_part[strlen(signed_part) - 1] = '\0'); - cp = strstr(query, SIG_QSTRING "="); - TSDebug(PLUGIN_NAME, "cp: %s, query: %s, signed_part: %s", cp, query, signed_part); - strncat(signed_part, query, (cp - query) + strlen(SIG_QSTRING) + 1); + // chop off the last /, replace with '?' or ';' as appropriate. + has_path_params == false ? (signed_part[strlen(signed_part) - 1] = '?') : (signed_part[strlen(signed_part) - 1] = '\0'); + cp = strstr(query, SIG_QSTRING "="); + TSDebug(PLUGIN_NAME, "cp: %s, query: %s, signed_part: %s", cp, query, signed_part); + strncat(signed_part, query, (cp - query) + strlen(SIG_QSTRING) + 1); + + TSDebug(PLUGIN_NAME, "Signed string=\"%s\"", signed_part); + + /* calculate the expected the signature with the right algorithm */ + switch (algorithm) { + case USIG_HMAC_SHA1: + HMAC(EVP_sha1(), (const unsigned char *)cfg->keys[keyindex], strlen(cfg->keys[keyindex]), + (const unsigned char *)signed_part, strlen(signed_part), sig, &sig_len); + if (sig_len != SHA1_SIG_SIZE) { + TSDebug(PLUGIN_NAME, "sig_len: %d", sig_len); + err_log(url, "Calculated sig len != SHA1_SIG_SIZE !"); + goto deny; + } + + break; + case USIG_HMAC_MD5: + HMAC(EVP_md5(), (const unsigned char *)cfg->keys[keyindex], strlen(cfg->keys[keyindex]), + (const unsigned char *)signed_part, strlen(signed_part), sig, &sig_len); + if (sig_len != MD5_SIG_SIZE) { + TSDebug(PLUGIN_NAME, "sig_len: %d", sig_len); + err_log(url, "Calculated sig len != MD5_SIG_SIZE !"); + goto deny; + } + break; + default: + err_log(url, "Algorithm not supported"); + goto deny; + } - TSDebug(PLUGIN_NAME, "Signed string=\"%s\"", signed_part); + for (i = 0; i < sig_len; i++) { + snprintf(&(sig_string[i * 2]), sizeof(sig_string) - (i * 2), "%02x", sig[i]); + } - /* calculate the expected the signature with the right algorithm */ - switch (algorithm) { - case USIG_HMAC_SHA1: - HMAC(EVP_sha1(), (const unsigned char *)cfg->keys[keyindex], strlen(cfg->keys[keyindex]), (const unsigned char *)signed_part, - strlen(signed_part), sig, &sig_len); - if (sig_len != SHA1_SIG_SIZE) { - TSDebug(PLUGIN_NAME, "sig_len: %d", sig_len); - err_log(url, "Calculated sig len != SHA1_SIG_SIZE !"); - goto deny; - } + TSDebug(PLUGIN_NAME, "Expected signature: %s", sig_string); - break; - case USIG_HMAC_MD5: - HMAC(EVP_md5(), (const unsigned char *)cfg->keys[keyindex], strlen(cfg->keys[keyindex]), (const unsigned char *)signed_part, - strlen(signed_part), sig, &sig_len); - if (sig_len != MD5_SIG_SIZE) { - TSDebug(PLUGIN_NAME, "sig_len: %d", sig_len); - err_log(url, "Calculated sig len != MD5_SIG_SIZE !"); - goto deny; + /* and compare to signature that was sent */ + cmp_res = strncmp(sig_string, signature, sig_len * 2); + if (cmp_res != 0) { + err_log(url, "Signature check failed"); + goto deny; + } else { + TSDebug(PLUGIN_NAME, "Signature check passed"); + goto allow; + } + } + } + } } - break; - default: - err_log(url, "Algorithm not supported"); - goto deny; - } - - for (i = 0; i < sig_len; i++) { - snprintf(&(sig_string[i * 2]), sizeof(sig_string) - (i * 2), "%02x", sig[i]); - } - - TSDebug(PLUGIN_NAME, "Expected signature: %s", sig_string); - - /* and compare to signature that was sent */ - cmp_res = strncmp(sig_string, signature, sig_len * 2); - if (cmp_res != 0) { - err_log(url, "Signature check failed"); - goto deny; - } else { - TSDebug(PLUGIN_NAME, "Signature check passed"); - goto allow; } /* ********* Deny ********* */ @@ -874,8 +891,8 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) } const char *current_query = strchr(current_url, '?'); - const char *app_qry = NULL; - if (current_query != NULL) { + const char *app_qry = nullptr; + if (current_query != nullptr) { current_query++; app_qry = getAppQueryString(current_query, strlen(current_query)); } @@ -884,17 +901,17 @@ TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) if (*new_path) { TSUrlPathSet(rri->requestBufp, rri->requestUrl, new_path, strlen(new_path)); } - TSUrlHttpParamsSet(rri->requestBufp, rri->requestUrl, NULL, 0); + TSUrlHttpParamsSet(rri->requestBufp, rri->requestUrl, nullptr, 0); } TSfree((void *)current_url); /* drop the query string so we can cache-hit */ - if (app_qry != NULL) { + if (app_qry != nullptr) { rval = TSUrlHttpQuerySet(rri->requestBufp, rri->requestUrl, app_qry, strlen(app_qry)); TSfree((void *)app_qry); } else { - rval = TSUrlHttpQuerySet(rri->requestBufp, rri->requestUrl, NULL, 0); + rval = TSUrlHttpQuerySet(rri->requestBufp, rri->requestUrl, nullptr, 0); } if (rval != TS_SUCCESS) { TSError("[url_sig] Error setting the query string: %d", rval); diff --git a/plugins/header_rewrite/header_rewrite_test.cc b/plugins/header_rewrite/header_rewrite_test.cc index 704c68d0a7c..aba3f2793bd 100644 --- a/plugins/header_rewrite/header_rewrite_test.cc +++ b/plugins/header_rewrite/header_rewrite_test.cc @@ -30,8 +30,8 @@ const char PLUGIN_NAME[] = "TEST_header_rewrite"; const char PLUGIN_NAME_DBG[] = "TEST_dbg_header_rewrite"; -extern "C" void -TSError(const char *fmt, ...) +void +tsapi::c::TSError(const char *fmt, ...) { va_list args; diff --git a/plugins/healthchecks/CMakeLists.txt b/plugins/healthchecks/CMakeLists.txt index ba2474d87f2..d267e74a8b3 100644 --- a/plugins/healthchecks/CMakeLists.txt +++ b/plugins/healthchecks/CMakeLists.txt @@ -15,4 +15,4 @@ # ####################### -add_atsplugin(healthchecks healthchecks.c) +add_atsplugin(healthchecks healthchecks.cc) diff --git a/plugins/healthchecks/Makefile.inc b/plugins/healthchecks/Makefile.inc index f9c027c3da4..242efe163cc 100644 --- a/plugins/healthchecks/Makefile.inc +++ b/plugins/healthchecks/Makefile.inc @@ -15,4 +15,4 @@ # limitations under the License. pkglib_LTLIBRARIES += healthchecks/healthchecks.la -healthchecks_healthchecks_la_SOURCES = healthchecks/healthchecks.c +healthchecks_healthchecks_la_SOURCES = healthchecks/healthchecks.cc diff --git a/plugins/healthchecks/healthchecks.c b/plugins/healthchecks/healthchecks.cc similarity index 87% rename from plugins/healthchecks/healthchecks.c rename to plugins/healthchecks/healthchecks.cc index 9bdab18530a..77a69b13164 100644 --- a/plugins/healthchecks/healthchecks.c +++ b/plugins/healthchecks/healthchecks.cc @@ -27,6 +27,7 @@ limitations under the License. #include #include #include +#include /* ToDo: Linux specific */ #include @@ -43,12 +44,6 @@ static const char SEPARATORS[] = " \t\n"; #define MAX_BODY_LEN 16384 #define FREELIST_TIMEOUT 300 -static inline void * -ink_atomic_swap_ptr(void *mem, void *value) -{ - return __sync_lock_test_and_set((void **)mem, value); -} - /* Directories that we are watching for inotify IN_CREATE events. */ typedef struct HCDirEntry_t { char dname[MAX_PATH_LEN]; /* Directory name */ @@ -59,7 +54,7 @@ typedef struct HCDirEntry_t { /* Information about a status file. This is never modified (only replaced, see HCFileInfo_t) */ typedef struct HCFileData_t { int exists; /* Does this file exist */ - char body[MAX_BODY_LEN]; /* Body from fname. NULL means file is missing */ + char body[MAX_BODY_LEN]; /* Body from fname. Empty string means file is missing */ int b_len; /* Length of data */ time_t remove; /* Used for deciding when the old object can be permanently removed */ struct HCFileData_t *_next; /* Only used when these guys end up on the freelist */ @@ -67,18 +62,18 @@ typedef struct HCFileData_t { /* The only thing that should change in this struct is data, atomically swapping ptrs */ typedef struct HCFileInfo_t { - char fname[MAX_PATH_LEN]; /* Filename */ - char *basename; /* The "basename" of the file */ - char path[PATH_NAME_MAX]; /* URL path for this HC */ - int p_len; /* Length of path */ - const char *ok; /* Header for an OK result */ - int o_len; /* Length of OK header */ - const char *miss; /* Header for miss results */ - int m_len; /* Length of miss header */ - HCFileData *data; /* Holds the current data for this health check file */ - int wd; /* Watch descriptor */ - HCDirEntry *dir; /* Reference to the directory this file resides in */ - struct HCFileInfo_t *_next; /* Linked list */ + char fname[MAX_PATH_LEN]; /* Filename */ + char *basename; /* The "basename" of the file */ + char path[PATH_NAME_MAX]; /* URL path for this HC */ + int p_len; /* Length of path */ + const char *ok; /* Header for an OK result */ + int o_len; /* Length of OK header */ + const char *miss; /* Header for miss results */ + int m_len; /* Length of miss header */ + std::atomic data; /* Holds the current data for this health check file */ + int wd; /* Watch descriptor */ + HCDirEntry *dir; /* Reference to the directory this file resides in */ + struct HCFileInfo_t *_next; /* Linked list */ } HCFileInfo; /* Global configuration */ @@ -108,7 +103,7 @@ reload_status_file(HCFileInfo *info, HCFileData *data) FILE *fd; memset(data, 0, sizeof(HCFileData)); - if (NULL != (fd = fopen(info->fname, "r"))) { + if (nullptr != (fd = fopen(info->fname, "r"))) { data->exists = 1; do { data->b_len = fread(data->body, 1, MAX_BODY_LEN, fd); @@ -127,7 +122,7 @@ find_direntry(const char *dname, HCDirEntry *dir) } dir = dir->_next; } - return NULL; + return nullptr; } /* Setup up watchers, directory as well as initial files */ @@ -135,7 +130,7 @@ static HCDirEntry * setup_watchers(int fd) { HCFileInfo *conf = g_config; - HCDirEntry *head_dir = NULL, *last_dir = NULL, *dir; + HCDirEntry *head_dir = nullptr, *last_dir = nullptr, *dir; char fname[MAX_PATH_LEN]; while (conf) { @@ -146,7 +141,7 @@ setup_watchers(int fd) /* Make sure to only watch each directory once */ if (!(dir = find_direntry(dname, head_dir))) { TSDebug(PLUGIN_NAME, "Setting up a watcher for directory %s", dname); - dir = TSmalloc(sizeof(HCDirEntry)); + dir = tsapi::malloc(); memset(dir, 0, sizeof(HCDirEntry)); strncpy(dir->dname, dname, MAX_PATH_LEN - 1); dir->wd = inotify_add_watch(fd, dname, IN_CREATE | IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB); @@ -171,19 +166,19 @@ static void * hc_thread(void *data ATS_UNUSED) { int fd = inotify_init(); - HCFileData *fl_head = NULL; + HCFileData *fl_head = nullptr; char buffer[INOTIFY_BUFLEN]; struct timeval last_free, now; - gettimeofday(&last_free, NULL); + gettimeofday(&last_free, nullptr); /* Setup watchers for the directories, these are a one time setup */ setup_watchers(fd); // This is a leak, but since we enter an infinite loop this is ok? while (1) { - HCFileData *fdata = fl_head, *fdata_prev = NULL; + HCFileData *fdata = fl_head, *fdata_prev = nullptr; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); /* Read the inotify events, blocking until we get something */ int len = read(fd, buffer, INOTIFY_BUFLEN); @@ -194,9 +189,9 @@ hc_thread(void *data ATS_UNUSED) if (now.tv_sec > fdata->remove) { /* Now drop off the "tail" from the freelist */ if (fdata_prev) { - fdata_prev->_next = NULL; + fdata_prev->_next = nullptr; } else { - fl_head = NULL; + fl_head = nullptr; } /* free() everything in the "tail" */ @@ -225,7 +220,7 @@ hc_thread(void *data ATS_UNUSED) finfo = finfo->_next; } if (finfo) { - HCFileData *new_data = TSmalloc(sizeof(HCFileData)); + auto *new_data = tsapi::malloc(); HCFileData *old_data; if (event->mask & (IN_CLOSE_WRITE | IN_ATTRIB)) { @@ -241,7 +236,7 @@ hc_thread(void *data ATS_UNUSED) memset(new_data, 0, sizeof(HCFileData)); reload_status_file(finfo, new_data); TSDebug(PLUGIN_NAME, "Reloaded %s, len == %d, exists == %d", finfo->fname, new_data->b_len, new_data->exists); - old_data = ink_atomic_swap_ptr(&(finfo->data), new_data); + old_data = finfo->data.exchange(new_data); /* Add the old data to the head of the freelist */ old_data->remove = now.tv_sec + FREELIST_TIMEOUT; @@ -254,7 +249,7 @@ hc_thread(void *data ATS_UNUSED) } } - return NULL; /* Yeah, that never happens */ + return nullptr; /* Yeah, that never happens */ } /* Config file parsing */ @@ -264,9 +259,9 @@ static char * gen_header(char *status_str, char *mime, int *header_len) { TSHttpStatus status; - char *buf = NULL; + char *buf = nullptr; - status = atoi(status_str); + status = TSHttpStatus(atoi(status_str)); if (status > TS_HTTP_STATUS_NONE && status < (TSHttpStatus)999) { const char *status_reason; int len = sizeof(HEADER_TEMPLATE) + 3 + 1; @@ -274,7 +269,7 @@ gen_header(char *status_str, char *mime, int *header_len) status_reason = TSHttpHdrReasonLookup(status); len += strlen(status_reason); len += strlen(mime); - buf = TSmalloc(len); + buf = tsapi::malloc(len); *header_len = snprintf(buf, len, HEADER_TEMPLATE, status, status_reason, mime); } else { *header_len = 0; @@ -288,10 +283,10 @@ parse_configs(const char *fname) { FILE *fd; char buf[2 * 1024]; - HCFileInfo *head_finfo = NULL, *finfo = NULL, *prev_finfo = NULL; + HCFileInfo *head_finfo = nullptr, *finfo = nullptr, *prev_finfo = nullptr; if (!fname) { - return NULL; + return nullptr; } if ('/' == *fname) { @@ -303,22 +298,22 @@ parse_configs(const char *fname) fd = fopen(filename, "r"); } - if (NULL == fd) { + if (nullptr == fd) { TSError("%s: Could not open config file", PLUGIN_NAME); - return NULL; + return nullptr; } while (!feof(fd)) { char *str, *save; - char *ok = NULL, *miss = NULL, *mime = NULL; + char *ok = nullptr, *miss = nullptr, *mime = nullptr; - finfo = TSmalloc(sizeof(HCFileInfo)); - memset(finfo, 0, sizeof(HCFileInfo)); + finfo = tsapi::malloc(); + memset(static_cast(finfo), 0, sizeof(HCFileInfo)); if (fgets(buf, sizeof(buf) - 1, fd)) { str = strtok_r(buf, SEPARATORS, &save); int state = 0; - while (NULL != str) { + while (nullptr != str) { if (strlen(str) > 0) { switch (state) { case 0: @@ -347,7 +342,7 @@ parse_configs(const char *fname) } ++state; } - str = strtok_r(NULL, SEPARATORS, &save); + str = strtok_r(nullptr, SEPARATORS, &save); } /* Fill in the info if everything was ok */ @@ -355,13 +350,13 @@ parse_configs(const char *fname) TSDebug(PLUGIN_NAME, "Parsed: %s %s %s %s %s", finfo->path, finfo->fname, mime, ok, miss); finfo->ok = gen_header(ok, mime, &finfo->o_len); finfo->miss = gen_header(miss, mime, &finfo->m_len); - finfo->data = TSmalloc(sizeof(HCFileData)); + finfo->data = tsapi::malloc(); memset(finfo->data, 0, sizeof(HCFileData)); reload_status_file(finfo, finfo->data); /* Add it the linked list */ TSDebug(PLUGIN_NAME, "Adding path=%s to linked list", finfo->path); - if (NULL == head_finfo) { + if (nullptr == head_finfo) { head_finfo = finfo; } else { prev_finfo->_next = finfo; @@ -383,12 +378,12 @@ cleanup(TSCont contp, HCState *my_state) { if (my_state->req_buffer) { TSIOBufferDestroy(my_state->req_buffer); - my_state->req_buffer = NULL; + my_state->req_buffer = nullptr; } if (my_state->resp_buffer) { TSIOBufferDestroy(my_state->resp_buffer); - my_state->resp_buffer = NULL; + my_state->resp_buffer = nullptr; } TSVConnClose(my_state->net_vc); @@ -470,7 +465,7 @@ hc_process_accept(TSCont contp, HCState *my_state) static int hc_intercept(TSCont contp, TSEvent event, void *edata) { - HCState *my_state = TSContDataGet(contp); + auto my_state = static_cast(TSContDataGet(contp)); if (event == TS_EVENT_NET_ACCEPT) { my_state->net_vc = (TSVConn)edata; @@ -491,7 +486,7 @@ static int health_check_origin(TSCont contp ATS_UNUSED, TSEvent event ATS_UNUSED, void *edata) { TSMBuffer reqp; - TSMLoc hdr_loc = NULL, url_loc = NULL; + TSMLoc hdr_loc = nullptr, url_loc = nullptr; TSCont icontp; HCState *my_state; TSHttpTxn txnp = (TSHttpTxn)edata; @@ -522,7 +517,7 @@ health_check_origin(TSCont contp ATS_UNUSED, TSEvent event ATS_UNUSED, void *eda /* This is us -- register our intercept */ icontp = TSContCreate(hc_intercept, TSMutexCreate()); - my_state = (HCState *)TSmalloc(sizeof(*my_state)); + my_state = tsapi::malloc(); memset(my_state, 0, sizeof(*my_state)); my_state->info = info; my_state->data = info->data; @@ -565,13 +560,13 @@ TSPluginInit(int argc, const char *argv[]) /* This will update the global configuration file, and is not reloaded at run time */ /* ToDo: Support reloading with traffic_ctl config reload ? */ - if (NULL == (g_config = parse_configs(argv[1]))) { + if (nullptr == (g_config = parse_configs(argv[1]))) { TSError("[healthchecks] Unable to read / parse %s config file", argv[1]); return; } /* Setup the background thread */ - if (!TSThreadCreate(hc_thread, NULL)) { + if (!TSThreadCreate(hc_thread, nullptr)) { TSError("[healthchecks] Failure in thread creation"); return; } @@ -579,5 +574,5 @@ TSPluginInit(int argc, const char *argv[]) /* Create a continuation with a mutex as there is a shared global structure containing the headers to add */ TSDebug(PLUGIN_NAME, "Started %s plugin", PLUGIN_NAME); - TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(health_check_origin, NULL)); + TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(health_check_origin, nullptr)); } diff --git a/plugins/libloader/CMakeLists.txt b/plugins/libloader/CMakeLists.txt index e917590c6b5..7bbe4c1092f 100644 --- a/plugins/libloader/CMakeLists.txt +++ b/plugins/libloader/CMakeLists.txt @@ -15,6 +15,6 @@ # ####################### -add_atsplugin(libloader libloader.c) +add_atsplugin(libloader libloader.cc) target_include_directories(libloader PRIVATE "${CMAKE_SOURCE_DIR}/include/ts") diff --git a/plugins/libloader/Makefile.inc b/plugins/libloader/Makefile.inc index bea71ec43df..68c172ca069 100644 --- a/plugins/libloader/Makefile.inc +++ b/plugins/libloader/Makefile.inc @@ -17,5 +17,5 @@ pkglib_LTLIBRARIES += libloader/libloader.la libloader_libloader_la_SOURCES = \ - libloader/libloader.c \ + libloader/libloader.cc \ libloader/libloader.h diff --git a/plugins/libloader/libloader.c b/plugins/libloader/libloader.cc similarity index 90% rename from plugins/libloader/libloader.c rename to plugins/libloader/libloader.cc index 2df6d8bc0f9..1f6e1f110b0 100644 --- a/plugins/libloader/libloader.c +++ b/plugins/libloader/libloader.cc @@ -32,24 +32,24 @@ #include #include -typedef struct { +typedef struct link_handle_s { void *handle; - void *next; + link_handle_s *next; } link_handle; -static link_handle *libs = NULL; +static link_handle *libs = nullptr; static void unloadlibs(void) { link_handle *p = libs; - while (p != NULL) { + while (p != nullptr) { link_handle *next = p->next; dlclose(p->handle); TSfree(p); p = next; } - libs = NULL; + libs = nullptr; } void @@ -73,10 +73,10 @@ TSPluginInit(int argc, const char *argv[]) const char *lib = argv[i]; void *handle = dlopen(lib, RTLD_GLOBAL | RTLD_NOW); if (handle) { - link_handle *l = TSmalloc(sizeof(link_handle)); - l->handle = handle; - l->next = libs; - libs = l; + auto l = tsapi::malloc(); + l->handle = handle; + l->next = libs; + libs = l; TSDebug("libloader", " loaded %s", lib); } else { TSError("[libloader] failed to load %s: %s\n", lib, dlerror()); diff --git a/plugins/lua/CMakeLists.txt b/plugins/lua/CMakeLists.txt index 6f060eaca5a..cf948119681 100644 --- a/plugins/lua/CMakeLists.txt +++ b/plugins/lua/CMakeLists.txt @@ -16,35 +16,35 @@ ####################### add_atsplugin(tslua - ts_lua.c - ts_lua_cached_response.c - ts_lua_client_request.c - ts_lua_client_response.c - ts_lua_client_response.c - ts_lua_context.c - ts_lua_hook.c - ts_lua_http.c - ts_lua_http_intercept.c - ts_lua_log.c - ts_lua_misc.c - ts_lua_server_request.c - ts_lua_server_response.c - ts_lua_transform.c - ts_lua_util.c - ts_lua_remap.c - ts_lua_http_cntl.c - ts_lua_http_milestone.c - ts_lua_http_txn_info.c - ts_lua_http_config.c - ts_lua_mgmt.c - ts_lua_package.c - ts_lua_string.c - ts_lua_crypto.c - ts_lua_stat.c - ts_lua_io.c - ts_lua_coroutine.c - ts_lua_fetch.c - ts_lua_constant.c + ts_lua.cc + ts_lua_cached_response.cc + ts_lua_client_request.cc + ts_lua_client_response.cc + ts_lua_client_response.cc + ts_lua_context.cc + ts_lua_hook.cc + ts_lua_http.cc + ts_lua_http_intercept.cc + ts_lua_log.cc + ts_lua_misc.cc + ts_lua_server_request.cc + ts_lua_server_response.cc + ts_lua_transform.cc + ts_lua_util.cc + ts_lua_remap.cc + ts_lua_http_cntl.cc + ts_lua_http_milestone.cc + ts_lua_http_txn_info.cc + ts_lua_http_config.cc + ts_lua_mgmt.cc + ts_lua_package.cc + ts_lua_string.cc + ts_lua_crypto.cc + ts_lua_stat.cc + ts_lua_io.cc + ts_lua_coroutine.cc + ts_lua_fetch.cc + ts_lua_constant.cc ) target_include_directories(tslua PRIVATE "${PROJECT_SOURCE_DIR}/include") diff --git a/plugins/lua/Makefile.inc b/plugins/lua/Makefile.inc index aaeb0c22a09..0df9df3252a 100644 --- a/plugins/lua/Makefile.inc +++ b/plugins/lua/Makefile.inc @@ -20,31 +20,31 @@ lua_tslua_la_LDFLAGS = $(AM_LDFLAGS) $(LUAJIT_LDFLAGS) pkglib_LTLIBRARIES += lua/tslua.la lua_tslua_la_SOURCES = \ - lua/ts_lua.c \ - lua/ts_lua_cached_response.c \ - lua/ts_lua_client_request.c \ - lua/ts_lua_client_response.c \ - lua/ts_lua_context.c \ - lua/ts_lua_hook.c \ - lua/ts_lua_http.c \ - lua/ts_lua_http_intercept.c \ - lua/ts_lua_log.c \ - lua/ts_lua_misc.c \ - lua/ts_lua_server_request.c \ - lua/ts_lua_server_response.c \ - lua/ts_lua_transform.c \ - lua/ts_lua_util.c \ - lua/ts_lua_remap.c \ - lua/ts_lua_http_cntl.c \ - lua/ts_lua_http_milestone.c \ - lua/ts_lua_http_txn_info.c \ - lua/ts_lua_http_config.c \ - lua/ts_lua_mgmt.c \ - lua/ts_lua_package.c \ - lua/ts_lua_string.c \ - lua/ts_lua_crypto.c \ - lua/ts_lua_stat.c \ - lua/ts_lua_io.c \ - lua/ts_lua_coroutine.c \ - lua/ts_lua_fetch.c \ - lua/ts_lua_constant.c + lua/ts_lua.cc \ + lua/ts_lua_cached_response.cc \ + lua/ts_lua_client_request.cc \ + lua/ts_lua_client_response.cc \ + lua/ts_lua_context.cc \ + lua/ts_lua_hook.cc \ + lua/ts_lua_http.cc \ + lua/ts_lua_http_intercept.cc \ + lua/ts_lua_log.cc \ + lua/ts_lua_misc.cc \ + lua/ts_lua_server_request.cc \ + lua/ts_lua_server_response.cc \ + lua/ts_lua_transform.cc \ + lua/ts_lua_util.cc \ + lua/ts_lua_remap.cc \ + lua/ts_lua_http_cntl.cc \ + lua/ts_lua_http_milestone.cc \ + lua/ts_lua_http_txn_info.cc \ + lua/ts_lua_http_config.cc \ + lua/ts_lua_mgmt.cc \ + lua/ts_lua_package.cc \ + lua/ts_lua_string.cc \ + lua/ts_lua_crypto.cc \ + lua/ts_lua_stat.cc \ + lua/ts_lua_io.cc \ + lua/ts_lua_coroutine.cc \ + lua/ts_lua_fetch.cc \ + lua/ts_lua_constant.cc diff --git a/plugins/lua/ts_lua.c b/plugins/lua/ts_lua.cc similarity index 92% rename from plugins/lua/ts_lua.c rename to plugins/lua/ts_lua.cc index 9154e105516..c78a605277b 100644 --- a/plugins/lua/ts_lua.c +++ b/plugins/lua/ts_lua.cc @@ -24,7 +24,10 @@ #include #include "ts_lua_util.h" + +extern "C" { #include "luajit.h" +} // extern "C" #define TS_LUA_MAX_STATE_COUNT 256 @@ -39,8 +42,8 @@ static uint64_t ts_lua_http_next_id = 0; static uint64_t ts_lua_g_http_next_id = 0; -static ts_lua_main_ctx *ts_lua_main_ctx_array = NULL; -static ts_lua_main_ctx *ts_lua_g_main_ctx_array = NULL; +static ts_lua_main_ctx *ts_lua_main_ctx_array = nullptr; +static ts_lua_main_ctx *ts_lua_g_main_ctx_array = nullptr; static pthread_key_t lua_g_state_key; static pthread_key_t lua_state_key; @@ -61,13 +64,13 @@ static char const *const ts_lua_stat_strs[] = { "plugin.lua.remap.states", "plugin.lua.remap.gc_bytes", "plugin.lua.remap.threads", - NULL, + nullptr, }; static char const *const ts_lua_g_stat_strs[] = { "plugin.lua.global.states", "plugin.lua.global.gc_bytes", "plugin.lua.global.threads", - NULL, + nullptr, }; typedef struct { @@ -83,7 +86,7 @@ typedef struct { ts_lua_plugin_stats * create_plugin_stats(ts_lua_main_ctx *const main_ctx_array, char const *const *stat_strs) { - ts_lua_plugin_stats *const stats = TSmalloc(sizeof(ts_lua_plugin_stats)); + auto *const stats = tsapi::malloc(); memset(stats, 0, sizeof(ts_lua_plugin_stats)); stats->main_ctx_array = main_ctx_array; @@ -110,7 +113,7 @@ create_plugin_stats(ts_lua_main_ctx *const main_ctx_array, char const *const *st ts_lua_main_ctx * create_lua_vms() { - ts_lua_main_ctx *ctx_array = NULL; + ts_lua_main_ctx *ctx_array = nullptr; // Inject the setting into records.yaml static bool ts_mgt_int_inserted = false; @@ -140,11 +143,11 @@ create_lua_vms() if (ts_lua_max_state_count < 1) { TSError("[ts_lua][%s] invalid %s: %d", __FUNCTION__, ts_lua_mgmt_state_str, ts_lua_max_state_count); ts_lua_max_state_count = 0; - return NULL; + return nullptr; } } - ctx_array = TSmalloc(sizeof(ts_lua_main_ctx) * ts_lua_max_state_count); + ctx_array = tsapi::malloc(ts_lua_max_state_count); memset(ctx_array, 0, sizeof(ts_lua_main_ctx) * ts_lua_max_state_count); int const ret = ts_lua_create_vm(ctx_array, ts_lua_max_state_count); @@ -152,8 +155,8 @@ create_lua_vms() if (ret) { ts_lua_destroy_vm(ctx_array, ts_lua_max_state_count); TSfree(ctx_array); - ctx_array = NULL; - return NULL; + ctx_array = nullptr; + return nullptr; } // Initialize the GC numbers, no need to lock here @@ -180,7 +183,7 @@ collectStats(ts_lua_plugin_stats *const plugin_stats) // aggregate stats on the states for (int index = 0; index < ts_lua_max_state_count; ++index) { ts_lua_main_ctx *const main_ctx = (main_ctx_array + index); - if (NULL != main_ctx) { + if (nullptr != main_ctx) { ts_lua_ctx_stats *const stats = main_ctx->stats; TSMutexLock(stats->mutexp); @@ -248,7 +251,7 @@ lifecycleHandler(TSCont contp, TSEvent event, void *edata) static char const *const remapstr = "remap"; static char const *const globalstr = "global"; - char const *labelstr = NULL; + char const *labelstr = nullptr; if (main_ctx_array == ts_lua_main_ctx_array) { labelstr = remapstr; @@ -274,9 +277,9 @@ lifecycleHandler(TSCont contp, TSEvent event, void *edata) for (int index = 0; index < ts_lua_max_state_count; ++index) { ts_lua_main_ctx *const main_ctx = (main_ctx_array + index); - if (NULL != main_ctx) { + if (nullptr != main_ctx) { ts_lua_ctx_stats *const stats = main_ctx->stats; - if (NULL != main_ctx) { + if (nullptr != main_ctx) { TSMutexLock(stats->mutexp); switch (state) { @@ -309,10 +312,10 @@ TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) return TS_ERROR; } - if (NULL == ts_lua_main_ctx_array) { + if (nullptr == ts_lua_main_ctx_array) { ts_lua_main_ctx_array = create_lua_vms(); - if (NULL != ts_lua_main_ctx_array) { - pthread_key_create(&lua_state_key, NULL); + if (nullptr != ts_lua_main_ctx_array) { + pthread_key_create(&lua_state_key, nullptr); TSCont const lcontp = TSContCreate(lifecycleHandler, TSMutexCreate()); TSContDataSet(lcontp, ts_lua_main_ctx_array); @@ -321,7 +324,7 @@ TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) ts_lua_plugin_stats *const plugin_stats = create_plugin_stats(ts_lua_main_ctx_array, ts_lua_stat_strs); // start the stats management - if (NULL != plugin_stats) { + if (nullptr != plugin_stats) { TSDebug(TS_LUA_DEBUG_TAG, "Starting up stats management continuation"); TSCont const scontp = TSContCreate(statsHandler, TSMutexCreate()); TSContDataSet(scontp, plugin_stats); @@ -340,7 +343,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s { int ret; char script[TS_LUA_MAX_SCRIPT_FNAME_LENGTH]; - char *inline_script = ""; + char const *inline_script = ""; int fn = 0; int states = ts_lua_max_state_count; int ljgc = 0; @@ -357,7 +360,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s for (;;) { int opt; - opt = getopt_long(argc, (char *const *)argv, "", longopt, NULL); + opt = getopt_long(argc, (char *const *)argv, "", longopt, nullptr); switch (opt) { case 's': states = atoi(optarg); @@ -404,7 +407,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s return TS_ERROR; } - ts_lua_instance_conf *conf = NULL; + ts_lua_instance_conf *conf = nullptr; // check to make sure it is a lua file and there is no parameter for the lua file if (fn && (argc - optind < 2)) { @@ -419,9 +422,9 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s if (!conf) { TSDebug(TS_LUA_DEBUG_TAG, "[%s] creating new conf instance", __FUNCTION__); - conf = TSmalloc(sizeof(ts_lua_instance_conf)); + conf = tsapi::malloc(); if (!conf) { - strncpy(errbuf, "[TSRemapNewInstance] TSmalloc failed!!", errbuf_size - 1); + strncpy(errbuf, "[TSRemapNewInstance] tsapi::malloc failed!!", errbuf_size - 1); errbuf[errbuf_size - 1] = '\0'; return TS_ERROR; } @@ -471,7 +474,7 @@ TSRemapDeleteInstance(void *ih) { int states = ((ts_lua_instance_conf *)ih)->states; ts_lua_del_module((ts_lua_instance_conf *)ih, ts_lua_main_ctx_array, states); - ts_lua_del_instance(ih); + ts_lua_del_instance(static_cast(ih)); ((ts_lua_instance_conf *)ih)->ref_count--; if (((ts_lua_instance_conf *)ih)->ref_count == 0) { TSDebug(TS_LUA_DEBUG_TAG, "Reference Count = %d , freeing...", ((ts_lua_instance_conf *)ih)->ref_count); @@ -497,11 +500,11 @@ ts_lua_remap_plugin_init(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) ts_lua_instance_conf *instance_conf; - int remap = (rri == NULL ? 0 : 1); + int remap = (rri == nullptr ? 0 : 1); instance_conf = (ts_lua_instance_conf *)ih; - main_ctx = pthread_getspecific(lua_state_key); - if (main_ctx == NULL) { + main_ctx = static_cast(pthread_getspecific(lua_state_key)); + if (main_ctx == nullptr) { req_id = __sync_fetch_and_add(&ts_lua_http_next_id, 1); main_ctx = &ts_lua_main_ctx_array[req_id % instance_conf->states]; pthread_setspecific(lua_state_key, main_ctx); @@ -514,7 +517,7 @@ ts_lua_remap_plugin_init(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) http_ctx->txnp = rh; http_ctx->has_hook = 0; http_ctx->rri = rri; - if (rri != NULL) { + if (rri != nullptr) { http_ctx->client_request_bufp = rri->requestBufp; http_ctx->client_request_hdrp = rri->requestHdrp; http_ctx->client_request_url = rri->requestUrl; @@ -523,7 +526,7 @@ ts_lua_remap_plugin_init(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) ci = &http_ctx->cinfo; L = ci->routine.lua; - contp = TSContCreate(ts_lua_http_cont_handler, NULL); + contp = TSContCreate(ts_lua_http_cont_handler, nullptr); TSContDataSet(contp, http_ctx); ci->contp = contp; @@ -537,7 +540,7 @@ ts_lua_remap_plugin_init(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) return TSREMAP_NO_REMAP; } - ts_lua_set_cont_info(L, NULL); + ts_lua_set_cont_info(L, nullptr); if (lua_pcall(L, 0, 1, 0) != 0) { TSError("[ts_lua][%s] lua_pcall failed: %s", __FUNCTION__, lua_tostring(L, -1)); ret = TSREMAP_NO_REMAP; @@ -558,14 +561,14 @@ ts_lua_remap_plugin_init(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) TSMutexUnlock(main_ctx->mutexp); - return ret; + return TSRemapStatus(ret); } void TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type) { TSDebug(TS_LUA_DEBUG_TAG, "[%s] os response function and type - %d", __FUNCTION__, os_response_type); - ts_lua_remap_plugin_init(ih, rh, NULL); + ts_lua_remap_plugin_init(ih, rh, nullptr); } TSRemapStatus @@ -605,8 +608,8 @@ globalHookHandler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) ts_lua_instance_conf *conf = (ts_lua_instance_conf *)TSContDataGet(contp); - main_ctx = pthread_getspecific(lua_g_state_key); - if (main_ctx == NULL) { + main_ctx = static_cast(pthread_getspecific(lua_g_state_key)); + if (main_ctx == nullptr) { req_id = __sync_fetch_and_add(&ts_lua_g_http_next_id, 1); TSDebug(TS_LUA_DEBUG_TAG, "[%s] req_id: %" PRId64, __FUNCTION__, req_id); main_ctx = &ts_lua_g_main_ctx_array[req_id % conf->states]; @@ -617,7 +620,7 @@ globalHookHandler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) http_ctx = ts_lua_create_http_ctx(main_ctx, conf); http_ctx->txnp = txnp; - http_ctx->rri = NULL; + http_ctx->rri = nullptr; http_ctx->has_hook = 0; if (!http_ctx->client_request_bufp) { @@ -639,7 +642,7 @@ globalHookHandler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) return 0; } - txn_contp = TSContCreate(ts_lua_http_cont_handler, NULL); + txn_contp = TSContCreate(ts_lua_http_cont_handler, nullptr); TSContDataSet(txn_contp, http_ctx); ci = &http_ctx->cinfo; @@ -709,7 +712,7 @@ globalHookHandler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) return 0; } - ts_lua_set_cont_info(l, NULL); + ts_lua_set_cont_info(l, nullptr); if (lua_pcall(l, 0, 1, 0) != 0) { TSError("[ts_lua][%s] lua_pcall failed: %s", __FUNCTION__, lua_tostring(l, -1)); @@ -753,10 +756,10 @@ TSPluginInit(int argc, const char *argv[]) TSError("[ts_lua][%s] Plugin registration failed", __FUNCTION__); } - if (NULL == ts_lua_g_main_ctx_array) { + if (nullptr == ts_lua_g_main_ctx_array) { ts_lua_g_main_ctx_array = create_lua_vms(); - if (NULL != ts_lua_g_main_ctx_array) { - pthread_key_create(&lua_g_state_key, NULL); + if (nullptr != ts_lua_g_main_ctx_array) { + pthread_key_create(&lua_g_state_key, nullptr); TSCont const contp = TSContCreate(lifecycleHandler, TSMutexCreate()); TSContDataSet(contp, ts_lua_g_main_ctx_array); @@ -764,7 +767,7 @@ TSPluginInit(int argc, const char *argv[]) ts_lua_plugin_stats *const plugin_stats = create_plugin_stats(ts_lua_g_main_ctx_array, ts_lua_g_stat_strs); - if (NULL != plugin_stats) { + if (nullptr != plugin_stats) { TSCont const scontp = TSContCreate(statsHandler, TSMutexCreate()); TSContDataSet(scontp, plugin_stats); TSContScheduleOnPool(scontp, TS_LUA_STATS_TIMEOUT, TS_THREAD_POOL_TASK); @@ -788,7 +791,7 @@ TSPluginInit(int argc, const char *argv[]) for (;;) { int opt; - opt = getopt_long(argc, (char *const *)argv, "", longopt, NULL); + opt = getopt_long(argc, (char *const *)argv, "", longopt, nullptr); switch (opt) { case 's': states = atoi(optarg); @@ -833,9 +836,9 @@ TSPluginInit(int argc, const char *argv[]) return; } - ts_lua_instance_conf *conf = TSmalloc(sizeof(ts_lua_instance_conf)); + auto *conf = tsapi::malloc(); if (!conf) { - TSError("[ts_lua][%s] TSmalloc failed !!", __FUNCTION__); + TSError("[ts_lua][%s] tsapi::malloc failed !!", __FUNCTION__); return; } memset(conf, 0, sizeof(ts_lua_instance_conf)); @@ -861,7 +864,7 @@ TSPluginInit(int argc, const char *argv[]) return; } - TSCont global_contp = TSContCreate(globalHookHandler, NULL); + TSCont global_contp = TSContCreate(globalHookHandler, nullptr); if (!global_contp) { TSError("[ts_lua][%s] could not create transaction start continuation", __FUNCTION__); return; @@ -954,7 +957,7 @@ TSPluginInit(int argc, const char *argv[]) // support for reload as global plugin if (reload) { - TSCont config_contp = TSContCreate(configHandler, NULL); + TSCont config_contp = TSContCreate(configHandler, nullptr); if (!config_contp) { TSError("[ts_lua][%s] could not create configuration continuation", __FUNCTION__); return; diff --git a/plugins/lua/ts_lua_cached_response.c b/plugins/lua/ts_lua_cached_response.cc similarity index 100% rename from plugins/lua/ts_lua_cached_response.c rename to plugins/lua/ts_lua_cached_response.cc diff --git a/plugins/lua/ts_lua_client_request.c b/plugins/lua/ts_lua_client_request.cc similarity index 99% rename from plugins/lua/ts_lua_client_request.c rename to plugins/lua/ts_lua_client_request.cc index 37ca12a18f2..696b43dcb9d 100644 --- a/plugins/lua/ts_lua_client_request.c +++ b/plugins/lua/ts_lua_client_request.cc @@ -217,7 +217,7 @@ ts_lua_client_request_header_set(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); remove = 0; - val = NULL; + val = nullptr; /* we skip the first argument that is the table */ key = luaL_checklstring(L, 2, &key_len); @@ -484,7 +484,7 @@ ts_lua_client_request_get_pristine_url(lua_State *L) lua_pushnil(L); } - TSHandleMLocRelease(bufp, NULL, url_loc); + TSHandleMLocRelease(bufp, nullptr, url_loc); return 1; } @@ -502,9 +502,9 @@ ts_lua_client_request_get_url_host(lua_State *L) host = TSUrlHostGet(http_ctx->client_request_bufp, http_ctx->client_request_url, &len); if (len == 0) { - char *key = "Host"; - char *l_key = "host"; - int key_len = 4; + char const *key = "Host"; + char const *l_key = "host"; + int key_len = 4; TSMLoc field_loc; @@ -757,7 +757,7 @@ ts_lua_client_request_client_addr_get_ip(lua_State *L) client_ip = TSHttpTxnClientAddrGet(http_ctx->txnp); - if (client_ip == NULL) { + if (client_ip == nullptr) { lua_pushnil(L); } else { @@ -784,7 +784,7 @@ ts_lua_client_request_client_addr_get_port(lua_State *L) client_ip = TSHttpTxnClientAddrGet(http_ctx->txnp); - if (client_ip == NULL) { + if (client_ip == nullptr) { lua_pushnil(L); } else { @@ -811,7 +811,7 @@ ts_lua_client_request_client_addr_get_incoming_port(lua_State *L) incoming_addr = TSHttpTxnIncomingAddrGet(http_ctx->txnp); - if (incoming_addr == NULL) { + if (incoming_addr == nullptr) { lua_pushnil(L); } else { @@ -840,7 +840,7 @@ ts_lua_client_request_client_addr_get_addr(lua_State *L) client_ip = TSHttpTxnClientAddrGet(http_ctx->txnp); - if (client_ip == NULL) { + if (client_ip == nullptr) { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); diff --git a/plugins/lua/ts_lua_client_response.c b/plugins/lua/ts_lua_client_response.cc similarity index 97% rename from plugins/lua/ts_lua_client_response.c rename to plugins/lua/ts_lua_client_response.cc index f7e3a35b699..b34e01b9122 100644 --- a/plugins/lua/ts_lua_client_response.c +++ b/plugins/lua/ts_lua_client_response.cc @@ -150,7 +150,7 @@ ts_lua_client_response_header_set(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); remove = 0; - val = NULL; + val = nullptr; /* we skip the first argument that is the table */ key = luaL_checklstring(L, 2, &key_len); @@ -400,10 +400,10 @@ ts_lua_client_response_set_status(lua_State *L) // NOLINTNEXTLINE status = luaL_checkint(L, 1); - reason = TSHttpHdrReasonLookup(status); + reason = TSHttpHdrReasonLookup(TSHttpStatus(status)); reason_len = strlen(reason); - TSHttpHdrStatusSet(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, status); + TSHttpHdrStatusSet(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, TSHttpStatus(status)); TSHttpHdrReasonSet(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, reason, reason_len); return 0; @@ -462,7 +462,7 @@ static int ts_lua_client_response_set_error_resp(lua_State *L) { int n, status; - const char *body = NULL; + const char *body = nullptr; size_t body_len = 0; const char *reason; int reason_len; @@ -480,10 +480,10 @@ ts_lua_client_response_set_error_resp(lua_State *L) status = luaL_checkinteger(L, 1); - reason = TSHttpHdrReasonLookup(status); + reason = TSHttpHdrReasonLookup(TSHttpStatus(status)); reason_len = strlen(reason); - TSHttpHdrStatusSet(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, status); + TSHttpHdrStatusSet(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, TSHttpStatus(status)); TSHttpHdrReasonSet(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, reason, reason_len); body_len = 0; @@ -493,12 +493,12 @@ ts_lua_client_response_set_error_resp(lua_State *L) } if (body_len && body) { - resp_buf = TSmalloc(body_len); + resp_buf = tsapi::malloc(body_len); memcpy(resp_buf, body, body_len); resp_len = body_len; } else { - resp_buf = TSmalloc(reason_len); + resp_buf = tsapi::malloc(reason_len); memcpy(resp_buf, reason, reason_len); resp_len = reason_len; } @@ -511,7 +511,7 @@ ts_lua_client_response_set_error_resp(lua_State *L) TSHandleMLocRelease(http_ctx->client_response_bufp, http_ctx->client_response_hdrp, field_loc); } - TSHttpTxnErrorBodySet(http_ctx->txnp, resp_buf, resp_len, NULL); + TSHttpTxnErrorBodySet(http_ctx->txnp, resp_buf, resp_len, nullptr); return 0; } diff --git a/plugins/lua/ts_lua_common.h b/plugins/lua/ts_lua_common.h index 0a16d1157b4..30dec10ea76 100644 --- a/plugins/lua/ts_lua_common.h +++ b/plugins/lua/ts_lua_common.h @@ -23,9 +23,11 @@ #include #include +extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" +} // extern "C" #include #include @@ -83,11 +85,11 @@ /* for http config or cntl var */ typedef struct { int nvar; - char *svar; + char const *svar; } ts_lua_var_item; typedef struct { - char *content; + char const *content; char script[TS_LUA_MAX_SCRIPT_FNAME_LENGTH]; void *conf_vars[TS_LUA_MAX_CONFIG_VARS_COUNT]; @@ -172,11 +174,11 @@ typedef struct { do { \ if (ih->reader) { \ TSIOBufferReaderFree(ih->reader); \ - ih->reader = NULL; \ + ih->reader = nullptr; \ } \ if (ih->buffer) { \ TSIOBufferDestroy(ih->buffer); \ - ih->buffer = NULL; \ + ih->buffer = nullptr; \ } \ } while (0) diff --git a/plugins/lua/ts_lua_constant.c b/plugins/lua/ts_lua_constant.cc similarity index 97% rename from plugins/lua/ts_lua_constant.c rename to plugins/lua/ts_lua_constant.cc index de5ebfce6c6..69a33411afb 100644 --- a/plugins/lua/ts_lua_constant.c +++ b/plugins/lua/ts_lua_constant.cc @@ -18,7 +18,10 @@ #include #include + +extern "C" { #include "lua.h" +} // extern "C" static void ts_lua_inject_number_variables(lua_State *L); diff --git a/plugins/lua/ts_lua_context.c b/plugins/lua/ts_lua_context.cc similarity index 100% rename from plugins/lua/ts_lua_context.c rename to plugins/lua/ts_lua_context.cc diff --git a/plugins/lua/ts_lua_coroutine.c b/plugins/lua/ts_lua_coroutine.cc similarity index 97% rename from plugins/lua/ts_lua_coroutine.c rename to plugins/lua/ts_lua_coroutine.cc index f99b4daabac..d7d467fc727 100644 --- a/plugins/lua/ts_lua_coroutine.c +++ b/plugins/lua/ts_lua_coroutine.cc @@ -55,8 +55,8 @@ ts_lua_async_create_item(TSCont cont, async_clean func, void *d, ts_lua_cont_inf ts_lua_async_item *ai; ai = (ts_lua_async_item *)TSmalloc(sizeof(ts_lua_async_item)); - if (ai == NULL) { - return NULL; + if (ai == nullptr) { + return nullptr; } ai->cinfo = ci; diff --git a/plugins/lua/ts_lua_coroutine.h b/plugins/lua/ts_lua_coroutine.h index 7b86b34a38b..4fe069af65b 100644 --- a/plugins/lua/ts_lua_coroutine.h +++ b/plugins/lua/ts_lua_coroutine.h @@ -20,9 +20,12 @@ #include +extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" +} // extern "C" + #include struct async_item; diff --git a/plugins/lua/ts_lua_crypto.c b/plugins/lua/ts_lua_crypto.cc similarity index 94% rename from plugins/lua/ts_lua_crypto.c rename to plugins/lua/ts_lua_crypto.cc index 279c57f8e08..5e66c0136e8 100644 --- a/plugins/lua/ts_lua_crypto.c +++ b/plugins/lua/ts_lua_crypto.cc @@ -323,12 +323,12 @@ ts_lua_hmac_md5(lua_State *L) src = (u_char *)luaL_checklstring(L, 2, &slen); } - key_bin = TSmalloc((int)((klen / 2) + 1)); - if (key_bin == NULL) { + key_bin = tsapi::malloc((klen / 2) + 1); + if (key_bin == nullptr) { TSDebug(TS_LUA_DEBUG_TAG, "unable to allocate buffer for hex to binary conversion"); return luaL_error(L, "unable to allocate buffer for hex to binary conversion"); } - if (ts_lua_hex_to_bin(key_bin, key, klen) == NULL) { + if (ts_lua_hex_to_bin(key_bin, key, klen) == nullptr) { TSfree(key_bin); return luaL_error(L, "hex to binary conversion failed"); } @@ -378,12 +378,12 @@ ts_lua_hmac_sha1(lua_State *L) src = (u_char *)luaL_checklstring(L, 2, &slen); } - key_bin = TSmalloc((int)((klen / 2) + 1)); - if (key_bin == NULL) { + key_bin = tsapi::malloc((klen / 2) + 1); + if (key_bin == nullptr) { TSDebug(TS_LUA_DEBUG_TAG, "unable to allocate buffer for hex to binary conversion"); return luaL_error(L, "unable to allocate buffer for hex to binary conversion"); } - if (ts_lua_hex_to_bin(key_bin, key, klen) == NULL) { + if (ts_lua_hex_to_bin(key_bin, key, klen) == nullptr) { TSfree(key_bin); return luaL_error(L, "hex to binary conversion failed"); } @@ -433,12 +433,12 @@ ts_lua_hmac_sha256(lua_State *L) src = (u_char *)luaL_checklstring(L, 2, &slen); } - key_bin = TSmalloc((int)((klen / 2) + 1)); - if (key_bin == NULL) { + key_bin = tsapi::malloc((klen / 2) + 1); + if (key_bin == nullptr) { TSDebug(TS_LUA_DEBUG_TAG, "unable to allocate buffer for hex to binary conversion"); return luaL_error(L, "unable to allocate buffer for hex to binary conversion"); } - if (ts_lua_hex_to_bin(key_bin, key, klen) == NULL) { + if (ts_lua_hex_to_bin(key_bin, key, klen) == nullptr) { TSfree(key_bin); return luaL_error(L, "hex to binary conversion failed"); } @@ -475,7 +475,7 @@ ts_lua_base64_encode(lua_State *L) } dlen = TS_LUA_MAX_STR_LENGTH; - dst = lua_newuserdata(L, dlen); + dst = static_cast(lua_newuserdata(L, dlen)); if (TS_SUCCESS == TSBase64Encode((const char *)src, slen, (char *)dst, dlen, &length)) { lua_pushlstring(L, (char *)dst, length); @@ -507,7 +507,7 @@ ts_lua_base64_decode(lua_State *L) } dlen = TS_LUA_MAX_STR_LENGTH; - dst = lua_newuserdata(L, dlen); + dst = static_cast(lua_newuserdata(L, dlen)); if (TS_SUCCESS == TSBase64Decode((const char *)src, slen, (unsigned char *)dst, dlen, &length)) { lua_pushlstring(L, (char *)dst, length); @@ -540,9 +540,9 @@ ts_lua_escape_uri(lua_State *L) } dlen = TS_LUA_MAX_STR_LENGTH; - dst = lua_newuserdata(L, dlen); + dst = static_cast(lua_newuserdata(L, dlen)); - if (TS_SUCCESS == TSStringPercentEncode((const char *)src, len, (char *)dst, dlen, &length, NULL)) { + if (TS_SUCCESS == TSStringPercentEncode((const char *)src, len, (char *)dst, dlen, &length, nullptr)) { lua_pushlstring(L, (char *)dst, length); return 1; } else { @@ -574,7 +574,7 @@ ts_lua_unescape_uri(lua_State *L) /* the unescaped string can not be larger, but need to account for terminating null. */ dlen = len + 1; - dst = lua_newuserdata(L, dlen); + dst = static_cast(lua_newuserdata(L, dlen)); if (TS_SUCCESS == TSStringPercentDecode((const char *)src, len, (char *)dst, dlen, &length)) { lua_pushlstring(L, (char *)dst, length); diff --git a/plugins/lua/ts_lua_fetch.c b/plugins/lua/ts_lua_fetch.cc similarity index 95% rename from plugins/lua/ts_lua_fetch.c rename to plugins/lua/ts_lua_fetch.cc index e3023ea476b..60528efd59b 100644 --- a/plugins/lua/ts_lua_fetch.c +++ b/plugins/lua/ts_lua_fetch.cc @@ -59,7 +59,7 @@ ts_lua_fetch(lua_State *L) ts_lua_fetch_multi_info *fmi; ci = ts_lua_get_cont_info(L); - if (ci == NULL) { + if (ci == nullptr) { return 0; } @@ -123,7 +123,7 @@ ts_lua_fetch_multi(lua_State *L) ts_lua_fetch_multi_info *fmi; ci = ts_lua_get_cont_info(L); - if (ci == NULL) { + if (ci == nullptr) { return 0; } @@ -231,7 +231,7 @@ ts_lua_fetch_one_item(lua_State *L, const char *url, size_t url_len, ts_lua_fetc } /* body */ - body = NULL; + body = nullptr; body_len = 0; if (tb) { @@ -349,13 +349,13 @@ ts_lua_fetch_one_item(lua_State *L, const char *url, size_t url_len, ts_lua_fetc /* Host */ if (ht == 0) { - ptr = memchr(url, ':', url_len); + ptr = static_cast(memchr(url, ':', url_len)); if (ptr) { host = ptr + 3; left = url_len - (host - url); - ptr = memchr(host, '/', left); + ptr = static_cast(memchr(host, '/', left)); if (ptr) { host_len = ptr - host; @@ -400,7 +400,7 @@ ts_lua_fetch_handler(TSCont contp, TSEvent ev, void *edata ATS_UNUSED) ts_lua_fetch_multi_info *fmi; event = (int)ev; - fi = TSContDataGet(contp); + fi = static_cast(TSContDataGet(contp)); fmi = fi->fmi; switch (event) { @@ -430,7 +430,7 @@ ts_lua_fetch_handler(TSCont contp, TSEvent ev, void *edata ATS_UNUSED) } if (fmi && (fi->over || fi->failed)) { - TSContCall(fmi->contp, TS_LUA_EVENT_FETCH_OVER, fi); // error exist + TSContCall(fmi->contp, TSEvent(TS_LUA_EVENT_FETCH_OVER), fi); // error exist ts_lua_destroy_fetch_multi_info(fmi); } @@ -519,7 +519,7 @@ ts_lua_fetch_multi_handler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) ts_lua_fetch_info *fi; ts_lua_fetch_multi_info *fmi; - ai = TSContDataGet(contp); + ai = static_cast(TSContDataGet(contp)); ci = ai->cinfo; fmi = (ts_lua_fetch_multi_info *)ai->data; @@ -539,7 +539,7 @@ ts_lua_fetch_multi_handler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) if (fmi->total == 1 && !fmi->multi) { ts_lua_fill_one_result(L, fi); - TSContCall(ci->contp, TS_LUA_EVENT_COROUTINE_CONT, (void *)1); + TSContCall(ci->contp, TSEvent(TS_LUA_EVENT_COROUTINE_CONT), reinterpret_cast(1)); } else { lua_newtable(L); @@ -549,7 +549,7 @@ ts_lua_fetch_multi_handler(TSCont contp, TSEvent event ATS_UNUSED, void *edata) lua_rawseti(L, -2, i); } - TSContCall(ci->contp, TS_LUA_EVENT_COROUTINE_CONT, (void *)1); + TSContCall(ci->contp, TSEvent(TS_LUA_EVENT_COROUTINE_CONT), reinterpret_cast(1)); } TSMutexUnlock(lmutex); @@ -562,7 +562,7 @@ ts_lua_destroy_fetch_multi_info(ts_lua_fetch_multi_info *fmi) int i; ts_lua_fetch_info *fi; - if (fmi == NULL) { + if (fmi == nullptr) { return; } @@ -597,9 +597,9 @@ ts_lua_fetch_multi_cleanup(ts_lua_async_item *ai) } if (ai->data) { - ai->data = NULL; + ai->data = nullptr; TSContDestroy(ai->contp); - ai->contp = NULL; + ai->contp = nullptr; } ai->deleted = 1; diff --git a/plugins/lua/ts_lua_hook.c b/plugins/lua/ts_lua_hook.cc similarity index 86% rename from plugins/lua/ts_lua_hook.c rename to plugins/lua/ts_lua_hook.cc index e245cbb8465..b408ea499c1 100644 --- a/plugins/lua/ts_lua_hook.c +++ b/plugins/lua/ts_lua_hook.cc @@ -40,23 +40,23 @@ typedef enum { TS_LUA_HOOK_LAST } TSLuaHookID; -char *ts_lua_hook_id_string[] = {"TS_LUA_HOOK_DUMMY", - "TS_LUA_HOOK_CACHE_LOOKUP_COMPLETE", - "TS_LUA_HOOK_SEND_REQUEST_HDR", - "TS_LUA_HOOK_READ_RESPONSE_HDR", - "TS_LUA_HOOK_SEND_RESPONSE_HDR", - "TS_LUA_HOOK_READ_REQUEST_HDR", - "TS_LUA_HOOK_TXN_START", - "TS_LUA_HOOK_PRE_REMAP", - "TS_LUA_HOOK_POST_REMAP", - "TS_LUA_HOOK_OS_DNS", - "TS_LUA_HOOK_READ_CACHE_HDR", - "TS_LUA_HOOK_TXN_CLOSE", - "TS_LUA_REQUEST_TRANSFORM", - "TS_LUA_RESPONSE_TRANSFORM", - "TS_LUA_REQUEST_CLIENT", - "TS_LUA_RESPONSE_CLIENT", - "TS_LUA_HOOK_LAST"}; +char const *ts_lua_hook_id_string[] = {"TS_LUA_HOOK_DUMMY", + "TS_LUA_HOOK_CACHE_LOOKUP_COMPLETE", + "TS_LUA_HOOK_SEND_REQUEST_HDR", + "TS_LUA_HOOK_READ_RESPONSE_HDR", + "TS_LUA_HOOK_SEND_RESPONSE_HDR", + "TS_LUA_HOOK_READ_REQUEST_HDR", + "TS_LUA_HOOK_TXN_START", + "TS_LUA_HOOK_PRE_REMAP", + "TS_LUA_HOOK_POST_REMAP", + "TS_LUA_HOOK_OS_DNS", + "TS_LUA_HOOK_READ_CACHE_HDR", + "TS_LUA_HOOK_TXN_CLOSE", + "TS_LUA_REQUEST_TRANSFORM", + "TS_LUA_RESPONSE_TRANSFORM", + "TS_LUA_REQUEST_CLIENT", + "TS_LUA_RESPONSE_CLIENT", + "TS_LUA_HOOK_LAST"}; static int ts_lua_add_hook(lua_State *L); static void ts_lua_inject_hook_variables(lua_State *L); diff --git a/plugins/lua/ts_lua_http.c b/plugins/lua/ts_lua_http.cc similarity index 97% rename from plugins/lua/ts_lua_http.c rename to plugins/lua/ts_lua_http.cc index c361b65d018..2b6a4960fb4 100644 --- a/plugins/lua/ts_lua_http.c +++ b/plugins/lua/ts_lua_http.cc @@ -332,7 +332,7 @@ ts_lua_http_set_retstatus(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); status = luaL_checkinteger(L, 1); - TSHttpTxnStatusSet(http_ctx->txnp, status); + TSHttpTxnStatusSet(http_ctx->txnp, TSHttpStatus(status)); return 0; } @@ -346,7 +346,7 @@ ts_lua_http_set_retbody(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); body = luaL_checklstring(L, 1, &body_len); - TSHttpTxnErrorBodySet(http_ctx->txnp, TSstrdup(body), body_len, NULL); // Defaults to text/html + TSHttpTxnErrorBodySet(http_ctx->txnp, TSstrdup(body), body_len, nullptr); // Defaults to text/html return 0; } @@ -363,11 +363,11 @@ ts_lua_http_set_resp(lua_State *L) n = lua_gettop(L); status = luaL_checkinteger(L, 1); - TSHttpTxnStatusSet(http_ctx->txnp, status); + TSHttpTxnStatusSet(http_ctx->txnp, TSHttpStatus(status)); if (n == 2) { body = luaL_checklstring(L, 2, &body_len); - TSHttpTxnErrorBodySet(http_ctx->txnp, TSstrdup(body), body_len, NULL); // Defaults to text/html + TSHttpTxnErrorBodySet(http_ctx->txnp, TSstrdup(body), body_len, nullptr); // Defaults to text/html } return 0; @@ -411,7 +411,7 @@ static int ts_lua_http_get_cache_lookup_url(lua_State *L) { TSMLoc url = TS_NULL_MLOC; - char *str = NULL; + char *str = nullptr; int len; ts_lua_http_ctx *http_ctx; @@ -437,7 +437,7 @@ ts_lua_http_get_cache_lookup_url(lua_State *L) TSHandleMLocRelease(http_ctx->client_request_bufp, TS_NULL_MLOC, url); } - if (str != NULL) { + if (str != nullptr) { TSfree(str); } @@ -496,7 +496,7 @@ ts_lua_http_redo_cache_lookup(lua_State *L) static int ts_lua_http_get_parent_proxy(lua_State *L) { - const char *hostname = NULL; + const char *hostname = nullptr; int port = 0; ts_lua_http_ctx *http_ctx; @@ -504,7 +504,7 @@ ts_lua_http_get_parent_proxy(lua_State *L) TSHttpTxnParentProxyGet(http_ctx->txnp, &hostname, &port); - if (hostname == NULL) { + if (hostname == nullptr) { lua_pushnil(L); } else { lua_pushstring(L, hostname); @@ -544,7 +544,7 @@ static int ts_lua_http_get_parent_selection_url(lua_State *L) { TSMLoc url = TS_NULL_MLOC; - char *str = NULL; + char *str = nullptr; int len; ts_lua_http_ctx *http_ctx; @@ -570,7 +570,7 @@ ts_lua_http_get_parent_selection_url(lua_State *L) TSHandleMLocRelease(http_ctx->client_request_bufp, TS_NULL_MLOC, url); } - if (str != NULL) { + if (str != nullptr) { TSfree(str); } @@ -884,7 +884,7 @@ static int ts_lua_http_get_remap_from_url(lua_State *L) { TSMLoc url = TS_NULL_MLOC; - char *str = NULL; + char *str = nullptr; int len; ts_lua_http_ctx *http_ctx; @@ -895,12 +895,12 @@ ts_lua_http_get_remap_from_url(lua_State *L) goto done; } - str = TSUrlStringGet(NULL, url, &len); + str = TSUrlStringGet(nullptr, url, &len); lua_pushlstring(L, str, len >= TS_LUA_MAX_URL_LENGTH ? TS_LUA_MAX_URL_LENGTH - 1 : len); done: - if (str != NULL) { + if (str != nullptr) { TSfree(str); } @@ -911,7 +911,7 @@ static int ts_lua_http_get_remap_to_url(lua_State *L) { TSMLoc url = TS_NULL_MLOC; - char *str = NULL; + char *str = nullptr; int len; ts_lua_http_ctx *http_ctx; @@ -922,12 +922,12 @@ ts_lua_http_get_remap_to_url(lua_State *L) goto done; } - str = TSUrlStringGet(NULL, url, &len); + str = TSUrlStringGet(nullptr, url, &len); lua_pushlstring(L, str, len >= TS_LUA_MAX_URL_LENGTH ? TS_LUA_MAX_URL_LENGTH - 1 : len); done: - if (str != NULL) { + if (str != nullptr) { TSfree(str); } @@ -974,7 +974,7 @@ ts_lua_http_resp_transform_get_upstream_bytes(lua_State *L) ts_lua_http_transform_ctx *transform_ctx; transform_ctx = ts_lua_get_http_transform_ctx(L); - if (transform_ctx == NULL) { + if (transform_ctx == nullptr) { TSError("[ts_lua][%s] missing transform_ctx", __FUNCTION__); return 0; } @@ -990,7 +990,7 @@ ts_lua_http_resp_transform_get_upstream_watermark_bytes(lua_State *L) ts_lua_http_transform_ctx *transform_ctx; transform_ctx = ts_lua_get_http_transform_ctx(L); - if (transform_ctx == NULL) { + if (transform_ctx == nullptr) { TSError("[ts_lua][%s] missing transform_ctx", __FUNCTION__); return 0; } @@ -1007,7 +1007,7 @@ ts_lua_http_resp_transform_set_upstream_watermark_bytes(lua_State *L) ts_lua_http_transform_ctx *transform_ctx; transform_ctx = ts_lua_get_http_transform_ctx(L); - if (transform_ctx == NULL) { + if (transform_ctx == nullptr) { TSError("[ts_lua][%s] missing transform_ctx", __FUNCTION__); return 0; } @@ -1026,7 +1026,7 @@ ts_lua_http_resp_transform_set_downstream_bytes(lua_State *L) ts_lua_http_transform_ctx *transform_ctx; transform_ctx = ts_lua_get_http_transform_ctx(L); - if (transform_ctx == NULL) { + if (transform_ctx == nullptr) { TSError("[ts_lua][%s] missing transform_ctx", __FUNCTION__); return 0; } diff --git a/plugins/lua/ts_lua_http_cntl.c b/plugins/lua/ts_lua_http_cntl.cc similarity index 94% rename from plugins/lua/ts_lua_http_cntl.c rename to plugins/lua/ts_lua_http_cntl.cc index c30bb2718ea..13965ca0ed3 100644 --- a/plugins/lua/ts_lua_http_cntl.c +++ b/plugins/lua/ts_lua_http_cntl.cc @@ -74,7 +74,7 @@ ts_lua_http_cntl_set(lua_State *L) cntl_type = luaL_checkinteger(L, 1); value = luaL_checkinteger(L, 2); - TSHttpTxnCntlSet(http_ctx->txnp, cntl_type, value ? true : false); + TSHttpTxnCntlSet(http_ctx->txnp, TSHttpCntlType(cntl_type), value ? true : false); return 0; } @@ -90,7 +90,7 @@ ts_lua_http_cntl_get(lua_State *L) cntl_type = luaL_checkinteger(L, 1); - value = (int64_t)TSHttpTxnCntlGet(http_ctx->txnp, cntl_type); + value = int64_t(TSHttpTxnCntlGet(http_ctx->txnp, TSHttpCntlType(cntl_type))); lua_pushnumber(L, value); diff --git a/plugins/lua/ts_lua_http_config.c b/plugins/lua/ts_lua_http_config.cc similarity index 98% rename from plugins/lua/ts_lua_http_config.c rename to plugins/lua/ts_lua_http_config.cc index ed95eb8f28d..744f7198bfb 100644 --- a/plugins/lua/ts_lua_http_config.c +++ b/plugins/lua/ts_lua_http_config.cc @@ -389,7 +389,7 @@ ts_lua_http_config_int_set(lua_State *L) conf = luaL_checkinteger(L, 1); value = luaL_checkinteger(L, 2); - TSHttpTxnConfigIntSet(http_ctx->txnp, conf, value); + TSHttpTxnConfigIntSet(http_ctx->txnp, TSOverridableConfigKey(conf), value); return 0; } @@ -405,7 +405,7 @@ ts_lua_http_config_int_get(lua_State *L) conf = luaL_checkinteger(L, 1); - TSHttpTxnConfigIntGet(http_ctx->txnp, conf, &value); + TSHttpTxnConfigIntGet(http_ctx->txnp, TSOverridableConfigKey(conf), &value); lua_pushnumber(L, value); @@ -424,7 +424,7 @@ ts_lua_http_config_float_set(lua_State *L) conf = luaL_checkinteger(L, 1); value = luaL_checknumber(L, 2); - TSHttpTxnConfigFloatSet(http_ctx->txnp, conf, value); + TSHttpTxnConfigFloatSet(http_ctx->txnp, TSOverridableConfigKey(conf), value); return 0; } @@ -440,7 +440,7 @@ ts_lua_http_config_float_get(lua_State *L) conf = luaL_checkinteger(L, 1); - TSHttpTxnConfigFloatGet(http_ctx->txnp, conf, &value); + TSHttpTxnConfigFloatGet(http_ctx->txnp, TSOverridableConfigKey(conf), &value); lua_pushnumber(L, value); @@ -460,7 +460,7 @@ ts_lua_http_config_string_set(lua_State *L) conf = luaL_checkinteger(L, 1); value = luaL_checklstring(L, 2, &value_len); - TSHttpTxnConfigStringSet(http_ctx->txnp, conf, value, value_len); + TSHttpTxnConfigStringSet(http_ctx->txnp, TSOverridableConfigKey(conf), value, value_len); return 0; } @@ -477,7 +477,7 @@ ts_lua_http_config_string_get(lua_State *L) conf = luaL_checkinteger(L, 1); - TSHttpTxnConfigStringGet(http_ctx->txnp, conf, &value, &value_len); + TSHttpTxnConfigStringGet(http_ctx->txnp, TSOverridableConfigKey(conf), &value, &value_len); lua_pushlstring(L, value, value_len); diff --git a/plugins/lua/ts_lua_http_intercept.c b/plugins/lua/ts_lua_http_intercept.cc similarity index 97% rename from plugins/lua/ts_lua_http_intercept.c rename to plugins/lua/ts_lua_http_intercept.cc index af867229962..8e5f758f8f7 100644 --- a/plugins/lua/ts_lua_http_intercept.c +++ b/plugins/lua/ts_lua_http_intercept.cc @@ -214,7 +214,7 @@ ts_lua_http_intercept_handler(TSCont contp, TSEvent event, void *edata) ts_lua_http_intercept_ctx *ictx; ictx = (ts_lua_http_intercept_ctx *)TSContDataGet(contp); - mtxp = NULL; + mtxp = nullptr; if (edata == ictx->input.vio) { ret = ts_lua_http_intercept_process_read(event, ictx); @@ -354,7 +354,7 @@ ts_lua_say(lua_State *L) ts_lua_http_intercept_ctx *ictx; ictx = ts_lua_get_http_intercept_ctx(L); - if (ictx == NULL) { + if (ictx == nullptr) { TSError("[ts_lua][%s] missing ictx", __FUNCTION__); return 0; } @@ -376,7 +376,7 @@ ts_lua_flush(lua_State *L) ts_lua_http_intercept_ctx *ictx; ictx = ts_lua_get_http_intercept_ctx(L); - if (ictx == NULL) { + if (ictx == nullptr) { TSError("[ts_lua][%s] missing ictx", __FUNCTION__); return 0; } @@ -418,14 +418,14 @@ ts_lua_flush_wakeup_handler(TSCont contp, TSEvent event ATS_UNUSED, void *edata ts_lua_async_item *ai; ts_lua_cont_info *ci; - ai = TSContDataGet(contp); + ai = static_cast(TSContDataGet(contp)); ci = ai->cinfo; - ai->data = NULL; + ai->data = nullptr; ts_lua_flush_cleanup(ai); - TSContCall(ci->contp, TS_LUA_EVENT_COROUTINE_CONT, 0); + TSContCall(ci->contp, TSEvent(TS_LUA_EVENT_COROUTINE_CONT), 0); return 0; } @@ -439,7 +439,7 @@ ts_lua_flush_cleanup(ts_lua_async_item *ai) if (ai->data) { TSActionCancel((TSAction)ai->data); - ai->data = NULL; + ai->data = nullptr; } TSContDestroy(ai->contp); diff --git a/plugins/lua/ts_lua_http_milestone.c b/plugins/lua/ts_lua_http_milestone.cc similarity index 98% rename from plugins/lua/ts_lua_http_milestone.c rename to plugins/lua/ts_lua_http_milestone.cc index 6d826ea7511..730b13651da 100644 --- a/plugins/lua/ts_lua_http_milestone.c +++ b/plugins/lua/ts_lua_http_milestone.cc @@ -107,7 +107,7 @@ ts_lua_http_milestone_get(lua_State *L) milestone_type = luaL_checkinteger(L, 1); if (TS_SUCCESS == TSHttpTxnMilestoneGet(http_ctx->txnp, TS_MILESTONE_SM_START, &epoch)) { - if (TS_SUCCESS == TSHttpTxnMilestoneGet(http_ctx->txnp, milestone_type, &value)) { + if (TS_SUCCESS == TSHttpTxnMilestoneGet(http_ctx->txnp, TSMilestonesType(milestone_type), &value)) { lua_pushnumber(L, (double)(value - epoch) / 1000000000); return 1; } diff --git a/plugins/lua/ts_lua_http_txn_info.c b/plugins/lua/ts_lua_http_txn_info.cc similarity index 98% rename from plugins/lua/ts_lua_http_txn_info.c rename to plugins/lua/ts_lua_http_txn_info.cc index 3f8bd8037e7..a128bbd5cc4 100644 --- a/plugins/lua/ts_lua_http_txn_info.c +++ b/plugins/lua/ts_lua_http_txn_info.cc @@ -65,7 +65,7 @@ ts_lua_txn_info_get(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - type = luaL_checkinteger(L, 1); + type = TSHttpTxnInfoKey(luaL_checkinteger(L, 1)); if (TS_SUCCESS == TSHttpTxnInfoIntGet(http_ctx->txnp, type, &value)) { lua_pushnumber(L, value); diff --git a/plugins/lua/ts_lua_io.c b/plugins/lua/ts_lua_io.cc similarity index 100% rename from plugins/lua/ts_lua_io.c rename to plugins/lua/ts_lua_io.cc diff --git a/plugins/lua/ts_lua_log.c b/plugins/lua/ts_lua_log.cc similarity index 98% rename from plugins/lua/ts_lua_log.c rename to plugins/lua/ts_lua_log.cc index f2db53a0668..ceeaf644cfc 100644 --- a/plugins/lua/ts_lua_log.c +++ b/plugins/lua/ts_lua_log.cc @@ -88,7 +88,7 @@ ts_lua_log_object_write(lua_State *L) text = luaL_checklstring(L, 1, &text_len); if (log) { - TSTextLogObjectWrite(log, (char *)text, NULL); + TSTextLogObjectWrite(log, (char *)text, nullptr); } else { TSError("[ts_lua][%s] log object does not exist for write", __FUNCTION__); } diff --git a/plugins/lua/ts_lua_mgmt.c b/plugins/lua/ts_lua_mgmt.cc similarity index 100% rename from plugins/lua/ts_lua_mgmt.c rename to plugins/lua/ts_lua_mgmt.cc diff --git a/plugins/lua/ts_lua_misc.c b/plugins/lua/ts_lua_misc.cc similarity index 95% rename from plugins/lua/ts_lua_misc.c rename to plugins/lua/ts_lua_misc.cc index f8848f04585..411cba53f4a 100644 --- a/plugins/lua/ts_lua_misc.c +++ b/plugins/lua/ts_lua_misc.cc @@ -303,7 +303,7 @@ ts_lua_schedule(lua_State *L) ts_lua_cont_info *nci; ci = ts_lua_get_cont_info(L); - if (ci == NULL) { + if (ci == nullptr) { return 0; } @@ -335,7 +335,7 @@ ts_lua_schedule(lua_State *L) nci->contp = contp; nci->mutex = ci->mutex; - TSContScheduleOnPool(contp, sec * 1000, entry); + TSContScheduleOnPool(contp, sec * 1000, TSThreadPool(entry)); return 0; } @@ -401,7 +401,7 @@ ts_lua_sleep(lua_State *L) ts_lua_cont_info *ci; ci = ts_lua_get_cont_info(L); - if (ci == NULL) { + if (ci == nullptr) { return 0; } @@ -425,13 +425,13 @@ ts_lua_sleep_handler(TSCont contp, TSEvent event ATS_UNUSED, void *edata ATS_UNU ts_lua_async_item *ai; ts_lua_cont_info *ci; - ai = TSContDataGet(contp); + ai = static_cast(TSContDataGet(contp)); ci = ai->cinfo; - ai->data = NULL; + ai->data = nullptr; ts_lua_sleep_cleanup(ai); - TSContCall(ci->contp, TS_LUA_EVENT_COROUTINE_CONT, 0); + TSContCall(ci->contp, TSEvent(TS_LUA_EVENT_COROUTINE_CONT), 0); return 0; } @@ -441,7 +441,7 @@ ts_lua_sleep_cleanup(ts_lua_async_item *ai) { if (ai->data) { TSActionCancel((TSAction)ai->data); - ai->data = NULL; + ai->data = nullptr; } TSContDestroy(ai->contp); @@ -461,7 +461,7 @@ ts_lua_host_lookup(lua_State *L) ts_lua_cont_info *ci; ci = ts_lua_get_cont_info(L); - if (ci == NULL) { + if (ci == nullptr) { return 0; } @@ -473,7 +473,7 @@ ts_lua_host_lookup(lua_State *L) host = luaL_checklstring(L, 1, &host_len); contp = TSContCreate(ts_lua_host_lookup_handler, ci->mutex); - ai = ts_lua_async_create_item(contp, ts_lua_host_lookup_cleanup, NULL, ci); + ai = ts_lua_async_create_item(contp, ts_lua_host_lookup_cleanup, nullptr, ci); TSContDataSet(contp, ai); action = TSHostLookup(contp, host, host_len); @@ -495,20 +495,20 @@ ts_lua_host_lookup_handler(TSCont contp, TSEvent event, void *edata) ts_lua_coroutine *crt; unsigned int resume; - ai = TSContDataGet(contp); + ai = static_cast(TSContDataGet(contp)); ci = ai->cinfo; crt = &ci->routine; L = crt->lua; // find out if need to resume luaVM before async item cleanup - if (ai->data != NULL) { + if (ai->data != nullptr) { resume = 1; } else { resume = 0; } // async item cleanup - ai->data = NULL; + ai->data = nullptr; ts_lua_host_lookup_cleanup(ai); if (event != TS_EVENT_HOST_LOOKUP) { @@ -530,7 +530,7 @@ ts_lua_host_lookup_handler(TSCont contp, TSEvent event, void *edata) } if (resume == 1) { - TSContCall(ci->contp, TS_LUA_EVENT_COROUTINE_CONT, (void *)1); + TSContCall(ci->contp, TSEvent(TS_LUA_EVENT_COROUTINE_CONT), (void *)1); } return 0; @@ -541,7 +541,7 @@ ts_lua_host_lookup_cleanup(ts_lua_async_item *ai) { if (ai->data) { TSActionCancel((TSAction)ai->data); - ai->data = NULL; + ai->data = nullptr; } TSContDestroy(ai->contp); diff --git a/plugins/lua/ts_lua_package.c b/plugins/lua/ts_lua_package.cc similarity index 97% rename from plugins/lua/ts_lua_package.c rename to plugins/lua/ts_lua_package.cc index 1ea6a874c78..a16a781372b 100644 --- a/plugins/lua/ts_lua_package.c +++ b/plugins/lua/ts_lua_package.cc @@ -68,7 +68,7 @@ ts_lua_add_package_path(lua_State *L) ts_lua_package_path *elt; conf = ts_lua_get_instance_conf(L); - if (conf == NULL) { + if (conf == nullptr) { return luaL_error(L, "can't get the instance conf"); } @@ -79,7 +79,7 @@ ts_lua_add_package_path(lua_State *L) n = 0; while (ptr < end) { - hit = memchr(ptr, ';', end - ptr); + hit = static_cast(memchr(ptr, ';', end - ptr)); if (hit) { item_len = hit - ptr; @@ -214,7 +214,7 @@ ts_lua_add_package_cpath(lua_State *L) ts_lua_package_path *elt; conf = ts_lua_get_instance_conf(L); - if (conf == NULL) { + if (conf == nullptr) { return luaL_error(L, "can't get the instance conf"); } @@ -225,7 +225,7 @@ ts_lua_add_package_cpath(lua_State *L) n = 0; while (ptr < end) { - hit = memchr(ptr, ';', end - ptr); + hit = static_cast(memchr(ptr, ';', end - ptr)); if (hit) { item_len = hit - ptr; diff --git a/plugins/lua/ts_lua_remap.c b/plugins/lua/ts_lua_remap.cc similarity index 95% rename from plugins/lua/ts_lua_remap.c rename to plugins/lua/ts_lua_remap.cc index b53b03a79d2..58d65546f05 100644 --- a/plugins/lua/ts_lua_remap.c +++ b/plugins/lua/ts_lua_remap.cc @@ -107,7 +107,7 @@ ts_lua_remap_get_from_url_host(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { host = TSUrlHostGet(http_ctx->client_request_bufp, http_ctx->rri->mapFromUrl, &len); if (len == 0) { @@ -131,7 +131,7 @@ ts_lua_remap_get_from_url_port(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { port = TSUrlPortGet(http_ctx->client_request_bufp, http_ctx->rri->mapFromUrl); lua_pushnumber(L, port); @@ -152,7 +152,7 @@ ts_lua_remap_get_from_url_scheme(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { scheme = TSUrlSchemeGet(http_ctx->client_request_bufp, http_ctx->rri->mapFromUrl, &len); if (len == 0) { @@ -177,7 +177,7 @@ ts_lua_remap_get_from_uri(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { path = TSUrlPathGet(http_ctx->client_request_bufp, http_ctx->rri->mapFromUrl, &path_len); lua_pushlstring(L, "/", 1); @@ -200,7 +200,7 @@ ts_lua_remap_get_from_url(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { url = TSUrlStringGet(http_ctx->client_request_bufp, http_ctx->rri->mapFromUrl, &url_len); lua_pushlstring(L, url, url_len >= TS_LUA_MAX_URL_LENGTH ? TS_LUA_MAX_URL_LENGTH - 1 : url_len); @@ -223,7 +223,7 @@ ts_lua_remap_get_to_url_host(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { host = TSUrlHostGet(http_ctx->client_request_bufp, http_ctx->rri->mapToUrl, &len); if (len == 0) { @@ -247,7 +247,7 @@ ts_lua_remap_get_to_url_port(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { port = TSUrlPortGet(http_ctx->client_request_bufp, http_ctx->rri->mapToUrl); lua_pushnumber(L, port); @@ -268,7 +268,7 @@ ts_lua_remap_get_to_url_scheme(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { scheme = TSUrlSchemeGet(http_ctx->client_request_bufp, http_ctx->rri->mapToUrl, &len); if (len == 0) { @@ -293,7 +293,7 @@ ts_lua_remap_get_to_uri(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { path = TSUrlPathGet(http_ctx->client_request_bufp, http_ctx->rri->mapToUrl, &path_len); lua_pushlstring(L, "/", 1); @@ -316,7 +316,7 @@ ts_lua_remap_get_to_url(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); - if (http_ctx->rri != NULL) { + if (http_ctx->rri != nullptr) { url = TSUrlStringGet(http_ctx->client_request_bufp, http_ctx->rri->mapToUrl, &url_len); lua_pushlstring(L, url, url_len >= TS_LUA_MAX_URL_LENGTH ? TS_LUA_MAX_URL_LENGTH - 1 : url_len); diff --git a/plugins/lua/ts_lua_server_request.c b/plugins/lua/ts_lua_server_request.cc similarity index 99% rename from plugins/lua/ts_lua_server_request.c rename to plugins/lua/ts_lua_server_request.cc index 931e53fc643..3fdea9c30f4 100644 --- a/plugins/lua/ts_lua_server_request.c +++ b/plugins/lua/ts_lua_server_request.cc @@ -242,7 +242,7 @@ ts_lua_server_request_header_set(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); remove = 0; - val = NULL; + val = nullptr; /* we skip the first argument that is the table */ key = luaL_checklstring(L, 2, &key_len); @@ -674,9 +674,9 @@ ts_lua_server_request_get_url_host(lua_State *L) host = TSUrlHostGet(http_ctx->server_request_bufp, http_ctx->server_request_url, &len); if (len == 0) { - char *key = "Host"; - char *l_key = "host"; - int key_len = 4; + char const *key = "Host"; + char const *l_key = "host"; + int key_len = 4; TSMLoc field_loc; @@ -813,7 +813,7 @@ ts_lua_server_request_server_addr_get_ip(lua_State *L) server_ip = TSHttpTxnServerAddrGet(http_ctx->txnp); - if (server_ip == NULL) { + if (server_ip == nullptr) { lua_pushnil(L); } else { @@ -840,7 +840,7 @@ ts_lua_server_request_server_addr_get_port(lua_State *L) server_ip = TSHttpTxnServerAddrGet(http_ctx->txnp); - if (server_ip == NULL) { + if (server_ip == nullptr) { lua_pushnil(L); } else { @@ -867,7 +867,7 @@ ts_lua_server_request_server_addr_get_outgoing_port(lua_State *L) outgoing_addr = TSHttpTxnOutgoingAddrGet(http_ctx->txnp); - if (outgoing_addr == NULL) { + if (outgoing_addr == nullptr) { lua_pushnil(L); } else { @@ -896,7 +896,7 @@ ts_lua_server_request_server_addr_get_addr(lua_State *L) server_ip = TSHttpTxnServerAddrGet(http_ctx->txnp); - if (server_ip == NULL) { + if (server_ip == nullptr) { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); @@ -933,7 +933,7 @@ ts_lua_server_request_server_addr_get_nexthop_addr(lua_State *L) server_ip = TSHttpTxnNextHopAddrGet(http_ctx->txnp); - if (server_ip == NULL) { + if (server_ip == nullptr) { lua_pushnil(L); lua_pushnil(L); lua_pushnil(L); @@ -967,7 +967,7 @@ ts_lua_server_request_server_addr_get_nexthop_name(lua_State *L) name = TSHttpTxnNextHopNameGet(http_ctx->txnp); - if (name == NULL) { + if (name == nullptr) { lua_pushnil(L); } else { lua_pushstring(L, name); diff --git a/plugins/lua/ts_lua_server_response.c b/plugins/lua/ts_lua_server_response.cc similarity index 98% rename from plugins/lua/ts_lua_server_response.c rename to plugins/lua/ts_lua_server_response.cc index 2beb34476ea..629d4445d0c 100644 --- a/plugins/lua/ts_lua_server_response.c +++ b/plugins/lua/ts_lua_server_response.cc @@ -248,7 +248,7 @@ ts_lua_server_response_header_set(lua_State *L) GET_HTTP_CONTEXT(http_ctx, L); remove = 0; - val = NULL; + val = nullptr; /* we skip the first argument that is the table */ key = luaL_checklstring(L, 2, &key_len); @@ -386,12 +386,12 @@ ts_lua_server_response_set_status(lua_State *L) // NOLINTNEXTLINE status = luaL_checkint(L, 1); - reason = TSHttpHdrReasonLookup(status); + reason = TSHttpHdrReasonLookup(TSHttpStatus(status)); if (reason) { reason_len = strlen(reason); } - TSHttpHdrStatusSet(http_ctx->server_response_bufp, http_ctx->server_response_hdrp, status); + TSHttpHdrStatusSet(http_ctx->server_response_bufp, http_ctx->server_response_hdrp, TSHttpStatus(status)); TSHttpHdrReasonSet(http_ctx->server_response_bufp, http_ctx->server_response_hdrp, reason, reason_len); return 0; @@ -456,7 +456,7 @@ ts_lua_server_response_is_cacheable(lua_State *L) TS_LUA_CHECK_SERVER_RESPONSE_HDR(http_ctx); - lua_pushnumber(L, TSHttpTxnIsCacheable(http_ctx->txnp, NULL, http_ctx->server_response_bufp)); + lua_pushnumber(L, TSHttpTxnIsCacheable(http_ctx->txnp, nullptr, http_ctx->server_response_bufp)); return 1; } diff --git a/plugins/lua/ts_lua_stat.c b/plugins/lua/ts_lua_stat.cc similarity index 98% rename from plugins/lua/ts_lua_stat.c rename to plugins/lua/ts_lua_stat.cc index 8a2db6e8a75..25285b41cb4 100644 --- a/plugins/lua/ts_lua_stat.c +++ b/plugins/lua/ts_lua_stat.cc @@ -125,7 +125,7 @@ ts_lua_stat_create(lua_State *L) if (name && name_len) { if (TSStatFindName(name, &idp) == TS_ERROR) { - idp = TSStatCreate(name, type, persist, sync); + idp = TSStatCreate(name, TSRecordDataType(type), TSStatPersistence(persist), TSStatSync(sync)); } lua_newtable(L); diff --git a/plugins/lua/ts_lua_string.c b/plugins/lua/ts_lua_string.cc similarity index 97% rename from plugins/lua/ts_lua_string.c rename to plugins/lua/ts_lua_string.cc index 727b5a30b47..c01c5d99807 100644 --- a/plugins/lua/ts_lua_string.c +++ b/plugins/lua/ts_lua_string.cc @@ -52,7 +52,7 @@ ts_lua_hex_to_bin(u_char *dst, u_char *src, size_t len) { if (len % 2 != 0) { TSDebug(TS_LUA_DEBUG_TAG, "ts_lua_hex_to_bin(): not an even number of hex digits"); - return NULL; + return nullptr; } for (unsigned int x = 0; x < len; x += 2) { @@ -60,7 +60,7 @@ ts_lua_hex_to_bin(u_char *dst, u_char *src, size_t len) unsigned char b = hex_to_int(src[x + 1]); if (a == 255 || b == 255) { TSDebug(TS_LUA_DEBUG_TAG, "ts_lua_hex_to_bin(): failure in hex to binary conversion"); - return NULL; + return nullptr; } unsigned char result = (a << 4) + b; dst[x / 2] = result; diff --git a/plugins/lua/ts_lua_transform.c b/plugins/lua/ts_lua_transform.cc similarity index 98% rename from plugins/lua/ts_lua_transform.c rename to plugins/lua/ts_lua_transform.cc index 7f797952952..0532de668af 100644 --- a/plugins/lua/ts_lua_transform.c +++ b/plugins/lua/ts_lua_transform.cc @@ -48,7 +48,7 @@ ts_lua_client_entry(TSCont contp, TSEvent ev, void *edata) /* FALL THROUGH */ case TS_EVENT_VCONN_WRITE_READY: default: - ts_lua_client_handler(contp, transform_ctx, event, n); + ts_lua_client_handler(contp, transform_ctx, TSEvent(event), n); break; } @@ -148,7 +148,7 @@ ts_lua_client_handler(TSCont contp, ts_lua_http_transform_ctx *transform_ctx, TS do { if (event == TS_LUA_EVENT_COROUTINE_CONT) { - event = 0; + event = TS_EVENT_NONE; goto launch; } else { n = 2; @@ -274,7 +274,7 @@ ts_lua_transform_entry(TSCont contp, TSEvent ev, void *edata) /* FALL THROUGH */ case TS_EVENT_VCONN_WRITE_READY: default: - ts_lua_transform_handler(contp, transform_ctx, event, n); + ts_lua_transform_handler(contp, transform_ctx, TSEvent(event), n); break; } @@ -386,7 +386,7 @@ ts_lua_transform_handler(TSCont contp, ts_lua_http_transform_ctx *transform_ctx, do { if (event == TS_LUA_EVENT_COROUTINE_CONT) { - event = 0; + event = TS_EVENT_NONE; goto launch; } else { n = 2; @@ -441,7 +441,7 @@ ts_lua_transform_handler(TSCont contp, ts_lua_http_transform_ctx *transform_ctx, res = lua_tolstring(L, -2, &res_len); } else { // what hells code are you writing ? ret = 0; - res = NULL; + res = nullptr; res_len = 0; } break; @@ -449,7 +449,7 @@ ts_lua_transform_handler(TSCont contp, ts_lua_http_transform_ctx *transform_ctx, default: // coroutine failed TSError("[ts_lua][%s] lua_resume failed: %s", __FUNCTION__, lua_tostring(L, -1)); ret = 1; - res = NULL; + res = nullptr; res_len = 0; break; } diff --git a/plugins/lua/ts_lua_util.c b/plugins/lua/ts_lua_util.cc similarity index 93% rename from plugins/lua/ts_lua_util.c rename to plugins/lua/ts_lua_util.cc index e2cb68b89f8..7eacada39cf 100644 --- a/plugins/lua/ts_lua_util.c +++ b/plugins/lua/ts_lua_util.cc @@ -60,48 +60,48 @@ ts_lua_update_server_response_hdrp(ts_lua_http_ctx *http_ctx) void ts_lua_clear_http_ctx(ts_lua_http_ctx *http_ctx) { - if (http_ctx->rri == NULL) { - if (http_ctx->client_request_url != NULL) { + if (http_ctx->rri == nullptr) { + if (http_ctx->client_request_url != nullptr) { TSHandleMLocRelease(http_ctx->client_request_bufp, http_ctx->client_request_hdrp, http_ctx->client_request_url); - http_ctx->client_request_url = NULL; + http_ctx->client_request_url = nullptr; } - if (http_ctx->client_request_bufp != NULL) { + if (http_ctx->client_request_bufp != nullptr) { TSHandleMLocRelease(http_ctx->client_request_bufp, TS_NULL_MLOC, http_ctx->client_request_hdrp); - http_ctx->client_request_bufp = NULL; - http_ctx->client_request_hdrp = NULL; + http_ctx->client_request_bufp = nullptr; + http_ctx->client_request_hdrp = nullptr; } } - if (http_ctx->server_request_url != NULL) { + if (http_ctx->server_request_url != nullptr) { TSHandleMLocRelease(http_ctx->server_request_bufp, http_ctx->server_request_hdrp, http_ctx->server_request_url); - http_ctx->server_request_url = NULL; + http_ctx->server_request_url = nullptr; } - if (http_ctx->server_request_hdrp != NULL) { + if (http_ctx->server_request_hdrp != nullptr) { TSHandleMLocRelease(http_ctx->server_request_bufp, TS_NULL_MLOC, http_ctx->server_request_hdrp); - http_ctx->server_request_bufp = NULL; - http_ctx->server_request_hdrp = NULL; + http_ctx->server_request_bufp = nullptr; + http_ctx->server_request_hdrp = nullptr; } - if (http_ctx->server_response_bufp != NULL) { + if (http_ctx->server_response_bufp != nullptr) { TSHandleMLocRelease(http_ctx->server_response_bufp, TS_NULL_MLOC, http_ctx->server_response_hdrp); - http_ctx->server_response_bufp = NULL; - http_ctx->server_response_hdrp = NULL; + http_ctx->server_response_bufp = nullptr; + http_ctx->server_response_hdrp = nullptr; } - if (http_ctx->client_response_hdrp != NULL) { + if (http_ctx->client_response_hdrp != nullptr) { TSHandleMLocRelease(http_ctx->client_response_bufp, TS_NULL_MLOC, http_ctx->client_response_hdrp); - http_ctx->client_response_bufp = NULL; - http_ctx->client_response_hdrp = NULL; + http_ctx->client_response_bufp = nullptr; + http_ctx->client_response_hdrp = nullptr; } - if (http_ctx->cached_response_bufp != NULL) { + if (http_ctx->cached_response_bufp != nullptr) { TSMimeHdrDestroy(http_ctx->cached_response_bufp, http_ctx->cached_response_hdrp); TSHandleMLocRelease(http_ctx->cached_response_bufp, TS_NULL_MLOC, http_ctx->cached_response_hdrp); TSMBufferDestroy(http_ctx->cached_response_bufp); - http_ctx->cached_response_bufp = NULL; - http_ctx->cached_response_hdrp = NULL; + http_ctx->cached_response_bufp = nullptr; + http_ctx->cached_response_hdrp = nullptr; } } @@ -114,7 +114,7 @@ ts_lua_create_vm(ts_lua_main_ctx *arr, int n) for (i = 0; i < n; i++) { L = ts_lua_new_state(); - if (L == NULL) + if (L == nullptr) return -1; lua_pushvalue(L, LUA_GLOBALSINDEX); @@ -140,18 +140,18 @@ ts_lua_destroy_vm(ts_lua_main_ctx *arr, int n) L = arr[i].lua; if (L) { lua_close(L); - arr[i].lua = NULL; + arr[i].lua = nullptr; } mutexp = arr[i].mutexp; if (mutexp) { TSMutexDestroy(mutexp); - arr[i].mutexp = NULL; + arr[i].mutexp = nullptr; } stats = arr[i].stats; if (stats) { ts_lua_destroy_ctx_stats(stats); - arr[i].stats = NULL; + arr[i].stats = nullptr; } } @@ -165,8 +165,8 @@ ts_lua_new_state() L = luaL_newstate(); - if (L == NULL) { - return NULL; + if (L == nullptr) { + return nullptr; } luaL_openlibs(L); @@ -181,10 +181,8 @@ ts_lua_new_state() ts_lua_ctx_stats * ts_lua_create_ctx_stats() { - ts_lua_ctx_stats *stats = NULL; - - stats = TSmalloc(sizeof(ts_lua_ctx_stats)); - memset(stats, 0, sizeof(ts_lua_ctx_stats)); + auto stats = tsapi::malloc(); + memset(stats, 0, sizeof(*stats)); stats->mutexp = TSMutexCreate(); @@ -196,7 +194,7 @@ ts_lua_destroy_ctx_stats(ts_lua_ctx_stats *stats) { if (stats) { TSMutexDestroy(stats->mutexp); - stats->mutexp = NULL; + stats->mutexp = nullptr; TSfree(stats); } } @@ -205,7 +203,7 @@ ts_lua_instance_conf * ts_lua_script_registered(lua_State *L, char *script) { TSMgmtInt curr_time; - ts_lua_instance_conf *conf = NULL; + ts_lua_instance_conf *conf = nullptr; TSDebug(TS_LUA_DEBUG_TAG, "[%s] checking if script [%s] is registered", __FUNCTION__, script); @@ -220,7 +218,7 @@ ts_lua_script_registered(lua_State *L, char *script) if (lua_isnil(L, -1)) { TSDebug(TS_LUA_DEBUG_TAG, "[%s] failed to get script time for [%s]", __FUNCTION__, script); lua_pop(L, -1); - return NULL; + return nullptr; } else { int time = lua_tonumber(L, -1); lua_pop(L, -1); @@ -233,21 +231,21 @@ ts_lua_script_registered(lua_State *L, char *script) if (lua_isnil(L, -1)) { TSDebug(TS_LUA_DEBUG_TAG, "[%s] failed to get script ptr for [%s]", __FUNCTION__, script); lua_pop(L, -1); - return NULL; + return nullptr; } else { - conf = lua_touserdata(L, -1); + conf = static_cast(lua_touserdata(L, -1)); lua_pop(L, -1); return conf; } } else { TSDebug(TS_LUA_DEBUG_TAG, "[%s] script time not matching for [%s]", __FUNCTION__, script); - return NULL; + return nullptr; } } } else { TSError("[ts_lua][%s] failed to get node's reconfigure time while checking script registration", __FUNCTION__); - return NULL; + return nullptr; } } @@ -578,7 +576,7 @@ ts_lua_get_instance_conf(lua_State *L) lua_pushliteral(L, "__ts_instance_conf"); lua_rawget(L, LUA_GLOBALSINDEX); - conf = lua_touserdata(L, -1); + conf = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); // pop the conf out @@ -600,7 +598,7 @@ ts_lua_get_cont_info(lua_State *L) lua_pushliteral(L, "__ts_cont_info"); lua_rawget(L, LUA_GLOBALSINDEX); - ci = lua_touserdata(L, -1); + ci = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); // pop the coroutine out @@ -615,8 +613,8 @@ ts_lua_create_async_ctx(lua_State *L, ts_lua_cont_info *hci, int n) ts_lua_coroutine *crt; ts_lua_http_ctx *actx; - actx = TSmalloc(sizeof(ts_lua_http_ctx)); - memset(actx, 0, sizeof(ts_lua_http_ctx)); + actx = tsapi::malloc(); + memset(actx, 0, sizeof(*actx)); // create lua_thread l = lua_newthread(L); @@ -682,7 +680,7 @@ ts_lua_get_http_ctx(lua_State *L) lua_pushliteral(L, "__ts_http_ctx"); lua_rawget(L, LUA_GLOBALSINDEX); - ctx = lua_touserdata(L, -1); + ctx = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); // pop the ctx out @@ -699,8 +697,8 @@ ts_lua_create_http_ctx(ts_lua_main_ctx *main_ctx, ts_lua_instance_conf *conf) L = main_ctx->lua; - http_ctx = TSmalloc(sizeof(ts_lua_http_ctx)); - memset(http_ctx, 0, sizeof(ts_lua_http_ctx)); + http_ctx = tsapi::malloc(); + memset(http_ctx, 0, sizeof(*http_ctx)); // create coroutine for http_ctx crt = &http_ctx->cinfo.routine; @@ -750,7 +748,7 @@ ts_lua_destroy_http_ctx(ts_lua_http_ctx *http_ctx) ci = &http_ctx->cinfo; - if (http_ctx->rri == NULL) { + if (http_ctx->rri == nullptr) { if (http_ctx->client_request_url) { TSHandleMLocRelease(http_ctx->client_request_bufp, http_ctx->client_request_hdrp, http_ctx->client_request_url); } @@ -809,7 +807,7 @@ ts_lua_get_http_intercept_ctx(lua_State *L) lua_pushliteral(L, "__ts_http_intercept_ctx"); lua_rawget(L, LUA_GLOBALSINDEX); - ictx = lua_touserdata(L, -1); + ictx = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); // pop the ictx out @@ -827,8 +825,8 @@ ts_lua_create_http_intercept_ctx(lua_State *L, ts_lua_http_ctx *http_ctx, int n) hci = &http_ctx->cinfo; - ictx = TSmalloc(sizeof(ts_lua_http_intercept_ctx)); - memset(ictx, 0, sizeof(ts_lua_http_intercept_ctx)); + ictx = tsapi::malloc(); + memset(ictx, 0, sizeof(*ictx)); ictx->hctx = http_ctx; @@ -888,7 +886,7 @@ ts_lua_get_http_transform_ctx(lua_State *L) lua_pushliteral(L, "__ts_http_transform_ctx"); lua_rawget(L, LUA_GLOBALSINDEX); - tctx = lua_touserdata(L, -1); + tctx = static_cast(lua_touserdata(L, -1)); lua_pop(L, 1); // pop the ictx out @@ -907,8 +905,8 @@ ts_lua_create_http_transform_ctx(ts_lua_http_ctx *http_ctx, TSVConn connp) hci = &http_ctx->cinfo; L = hci->routine.lua; - transform_ctx = (ts_lua_http_transform_ctx *)TSmalloc(sizeof(ts_lua_http_transform_ctx)); - memset(transform_ctx, 0, sizeof(ts_lua_http_transform_ctx)); + transform_ctx = tsapi::malloc(); + memset(transform_ctx, 0, sizeof(*transform_ctx)); transform_ctx->hctx = http_ctx; TSContDataSet(connp, transform_ctx); diff --git a/plugins/regex_revalidate/CMakeLists.txt b/plugins/regex_revalidate/CMakeLists.txt index 6e16c147867..67ae24b76ff 100644 --- a/plugins/regex_revalidate/CMakeLists.txt +++ b/plugins/regex_revalidate/CMakeLists.txt @@ -15,7 +15,7 @@ # ####################### -add_atsplugin(regex_revalidate regex_revalidate.c) +add_atsplugin(regex_revalidate regex_revalidate.cc) target_include_directories(regex_revalidate PRIVATE "${PROJECT_SOURCE_DIR}/include") diff --git a/plugins/regex_revalidate/Makefile.inc b/plugins/regex_revalidate/Makefile.inc index 30dce81389e..9c6f41491b0 100644 --- a/plugins/regex_revalidate/Makefile.inc +++ b/plugins/regex_revalidate/Makefile.inc @@ -15,4 +15,4 @@ # limitations under the License. pkglib_LTLIBRARIES += regex_revalidate/regex_revalidate.la -regex_revalidate_regex_revalidate_la_SOURCES = regex_revalidate/regex_revalidate.c +regex_revalidate_regex_revalidate_la_SOURCES = regex_revalidate/regex_revalidate.cc diff --git a/plugins/regex_revalidate/regex_revalidate.c b/plugins/regex_revalidate/regex_revalidate.cc similarity index 90% rename from plugins/regex_revalidate/regex_revalidate.c rename to plugins/regex_revalidate/regex_revalidate.cc index 036f53496c1..bc4f2f35980 100644 --- a/plugins/regex_revalidate/regex_revalidate.c +++ b/plugins/regex_revalidate/regex_revalidate.cc @@ -133,13 +133,13 @@ typedef struct { static invalidate_t * init_invalidate_t(invalidate_t *i) { - i->regex_text = NULL; - i->regex = NULL; - i->regex_extra = NULL; + i->regex_text = nullptr; + i->regex = nullptr; + i->regex_extra = nullptr; i->epoch = 0; i->expiry = 0; i->new_result = TS_CACHE_LOOKUP_HIT_STALE; - i->next = NULL; + i->next = nullptr; return i; } @@ -165,7 +165,7 @@ free_invalidate_t(invalidate_t *i) static void free_invalidate_t_list(invalidate_t *iptr) { - while (NULL != iptr) { + while (nullptr != iptr) { invalidate_t *const next = iptr->next; free_invalidate_t(iptr); iptr = next; @@ -175,12 +175,12 @@ free_invalidate_t_list(invalidate_t *iptr) static plugin_state_t * init_plugin_state_t(plugin_state_t *pstate) { - pstate->invalidate_list = NULL; - pstate->config_path = NULL; - pstate->match_header = NULL; + pstate->invalidate_list = nullptr; + pstate->config_path = nullptr; + pstate->match_header = nullptr; pstate->last_load = 0; - pstate->log = NULL; - pstate->state_path = NULL; + pstate->log = nullptr; + pstate->state_path = nullptr; return pstate; } @@ -214,19 +214,19 @@ copy_invalidate_t(invalidate_t *i) iptr = (invalidate_t *)TSmalloc(sizeof(invalidate_t)); iptr->regex_text = TSstrdup(i->regex_text); - iptr->regex = pcre_compile(iptr->regex_text, 0, &errptr, &erroffset, NULL); // There is no pcre_copy :-( + iptr->regex = pcre_compile(iptr->regex_text, 0, &errptr, &erroffset, nullptr); // There is no pcre_copy :-( iptr->regex_extra = pcre_study(iptr->regex, 0, &errptr); // Assuming no errors since this worked before :-/ iptr->epoch = i->epoch; iptr->expiry = i->expiry; iptr->new_result = i->new_result; - iptr->next = NULL; + iptr->next = nullptr; return iptr; } static invalidate_t * copy_config(invalidate_t *old_list) { - invalidate_t *new_list = NULL; + invalidate_t *new_list = nullptr; invalidate_t *iptr_old, *iptr_new; if (old_list) { @@ -250,11 +250,11 @@ prune_config(invalidate_t **i) time_t now; bool pruned = false; - now = time(NULL); + now = time(nullptr); if (*i) { iptr = *i; - ilast = NULL; + ilast = nullptr; while (iptr) { if (iptr->expiry <= now) { TSDebug(PLUGIN_NAME, "Removing %s expiry: %jd type: %s now: %jd", iptr->regex_text, (intmax_t)iptr->expiry, @@ -281,11 +281,11 @@ prune_config(invalidate_t **i) static bool load_state(plugin_state_t *pstate, invalidate_t **ilist) { - FILE *fs = NULL; + FILE *fs = nullptr; struct stat s; char line[LINE_MAX]; time_t now; - pcre *config_re = NULL; + pcre *config_re = nullptr; const char *errptr; int erroffset, ovector[OVECTOR_SIZE], rc; int ln = 0; @@ -304,15 +304,15 @@ load_state(plugin_state_t *pstate, invalidate_t **ilist) return false; } - now = time(NULL); + now = time(nullptr); - config_re = pcre_compile("^([^#].+?)\\s+(\\d+)\\s+(\\d+)\\s+(\\w+)\\s*$", 0, &errptr, &erroffset, NULL); - TSReleaseAssert(NULL != config_re); + config_re = pcre_compile("^([^#].+?)\\s+(\\d+)\\s+(\\d+)\\s+(\\w+)\\s*$", 0, &errptr, &erroffset, nullptr); + TSReleaseAssert(nullptr != config_re); - while (fgets(line, LINE_MAX, fs) != NULL) { + while (fgets(line, LINE_MAX, fs) != nullptr) { TSDebug(PLUGIN_NAME, "state: processing: %d %s", ln, line); ++ln; - rc = pcre_exec(config_re, NULL, line, strlen(line), 0, 0, ovector, OVECTOR_SIZE); + rc = pcre_exec(config_re, nullptr, line, strlen(line), 0, 0, ovector, OVECTOR_SIZE); if (5 == rc) { invalidate_t *const inv = (invalidate_t *)TSmalloc(sizeof(invalidate_t)); @@ -351,11 +351,11 @@ load_state(plugin_state_t *pstate, invalidate_t **ilist) break; } - if (NULL == iptr->next) { + if (nullptr == iptr->next) { break; } iptr = iptr->next; - } while (NULL != iptr); + } while (nullptr != iptr); free_invalidate_t(inv); } else { @@ -385,7 +385,7 @@ load_config(plugin_state_t *pstate, invalidate_t **ilist) if (pstate->config_path[0] != '/') { path_len = strlen(TSConfigDirGet()) + strlen(pstate->config_path) + 2; - path = alloca(path_len); + path = static_cast(alloca(path_len)); snprintf(path, path_len, "%s/%s", TSConfigDirGet(), pstate->config_path); } else { path = pstate->config_path; @@ -395,26 +395,26 @@ load_config(plugin_state_t *pstate, invalidate_t **ilist) return false; } if (pstate->last_load < s.st_mtime) { - now = time(NULL); + now = time(nullptr); if (!(fs = fopen(path, "r"))) { TSDebug(PLUGIN_NAME, "Could not open %s for reading", path); return false; } TSDebug(PLUGIN_NAME, "Attempting to load rules from: '%s'", path); - config_re = pcre_compile("^([^#].+?)\\s+(\\d+)(\\s+(\\w+))?\\s*$", 0, &errptr, &erroffset, NULL); - TSReleaseAssert(NULL != config_re); + config_re = pcre_compile("^([^#].+?)\\s+(\\d+)(\\s+(\\w+))?\\s*$", 0, &errptr, &erroffset, nullptr); + TSReleaseAssert(nullptr != config_re); - while (fgets(line, LINE_MAX, fs) != NULL) { + while (fgets(line, LINE_MAX, fs) != nullptr) { TSDebug(PLUGIN_NAME, "Processing: %d %s", ln, line); ++ln; - rc = pcre_exec(config_re, NULL, line, strlen(line), 0, 0, ovector, OVECTOR_SIZE); + rc = pcre_exec(config_re, nullptr, line, strlen(line), 0, 0, ovector, OVECTOR_SIZE); if (3 <= rc) { i = (invalidate_t *)TSmalloc(sizeof(invalidate_t)); init_invalidate_t(i); pcre_get_substring(line, ovector, rc, 1, &i->regex_text); - i->regex = pcre_compile(i->regex_text, 0, &errptr, &erroffset, NULL); + i->regex = pcre_compile(i->regex_text, 0, &errptr, &erroffset, nullptr); i->epoch = now; i->expiry = atoi(line + ovector[4]); @@ -432,11 +432,11 @@ load_config(plugin_state_t *pstate, invalidate_t **ilist) if (i->expiry <= i->epoch) { TSDebug(PLUGIN_NAME, "Rule is already expired!"); free_invalidate_t(i); - i = NULL; - } else if (i->regex == NULL) { + i = nullptr; + } else if (i->regex == nullptr) { TSDebug(PLUGIN_NAME, "%s did not compile", i->regex_text); free_invalidate_t(i); - i = NULL; + i = nullptr; } else { i->regex_extra = pcre_study(i->regex, 0, &errptr); if (!*ilist) { @@ -458,7 +458,7 @@ load_config(plugin_state_t *pstate, invalidate_t **ilist) iptr->epoch = now; } free_invalidate_t(i); - i = NULL; + i = nullptr; break; } else if (!iptr->next) { break; @@ -498,10 +498,10 @@ list_config(plugin_state_t *pstate, invalidate_t *i) TSTextLogObjectWrite(pstate->log, "Current config:"); } - FILE *state_file = NULL; + FILE *state_file = nullptr; if (pstate->state_path) { state_file = fopen(pstate->state_path, "w"); - if (NULL == state_file) { + if (nullptr == state_file) { TSDebug(PLUGIN_NAME, "Unable to open state file %s\n", pstate->state_path); } } @@ -529,7 +529,7 @@ list_config(plugin_state_t *pstate, invalidate_t *i) } } - if (NULL != state_file) { + if (nullptr != state_file) { fclose(state_file); } } @@ -671,7 +671,7 @@ main_handler(TSCont cont, TSEvent event, void *edata) plugin_state_t *pstate = NULL; time_t date = 0, now = 0; - char *url = NULL; + char *url = nullptr; int url_len = 0; switch (event) { @@ -683,24 +683,24 @@ main_handler(TSCont cont, TSEvent event, void *edata) while (iptr) { if (!date) { date = get_date_from_cached_hdr(txn); - TSDebug(PLUGIN_NAME, "Cached Date header is: %jd", (intmax_t)date); - now = time(NULL); + TSDebug(PLUGIN_NAME, "Cached Date header is: %jd", intmax_t(date)); + now = time(nullptr); } if (date <= iptr->epoch && now < iptr->expiry) { if (!url) { url = TSHttpTxnEffectiveUrlStringGet(txn, &url_len); TSDebug(PLUGIN_NAME, "Effective url is is '%.*s'", url_len, url); } - if (pcre_exec(iptr->regex, iptr->regex_extra, url, url_len, 0, 0, NULL, 0) >= 0) { + if (pcre_exec(iptr->regex, iptr->regex_extra, url, url_len, 0, 0, nullptr, 0) >= 0) { TSDebug(PLUGIN_NAME, "Forced revalidate, Match with rule regex: '%s' epoch: %jd, expiry: %jd, result: '%s'", - iptr->regex_text, (intmax_t)iptr->epoch, (intmax_t)iptr->expiry, strForResult(iptr->new_result)); + iptr->regex_text, intmax_t(iptr->epoch), intmax_t(iptr->expiry), strForResult(iptr->new_result)); TSHttpTxnCacheLookupStatusSet(txn, iptr->new_result); increment_stat(iptr->new_result); if (pstate->match_header) { add_header(txn, pstate->match_header, iptr); } - iptr = NULL; + iptr = nullptr; } } if (iptr) { @@ -733,7 +733,7 @@ make_state_path(const char *filename) return TSstrdup(buf); } - return NULL; + return nullptr; } void @@ -742,7 +742,7 @@ TSPluginInit(int argc, const char *argv[]) TSPluginRegistrationInfo info; TSCont main_cont, config_cont; plugin_state_t *pstate; - invalidate_t *iptr = NULL; + invalidate_t *iptr = nullptr; bool disable_timed_reload = false; TSDebug(PLUGIN_NAME, "Starting plugin init"); @@ -752,15 +752,15 @@ TSPluginInit(int argc, const char *argv[]) int c; static const struct option longopts[] = { - {"config", required_argument, NULL, 'c'}, - {"log", required_argument, NULL, 'l'}, - {"disable-timed-reload", no_argument, NULL, 'd'}, - {"state-file", required_argument, NULL, 'f'}, - {"match-header", required_argument, NULL, 'm'}, - {NULL, 0, NULL, 0 } + {"config", required_argument, nullptr, 'c'}, + {"log", required_argument, nullptr, 'l'}, + {"disable-timed-reload", no_argument, nullptr, 'd'}, + {"state-file", required_argument, nullptr, 'f'}, + {"match-header", required_argument, nullptr, 'm'}, + {nullptr, 0, nullptr, 0 } }; - while ((c = getopt_long(argc, (char *const *)argv, "c:l:f:m:", longopts, NULL)) != -1) { + while ((c = getopt_long(argc, (char *const *)argv, "c:l:f:m:", longopts, nullptr)) != -1) { switch (c) { case 'c': pstate->config_path = TSstrdup(optarg); @@ -785,7 +785,7 @@ TSPluginInit(int argc, const char *argv[]) } } - if (NULL == pstate->config_path) { + if (nullptr == pstate->config_path) { TSError("[regex_revalidate] Plugin requires a --config option along with a config file name"); free_plugin_state_t(pstate); return; @@ -797,7 +797,7 @@ TSPluginInit(int argc, const char *argv[]) pstate->invalidate_list = iptr; /* Load and merge previous state if provided */ - if (NULL != pstate->state_path) { + if (nullptr != pstate->state_path) { if (!load_state(pstate, &iptr)) { TSDebug(PLUGIN_NAME, "Problem loading state from file %s", pstate->state_path); } else { @@ -823,7 +823,7 @@ TSPluginInit(int argc, const char *argv[]) create_stats(); - main_cont = TSContCreate(main_handler, NULL); + main_cont = TSContCreate(main_handler, nullptr); TSContDataSet(main_cont, (void *)pstate); TSHttpHookAdd(TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK, main_cont); diff --git a/plugins/remap_purge/CMakeLists.txt b/plugins/remap_purge/CMakeLists.txt index e43f9db5fa1..ae1fac4d8dc 100644 --- a/plugins/remap_purge/CMakeLists.txt +++ b/plugins/remap_purge/CMakeLists.txt @@ -15,6 +15,6 @@ # ####################### -add_atsplugin(remap_purge remap_purge.c) +add_atsplugin(remap_purge remap_purge.cc) target_include_directories(remap_purge PRIVATE "${PROJECT_SOURCE_DIR}/include") diff --git a/plugins/remap_purge/Makefile.inc b/plugins/remap_purge/Makefile.inc index 72db237f205..3189cee774c 100644 --- a/plugins/remap_purge/Makefile.inc +++ b/plugins/remap_purge/Makefile.inc @@ -17,4 +17,4 @@ pkglib_LTLIBRARIES += remap_purge/remap_purge.la remap_purge_remap_purge_la_SOURCES = \ - remap_purge/remap_purge.c + remap_purge/remap_purge.cc diff --git a/plugins/remap_purge/remap_purge.c b/plugins/remap_purge/remap_purge.cc similarity index 93% rename from plugins/remap_purge/remap_purge.c rename to plugins/remap_purge/remap_purge.cc index 46fa41a3b86..f5941d662d2 100644 --- a/plugins/remap_purge/remap_purge.c +++ b/plugins/remap_purge/remap_purge.cc @@ -64,14 +64,14 @@ make_state_path(const char *filename) if (-1 == mkdir(buf, S_IRWXU)) { if (EEXIST != errno) { TSError("[%s] Unable to create directory %s: %s (%d)", PLUGIN_NAME, buf, strerror(errno), errno); - return NULL; + return nullptr; } } snprintf(buf, sizeof(buf), "%s/%s/%s/%s.genid", dir, DEFAULT_DIR, PLUGIN_NAME, filename); return TSstrdup(buf); } - return NULL; + return nullptr; } /* Constructor and destructor for the PurgeInstance */ @@ -143,7 +143,7 @@ on_send_response_header(TSHttpTxn txnp, TSCont contp, PurgeInstance *purge) TSHttpHdrStatusSet(bufp, hdr_loc, TS_HTTP_STATUS_OK); TSHttpHdrReasonSet(bufp, hdr_loc, "OK", 2); - TSHttpTxnErrorBodySet(txnp, TSstrdup(response), len >= (int)sizeof(response) ? (int)sizeof(response) - 1 : len, NULL); + TSHttpTxnErrorBodySet(txnp, TSstrdup(response), len >= (int)sizeof(response) ? (int)sizeof(response) - 1 : len, nullptr); TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc); TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE); @@ -180,7 +180,7 @@ static void handle_purge(TSHttpTxn txnp, PurgeInstance *purge) { TSMBuffer reqp; - TSMLoc hdr_loc = NULL, url_loc = NULL; + TSMLoc hdr_loc = nullptr, url_loc = nullptr; bool should_purge = false; if (TS_SUCCESS == TSHttpTxnClientReqGet(txnp, &reqp, &hdr_loc)) { @@ -255,14 +255,14 @@ TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size) { char *id = argv[0]; /* The ID is default to the "from" URL, so save it */ - PurgeInstance *purge = TSmalloc(sizeof(PurgeInstance)); + auto purge = tsapi::malloc(); static const struct option longopt[] = { - {(char *)"id", required_argument, NULL, 'i' }, - {(char *)"secret", required_argument, NULL, 's' }, - {(char *)"header", required_argument, NULL, 'h' }, - {(char *)"state-file", required_argument, NULL, 'f' }, - {(char *)"allow-get", no_argument, NULL, 'a' }, - {NULL, no_argument, NULL, '\0'}, + {(char *)"id", required_argument, nullptr, 'i' }, + {(char *)"secret", required_argument, nullptr, 's' }, + {(char *)"header", required_argument, nullptr, 'h' }, + {(char *)"state-file", required_argument, nullptr, 'f' }, + {(char *)"allow-get", no_argument, nullptr, 'a' }, + {nullptr, no_argument, nullptr, '\0'}, }; memset(purge, 0, sizeof(PurgeInstance)); @@ -274,7 +274,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s argv++; for (;;) { - int opt = getopt_long(argc, (char *const *)argv, "", longopt, NULL); + int opt = getopt_long(argc, (char *const *)argv, "", longopt, nullptr); if (opt == -1) { break; @@ -301,7 +301,7 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s } } - if ((NULL == purge->secret) || (NULL == purge->state_file) || !purge->secret_len) { + if ((nullptr == purge->secret) || (nullptr == purge->state_file) || !purge->secret_len) { TSError("[%s] Unable to create remap instance, need at least a secret (--secret) and state (--state_file)", PLUGIN_NAME); delete_purge_instance(purge); return TS_ERROR; diff --git a/proxy/http/remap/unit-tests/nexthop_test_stubs.h b/proxy/http/remap/unit-tests/nexthop_test_stubs.h index c6abe37b887..6325263a81d 100644 --- a/proxy/http/remap/unit-tests/nexthop_test_stubs.h +++ b/proxy/http/remap/unit-tests/nexthop_test_stubs.h @@ -36,10 +36,6 @@ #include #include -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #define NH_Debug(tag, fmt, ...) PrintToStdErr("%s %s:%d:%s() " fmt "\n", tag, __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define NH_Error(fmt, ...) PrintToStdErr("%s:%d:%s() " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define NH_Note(fmt, ...) PrintToStdErr("%s:%d:%s() " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__) @@ -52,10 +48,6 @@ void GetConfigInteger(int *v, const char *n); void PrintToStdErr(const char *fmt, ...); void build_request(HttpRequestData &h, const char *os_hostname); -#ifdef __cplusplus -} -#endif /* __cplusplus */ - #include "ControlMatcher.h" #include "ParentSelection.h" diff --git a/proxy/http/remap/unit-tests/plugin_init_fail.cc b/proxy/http/remap/unit-tests/plugin_init_fail.cc index 151382f7009..724e1153e08 100644 --- a/proxy/http/remap/unit-tests/plugin_init_fail.cc +++ b/proxy/http/remap/unit-tests/plugin_init_fail.cc @@ -29,10 +29,6 @@ #include "plugin_testing_common.h" -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -52,7 +48,3 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) { return TSREMAP_NO_REMAP; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_instinit_fail.cc b/proxy/http/remap/unit-tests/plugin_instinit_fail.cc index 41bf6b1bbc9..c2207bcff4d 100644 --- a/proxy/http/remap/unit-tests/plugin_instinit_fail.cc +++ b/proxy/http/remap/unit-tests/plugin_instinit_fail.cc @@ -29,10 +29,6 @@ #include "plugin_testing_common.h" -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -63,7 +59,3 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) { return TSREMAP_NO_REMAP; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_misc_cb.cc b/proxy/http/remap/unit-tests/plugin_misc_cb.cc index f0792fc463d..91f7c152898 100644 --- a/proxy/http/remap/unit-tests/plugin_misc_cb.cc +++ b/proxy/http/remap/unit-tests/plugin_misc_cb.cc @@ -29,10 +29,6 @@ #include "plugin_testing_common.h" -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -85,7 +81,7 @@ TSRemapConfigReload(void) } /* This is meant for test with plugins of different versions */ -int +extern "C" int pluginDsoVersionTest() { #ifdef PLUGINDSOVER @@ -100,7 +96,3 @@ getPluginDebugObjectTest() { return (void *)&debugObject; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_missing_deleteinstance.cc b/proxy/http/remap/unit-tests/plugin_missing_deleteinstance.cc index 03ded2d1913..d569c8abe58 100644 --- a/proxy/http/remap/unit-tests/plugin_missing_deleteinstance.cc +++ b/proxy/http/remap/unit-tests/plugin_missing_deleteinstance.cc @@ -27,10 +27,6 @@ */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -51,7 +47,3 @@ TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_s { return TS_SUCCESS; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_missing_doremap.cc b/proxy/http/remap/unit-tests/plugin_missing_doremap.cc index f727f6dee58..2664d06dece 100644 --- a/proxy/http/remap/unit-tests/plugin_missing_doremap.cc +++ b/proxy/http/remap/unit-tests/plugin_missing_doremap.cc @@ -27,10 +27,6 @@ */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -39,7 +35,3 @@ TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { return TS_SUCCESS; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_missing_init.cc b/proxy/http/remap/unit-tests/plugin_missing_init.cc index 265bfa5f916..f14d726c582 100644 --- a/proxy/http/remap/unit-tests/plugin_missing_init.cc +++ b/proxy/http/remap/unit-tests/plugin_missing_init.cc @@ -27,10 +27,6 @@ */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -39,7 +35,3 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) { return TSREMAP_NO_REMAP; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_missing_newinstance.cc b/proxy/http/remap/unit-tests/plugin_missing_newinstance.cc index bed55d6dae2..67262b07297 100644 --- a/proxy/http/remap/unit-tests/plugin_missing_newinstance.cc +++ b/proxy/http/remap/unit-tests/plugin_missing_newinstance.cc @@ -27,10 +27,6 @@ */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -50,7 +46,3 @@ void TSRemapDeleteInstance(void *) { } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_required_cb.cc b/proxy/http/remap/unit-tests/plugin_required_cb.cc index 65b8026f75c..e4741ffdd8a 100644 --- a/proxy/http/remap/unit-tests/plugin_required_cb.cc +++ b/proxy/http/remap/unit-tests/plugin_required_cb.cc @@ -27,10 +27,6 @@ */ -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - #include "ts/ts.h" #include "ts/remap.h" @@ -45,7 +41,3 @@ TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri) { return TSREMAP_NO_REMAP; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_testing_calls.cc b/proxy/http/remap/unit-tests/plugin_testing_calls.cc index cf8aa045f98..2ea2989ef08 100644 --- a/proxy/http/remap/unit-tests/plugin_testing_calls.cc +++ b/proxy/http/remap/unit-tests/plugin_testing_calls.cc @@ -36,10 +36,6 @@ PluginDebugObject debugObject; -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - TSReturnCode handleInitRun(char *errbuf, int errbuf_size, int &counter) { @@ -116,7 +112,7 @@ TSRemapPostConfigReload(TSRemapReloadStatus reloadStatus) } /* The following functions are meant for unit testing */ -int +extern "C" int pluginDsoVersionTest() { #ifdef PLUGINDSOVER @@ -131,7 +127,3 @@ getPluginDebugObjectTest() { return (void *)&debugObject; } - -#ifdef __cplusplus -} -#endif /* __cplusplus */ diff --git a/proxy/http/remap/unit-tests/plugin_testing_common.h b/proxy/http/remap/unit-tests/plugin_testing_common.h index c4938724b84..a4f0ea7619a 100644 --- a/proxy/http/remap/unit-tests/plugin_testing_common.h +++ b/proxy/http/remap/unit-tests/plugin_testing_common.h @@ -86,22 +86,14 @@ class PluginDebugObject char **argv = nullptr; /* plugin instance parameters received by the plugin */ }; -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - using GetPluginDebugObjectFunction = void *(); -GetPluginDebugObjectFunction getPluginDebugObjectTest; +extern "C" GetPluginDebugObjectFunction getPluginDebugObjectTest; #define PluginDebug(category, fmt, ...) \ PrintToStdErr("(%s) %s:%d:%s() " fmt "\n", category, __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define PluginError(fmt, ...) PrintToStdErr("%s:%d:%s() " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__) void PrintToStdErr(const char *fmt, ...); -#ifdef __cplusplus -} -#endif /* __cplusplus */ - // functions to support unit-testing of option to enable/disable dynamic reload of plugins void enablePluginDynamicReload(); void disablePluginDynamicReload(); diff --git a/src/records/RecHttp.cc b/src/records/RecHttp.cc index 1b78d7c6968..4a95a44a084 100644 --- a/src/records/RecHttp.cc +++ b/src/records/RecHttp.cc @@ -40,49 +40,57 @@ using swoc::TextView; SessionProtocolNameRegistry globalSessionProtocolNameRegistry; -/* Protocol session well-known protocol names. - These are also used for NPN setup. -*/ +namespace tsapi +{ +namespace c +{ -const char *const TS_ALPN_PROTOCOL_HTTP_0_9 = IP_PROTO_TAG_HTTP_0_9.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_1_0 = IP_PROTO_TAG_HTTP_1_0.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_1_1 = IP_PROTO_TAG_HTTP_1_1.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_2_0 = IP_PROTO_TAG_HTTP_2_0.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_3 = IP_PROTO_TAG_HTTP_3.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_QUIC = IP_PROTO_TAG_HTTP_QUIC.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_3_D29 = IP_PROTO_TAG_HTTP_3_D29.data(); -const char *const TS_ALPN_PROTOCOL_HTTP_QUIC_D29 = IP_PROTO_TAG_HTTP_QUIC_D29.data(); - -const char *const TS_ALPN_PROTOCOL_GROUP_HTTP = "http"; -const char *const TS_ALPN_PROTOCOL_GROUP_HTTP2 = "http2"; - -const char *const TS_PROTO_TAG_HTTP_1_0 = TS_ALPN_PROTOCOL_HTTP_1_0; -const char *const TS_PROTO_TAG_HTTP_1_1 = TS_ALPN_PROTOCOL_HTTP_1_1; -const char *const TS_PROTO_TAG_HTTP_2_0 = TS_ALPN_PROTOCOL_HTTP_2_0; -const char *const TS_PROTO_TAG_HTTP_3 = TS_ALPN_PROTOCOL_HTTP_3; -const char *const TS_PROTO_TAG_HTTP_QUIC = TS_ALPN_PROTOCOL_HTTP_QUIC; -const char *const TS_PROTO_TAG_HTTP_3_D29 = TS_ALPN_PROTOCOL_HTTP_3_D29; -const char *const TS_PROTO_TAG_HTTP_QUIC_D29 = TS_ALPN_PROTOCOL_HTTP_QUIC_D29; -const char *const TS_PROTO_TAG_TLS_1_3 = IP_PROTO_TAG_TLS_1_3.data(); -const char *const TS_PROTO_TAG_TLS_1_2 = IP_PROTO_TAG_TLS_1_2.data(); -const char *const TS_PROTO_TAG_TLS_1_1 = IP_PROTO_TAG_TLS_1_1.data(); -const char *const TS_PROTO_TAG_TLS_1_0 = IP_PROTO_TAG_TLS_1_0.data(); -const char *const TS_PROTO_TAG_TCP = IP_PROTO_TAG_TCP.data(); -const char *const TS_PROTO_TAG_UDP = IP_PROTO_TAG_UDP.data(); -const char *const TS_PROTO_TAG_IPV4 = IP_PROTO_TAG_IPV4.data(); -const char *const TS_PROTO_TAG_IPV6 = IP_PROTO_TAG_IPV6.data(); - -std::unordered_set TSProtoTags; - -// Precomputed indices for ease of use. -int TS_ALPN_PROTOCOL_INDEX_HTTP_0_9 = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_1_0 = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_1_1 = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_2_0 = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_3 = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_QUIC = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_3_D29 = SessionProtocolNameRegistry::INVALID; -int TS_ALPN_PROTOCOL_INDEX_HTTP_QUIC_D29 = SessionProtocolNameRegistry::INVALID; + /* Protocol session well-known protocol names. + These are also used for NPN setup. + */ + + const char *const TS_ALPN_PROTOCOL_HTTP_0_9 = IP_PROTO_TAG_HTTP_0_9.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_1_0 = IP_PROTO_TAG_HTTP_1_0.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_1_1 = IP_PROTO_TAG_HTTP_1_1.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_2_0 = IP_PROTO_TAG_HTTP_2_0.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_3 = IP_PROTO_TAG_HTTP_3.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_QUIC = IP_PROTO_TAG_HTTP_QUIC.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_3_D29 = IP_PROTO_TAG_HTTP_3_D29.data(); + const char *const TS_ALPN_PROTOCOL_HTTP_QUIC_D29 = IP_PROTO_TAG_HTTP_QUIC_D29.data(); + + const char *const TS_ALPN_PROTOCOL_GROUP_HTTP = "http"; + const char *const TS_ALPN_PROTOCOL_GROUP_HTTP2 = "http2"; + + const char *const TS_PROTO_TAG_HTTP_1_0 = TS_ALPN_PROTOCOL_HTTP_1_0; + const char *const TS_PROTO_TAG_HTTP_1_1 = TS_ALPN_PROTOCOL_HTTP_1_1; + const char *const TS_PROTO_TAG_HTTP_2_0 = TS_ALPN_PROTOCOL_HTTP_2_0; + const char *const TS_PROTO_TAG_HTTP_3 = TS_ALPN_PROTOCOL_HTTP_3; + const char *const TS_PROTO_TAG_HTTP_QUIC = TS_ALPN_PROTOCOL_HTTP_QUIC; + const char *const TS_PROTO_TAG_HTTP_3_D29 = TS_ALPN_PROTOCOL_HTTP_3_D29; + const char *const TS_PROTO_TAG_HTTP_QUIC_D29 = TS_ALPN_PROTOCOL_HTTP_QUIC_D29; + const char *const TS_PROTO_TAG_TLS_1_3 = IP_PROTO_TAG_TLS_1_3.data(); + const char *const TS_PROTO_TAG_TLS_1_2 = IP_PROTO_TAG_TLS_1_2.data(); + const char *const TS_PROTO_TAG_TLS_1_1 = IP_PROTO_TAG_TLS_1_1.data(); + const char *const TS_PROTO_TAG_TLS_1_0 = IP_PROTO_TAG_TLS_1_0.data(); + const char *const TS_PROTO_TAG_TCP = IP_PROTO_TAG_TCP.data(); + const char *const TS_PROTO_TAG_UDP = IP_PROTO_TAG_UDP.data(); + const char *const TS_PROTO_TAG_IPV4 = IP_PROTO_TAG_IPV4.data(); + const char *const TS_PROTO_TAG_IPV6 = IP_PROTO_TAG_IPV6.data(); + + std::unordered_set TSProtoTags; + + // Precomputed indices for ease of use. + int TS_ALPN_PROTOCOL_INDEX_HTTP_0_9 = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_1_0 = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_1_1 = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_2_0 = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_3 = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_QUIC = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_3_D29 = SessionProtocolNameRegistry::INVALID; + int TS_ALPN_PROTOCOL_INDEX_HTTP_QUIC_D29 = SessionProtocolNameRegistry::INVALID; + +} // end namespace c +} // end namespace tsapi // Predefined protocol sets for ease of use. SessionProtocolSet HTTP_PROTOCOL_SET; diff --git a/src/traffic_server/InkAPI.cc b/src/traffic_server/InkAPI.cc index 734314881bd..a8830cc2bad 100644 --- a/src/traffic_server/InkAPI.cc +++ b/src/traffic_server/InkAPI.cc @@ -116,271 +116,279 @@ UserArg UserArgTable[TS_USER_ARGS_COUNT][MAX_USER_ARGS[TS_USER_ARGS_GLB]]; static PluginUserArgs global_user_args; std::atomic UserArgIdx[TS_USER_ARGS_COUNT]; // Table of next reserved index. -/* URL schemes */ -tsapi const char *TS_URL_SCHEME_FILE; -tsapi const char *TS_URL_SCHEME_FTP; -tsapi const char *TS_URL_SCHEME_GOPHER; -tsapi const char *TS_URL_SCHEME_HTTP; -tsapi const char *TS_URL_SCHEME_HTTPS; -tsapi const char *TS_URL_SCHEME_MAILTO; -tsapi const char *TS_URL_SCHEME_NEWS; -tsapi const char *TS_URL_SCHEME_NNTP; -tsapi const char *TS_URL_SCHEME_PROSPERO; -tsapi const char *TS_URL_SCHEME_TELNET; -tsapi const char *TS_URL_SCHEME_TUNNEL; -tsapi const char *TS_URL_SCHEME_WAIS; -tsapi const char *TS_URL_SCHEME_PNM; -tsapi const char *TS_URL_SCHEME_RTSP; -tsapi const char *TS_URL_SCHEME_RTSPU; -tsapi const char *TS_URL_SCHEME_MMS; -tsapi const char *TS_URL_SCHEME_MMSU; -tsapi const char *TS_URL_SCHEME_MMST; -tsapi const char *TS_URL_SCHEME_WS; -tsapi const char *TS_URL_SCHEME_WSS; - -/* URL schemes string lengths */ -tsapi int TS_URL_LEN_FILE; -tsapi int TS_URL_LEN_FTP; -tsapi int TS_URL_LEN_GOPHER; -tsapi int TS_URL_LEN_HTTP; -tsapi int TS_URL_LEN_HTTPS; -tsapi int TS_URL_LEN_MAILTO; -tsapi int TS_URL_LEN_NEWS; -tsapi int TS_URL_LEN_NNTP; -tsapi int TS_URL_LEN_PROSPERO; -tsapi int TS_URL_LEN_TELNET; -tsapi int TS_URL_LEN_TUNNEL; -tsapi int TS_URL_LEN_WAIS; -tsapi int TS_URL_LEN_PNM; -tsapi int TS_URL_LEN_RTSP; -tsapi int TS_URL_LEN_RTSPU; -tsapi int TS_URL_LEN_MMS; -tsapi int TS_URL_LEN_MMSU; -tsapi int TS_URL_LEN_MMST; -tsapi int TS_URL_LEN_WS; -tsapi int TS_URL_LEN_WSS; - -/* MIME fields */ -tsapi const char *TS_MIME_FIELD_ACCEPT; -tsapi const char *TS_MIME_FIELD_ACCEPT_CHARSET; -tsapi const char *TS_MIME_FIELD_ACCEPT_ENCODING; -tsapi const char *TS_MIME_FIELD_ACCEPT_LANGUAGE; -tsapi const char *TS_MIME_FIELD_ACCEPT_RANGES; -tsapi const char *TS_MIME_FIELD_AGE; -tsapi const char *TS_MIME_FIELD_ALLOW; -tsapi const char *TS_MIME_FIELD_APPROVED; -tsapi const char *TS_MIME_FIELD_AUTHORIZATION; -tsapi const char *TS_MIME_FIELD_BYTES; -tsapi const char *TS_MIME_FIELD_CACHE_CONTROL; -tsapi const char *TS_MIME_FIELD_CLIENT_IP; -tsapi const char *TS_MIME_FIELD_CONNECTION; -tsapi const char *TS_MIME_FIELD_CONTENT_BASE; -tsapi const char *TS_MIME_FIELD_CONTENT_ENCODING; -tsapi const char *TS_MIME_FIELD_CONTENT_LANGUAGE; -tsapi const char *TS_MIME_FIELD_CONTENT_LENGTH; -tsapi const char *TS_MIME_FIELD_CONTENT_LOCATION; -tsapi const char *TS_MIME_FIELD_CONTENT_MD5; -tsapi const char *TS_MIME_FIELD_CONTENT_RANGE; -tsapi const char *TS_MIME_FIELD_CONTENT_TYPE; -tsapi const char *TS_MIME_FIELD_CONTROL; -tsapi const char *TS_MIME_FIELD_COOKIE; -tsapi const char *TS_MIME_FIELD_DATE; -tsapi const char *TS_MIME_FIELD_DISTRIBUTION; -tsapi const char *TS_MIME_FIELD_ETAG; -tsapi const char *TS_MIME_FIELD_EXPECT; -tsapi const char *TS_MIME_FIELD_EXPIRES; -tsapi const char *TS_MIME_FIELD_FOLLOWUP_TO; -tsapi const char *TS_MIME_FIELD_FROM; -tsapi const char *TS_MIME_FIELD_HOST; -tsapi const char *TS_MIME_FIELD_IF_MATCH; -tsapi const char *TS_MIME_FIELD_IF_MODIFIED_SINCE; -tsapi const char *TS_MIME_FIELD_IF_NONE_MATCH; -tsapi const char *TS_MIME_FIELD_IF_RANGE; -tsapi const char *TS_MIME_FIELD_IF_UNMODIFIED_SINCE; -tsapi const char *TS_MIME_FIELD_KEEP_ALIVE; -tsapi const char *TS_MIME_FIELD_KEYWORDS; -tsapi const char *TS_MIME_FIELD_LAST_MODIFIED; -tsapi const char *TS_MIME_FIELD_LINES; -tsapi const char *TS_MIME_FIELD_LOCATION; -tsapi const char *TS_MIME_FIELD_MAX_FORWARDS; -tsapi const char *TS_MIME_FIELD_MESSAGE_ID; -tsapi const char *TS_MIME_FIELD_NEWSGROUPS; -tsapi const char *TS_MIME_FIELD_ORGANIZATION; -tsapi const char *TS_MIME_FIELD_PATH; -tsapi const char *TS_MIME_FIELD_PRAGMA; -tsapi const char *TS_MIME_FIELD_PROXY_AUTHENTICATE; -tsapi const char *TS_MIME_FIELD_PROXY_AUTHORIZATION; -tsapi const char *TS_MIME_FIELD_PROXY_CONNECTION; -tsapi const char *TS_MIME_FIELD_PUBLIC; -tsapi const char *TS_MIME_FIELD_RANGE; -tsapi const char *TS_MIME_FIELD_REFERENCES; -tsapi const char *TS_MIME_FIELD_REFERER; -tsapi const char *TS_MIME_FIELD_REPLY_TO; -tsapi const char *TS_MIME_FIELD_RETRY_AFTER; -tsapi const char *TS_MIME_FIELD_SENDER; -tsapi const char *TS_MIME_FIELD_SERVER; -tsapi const char *TS_MIME_FIELD_SET_COOKIE; -tsapi const char *TS_MIME_FIELD_STRICT_TRANSPORT_SECURITY; -tsapi const char *TS_MIME_FIELD_SUBJECT; -tsapi const char *TS_MIME_FIELD_SUMMARY; -tsapi const char *TS_MIME_FIELD_TE; -tsapi const char *TS_MIME_FIELD_TRANSFER_ENCODING; -tsapi const char *TS_MIME_FIELD_UPGRADE; -tsapi const char *TS_MIME_FIELD_USER_AGENT; -tsapi const char *TS_MIME_FIELD_VARY; -tsapi const char *TS_MIME_FIELD_VIA; -tsapi const char *TS_MIME_FIELD_WARNING; -tsapi const char *TS_MIME_FIELD_WWW_AUTHENTICATE; -tsapi const char *TS_MIME_FIELD_XREF; -tsapi const char *TS_MIME_FIELD_X_FORWARDED_FOR; -tsapi const char *TS_MIME_FIELD_FORWARDED; - -/* MIME fields string lengths */ -tsapi int TS_MIME_LEN_ACCEPT; -tsapi int TS_MIME_LEN_ACCEPT_CHARSET; -tsapi int TS_MIME_LEN_ACCEPT_ENCODING; -tsapi int TS_MIME_LEN_ACCEPT_LANGUAGE; -tsapi int TS_MIME_LEN_ACCEPT_RANGES; -tsapi int TS_MIME_LEN_AGE; -tsapi int TS_MIME_LEN_ALLOW; -tsapi int TS_MIME_LEN_APPROVED; -tsapi int TS_MIME_LEN_AUTHORIZATION; -tsapi int TS_MIME_LEN_BYTES; -tsapi int TS_MIME_LEN_CACHE_CONTROL; -tsapi int TS_MIME_LEN_CLIENT_IP; -tsapi int TS_MIME_LEN_CONNECTION; -tsapi int TS_MIME_LEN_CONTENT_BASE; -tsapi int TS_MIME_LEN_CONTENT_ENCODING; -tsapi int TS_MIME_LEN_CONTENT_LANGUAGE; -tsapi int TS_MIME_LEN_CONTENT_LENGTH; -tsapi int TS_MIME_LEN_CONTENT_LOCATION; -tsapi int TS_MIME_LEN_CONTENT_MD5; -tsapi int TS_MIME_LEN_CONTENT_RANGE; -tsapi int TS_MIME_LEN_CONTENT_TYPE; -tsapi int TS_MIME_LEN_CONTROL; -tsapi int TS_MIME_LEN_COOKIE; -tsapi int TS_MIME_LEN_DATE; -tsapi int TS_MIME_LEN_DISTRIBUTION; -tsapi int TS_MIME_LEN_ETAG; -tsapi int TS_MIME_LEN_EXPECT; -tsapi int TS_MIME_LEN_EXPIRES; -tsapi int TS_MIME_LEN_FOLLOWUP_TO; -tsapi int TS_MIME_LEN_FROM; -tsapi int TS_MIME_LEN_HOST; -tsapi int TS_MIME_LEN_IF_MATCH; -tsapi int TS_MIME_LEN_IF_MODIFIED_SINCE; -tsapi int TS_MIME_LEN_IF_NONE_MATCH; -tsapi int TS_MIME_LEN_IF_RANGE; -tsapi int TS_MIME_LEN_IF_UNMODIFIED_SINCE; -tsapi int TS_MIME_LEN_KEEP_ALIVE; -tsapi int TS_MIME_LEN_KEYWORDS; -tsapi int TS_MIME_LEN_LAST_MODIFIED; -tsapi int TS_MIME_LEN_LINES; -tsapi int TS_MIME_LEN_LOCATION; -tsapi int TS_MIME_LEN_MAX_FORWARDS; -tsapi int TS_MIME_LEN_MESSAGE_ID; -tsapi int TS_MIME_LEN_NEWSGROUPS; -tsapi int TS_MIME_LEN_ORGANIZATION; -tsapi int TS_MIME_LEN_PATH; -tsapi int TS_MIME_LEN_PRAGMA; -tsapi int TS_MIME_LEN_PROXY_AUTHENTICATE; -tsapi int TS_MIME_LEN_PROXY_AUTHORIZATION; -tsapi int TS_MIME_LEN_PROXY_CONNECTION; -tsapi int TS_MIME_LEN_PUBLIC; -tsapi int TS_MIME_LEN_RANGE; -tsapi int TS_MIME_LEN_REFERENCES; -tsapi int TS_MIME_LEN_REFERER; -tsapi int TS_MIME_LEN_REPLY_TO; -tsapi int TS_MIME_LEN_RETRY_AFTER; -tsapi int TS_MIME_LEN_SENDER; -tsapi int TS_MIME_LEN_SERVER; -tsapi int TS_MIME_LEN_SET_COOKIE; -tsapi int TS_MIME_LEN_STRICT_TRANSPORT_SECURITY; -tsapi int TS_MIME_LEN_SUBJECT; -tsapi int TS_MIME_LEN_SUMMARY; -tsapi int TS_MIME_LEN_TE; -tsapi int TS_MIME_LEN_TRANSFER_ENCODING; -tsapi int TS_MIME_LEN_UPGRADE; -tsapi int TS_MIME_LEN_USER_AGENT; -tsapi int TS_MIME_LEN_VARY; -tsapi int TS_MIME_LEN_VIA; -tsapi int TS_MIME_LEN_WARNING; -tsapi int TS_MIME_LEN_WWW_AUTHENTICATE; -tsapi int TS_MIME_LEN_XREF; -tsapi int TS_MIME_LEN_X_FORWARDED_FOR; -tsapi int TS_MIME_LEN_FORWARDED; - -/* HTTP miscellaneous values */ -tsapi const char *TS_HTTP_VALUE_BYTES; -tsapi const char *TS_HTTP_VALUE_CHUNKED; -tsapi const char *TS_HTTP_VALUE_CLOSE; -tsapi const char *TS_HTTP_VALUE_COMPRESS; -tsapi const char *TS_HTTP_VALUE_DEFLATE; -tsapi const char *TS_HTTP_VALUE_GZIP; -tsapi const char *TS_HTTP_VALUE_BROTLI; -tsapi const char *TS_HTTP_VALUE_IDENTITY; -tsapi const char *TS_HTTP_VALUE_KEEP_ALIVE; -tsapi const char *TS_HTTP_VALUE_MAX_AGE; -tsapi const char *TS_HTTP_VALUE_MAX_STALE; -tsapi const char *TS_HTTP_VALUE_MIN_FRESH; -tsapi const char *TS_HTTP_VALUE_MUST_REVALIDATE; -tsapi const char *TS_HTTP_VALUE_NONE; -tsapi const char *TS_HTTP_VALUE_NO_CACHE; -tsapi const char *TS_HTTP_VALUE_NO_STORE; -tsapi const char *TS_HTTP_VALUE_NO_TRANSFORM; -tsapi const char *TS_HTTP_VALUE_ONLY_IF_CACHED; -tsapi const char *TS_HTTP_VALUE_PRIVATE; -tsapi const char *TS_HTTP_VALUE_PROXY_REVALIDATE; -tsapi const char *TS_HTTP_VALUE_PUBLIC; -tsapi const char *TS_HTTP_VALUE_S_MAXAGE; - -/* HTTP miscellaneous values string lengths */ -tsapi int TS_HTTP_LEN_BYTES; -tsapi int TS_HTTP_LEN_CHUNKED; -tsapi int TS_HTTP_LEN_CLOSE; -tsapi int TS_HTTP_LEN_COMPRESS; -tsapi int TS_HTTP_LEN_DEFLATE; -tsapi int TS_HTTP_LEN_GZIP; -tsapi int TS_HTTP_LEN_BROTLI; -tsapi int TS_HTTP_LEN_IDENTITY; -tsapi int TS_HTTP_LEN_KEEP_ALIVE; -tsapi int TS_HTTP_LEN_MAX_AGE; -tsapi int TS_HTTP_LEN_MAX_STALE; -tsapi int TS_HTTP_LEN_MIN_FRESH; -tsapi int TS_HTTP_LEN_MUST_REVALIDATE; -tsapi int TS_HTTP_LEN_NONE; -tsapi int TS_HTTP_LEN_NO_CACHE; -tsapi int TS_HTTP_LEN_NO_STORE; -tsapi int TS_HTTP_LEN_NO_TRANSFORM; -tsapi int TS_HTTP_LEN_ONLY_IF_CACHED; -tsapi int TS_HTTP_LEN_PRIVATE; -tsapi int TS_HTTP_LEN_PROXY_REVALIDATE; -tsapi int TS_HTTP_LEN_PUBLIC; -tsapi int TS_HTTP_LEN_S_MAXAGE; - -/* HTTP methods */ -tsapi const char *TS_HTTP_METHOD_CONNECT; -tsapi const char *TS_HTTP_METHOD_DELETE; -tsapi const char *TS_HTTP_METHOD_GET; -tsapi const char *TS_HTTP_METHOD_HEAD; -tsapi const char *TS_HTTP_METHOD_OPTIONS; -tsapi const char *TS_HTTP_METHOD_POST; -tsapi const char *TS_HTTP_METHOD_PURGE; -tsapi const char *TS_HTTP_METHOD_PUT; -tsapi const char *TS_HTTP_METHOD_TRACE; -tsapi const char *TS_HTTP_METHOD_PUSH; - -/* HTTP methods string lengths */ -tsapi int TS_HTTP_LEN_CONNECT; -tsapi int TS_HTTP_LEN_DELETE; -tsapi int TS_HTTP_LEN_GET; -tsapi int TS_HTTP_LEN_HEAD; -tsapi int TS_HTTP_LEN_OPTIONS; -tsapi int TS_HTTP_LEN_POST; -tsapi int TS_HTTP_LEN_PURGE; -tsapi int TS_HTTP_LEN_PUT; -tsapi int TS_HTTP_LEN_TRACE; -tsapi int TS_HTTP_LEN_PUSH; +namespace tsapi +{ +namespace c +{ + + /* URL schemes */ + const char *TS_URL_SCHEME_FILE; + const char *TS_URL_SCHEME_FTP; + const char *TS_URL_SCHEME_GOPHER; + const char *TS_URL_SCHEME_HTTP; + const char *TS_URL_SCHEME_HTTPS; + const char *TS_URL_SCHEME_MAILTO; + const char *TS_URL_SCHEME_NEWS; + const char *TS_URL_SCHEME_NNTP; + const char *TS_URL_SCHEME_PROSPERO; + const char *TS_URL_SCHEME_TELNET; + const char *TS_URL_SCHEME_TUNNEL; + const char *TS_URL_SCHEME_WAIS; + const char *TS_URL_SCHEME_PNM; + const char *TS_URL_SCHEME_RTSP; + const char *TS_URL_SCHEME_RTSPU; + const char *TS_URL_SCHEME_MMS; + const char *TS_URL_SCHEME_MMSU; + const char *TS_URL_SCHEME_MMST; + const char *TS_URL_SCHEME_WS; + const char *TS_URL_SCHEME_WSS; + + /* URL schemes string lengths */ + int TS_URL_LEN_FILE; + int TS_URL_LEN_FTP; + int TS_URL_LEN_GOPHER; + int TS_URL_LEN_HTTP; + int TS_URL_LEN_HTTPS; + int TS_URL_LEN_MAILTO; + int TS_URL_LEN_NEWS; + int TS_URL_LEN_NNTP; + int TS_URL_LEN_PROSPERO; + int TS_URL_LEN_TELNET; + int TS_URL_LEN_TUNNEL; + int TS_URL_LEN_WAIS; + int TS_URL_LEN_PNM; + int TS_URL_LEN_RTSP; + int TS_URL_LEN_RTSPU; + int TS_URL_LEN_MMS; + int TS_URL_LEN_MMSU; + int TS_URL_LEN_MMST; + int TS_URL_LEN_WS; + int TS_URL_LEN_WSS; + + /* MIME fields */ + const char *TS_MIME_FIELD_ACCEPT; + const char *TS_MIME_FIELD_ACCEPT_CHARSET; + const char *TS_MIME_FIELD_ACCEPT_ENCODING; + const char *TS_MIME_FIELD_ACCEPT_LANGUAGE; + const char *TS_MIME_FIELD_ACCEPT_RANGES; + const char *TS_MIME_FIELD_AGE; + const char *TS_MIME_FIELD_ALLOW; + const char *TS_MIME_FIELD_APPROVED; + const char *TS_MIME_FIELD_AUTHORIZATION; + const char *TS_MIME_FIELD_BYTES; + const char *TS_MIME_FIELD_CACHE_CONTROL; + const char *TS_MIME_FIELD_CLIENT_IP; + const char *TS_MIME_FIELD_CONNECTION; + const char *TS_MIME_FIELD_CONTENT_BASE; + const char *TS_MIME_FIELD_CONTENT_ENCODING; + const char *TS_MIME_FIELD_CONTENT_LANGUAGE; + const char *TS_MIME_FIELD_CONTENT_LENGTH; + const char *TS_MIME_FIELD_CONTENT_LOCATION; + const char *TS_MIME_FIELD_CONTENT_MD5; + const char *TS_MIME_FIELD_CONTENT_RANGE; + const char *TS_MIME_FIELD_CONTENT_TYPE; + const char *TS_MIME_FIELD_CONTROL; + const char *TS_MIME_FIELD_COOKIE; + const char *TS_MIME_FIELD_DATE; + const char *TS_MIME_FIELD_DISTRIBUTION; + const char *TS_MIME_FIELD_ETAG; + const char *TS_MIME_FIELD_EXPECT; + const char *TS_MIME_FIELD_EXPIRES; + const char *TS_MIME_FIELD_FOLLOWUP_TO; + const char *TS_MIME_FIELD_FROM; + const char *TS_MIME_FIELD_HOST; + const char *TS_MIME_FIELD_IF_MATCH; + const char *TS_MIME_FIELD_IF_MODIFIED_SINCE; + const char *TS_MIME_FIELD_IF_NONE_MATCH; + const char *TS_MIME_FIELD_IF_RANGE; + const char *TS_MIME_FIELD_IF_UNMODIFIED_SINCE; + const char *TS_MIME_FIELD_KEEP_ALIVE; + const char *TS_MIME_FIELD_KEYWORDS; + const char *TS_MIME_FIELD_LAST_MODIFIED; + const char *TS_MIME_FIELD_LINES; + const char *TS_MIME_FIELD_LOCATION; + const char *TS_MIME_FIELD_MAX_FORWARDS; + const char *TS_MIME_FIELD_MESSAGE_ID; + const char *TS_MIME_FIELD_NEWSGROUPS; + const char *TS_MIME_FIELD_ORGANIZATION; + const char *TS_MIME_FIELD_PATH; + const char *TS_MIME_FIELD_PRAGMA; + const char *TS_MIME_FIELD_PROXY_AUTHENTICATE; + const char *TS_MIME_FIELD_PROXY_AUTHORIZATION; + const char *TS_MIME_FIELD_PROXY_CONNECTION; + const char *TS_MIME_FIELD_PUBLIC; + const char *TS_MIME_FIELD_RANGE; + const char *TS_MIME_FIELD_REFERENCES; + const char *TS_MIME_FIELD_REFERER; + const char *TS_MIME_FIELD_REPLY_TO; + const char *TS_MIME_FIELD_RETRY_AFTER; + const char *TS_MIME_FIELD_SENDER; + const char *TS_MIME_FIELD_SERVER; + const char *TS_MIME_FIELD_SET_COOKIE; + const char *TS_MIME_FIELD_STRICT_TRANSPORT_SECURITY; + const char *TS_MIME_FIELD_SUBJECT; + const char *TS_MIME_FIELD_SUMMARY; + const char *TS_MIME_FIELD_TE; + const char *TS_MIME_FIELD_TRANSFER_ENCODING; + const char *TS_MIME_FIELD_UPGRADE; + const char *TS_MIME_FIELD_USER_AGENT; + const char *TS_MIME_FIELD_VARY; + const char *TS_MIME_FIELD_VIA; + const char *TS_MIME_FIELD_WARNING; + const char *TS_MIME_FIELD_WWW_AUTHENTICATE; + const char *TS_MIME_FIELD_XREF; + const char *TS_MIME_FIELD_X_FORWARDED_FOR; + const char *TS_MIME_FIELD_FORWARDED; + + /* MIME fields string lengths */ + int TS_MIME_LEN_ACCEPT; + int TS_MIME_LEN_ACCEPT_CHARSET; + int TS_MIME_LEN_ACCEPT_ENCODING; + int TS_MIME_LEN_ACCEPT_LANGUAGE; + int TS_MIME_LEN_ACCEPT_RANGES; + int TS_MIME_LEN_AGE; + int TS_MIME_LEN_ALLOW; + int TS_MIME_LEN_APPROVED; + int TS_MIME_LEN_AUTHORIZATION; + int TS_MIME_LEN_BYTES; + int TS_MIME_LEN_CACHE_CONTROL; + int TS_MIME_LEN_CLIENT_IP; + int TS_MIME_LEN_CONNECTION; + int TS_MIME_LEN_CONTENT_BASE; + int TS_MIME_LEN_CONTENT_ENCODING; + int TS_MIME_LEN_CONTENT_LANGUAGE; + int TS_MIME_LEN_CONTENT_LENGTH; + int TS_MIME_LEN_CONTENT_LOCATION; + int TS_MIME_LEN_CONTENT_MD5; + int TS_MIME_LEN_CONTENT_RANGE; + int TS_MIME_LEN_CONTENT_TYPE; + int TS_MIME_LEN_CONTROL; + int TS_MIME_LEN_COOKIE; + int TS_MIME_LEN_DATE; + int TS_MIME_LEN_DISTRIBUTION; + int TS_MIME_LEN_ETAG; + int TS_MIME_LEN_EXPECT; + int TS_MIME_LEN_EXPIRES; + int TS_MIME_LEN_FOLLOWUP_TO; + int TS_MIME_LEN_FROM; + int TS_MIME_LEN_HOST; + int TS_MIME_LEN_IF_MATCH; + int TS_MIME_LEN_IF_MODIFIED_SINCE; + int TS_MIME_LEN_IF_NONE_MATCH; + int TS_MIME_LEN_IF_RANGE; + int TS_MIME_LEN_IF_UNMODIFIED_SINCE; + int TS_MIME_LEN_KEEP_ALIVE; + int TS_MIME_LEN_KEYWORDS; + int TS_MIME_LEN_LAST_MODIFIED; + int TS_MIME_LEN_LINES; + int TS_MIME_LEN_LOCATION; + int TS_MIME_LEN_MAX_FORWARDS; + int TS_MIME_LEN_MESSAGE_ID; + int TS_MIME_LEN_NEWSGROUPS; + int TS_MIME_LEN_ORGANIZATION; + int TS_MIME_LEN_PATH; + int TS_MIME_LEN_PRAGMA; + int TS_MIME_LEN_PROXY_AUTHENTICATE; + int TS_MIME_LEN_PROXY_AUTHORIZATION; + int TS_MIME_LEN_PROXY_CONNECTION; + int TS_MIME_LEN_PUBLIC; + int TS_MIME_LEN_RANGE; + int TS_MIME_LEN_REFERENCES; + int TS_MIME_LEN_REFERER; + int TS_MIME_LEN_REPLY_TO; + int TS_MIME_LEN_RETRY_AFTER; + int TS_MIME_LEN_SENDER; + int TS_MIME_LEN_SERVER; + int TS_MIME_LEN_SET_COOKIE; + int TS_MIME_LEN_STRICT_TRANSPORT_SECURITY; + int TS_MIME_LEN_SUBJECT; + int TS_MIME_LEN_SUMMARY; + int TS_MIME_LEN_TE; + int TS_MIME_LEN_TRANSFER_ENCODING; + int TS_MIME_LEN_UPGRADE; + int TS_MIME_LEN_USER_AGENT; + int TS_MIME_LEN_VARY; + int TS_MIME_LEN_VIA; + int TS_MIME_LEN_WARNING; + int TS_MIME_LEN_WWW_AUTHENTICATE; + int TS_MIME_LEN_XREF; + int TS_MIME_LEN_X_FORWARDED_FOR; + int TS_MIME_LEN_FORWARDED; + + /* HTTP miscellaneous values */ + const char *TS_HTTP_VALUE_BYTES; + const char *TS_HTTP_VALUE_CHUNKED; + const char *TS_HTTP_VALUE_CLOSE; + const char *TS_HTTP_VALUE_COMPRESS; + const char *TS_HTTP_VALUE_DEFLATE; + const char *TS_HTTP_VALUE_GZIP; + const char *TS_HTTP_VALUE_BROTLI; + const char *TS_HTTP_VALUE_IDENTITY; + const char *TS_HTTP_VALUE_KEEP_ALIVE; + const char *TS_HTTP_VALUE_MAX_AGE; + const char *TS_HTTP_VALUE_MAX_STALE; + const char *TS_HTTP_VALUE_MIN_FRESH; + const char *TS_HTTP_VALUE_MUST_REVALIDATE; + const char *TS_HTTP_VALUE_NONE; + const char *TS_HTTP_VALUE_NO_CACHE; + const char *TS_HTTP_VALUE_NO_STORE; + const char *TS_HTTP_VALUE_NO_TRANSFORM; + const char *TS_HTTP_VALUE_ONLY_IF_CACHED; + const char *TS_HTTP_VALUE_PRIVATE; + const char *TS_HTTP_VALUE_PROXY_REVALIDATE; + const char *TS_HTTP_VALUE_PUBLIC; + const char *TS_HTTP_VALUE_S_MAXAGE; + + /* HTTP miscellaneous values string lengths */ + int TS_HTTP_LEN_BYTES; + int TS_HTTP_LEN_CHUNKED; + int TS_HTTP_LEN_CLOSE; + int TS_HTTP_LEN_COMPRESS; + int TS_HTTP_LEN_DEFLATE; + int TS_HTTP_LEN_GZIP; + int TS_HTTP_LEN_BROTLI; + int TS_HTTP_LEN_IDENTITY; + int TS_HTTP_LEN_KEEP_ALIVE; + int TS_HTTP_LEN_MAX_AGE; + int TS_HTTP_LEN_MAX_STALE; + int TS_HTTP_LEN_MIN_FRESH; + int TS_HTTP_LEN_MUST_REVALIDATE; + int TS_HTTP_LEN_NONE; + int TS_HTTP_LEN_NO_CACHE; + int TS_HTTP_LEN_NO_STORE; + int TS_HTTP_LEN_NO_TRANSFORM; + int TS_HTTP_LEN_ONLY_IF_CACHED; + int TS_HTTP_LEN_PRIVATE; + int TS_HTTP_LEN_PROXY_REVALIDATE; + int TS_HTTP_LEN_PUBLIC; + int TS_HTTP_LEN_S_MAXAGE; + + /* HTTP methods */ + const char *TS_HTTP_METHOD_CONNECT; + const char *TS_HTTP_METHOD_DELETE; + const char *TS_HTTP_METHOD_GET; + const char *TS_HTTP_METHOD_HEAD; + const char *TS_HTTP_METHOD_OPTIONS; + const char *TS_HTTP_METHOD_POST; + const char *TS_HTTP_METHOD_PURGE; + const char *TS_HTTP_METHOD_PUT; + const char *TS_HTTP_METHOD_TRACE; + const char *TS_HTTP_METHOD_PUSH; + + /* HTTP methods string lengths */ + int TS_HTTP_LEN_CONNECT; + int TS_HTTP_LEN_DELETE; + int TS_HTTP_LEN_GET; + int TS_HTTP_LEN_HEAD; + int TS_HTTP_LEN_OPTIONS; + int TS_HTTP_LEN_POST; + int TS_HTTP_LEN_PURGE; + int TS_HTTP_LEN_PUT; + int TS_HTTP_LEN_TRACE; + int TS_HTTP_LEN_PUSH; + +} // end namespace c +} // end namespace tsapi HttpAPIHooks *http_global_hooks = nullptr; SslAPIHooks *ssl_hooks = nullptr; @@ -405,7 +413,7 @@ static ClassAllocator mHandleAllocator("MIMEFieldSDKHandle") //////////////////////////////////////////////////////////////////// void -TSStatus(const char *fmt, ...) +tsapi::c::TSStatus(const char *fmt, ...) { va_list args; @@ -415,7 +423,7 @@ TSStatus(const char *fmt, ...) } void -TSNote(const char *fmt, ...) +tsapi::c::TSNote(const char *fmt, ...) { va_list args; @@ -425,7 +433,7 @@ TSNote(const char *fmt, ...) } void -TSWarning(const char *fmt, ...) +tsapi::c::TSWarning(const char *fmt, ...) { va_list args; @@ -435,7 +443,7 @@ TSWarning(const char *fmt, ...) } void -TSError(const char *fmt, ...) +tsapi::c::TSError(const char *fmt, ...) { va_list args; @@ -445,7 +453,7 @@ TSError(const char *fmt, ...) } void -TSFatal(const char *fmt, ...) +tsapi::c::TSFatal(const char *fmt, ...) { va_list args; @@ -455,7 +463,7 @@ TSFatal(const char *fmt, ...) } void -TSAlert(const char *fmt, ...) +tsapi::c::TSAlert(const char *fmt, ...) { va_list args; @@ -465,7 +473,7 @@ TSAlert(const char *fmt, ...) } void -TSEmergency(const char *fmt, ...) +tsapi::c::TSEmergency(const char *fmt, ...) { va_list args; @@ -476,7 +484,7 @@ TSEmergency(const char *fmt, ...) // Assert in debug AND optim void -_TSReleaseAssert(const char *text, const char *file, int line) +tsapi::c::_TSReleaseAssert(const char *text, const char *file, int line) { _ink_assert(text, file, line); } @@ -484,13 +492,13 @@ _TSReleaseAssert(const char *text, const char *file, int line) // Assert only in debug int #ifdef DEBUG -_TSAssert(const char *text, const char *file, int line) +tsapi::c::_TSAssert(const char *text, const char *file, int line) { _ink_assert(text, file, line); return 0; } #else -_TSAssert(const char *, const char *, int) +tsapi::c::_TSAssert(const char *, const char *, int) { return 0; } @@ -545,7 +553,7 @@ _TSAssert(const char *, const char *, int) // * maintains the associated MIMEHdrImpl when returning field // slots from lookup and create functions // -// If the MIMEHdrImpl pointer is NULL, then the handle points +// If the MIMEHdrImpl pointer is null, then the handle points // to a standalone field, otherwise the handle points to a field // within the MIME header. // @@ -1717,38 +1725,38 @@ api_init() //////////////////////////////////////////////////////////////////// void * -_TSmalloc(size_t size, const char * /* path ATS_UNUSED */) +tsapi::c::_TSmalloc(size_t size, const char * /* path ATS_UNUSED */) { return ats_malloc(size); } void * -_TSrealloc(void *ptr, size_t size, const char * /* path ATS_UNUSED */) +tsapi::c::_TSrealloc(void *ptr, size_t size, const char * /* path ATS_UNUSED */) { return ats_realloc(ptr, size); } // length has to be int64_t and not size_t, since -1 means to call strlen() to get length char * -_TSstrdup(const char *str, int64_t length, const char *path) +tsapi::c::_TSstrdup(const char *str, int64_t length, const char *path) { return _xstrdup(str, length, path); } size_t -_TSstrlcpy(char *dst, const char *str, size_t siz) +tsapi::c::TSstrlcpy(char *dst, const char *str, size_t siz) { return ink_strlcpy(dst, str, siz); } size_t -_TSstrlcat(char *dst, const char *str, size_t siz) +tsapi::c::TSstrlcat(char *dst, const char *str, size_t siz) { return ink_strlcat(dst, str, siz); } void -_TSfree(void *ptr) +tsapi::c::TSfree(void *ptr) { ats_free(ptr); } @@ -1759,7 +1767,7 @@ _TSfree(void *ptr) // //////////////////////////////////////////////////////////////////// TSReturnCode -TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_size, size_t *length) +tsapi::c::TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_size, size_t *length) { sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS); @@ -1768,7 +1776,7 @@ TSBase64Decode(const char *str, size_t str_len, unsigned char *dst, size_t dst_s } TSReturnCode -TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length) +tsapi::c::TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length) { sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS); @@ -1783,19 +1791,19 @@ TSBase64Encode(const char *str, size_t str_len, char *dst, size_t dst_size, size //////////////////////////////////////////////////////////////////// unsigned int -TSrandom() +tsapi::c::TSrandom() { return this_ethread()->generator.random(); } double -TSdrandom() +tsapi::c::TSdrandom() { return this_ethread()->generator.drandom(); } ink_hrtime -TShrtime() +tsapi::c::TShrtime() { return ink_get_hrtime(); } @@ -1807,50 +1815,50 @@ TShrtime() //////////////////////////////////////////////////////////////////// const char * -TSInstallDirGet() +tsapi::c::TSInstallDirGet() { static std::string prefix = Layout::get()->prefix; return prefix.c_str(); } const char * -TSConfigDirGet() +tsapi::c::TSConfigDirGet() { static std::string sysconfdir = RecConfigReadConfigDir(); return sysconfdir.c_str(); } const char * -TSRuntimeDirGet() +tsapi::c::TSRuntimeDirGet() { static std::string runtimedir = RecConfigReadRuntimeDir(); return runtimedir.c_str(); } const char * -TSTrafficServerVersionGet() +tsapi::c::TSTrafficServerVersionGet() { return traffic_server_version; } int -TSTrafficServerVersionGetMajor() +tsapi::c::TSTrafficServerVersionGetMajor() { return ts_major_version; } int -TSTrafficServerVersionGetMinor() +tsapi::c::TSTrafficServerVersionGetMinor() { return ts_minor_version; } int -TSTrafficServerVersionGetPatch() +tsapi::c::TSTrafficServerVersionGetPatch() { return ts_patch_version; } const char * -TSPluginDirGet() +tsapi::c::TSPluginDirGet() { static std::string path = RecConfigReadPluginDir(); return path.c_str(); @@ -1863,7 +1871,7 @@ TSPluginDirGet() //////////////////////////////////////////////////////////////////// TSReturnCode -TSPluginRegister(const TSPluginRegistrationInfo *plugin_info) +tsapi::c::TSPluginRegister(const TSPluginRegistrationInfo *plugin_info) { sdk_assert(sdk_sanity_check_null_ptr((void *)plugin_info) == TS_SUCCESS); @@ -1889,7 +1897,7 @@ TSPluginRegister(const TSPluginRegistrationInfo *plugin_info) } TSReturnCode -TSPluginDSOReloadEnable(int enabled) +tsapi::c::TSPluginDSOReloadEnable(int enabled) { TSReturnCode ret = TS_SUCCESS; if (!plugin_reg_current) { @@ -1911,8 +1919,8 @@ TSPluginDSOReloadEnable(int enabled) // //////////////////////////////////////////////////////////////////// -TSFile -TSfopen(const char *filename, const char *mode) +tsapi::c::TSFile +tsapi::c::TSfopen(const char *filename, const char *mode) { FileImpl *file; @@ -1926,7 +1934,7 @@ TSfopen(const char *filename, const char *mode) } void -TSfclose(TSFile filep) +tsapi::c::TSfclose(TSFile filep) { FileImpl *file = (FileImpl *)filep; file->fclose(); @@ -1934,28 +1942,28 @@ TSfclose(TSFile filep) } ssize_t -TSfread(TSFile filep, void *buf, size_t length) +tsapi::c::TSfread(TSFile filep, void *buf, size_t length) { FileImpl *file = (FileImpl *)filep; return file->fread(buf, length); } ssize_t -TSfwrite(TSFile filep, const void *buf, size_t length) +tsapi::c::TSfwrite(TSFile filep, const void *buf, size_t length) { FileImpl *file = (FileImpl *)filep; return file->fwrite(buf, length); } void -TSfflush(TSFile filep) +tsapi::c::TSfflush(TSFile filep) { FileImpl *file = (FileImpl *)filep; file->fflush(); } char * -TSfgets(TSFile filep, char *buf, size_t length) +tsapi::c::TSfgets(TSFile filep, char *buf, size_t length) { FileImpl *file = (FileImpl *)filep; return file->fgets(buf, length); @@ -1968,7 +1976,7 @@ TSfgets(TSFile filep, char *buf, size_t length) //////////////////////////////////////////////////////////////////// TSReturnCode -TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc) +tsapi::c::TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc) { MIMEFieldSDKHandle *field_handle; HdrHeapObjImpl *obj = (HdrHeapObjImpl *)mloc; @@ -2008,8 +2016,8 @@ TSHandleMLocRelease(TSMBuffer bufp, TSMLoc parent, TSMLoc mloc) // TSMBuffer: pointers to HdrHeapSDKHandle objects -TSMBuffer -TSMBufferCreate() +tsapi::c::TSMBuffer +tsapi::c::TSMBufferCreate() { TSMBuffer bufp; HdrHeapSDKHandle *new_heap = new HdrHeapSDKHandle; @@ -2022,7 +2030,7 @@ TSMBufferCreate() } TSReturnCode -TSMBufferDestroy(TSMBuffer bufp) +tsapi::c::TSMBufferDestroy(TSMBuffer bufp) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -2048,7 +2056,7 @@ TSMBufferDestroy(TSMBuffer bufp) // TSMBuffer: pointers to HdrHeapSDKHandle objects // TSMLoc: pointers to URLImpl objects TSReturnCode -TSUrlCreate(TSMBuffer bufp, TSMLoc *locp) +tsapi::c::TSUrlCreate(TSMBuffer bufp, TSMLoc *locp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr(locp) == TS_SUCCESS); @@ -2062,7 +2070,7 @@ TSUrlCreate(TSMBuffer bufp, TSMLoc *locp) } TSReturnCode -TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp) +tsapi::c::TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp) { sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS); @@ -2086,7 +2094,7 @@ TSUrlClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_url, TSMLoc *locp } TSReturnCode -TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj) +tsapi::c::TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj) { sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS); @@ -2110,7 +2118,7 @@ TSUrlCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_o } void -TSUrlPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) +tsapi::c::TSUrlPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2144,8 +2152,8 @@ TSUrlPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) } while (!done); } -TSParseResult -TSUrlParse(TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) +tsapi::c::TSParseResult +tsapi::c::TSUrlParse(TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2165,7 +2173,7 @@ TSUrlParse(TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) } int -TSUrlLengthGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSUrlLengthGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2175,7 +2183,7 @@ TSUrlLengthGet(TSMBuffer bufp, TSMLoc obj) } char * -TSUrlStringGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlStringGet(TSMBuffer bufp, TSMLoc obj, int *length) { // bufp is not actually used anymore, so it can be null. if (bufp) { @@ -2231,13 +2239,13 @@ URLPartSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length, URLPartSet } const char * -TSUrlRawSchemeGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlRawSchemeGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::scheme_get); } const char * -TSUrlSchemeGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlSchemeGet(TSMBuffer bufp, TSMLoc obj, int *length) { char const *data = TSUrlRawSchemeGet(bufp, obj, length); if (data && *length) { @@ -2260,7 +2268,7 @@ TSUrlSchemeGet(TSMBuffer bufp, TSMLoc obj, int *length) } TSReturnCode -TSUrlSchemeSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlSchemeSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::scheme_set); } @@ -2268,43 +2276,43 @@ TSUrlSchemeSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) /* Internet specific URLs */ const char * -TSUrlUserGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlUserGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::user_get); } TSReturnCode -TSUrlUserSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlUserSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::user_set); } const char * -TSUrlPasswordGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlPasswordGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::password_get); } TSReturnCode -TSUrlPasswordSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlPasswordSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::password_set); } const char * -TSUrlHostGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlHostGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::host_get); } TSReturnCode -TSUrlHostSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlHostSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::host_set); } int -TSUrlPortGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSUrlPortGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2317,7 +2325,7 @@ TSUrlPortGet(TSMBuffer bufp, TSMLoc obj) } int -TSUrlRawPortGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSUrlRawPortGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2330,7 +2338,7 @@ TSUrlRawPortGet(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSUrlPortSet(TSMBuffer bufp, TSMLoc obj, int port) +tsapi::c::TSUrlPortSet(TSMBuffer bufp, TSMLoc obj, int port) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2350,13 +2358,13 @@ TSUrlPortSet(TSMBuffer bufp, TSMLoc obj, int port) /* FTP and HTTP specific URLs */ const char * -TSUrlPathGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlPathGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::path_get); } TSReturnCode -TSUrlPathSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlPathSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::path_set); } @@ -2364,7 +2372,7 @@ TSUrlPathSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) /* FTP specific URLs */ int -TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2376,7 +2384,7 @@ TSUrlFtpTypeGet(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc obj, int type) +tsapi::c::TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc obj, int type) { // The valid values are : 0, 65('A'), 97('a'), // 69('E'), 101('e'), 73 ('I') and 105('i'). @@ -2398,44 +2406,44 @@ TSUrlFtpTypeSet(TSMBuffer bufp, TSMLoc obj, int type) /* HTTP specific URLs */ const char * -TSUrlHttpParamsGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlHttpParamsGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::params_get); } TSReturnCode -TSUrlHttpParamsSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlHttpParamsSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::params_set); } const char * -TSUrlHttpQueryGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlHttpQueryGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::query_get); } TSReturnCode -TSUrlHttpQuerySet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlHttpQuerySet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::query_set); } const char * -TSUrlHttpFragmentGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSUrlHttpFragmentGet(TSMBuffer bufp, TSMLoc obj, int *length) { return URLPartGet(bufp, obj, length, &URL::fragment_get); } TSReturnCode -TSUrlHttpFragmentSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSUrlHttpFragmentSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { return URLPartSet(bufp, obj, value, length, &URL::fragment_set); } // URL percent encoding TSReturnCode -TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, size_t *length, const unsigned char *map) +tsapi::c::TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, size_t *length, const unsigned char *map) { sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS); @@ -2469,7 +2477,7 @@ TSStringPercentEncode(const char *str, int str_len, char *dst, size_t dst_size, } TSReturnCode -TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length) +tsapi::c::TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_size, size_t *length) { sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)dst) == TS_SUCCESS); @@ -2497,7 +2505,7 @@ TSStringPercentDecode(const char *str, size_t str_len, char *dst, size_t dst_siz } TSReturnCode -TSUrlPercentEncode(TSMBuffer bufp, TSMLoc obj, char *dst, size_t dst_size, size_t *length, const unsigned char *map) +tsapi::c::TSUrlPercentEncode(TSMBuffer bufp, TSMLoc obj, char *dst, size_t dst_size, size_t *length, const unsigned char *map) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_url_handle(obj) == TS_SUCCESS); @@ -2517,7 +2525,7 @@ TSUrlPercentEncode(TSMBuffer bufp, TSMLoc obj, char *dst, size_t dst_size, size_ // pton TSReturnCode -TSIpStringToAddr(const char *str, size_t str_len, sockaddr *addr) +tsapi::c::TSIpStringToAddr(const char *str, size_t str_len, sockaddr *addr) { sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS); @@ -2538,8 +2546,8 @@ TSIpStringToAddr(const char *str, size_t str_len, sockaddr *addr) /* MimeParser */ /**************/ -TSMimeParser -TSMimeParserCreate() +tsapi::c::TSMimeParser +tsapi::c::TSMimeParserCreate() { TSMimeParser parser = reinterpret_cast(ats_malloc(sizeof(MIMEParser))); @@ -2548,7 +2556,7 @@ TSMimeParserCreate() } void -TSMimeParserClear(TSMimeParser parser) +tsapi::c::TSMimeParserClear(TSMimeParser parser) { sdk_assert(sdk_sanity_check_mime_parser(parser) == TS_SUCCESS); @@ -2556,7 +2564,7 @@ TSMimeParserClear(TSMimeParser parser) } void -TSMimeParserDestroy(TSMimeParser parser) +tsapi::c::TSMimeParserDestroy(TSMimeParser parser) { sdk_assert(sdk_sanity_check_mime_parser(parser) == TS_SUCCESS); @@ -2572,11 +2580,11 @@ TSMimeParserDestroy(TSMimeParser parser) // TSMLoc: pointers to MIMEFieldSDKHandle objects TSReturnCode -TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp) +tsapi::c::TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return - // TS_ERROR. If not allowed, return NULL. + // TS_ERROR. If not allowed, set *locp to TS_NULL_MLOC. sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)locp) == TS_SUCCESS); @@ -2589,7 +2597,7 @@ TSMimeHdrCreate(TSMBuffer bufp, TSMLoc *locp) } TSReturnCode -TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc obj) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -2609,11 +2617,11 @@ TSMimeHdrDestroy(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp) +tsapi::c::TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return - // TS_ERROR. If not allowed, return NULL. + // TS_ERROR. If not allowed, set *locp to TS_NULL_MLOC. sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mime_hdr_handle(src_hdr) == TS_SUCCESS); @@ -2638,7 +2646,7 @@ TSMimeHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc * } TSReturnCode -TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj) +tsapi::c::TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -2669,7 +2677,7 @@ TSMimeHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc s } void -TSMimeHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) +tsapi::c::TSMimeHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS)); @@ -2699,8 +2707,8 @@ TSMimeHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) } while (!done); } -TSParseResult -TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) +tsapi::c::TSParseResult +tsapi::c::TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS)); @@ -2719,7 +2727,7 @@ TSMimeHdrParse(TSMimeParser parser, TSMBuffer bufp, TSMLoc obj, const char **sta } int -TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS)); @@ -2729,7 +2737,7 @@ TSMimeHdrLengthGet(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS)); @@ -2745,7 +2753,7 @@ TSMimeHdrFieldsClear(TSMBuffer bufp, TSMLoc obj) } int -TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(obj) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS)); @@ -2756,7 +2764,7 @@ TSMimeHdrFieldsCount(TSMBuffer bufp, TSMLoc obj) // The following three helper functions should not be used in plugins! Since they are not used // by plugins, there's no need to validate the input. -const char * +static const char * TSMimeFieldValueGet(TSMBuffer /* bufp ATS_UNUSED */, TSMLoc field_obj, int idx, int *value_len_ptr) { MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field_obj; @@ -2768,7 +2776,7 @@ TSMimeFieldValueGet(TSMBuffer /* bufp ATS_UNUSED */, TSMLoc field_obj, int idx, } } -void +static void TSMimeFieldValueSet(TSMBuffer bufp, TSMLoc field_obj, int idx, const char *value, int length) { MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field_obj; @@ -2785,7 +2793,7 @@ TSMimeFieldValueSet(TSMBuffer bufp, TSMLoc field_obj, int idx, const char *value } } -void +static void TSMimeFieldValueInsert(TSMBuffer bufp, TSMLoc field_obj, const char *value, int length, int idx) { MIMEFieldSDKHandle *handle = (MIMEFieldSDKHandle *)field_obj; @@ -2806,7 +2814,7 @@ TSMimeFieldValueInsert(TSMBuffer bufp, TSMLoc field_obj, const char *value, int // TSMLoc: pointers to MIMEFieldSDKHandle objects int -TSMimeHdrFieldEqual(TSMBuffer bufp, TSMLoc hdr_obj, TSMLoc field1_obj, TSMLoc field2_obj) +tsapi::c::TSMimeHdrFieldEqual(TSMBuffer bufp, TSMLoc hdr_obj, TSMLoc field1_obj, TSMLoc field2_obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_field_handle(field1_obj, hdr_obj) == TS_SUCCESS); @@ -2821,8 +2829,8 @@ TSMimeHdrFieldEqual(TSMBuffer bufp, TSMLoc hdr_obj, TSMLoc field1_obj, TSMLoc fi return (field1_handle->field_ptr == field2_handle->field_ptr); } -TSMLoc -TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr_obj, int idx) +tsapi::c::TSMLoc +tsapi::c::TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr_obj, int idx) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr_obj) == TS_SUCCESS) || @@ -2842,8 +2850,8 @@ TSMimeHdrFieldGet(TSMBuffer bufp, TSMLoc hdr_obj, int idx) return reinterpret_cast(h); } -TSMLoc -TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr_obj, const char *name, int length) +tsapi::c::TSMLoc +tsapi::c::TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr_obj, const char *name, int length) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr_obj) == TS_SUCCESS) || @@ -2868,7 +2876,7 @@ TSMimeHdrFieldFind(TSMBuffer bufp, TSMLoc hdr_obj, const char *name, int length) } TSReturnCode -TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) +tsapi::c::TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -2892,7 +2900,7 @@ TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) // inside a MIME header (the correct way), or it might have been // // created in isolation as a "standalone field" (the old way). // // // - // If it's a standalone field (the associated mime header is NULL), // + // If it's a standalone field (the associated mime header is null), // // then we need to now allocate a real field inside the header, // // copy over the data, and convert the standalone field into a // // forwarding pointer to the real field, in case it's used again // @@ -2919,7 +2927,7 @@ TSMimeHdrFieldAppend(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) } TSReturnCode -TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) +tsapi::c::TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -2946,7 +2954,7 @@ TSMimeHdrFieldRemove(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) } TSReturnCode -TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) +tsapi::c::TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -2983,11 +2991,11 @@ TSMimeHdrFieldDestroy(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc field_mloc) } TSReturnCode -TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc *locp) +tsapi::c::TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc *locp) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return - // TS_ERROR. If not allowed, return NULL. + // TS_ERROR. If not allowed, set *locp to TS_NULL_MLOC. sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(mh_mloc) == TS_SUCCESS)); @@ -3007,7 +3015,7 @@ TSMimeHdrFieldCreate(TSMBuffer bufp, TSMLoc mh_mloc, TSMLoc *locp) } TSReturnCode -TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int name_len, TSMLoc *locp) +tsapi::c::TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int name_len, TSMLoc *locp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(mh_mloc) == TS_SUCCESS) || @@ -3032,7 +3040,8 @@ TSMimeHdrFieldCreateNamed(TSMBuffer bufp, TSMLoc mh_mloc, const char *name, int } TSReturnCode -TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field) +tsapi::c::TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, + TSMLoc src_field) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3079,11 +3088,12 @@ TSMimeHdrFieldCopy(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMB } TSReturnCode -TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field, TSMLoc *locp) +tsapi::c::TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc src_field, + TSMLoc *locp) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return - // TS_ERROR. If not allowed, return NULL. + // TS_ERROR. If not allowed, set *locp to TS_NULL_MLOC. sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(dest_hdr) == TS_SUCCESS) || @@ -3107,8 +3117,8 @@ TSMimeHdrFieldClone(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMBuffer src_bufp, TS } TSReturnCode -TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, - TSMLoc src_field) +tsapi::c::TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field, TSMBuffer src_bufp, TSMLoc src_hdr, + TSMLoc src_field) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3138,8 +3148,8 @@ TSMimeHdrFieldCopyValues(TSMBuffer dest_bufp, TSMLoc dest_hdr, TSMLoc dest_field return TS_SUCCESS; } -TSMLoc -TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) +tsapi::c::TSMLoc +tsapi::c::TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3158,8 +3168,8 @@ TSMimeHdrFieldNext(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) return TS_NULL_MLOC; } -TSMLoc -TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) +tsapi::c::TSMLoc +tsapi::c::TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3178,7 +3188,7 @@ TSMimeHdrFieldNextDup(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) } int -TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) +tsapi::c::TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3189,7 +3199,7 @@ TSMimeHdrFieldLengthGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) } const char * -TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length) +tsapi::c::TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3201,7 +3211,7 @@ TSMimeHdrFieldNameGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int *length) } TSReturnCode -TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name, int length) +tsapi::c::TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name, int length) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3238,7 +3248,7 @@ TSMimeHdrFieldNameSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, const char *name } TSReturnCode -TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) +tsapi::c::TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3256,16 +3266,16 @@ TSMimeHdrFieldValuesClear(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) HdrHeap *heap = ((HdrHeapSDKHandle *)bufp)->m_heap; /** - * Modified the string value passed from an empty string ("") to NULL. + * Modified the string value passed from an empty string ("") to null. * An empty string is also considered to be a token. The correct value of - * the field after this function should be NULL. + * the field after this function should be null. */ mime_field_value_set(heap, handle->mh, handle->field_ptr, nullptr, 0, true); return TS_SUCCESS; } int -TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) +tsapi::c::TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3276,7 +3286,7 @@ TSMimeHdrFieldValuesCount(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) } const char * -TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int *value_len_ptr) +tsapi::c::TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int *value_len_ptr) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3287,7 +3297,7 @@ TSMimeHdrFieldValueStringGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, } time_t -TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) +tsapi::c::TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3304,7 +3314,7 @@ TSMimeHdrFieldValueDateGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field) } time_t -TSMimeParseDate(char const *const value_str, int const value_len) +tsapi::c::TSMimeParseDate(char const *const value_str, int const value_len) { if (value_str == nullptr) { return (time_t)0; @@ -3314,7 +3324,7 @@ TSMimeParseDate(char const *const value_str, int const value_len) } int -TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) +tsapi::c::TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3331,7 +3341,7 @@ TSMimeHdrFieldValueIntGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) } int64_t -TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) +tsapi::c::TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3348,7 +3358,7 @@ TSMimeHdrFieldValueInt64Get(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) } unsigned int -TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) +tsapi::c::TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert((sdk_sanity_check_mime_hdr_handle(hdr) == TS_SUCCESS) || (sdk_sanity_check_http_hdr_handle(hdr) == TS_SUCCESS)); @@ -3365,7 +3375,7 @@ TSMimeHdrFieldValueUintGet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) } TSReturnCode -TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length) +tsapi::c::TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3389,7 +3399,7 @@ TSMimeHdrFieldValueStringSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, } TSReturnCode -TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value) +tsapi::c::TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3413,7 +3423,7 @@ TSMimeHdrFieldValueDateSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t valu } TSReturnCode -TSMimeFormatDate(time_t const value_time, char *const value_str, int *const value_length) +tsapi::c::TSMimeFormatDate(time_t const value_time, char *const value_str, int *const value_length) { if (value_length == nullptr) { return TS_ERROR; @@ -3428,7 +3438,7 @@ TSMimeFormatDate(time_t const value_time, char *const value_str, int *const valu } TSReturnCode -TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value) +tsapi::c::TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3450,7 +3460,7 @@ TSMimeHdrFieldValueIntSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int } TSReturnCode -TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int64_t value) +tsapi::c::TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int64_t value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3472,7 +3482,7 @@ TSMimeHdrFieldValueInt64Set(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, i } TSReturnCode -TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value) +tsapi::c::TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3494,7 +3504,7 @@ TSMimeHdrFieldValueUintSet(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, un } TSReturnCode -TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length) +tsapi::c::TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3521,7 +3531,7 @@ TSMimeHdrFieldValueAppend(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, con } TSReturnCode -TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length) +tsapi::c::TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, const char *value, int length) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3543,7 +3553,7 @@ TSMimeHdrFieldValueStringInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int id } TSReturnCode -TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value) +tsapi::c::TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, int value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3564,7 +3574,7 @@ TSMimeHdrFieldValueIntInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, } TSReturnCode -TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value) +tsapi::c::TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, unsigned int value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3585,7 +3595,7 @@ TSMimeHdrFieldValueUintInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx, } TSReturnCode -TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value) +tsapi::c::TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t value) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3611,7 +3621,7 @@ TSMimeHdrFieldValueDateInsert(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, time_t v } TSReturnCode -TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) +tsapi::c::TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3634,7 +3644,7 @@ TSMimeHdrFieldValueDelete(TSMBuffer bufp, TSMLoc hdr, TSMLoc field, int idx) } const char * -TSMimeHdrStringToWKS(const char *str, int length) +tsapi::c::TSMimeHdrStringToWKS(const char *str, int length) { if (length < 0) { return hdrtoken_string_to_wks(str); @@ -3646,8 +3656,8 @@ TSMimeHdrStringToWKS(const char *str, int length) /**************/ /* HttpParser */ /**************/ -TSHttpParser -TSHttpParserCreate() +tsapi::c::TSHttpParser +tsapi::c::TSHttpParserCreate() { TSHttpParser parser = reinterpret_cast(ats_malloc(sizeof(HTTPParser))); http_parser_init((HTTPParser *)parser); @@ -3656,14 +3666,14 @@ TSHttpParserCreate() } void -TSHttpParserClear(TSHttpParser parser) +tsapi::c::TSHttpParserClear(TSHttpParser parser) { sdk_assert(sdk_sanity_check_http_parser(parser) == TS_SUCCESS); http_parser_clear((HTTPParser *)parser); } void -TSHttpParserDestroy(TSHttpParser parser) +tsapi::c::TSHttpParserDestroy(TSHttpParser parser) { sdk_assert(sdk_sanity_check_http_parser(parser) == TS_SUCCESS); http_parser_clear((HTTPParser *)parser); @@ -3674,8 +3684,8 @@ TSHttpParserDestroy(TSHttpParser parser) /* HttpHdr */ /***********/ -TSMLoc -TSHttpHdrCreate(TSMBuffer bufp) +tsapi::c::TSMLoc +tsapi::c::TSHttpHdrCreate(TSMBuffer bufp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); @@ -3686,7 +3696,7 @@ TSHttpHdrCreate(TSMBuffer bufp) } void -TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3698,11 +3708,11 @@ TSHttpHdrDestroy(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp) +tsapi::c::TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc *locp) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return - // TS_ERROR. If not allowed, return NULL. + // TS_ERROR. If not allowed, set *locp to TS_NULL_MLOC. sdk_assert(sdk_sanity_check_mbuffer(dest_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(src_bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(src_hdr) == TS_SUCCESS); @@ -3731,7 +3741,7 @@ TSHttpHdrClone(TSMBuffer dest_bufp, TSMBuffer src_bufp, TSMLoc src_hdr, TSMLoc * } TSReturnCode -TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj) +tsapi::c::TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc src_obj) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3766,7 +3776,7 @@ TSHttpHdrCopy(TSMBuffer dest_bufp, TSMLoc dest_obj, TSMBuffer src_bufp, TSMLoc s } void -TSHttpHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) +tsapi::c::TSHttpHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3800,8 +3810,8 @@ TSHttpHdrPrint(TSMBuffer bufp, TSMLoc obj, TSIOBuffer iobufp) } while (!done); } -TSParseResult -TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) +tsapi::c::TSParseResult +tsapi::c::TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3821,8 +3831,8 @@ TSHttpHdrParseReq(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char ** return (TSParseResult)h.parse_req((HTTPParser *)parser, start, end, false); } -TSParseResult -TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) +tsapi::c::TSParseResult +tsapi::c::TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char **start, const char *end) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3843,7 +3853,7 @@ TSHttpHdrParseResp(TSHttpParser parser, TSMBuffer bufp, TSMLoc obj, const char * } int -TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3855,8 +3865,8 @@ TSHttpHdrLengthGet(TSMBuffer bufp, TSMLoc obj) return h.length_get(); } -TSHttpType -TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpType +tsapi::c::TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3870,7 +3880,7 @@ TSHttpHdrTypeGet(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc obj, TSHttpType type) +tsapi::c::TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc obj, TSHttpType type) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3909,7 +3919,7 @@ TSHttpHdrTypeSet(TSMBuffer bufp, TSMLoc obj, TSHttpType type) } int -TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3922,7 +3932,7 @@ TSHttpHdrVersionGet(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc obj, int ver) +tsapi::c::TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc obj, int ver) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3946,7 +3956,7 @@ TSHttpHdrVersionSet(TSMBuffer bufp, TSMLoc obj, int ver) } const char * -TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc obj, int *length) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3959,7 +3969,7 @@ TSHttpHdrMethodGet(TSMBuffer bufp, TSMLoc obj, int *length) } TSReturnCode -TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -3985,7 +3995,7 @@ TSHttpHdrMethodSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) } const char * -TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc obj, int *length) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -3998,7 +4008,7 @@ TSHttpHdrHostGet(TSMBuffer bufp, TSMLoc obj, int *length) } TSReturnCode -TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc obj, TSMLoc *locp) +tsapi::c::TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc obj, TSMLoc *locp) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -4014,7 +4024,7 @@ TSHttpHdrUrlGet(TSMBuffer bufp, TSMLoc obj, TSMLoc *locp) } TSReturnCode -TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc obj, TSMLoc url) +tsapi::c::TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc obj, TSMLoc url) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -4040,8 +4050,8 @@ TSHttpHdrUrlSet(TSMBuffer bufp, TSMLoc obj, TSMLoc url) return TS_SUCCESS; } -TSHttpStatus -TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpStatus +tsapi::c::TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -4053,7 +4063,7 @@ TSHttpHdrStatusGet(TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc obj, TSHttpStatus status) +tsapi::c::TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc obj, TSHttpStatus status) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -4075,7 +4085,7 @@ TSHttpHdrStatusSet(TSMBuffer bufp, TSMLoc obj, TSHttpStatus status) } const char * -TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc obj, int *length) +tsapi::c::TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc obj, int *length) { sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(obj) == TS_SUCCESS); @@ -4088,7 +4098,7 @@ TSHttpHdrReasonGet(TSMBuffer bufp, TSMLoc obj, int *length) } TSReturnCode -TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) +tsapi::c::TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) { // Allow to modify the buffer only // if bufp is modifiable. If bufp is not modifiable return @@ -4117,7 +4127,7 @@ TSHttpHdrReasonSet(TSMBuffer bufp, TSMLoc obj, const char *value, int length) } const char * -TSHttpHdrReasonLookup(TSHttpStatus status) +tsapi::c::TSHttpHdrReasonLookup(TSHttpStatus status) { return http_hdr_reason_lookup((HTTPStatus)status); } @@ -4138,8 +4148,8 @@ sdk_sanity_check_cachekey(TSCacheKey key) return TS_SUCCESS; } -TSCacheKey -TSCacheKeyCreate() +tsapi::c::TSCacheKey +tsapi::c::TSCacheKeyCreate() { TSCacheKey key = (TSCacheKey) new CacheInfo(); @@ -4149,7 +4159,7 @@ TSCacheKeyCreate() } TSReturnCode -TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length) +tsapi::c::TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length) { sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); sdk_assert(sdk_sanity_check_iocore_structure((void *)input) == TS_SUCCESS); @@ -4165,7 +4175,7 @@ TSCacheKeyDigestSet(TSCacheKey key, const char *input, int length) } TSReturnCode -TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url) +tsapi::c::TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url) { sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -4178,7 +4188,7 @@ TSCacheKeyDigestFromUrlSet(TSCacheKey key, TSMLoc url) } TSReturnCode -TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type) +tsapi::c::TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type) { sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -4202,7 +4212,7 @@ TSCacheKeyDataTypeSet(TSCacheKey key, TSCacheDataType type) } TSReturnCode -TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len) +tsapi::c::TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len) { sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)hostname) == TS_SUCCESS); @@ -4222,7 +4232,7 @@ TSCacheKeyHostNameSet(TSCacheKey key, const char *hostname, int host_len) } TSReturnCode -TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache) +tsapi::c::TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache) { sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -4236,7 +4246,7 @@ TSCacheKeyPinnedSet(TSCacheKey key, time_t pin_in_cache) } TSReturnCode -TSCacheKeyDestroy(TSCacheKey key) +tsapi::c::TSCacheKeyDestroy(TSCacheKey key) { sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -4252,8 +4262,8 @@ TSCacheKeyDestroy(TSCacheKey key) return TS_SUCCESS; } -TSCacheHttpInfo -TSCacheHttpInfoCopy(TSCacheHttpInfo infop) +tsapi::c::TSCacheHttpInfo +tsapi::c::TSCacheHttpInfoCopy(TSCacheHttpInfo infop) { CacheHTTPInfo *new_info = new CacheHTTPInfo; @@ -4262,7 +4272,7 @@ TSCacheHttpInfoCopy(TSCacheHttpInfo infop) } void -TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj) { CacheHTTPInfo *info = (CacheHTTPInfo *)infop; @@ -4272,7 +4282,7 @@ TSCacheHttpInfoReqGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj) } void -TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj) { CacheHTTPInfo *info = (CacheHTTPInfo *)infop; @@ -4282,28 +4292,28 @@ TSCacheHttpInfoRespGet(TSCacheHttpInfo infop, TSMBuffer *bufp, TSMLoc *obj) } time_t -TSCacheHttpInfoReqSentTimeGet(TSCacheHttpInfo infop) +tsapi::c::TSCacheHttpInfoReqSentTimeGet(TSCacheHttpInfo infop) { CacheHTTPInfo *info = (CacheHTTPInfo *)infop; return info->request_sent_time_get(); } time_t -TSCacheHttpInfoRespReceivedTimeGet(TSCacheHttpInfo infop) +tsapi::c::TSCacheHttpInfoRespReceivedTimeGet(TSCacheHttpInfo infop) { CacheHTTPInfo *info = (CacheHTTPInfo *)infop; return info->response_received_time_get(); } int64_t -TSCacheHttpInfoSizeGet(TSCacheHttpInfo infop) +tsapi::c::TSCacheHttpInfoSizeGet(TSCacheHttpInfo infop) { CacheHTTPInfo *info = (CacheHTTPInfo *)infop; return info->object_size_get(); } void -TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj) { HTTPHdr h; @@ -4314,7 +4324,7 @@ TSCacheHttpInfoReqSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj) } void -TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj) { HTTPHdr h; @@ -4325,7 +4335,7 @@ TSCacheHttpInfoRespSet(TSCacheHttpInfo infop, TSMBuffer bufp, TSMLoc obj) } int -TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length) +tsapi::c::TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length) { CacheHTTPInfo *info = (CacheHTTPInfo *)infop; CacheHTTPInfoVector vector; @@ -4343,13 +4353,13 @@ TSCacheHttpInfoVector(TSCacheHttpInfo infop, void *data, int length) } void -TSCacheHttpInfoDestroy(TSCacheHttpInfo infop) +tsapi::c::TSCacheHttpInfoDestroy(TSCacheHttpInfo infop) { ((CacheHTTPInfo *)infop)->destroy(); } -TSCacheHttpInfo -TSCacheHttpInfoCreate() +tsapi::c::TSCacheHttpInfo +tsapi::c::TSCacheHttpInfoCreate() { CacheHTTPInfo *info = new CacheHTTPInfo; info->create(); @@ -4364,7 +4374,7 @@ TSCacheHttpInfoCreate() //////////////////////////////////////////////////////////////////// unsigned int -TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp) +tsapi::c::TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp) { INKConfigImpl *config = new INKConfigImpl; config->mdata = data; @@ -4372,20 +4382,20 @@ TSConfigSet(unsigned int id, void *data, TSConfigDestroyFunc funcp) return configProcessor.set(id, config); } -TSConfig -TSConfigGet(unsigned int id) +tsapi::c::TSConfig +tsapi::c::TSConfigGet(unsigned int id) { return reinterpret_cast(configProcessor.get(id)); } void -TSConfigRelease(unsigned int id, TSConfig configp) +tsapi::c::TSConfigRelease(unsigned int id, TSConfig configp) { configProcessor.release(id, (ConfigInfo *)configp); } void * -TSConfigDataGet(TSConfig configp) +tsapi::c::TSConfigDataGet(TSConfig configp) { INKConfigImpl *config = (INKConfigImpl *)configp; return config->mdata; @@ -4398,7 +4408,7 @@ TSConfigDataGet(TSConfig configp) //////////////////////////////////////////////////////////////////// void -TSMgmtUpdateRegister(TSCont contp, const char *plugin_name) +tsapi::c::TSMgmtUpdateRegister(TSCont contp, const char *plugin_name) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)plugin_name) == TS_SUCCESS); @@ -4407,25 +4417,25 @@ TSMgmtUpdateRegister(TSCont contp, const char *plugin_name) } TSReturnCode -TSMgmtIntGet(const char *var_name, TSMgmtInt *result) +tsapi::c::TSMgmtIntGet(const char *var_name, TSMgmtInt *result) { return RecGetRecordInt((char *)var_name, (RecInt *)result) == REC_ERR_OKAY ? TS_SUCCESS : TS_ERROR; } TSReturnCode -TSMgmtCounterGet(const char *var_name, TSMgmtCounter *result) +tsapi::c::TSMgmtCounterGet(const char *var_name, TSMgmtCounter *result) { return RecGetRecordCounter((char *)var_name, (RecCounter *)result) == REC_ERR_OKAY ? TS_SUCCESS : TS_ERROR; } TSReturnCode -TSMgmtFloatGet(const char *var_name, TSMgmtFloat *result) +tsapi::c::TSMgmtFloatGet(const char *var_name, TSMgmtFloat *result) { return RecGetRecordFloat((char *)var_name, (RecFloat *)result) == REC_ERR_OKAY ? TS_SUCCESS : TS_ERROR; } TSReturnCode -TSMgmtStringGet(const char *var_name, TSMgmtString *result) +tsapi::c::TSMgmtStringGet(const char *var_name, TSMgmtString *result) { RecString tmp = nullptr; (void)RecGetRecordString_Xmalloc((char *)var_name, &tmp); @@ -4439,13 +4449,13 @@ TSMgmtStringGet(const char *var_name, TSMgmtString *result) } TSReturnCode -TSMgmtSourceGet(const char *var_name, TSMgmtSource *source) +tsapi::c::TSMgmtSourceGet(const char *var_name, TSMgmtSource *source) { return REC_ERR_OKAY == RecGetRecordSource(var_name, reinterpret_cast(source)) ? TS_SUCCESS : TS_ERROR; } TSReturnCode -TSMgmtDataTypeGet(const char *var_name, TSRecordDataType *result) +tsapi::c::TSMgmtDataTypeGet(const char *var_name, TSRecordDataType *result) { return REC_ERR_OKAY == RecGetRecordDataType(var_name, reinterpret_cast(result)) ? TS_SUCCESS : TS_ERROR; } @@ -4458,10 +4468,10 @@ TSMgmtDataTypeGet(const char *var_name, TSRecordDataType *result) extern thread_local PluginThreadContext *pluginThreadContext; -TSCont -TSContCreate(TSEventFunc funcp, TSMutex mutexp) +tsapi::c::TSCont +tsapi::c::TSContCreate(TSEventFunc funcp, TSMutex mutexp) { - // mutexp can be NULL + // mutexp can be null if (mutexp != nullptr) { sdk_assert(sdk_sanity_check_mutex(mutexp) == TS_SUCCESS); } @@ -4477,7 +4487,7 @@ TSContCreate(TSEventFunc funcp, TSMutex mutexp) } void -TSContDestroy(TSCont contp) +tsapi::c::TSContDestroy(TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4491,7 +4501,7 @@ TSContDestroy(TSCont contp) } void -TSContDataSet(TSCont contp, void *data) +tsapi::c::TSContDataSet(TSCont contp, void *data) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4501,7 +4511,7 @@ TSContDataSet(TSCont contp, void *data) } void * -TSContDataGet(TSCont contp) +tsapi::c::TSContDataGet(TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4510,8 +4520,8 @@ TSContDataGet(TSCont contp) return i->mdata; } -TSAction -TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp) +tsapi::c::TSAction +tsapi::c::TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4558,8 +4568,8 @@ TSContScheduleOnPool(TSCont contp, TSHRTime timeout, TSThreadPool tp) return action; } -TSAction -TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread) +tsapi::c::TSAction +tsapi::c::TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread) { ink_release_assert(ethread != nullptr); @@ -4590,8 +4600,8 @@ TSContScheduleOnThread(TSCont contp, TSHRTime timeout, TSEventThread ethread) return action; } -TSAction -TSContScheduleEveryOnPool(TSCont contp, TSHRTime every, TSThreadPool tp) +tsapi::c::TSAction +tsapi::c::TSContScheduleEveryOnPool(TSCont contp, TSHRTime every, TSThreadPool tp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4627,8 +4637,8 @@ TSContScheduleEveryOnPool(TSCont contp, TSHRTime every, TSThreadPool tp) return action; } -TSAction -TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEventThread ethread) +tsapi::c::TSAction +tsapi::c::TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEventThread ethread) { ink_release_assert(ethread != nullptr); @@ -4655,7 +4665,7 @@ TSContScheduleEveryOnThread(TSCont contp, TSHRTime every /* millisecs */, TSEven } TSReturnCode -TSContThreadAffinitySet(TSCont contp, TSEventThread ethread) +tsapi::c::TSContThreadAffinitySet(TSCont contp, TSEventThread ethread) { ink_release_assert(ethread != nullptr); @@ -4672,8 +4682,8 @@ TSContThreadAffinitySet(TSCont contp, TSEventThread ethread) return TS_ERROR; } -TSEventThread -TSContThreadAffinityGet(TSCont contp) +tsapi::c::TSEventThread +tsapi::c::TSContThreadAffinityGet(TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4685,7 +4695,7 @@ TSContThreadAffinityGet(TSCont contp) } void -TSContThreadAffinityClear(TSCont contp) +tsapi::c::TSContThreadAffinityClear(TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4696,8 +4706,8 @@ TSContThreadAffinityClear(TSCont contp) i->clearThreadAffinity(); } -TSAction -TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout) +tsapi::c::TSAction +tsapi::c::TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4726,7 +4736,7 @@ TSHttpSchedule(TSCont contp, TSHttpTxn txnp, TSHRTime timeout) } int -TSContCall(TSCont contp, TSEvent event, void *edata) +tsapi::c::TSContCall(TSCont contp, TSEvent event, void *edata) { Continuation *c = (Continuation *)contp; WEAK_MUTEX_TRY_LOCK(lock, c->mutex, this_ethread()); @@ -4737,8 +4747,8 @@ TSContCall(TSCont contp, TSEvent event, void *edata) return c->handleEvent((int)event, edata); } -TSMutex -TSContMutexGet(TSCont contp) +tsapi::c::TSMutex +tsapi::c::TSContMutexGet(TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -4749,7 +4759,7 @@ TSContMutexGet(TSCont contp) /* HTTP hooks */ void -TSHttpHookAdd(TSHttpHookID id, TSCont contp) +tsapi::c::TSHttpHookAdd(TSHttpHookID id, TSCont contp) { INKContInternal *icontp; sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); @@ -4766,7 +4776,7 @@ TSHttpHookAdd(TSHttpHookID id, TSCont contp) } void -TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp) +tsapi::c::TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp) { sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_lifecycle_hook_id(id) == TS_SUCCESS); @@ -4776,7 +4786,7 @@ TSLifecycleHookAdd(TSLifecycleHookID id, TSCont contp) /* HTTP sessions */ void -TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp) +tsapi::c::TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); @@ -4787,7 +4797,7 @@ TSHttpSsnHookAdd(TSHttpSsn ssnp, TSHttpHookID id, TSCont contp) } int -TSHttpSsnTransactionCount(TSHttpSsn ssnp) +tsapi::c::TSHttpSsnTransactionCount(TSHttpSsn ssnp) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); @@ -4795,15 +4805,15 @@ TSHttpSsnTransactionCount(TSHttpSsn ssnp) return cs->get_transact_count(); } -TSVConn -TSHttpSsnClientVConnGet(TSHttpSsn ssnp) +tsapi::c::TSVConn +tsapi::c::TSHttpSsnClientVConnGet(TSHttpSsn ssnp) { ProxySession *cs = reinterpret_cast(ssnp); return reinterpret_cast(cs->get_netvc()); } -TSVConn -TSHttpSsnServerVConnGet(TSHttpSsn ssnp) +tsapi::c::TSVConn +tsapi::c::TSHttpSsnServerVConnGet(TSHttpSsn ssnp) { PoolableSession *ss = reinterpret_cast(ssnp); if (ss != nullptr) { @@ -4812,8 +4822,8 @@ TSHttpSsnServerVConnGet(TSHttpSsn ssnp) return nullptr; } -TSVConn -TSHttpTxnServerVConnGet(TSHttpTxn txnp) +tsapi::c::TSVConn +tsapi::c::TSHttpTxnServerVConnGet(TSHttpTxn txnp) { TSVConn vconn = nullptr; sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -4859,7 +4869,7 @@ class TSHttpSsnCallback : public Continuation }; void -TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event) +tsapi::c::TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); @@ -4895,7 +4905,7 @@ TSHttpSsnReenable(TSHttpSsn ssnp, TSEvent event) /* HTTP transactions */ void -TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp) +tsapi::c::TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); @@ -4917,7 +4927,7 @@ TSHttpTxnHookAdd(TSHttpTxn txnp, TSHttpHookID id, TSCont contp) // Private api function for gzip plugin. // This function should only appear in TsapiPrivate.h TSReturnCode -TSHttpTxnHookRegisteredFor(TSHttpTxn txnp, TSHttpHookID id, TSEventFunc funcp) +tsapi::c::TSHttpTxnHookRegisteredFor(TSHttpTxn txnp, TSHttpHookID id, TSEventFunc funcp) { HttpSM *sm = (HttpSM *)txnp; APIHook *hook = sm->txn_hook_get(id); @@ -4932,8 +4942,8 @@ TSHttpTxnHookRegisteredFor(TSHttpTxn txnp, TSHttpHookID id, TSEventFunc funcp) return TS_ERROR; } -TSHttpSsn -TSHttpTxnSsnGet(TSHttpTxn txnp) +tsapi::c::TSHttpSsn +tsapi::c::TSHttpTxnSsnGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -4943,7 +4953,7 @@ TSHttpTxnSsnGet(TSHttpTxn txnp) // TODO: Is this still necessary ?? void -TSHttpTxnClientKeepaliveSet(TSHttpTxn txnp, int set) +tsapi::c::TSHttpTxnClientKeepaliveSet(TSHttpTxn txnp, int set) { HttpSM *sm = (HttpSM *)txnp; HttpTransact::State *s = &(sm->t_state); @@ -4952,7 +4962,7 @@ TSHttpTxnClientKeepaliveSet(TSHttpTxn txnp, int set) } TSReturnCode -TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -4975,7 +4985,7 @@ TSHttpTxnClientReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) // pristine url is the url before remap TSReturnCode -TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc) +tsapi::c::TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5001,7 +5011,7 @@ TSHttpTxnPristineUrlGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *url_loc) } int -TSHttpTxnServerSsnTransactionCount(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerSsnTransactionCount(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5014,7 +5024,7 @@ TSHttpTxnServerSsnTransactionCount(TSHttpTxn txnp) // The caller is responsible to free memory that is allocated for the string // that is returned. char * -TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length) +tsapi::c::TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length) { sdk_assert(TS_SUCCESS == sdk_sanity_check_txn(txnp)); sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS); @@ -5024,7 +5034,7 @@ TSHttpTxnEffectiveUrlStringGet(TSHttpTxn txnp, int *length) } TSReturnCode -TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_t size, int64_t *length) +tsapi::c::TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_t size, int64_t *length) { sdk_assert(sdk_sanity_check_mbuffer(hdr_buf) == TS_SUCCESS); sdk_assert(sdk_sanity_check_http_hdr_handle(hdr_loc) == TS_SUCCESS); @@ -5061,7 +5071,7 @@ TSHttpHdrEffectiveUrlBufGet(TSMBuffer hdr_buf, TSMLoc hdr_loc, char *buf, int64_ } TSReturnCode -TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5081,7 +5091,7 @@ TSHttpTxnClientRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5101,7 +5111,7 @@ TSHttpTxnServerReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5121,7 +5131,7 @@ TSHttpTxnServerRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5159,7 +5169,7 @@ TSHttpTxnCachedReqGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5198,7 +5208,7 @@ TSHttpTxnCachedRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); @@ -5234,7 +5244,7 @@ TSHttpTxnCachedRespModifiableGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status) +tsapi::c::TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)lookup_status) == TS_SUCCESS); @@ -5264,7 +5274,7 @@ TSHttpTxnCacheLookupStatusGet(TSHttpTxn txnp, int *lookup_status) } TSReturnCode -TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count) +tsapi::c::TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)lookup_count) == TS_SUCCESS); @@ -5279,7 +5289,7 @@ TSHttpTxnCacheLookupCountGet(TSHttpTxn txnp, int *lookup_count) TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK */ TSReturnCode -TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup) +tsapi::c::TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5316,7 +5326,7 @@ TSHttpTxnCacheLookupStatusSet(TSHttpTxn txnp, int cachelookup) } TSReturnCode -TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value) +tsapi::c::TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS); @@ -5351,7 +5361,7 @@ TSHttpTxnInfoIntGet(TSHttpTxn txnp, TSHttpTxnInfoKey key, TSMgmtInt *value) } int -TSHttpTxnIsWebsocket(TSHttpTxn txnp) +tsapi::c::TSHttpTxnIsWebsocket(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5360,7 +5370,7 @@ TSHttpTxnIsWebsocket(TSHttpTxn txnp) } const char * -TSHttpTxnCacheDiskPathGet(TSHttpTxn txnp, int *length) +tsapi::c::TSHttpTxnCacheDiskPathGet(TSHttpTxn txnp, int *length) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5378,7 +5388,7 @@ TSHttpTxnCacheDiskPathGet(TSHttpTxn txnp, int *length) } TSReturnCode -TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); @@ -5403,7 +5413,7 @@ TSHttpTxnCacheLookupUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); @@ -5439,7 +5449,7 @@ TSHttpTxnCacheLookupUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) * overrides as proxy.config.http.transaction_active_timeout_out **/ void -TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout) +tsapi::c::TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5452,7 +5462,7 @@ TSHttpTxnActiveTimeoutSet(TSHttpTxn txnp, int timeout) * overrides as proxy.config.http.connect_attempts_timeout **/ void -TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout) +tsapi::c::TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5465,7 +5475,7 @@ TSHttpTxnConnectTimeoutSet(TSHttpTxn txnp, int timeout) * overrides as proxy.config.dns.lookup_timeout **/ void -TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout) +tsapi::c::TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5479,7 +5489,7 @@ TSHttpTxnDNSTimeoutSet(TSHttpTxn txnp, int timeout) * overrides as proxy.config.http.transaction_no_activity_timeout_out **/ void -TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout) +tsapi::c::TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5488,7 +5498,7 @@ TSHttpTxnNoActivityTimeoutSet(TSHttpTxn txnp, int timeout) } TSReturnCode -TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag) +tsapi::c::TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5499,7 +5509,7 @@ TSHttpTxnServerRespNoStoreSet(TSHttpTxn txnp, int flag) } bool -TSHttpTxnServerRespNoStoreGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerRespNoStoreGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5508,7 +5518,7 @@ TSHttpTxnServerRespNoStoreGet(TSHttpTxn txnp) } TSReturnCode -TSHttpTxnServerRespIgnore(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerRespIgnore(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5531,7 +5541,7 @@ TSHttpTxnServerRespIgnore(TSHttpTxn txnp) } TSReturnCode -TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event) +tsapi::c::TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5546,7 +5556,7 @@ TSHttpTxnShutDown(TSHttpTxn txnp, TSEvent event) } TSReturnCode -TSHttpTxnAborted(TSHttpTxn txnp, bool *client_abort) +tsapi::c::TSHttpTxnAborted(TSHttpTxn txnp, bool *client_abort) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(client_abort != nullptr); @@ -5573,7 +5583,7 @@ TSHttpTxnAborted(TSHttpTxn txnp, bool *client_abort) } void -TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag) +tsapi::c::TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5582,7 +5592,7 @@ TSHttpTxnReqCacheableSet(TSHttpTxn txnp, int flag) } void -TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag) +tsapi::c::TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5591,7 +5601,7 @@ TSHttpTxnRespCacheableSet(TSHttpTxn txnp, int flag) } int -TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp) +tsapi::c::TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5600,7 +5610,7 @@ TSHttpTxnClientReqIsServerStyle(TSHttpTxn txnp) } void -TSHttpTxnOverwriteExpireTime(TSHttpTxn txnp, time_t expire_time) +tsapi::c::TSHttpTxnOverwriteExpireTime(TSHttpTxn txnp, time_t expire_time) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5609,7 +5619,7 @@ TSHttpTxnOverwriteExpireTime(TSHttpTxn txnp, time_t expire_time) } TSReturnCode -TSHttpTxnUpdateCachedObject(TSHttpTxn txnp) +tsapi::c::TSHttpTxnUpdateCachedObject(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5635,7 +5645,7 @@ TSHttpTxnUpdateCachedObject(TSHttpTxn txnp) } TSReturnCode -TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5652,7 +5662,7 @@ TSHttpTxnTransformRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) } sockaddr const * -TSHttpSsnClientAddrGet(TSHttpSsn ssnp) +tsapi::c::TSHttpSsnClientAddrGet(TSHttpSsn ssnp) { ProxySession *cs = reinterpret_cast(ssnp); @@ -5662,7 +5672,7 @@ TSHttpSsnClientAddrGet(TSHttpSsn ssnp) return cs->get_remote_addr(); } sockaddr const * -TSHttpTxnClientAddrGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnClientAddrGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5671,7 +5681,7 @@ TSHttpTxnClientAddrGet(TSHttpTxn txnp) } sockaddr const * -TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp) +tsapi::c::TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp) { ProxySession *cs = reinterpret_cast(ssnp); @@ -5681,7 +5691,7 @@ TSHttpSsnIncomingAddrGet(TSHttpSsn ssnp) return cs->get_local_addr(); } sockaddr const * -TSHttpTxnIncomingAddrGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnIncomingAddrGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5690,7 +5700,7 @@ TSHttpTxnIncomingAddrGet(TSHttpTxn txnp) } sockaddr const * -TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5708,7 +5718,7 @@ TSHttpTxnOutgoingAddrGet(TSHttpTxn txnp) } sockaddr const * -TSHttpTxnServerAddrGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerAddrGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5717,7 +5727,7 @@ TSHttpTxnServerAddrGet(TSHttpTxn txnp) } TSReturnCode -TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr) +tsapi::c::TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5730,7 +5740,7 @@ TSHttpTxnServerAddrSet(TSHttpTxn txnp, struct sockaddr const *addr) } void -TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port) +tsapi::c::TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5741,7 +5751,7 @@ TSHttpTxnClientIncomingPortSet(TSHttpTxn txnp, int port) // [amc] This might use the port. The code path should do that but it // hasn't been tested. TSReturnCode -TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, const struct sockaddr *addr) +tsapi::c::TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, const struct sockaddr *addr) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -5752,7 +5762,7 @@ TSHttpTxnOutgoingAddrSet(TSHttpTxn txnp, const struct sockaddr *addr) } sockaddr const * -TSHttpTxnNextHopAddrGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnNextHopAddrGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5769,7 +5779,7 @@ TSHttpTxnNextHopAddrGet(TSHttpTxn txnp) } const char * -TSHttpTxnNextHopNameGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnNextHopNameGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5786,7 +5796,7 @@ TSHttpTxnNextHopNameGet(TSHttpTxn txnp) } int -TSHttpTxnNextHopPortGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnNextHopPortGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); auto sm = reinterpret_cast(txnp); @@ -5800,7 +5810,7 @@ TSHttpTxnNextHopPortGet(TSHttpTxn txnp) } TSReturnCode -TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag) +tsapi::c::TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag) { if (TS_SUCCESS != sdk_sanity_check_txn(txnp)) { return TS_ERROR; @@ -5816,7 +5826,7 @@ TSHttpTxnOutgoingTransparencySet(TSHttpTxn txnp, int flag) } TSReturnCode -TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark) +tsapi::c::TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -5835,7 +5845,7 @@ TSHttpTxnClientPacketMarkSet(TSHttpTxn txnp, int mark) } TSReturnCode -TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark) +tsapi::c::TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -5856,7 +5866,7 @@ TSHttpTxnServerPacketMarkSet(TSHttpTxn txnp, int mark) } TSReturnCode -TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp) +tsapi::c::TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -5875,7 +5885,7 @@ TSHttpTxnClientPacketDscpSet(TSHttpTxn txnp, int dscp) } TSReturnCode -TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp) +tsapi::c::TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -5895,9 +5905,9 @@ TSHttpTxnServerPacketDscpSet(TSHttpTxn txnp, int dscp) return TS_SUCCESS; } -// Set the body, or, if you provide a NULL buffer, clear the body message +// Set the body, or, if you provide a null buffer, clear the body message void -TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetype) +tsapi::c::TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetype) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5916,7 +5926,7 @@ TSHttpTxnErrorBodySet(TSHttpTxn txnp, char *buf, size_t buflength, char *mimetyp } void -TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength) +tsapi::c::TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5939,7 +5949,7 @@ TSHttpTxnServerRequestBodySet(TSHttpTxn txnp, char *buf, int64_t buflength) } TSReturnCode -TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port) +tsapi::c::TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -5952,7 +5962,7 @@ TSHttpTxnParentProxyGet(TSHttpTxn txnp, const char **hostname, int *port) } void -TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port) +tsapi::c::TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)hostname) == TS_SUCCESS); @@ -5965,7 +5975,7 @@ TSHttpTxnParentProxySet(TSHttpTxn txnp, const char *hostname, int port) } TSReturnCode -TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); @@ -5990,7 +6000,7 @@ TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) } TSReturnCode -TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) +tsapi::c::TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_mbuffer(bufp) == TS_SUCCESS); @@ -6025,7 +6035,7 @@ TSHttpTxnParentSelectionUrlSet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj) } void -TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on) +tsapi::c::TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6034,7 +6044,7 @@ TSHttpTxnUntransformedRespCache(TSHttpTxn txnp, int on) } void -TSHttpTxnTransformedRespCache(TSHttpTxn txnp, int on) +tsapi::c::TSHttpTxnTransformedRespCache(TSHttpTxn txnp, int on) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6065,7 +6075,7 @@ class TSHttpSMCallback : public Continuation //---------------------------------------------------------------------------- void -TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event) +tsapi::c::TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6073,7 +6083,7 @@ TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event) EThread *eth = this_ethread(); // TS-2271: If this function is being executed on a thread which was not - // created using the ATS EThread API, eth will be NULL, and the + // created using the ATS EThread API, eth will be null, and the // continuation needs to be called back on a REGULAR thread. // // If we are not coming from the thread associated with the state machine, @@ -6092,10 +6102,10 @@ TSHttpTxnReenable(TSHttpTxn txnp, TSEvent event) eventProcessor.schedule_imm(cb, ET_NET); } -TSReturnCode TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description); +tsapi::c::TSReturnCode TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description); TSReturnCode -TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *description, int *ptr_idx) +tsapi::c::TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *description, int *ptr_idx) { sdk_assert(sdk_sanity_check_null_ptr(ptr_idx) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr(name) == TS_SUCCESS); @@ -6134,7 +6144,7 @@ TSUserArgIndexReserve(TSUserArgType type, const char *name, const char *descript } TSReturnCode -TSUserArgIndexLookup(TSUserArgType type, int idx, const char **name, const char **description) +tsapi::c::TSUserArgIndexLookup(TSUserArgType type, int idx, const char **name, const char **description) { sdk_assert(0 <= type && type < TS_USER_ARGS_COUNT); sdk_assert(SanityCheckUserIndex(type, idx)); @@ -6154,7 +6164,7 @@ TSUserArgIndexLookup(TSUserArgType type, int idx, const char **name, const char // Not particularly efficient, but good enough for now. TSReturnCode -TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description) +tsapi::c::TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, const char **description) { sdk_assert(sdk_sanity_check_null_ptr(arg_idx) == TS_SUCCESS); sdk_assert(0 <= type && type < TS_USER_ARGS_COUNT); @@ -6175,7 +6185,7 @@ TSUserArgIndexNameLookup(TSUserArgType type, const char *name, int *arg_idx, con // ------------- void -TSUserArgSet(void *data, int arg_idx, void *arg) +tsapi::c::TSUserArgSet(void *data, int arg_idx, void *arg) { if (nullptr != data) { PluginUserArgsMixin *user_args = dynamic_cast(static_cast(data)); @@ -6188,7 +6198,7 @@ TSUserArgSet(void *data, int arg_idx, void *arg) } void * -TSUserArgGet(void *data, int arg_idx) +tsapi::c::TSUserArgGet(void *data, int arg_idx) { if (nullptr != data) { PluginUserArgsMixin *user_args = dynamic_cast(static_cast(data)); @@ -6201,7 +6211,7 @@ TSUserArgGet(void *data, int arg_idx) } void -TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status) +tsapi::c::TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6209,8 +6219,8 @@ TSHttpTxnStatusSet(TSHttpTxn txnp, TSHttpStatus status) sm->t_state.http_return_code = static_cast(status); } -TSHttpStatus -TSHttpTxnStatusGet(TSHttpTxn txnp) +tsapi::c::TSHttpStatus +tsapi::c::TSHttpTxnStatusGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6219,7 +6229,7 @@ TSHttpTxnStatusGet(TSHttpTxn txnp) } TSReturnCode -TSHttpTxnCntlSet(TSHttpTxn txnp, TSHttpCntlType cntl, bool data) +tsapi::c::TSHttpTxnCntlSet(TSHttpTxn txnp, TSHttpCntlType cntl, bool data) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6263,7 +6273,7 @@ TSHttpTxnCntlSet(TSHttpTxn txnp, TSHttpCntlType cntl, bool data) } bool -TSHttpTxnCntlGet(TSHttpTxn txnp, TSHttpCntlType ctrl) +tsapi::c::TSHttpTxnCntlGet(TSHttpTxn txnp, TSHttpCntlType ctrl) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6308,8 +6318,8 @@ TSHttpTxnCntlGet(TSHttpTxn txnp, TSHttpCntlType ctrl) /* This is kinda horky, we have to use TSServerState instead of HttpTransact::ServerState_t, otherwise we have a prototype mismatch in the public ts/ts.h interfaces. */ -TSServerState -TSHttpTxnServerStateGet(TSHttpTxn txnp) +tsapi::c::TSServerState +tsapi::c::TSHttpTxnServerStateGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6318,35 +6328,37 @@ TSHttpTxnServerStateGet(TSHttpTxn txnp) } void -TSHttpTxnDebugSet(TSHttpTxn txnp, int on) +tsapi::c::TSHttpTxnDebugSet(TSHttpTxn txnp, int on) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); ((HttpSM *)txnp)->debug_on = on; } int -TSHttpTxnDebugGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnDebugGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); return ((HttpSM *)txnp)->debug_on; } void -TSHttpSsnDebugSet(TSHttpSsn ssnp, int on) +tsapi::c::TSHttpSsnDebugSet(TSHttpSsn ssnp, int on) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); (reinterpret_cast(ssnp))->set_debug(0 != on); } int -TSHttpSsnDebugGet(TSHttpSsn ssnp) +tsapi::c::TSHttpSsnDebugGet(TSHttpSsn ssnp, int *on) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); - return (reinterpret_cast(ssnp))->debug(); + sdk_assert(on != nullptr); + *on = (reinterpret_cast(ssnp))->debug(); + return TS_SUCCESS; } int -TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6355,7 +6367,7 @@ TSHttpTxnClientReqHdrBytesGet(TSHttpTxn txnp) } int64_t -TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6364,7 +6376,7 @@ TSHttpTxnClientReqBodyBytesGet(TSHttpTxn txnp) } int -TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6373,7 +6385,7 @@ TSHttpTxnServerReqHdrBytesGet(TSHttpTxn txnp) } int64_t -TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6382,7 +6394,7 @@ TSHttpTxnServerReqBodyBytesGet(TSHttpTxn txnp) } int -TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6391,7 +6403,7 @@ TSHttpTxnServerRespHdrBytesGet(TSHttpTxn txnp) } int64_t -TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6400,7 +6412,7 @@ TSHttpTxnServerRespBodyBytesGet(TSHttpTxn txnp) } int -TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6409,7 +6421,7 @@ TSHttpTxnClientRespHdrBytesGet(TSHttpTxn txnp) } int64_t -TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6418,7 +6430,7 @@ TSHttpTxnClientRespBodyBytesGet(TSHttpTxn txnp) } int -TSVConnIsSslReused(TSVConn sslp) +tsapi::c::TSVConnIsSslReused(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); SSLNetVConnection *ssl_vc = dynamic_cast(vc); @@ -6427,7 +6439,7 @@ TSVConnIsSslReused(TSVConn sslp) } const char * -TSVConnSslCipherGet(TSVConn sslp) +tsapi::c::TSVConnSslCipherGet(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); TLSBasicSupport *tlsbs = vc->get_service(); @@ -6436,7 +6448,7 @@ TSVConnSslCipherGet(TSVConn sslp) } const char * -TSVConnSslProtocolGet(TSVConn sslp) +tsapi::c::TSVConnSslProtocolGet(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); TLSBasicSupport *tlsbs = vc->get_service(); @@ -6445,7 +6457,7 @@ TSVConnSslProtocolGet(TSVConn sslp) } const char * -TSVConnSslCurveGet(TSVConn sslp) +tsapi::c::TSVConnSslCurveGet(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); TLSBasicSupport *tlsbs = vc->get_service(); @@ -6454,7 +6466,7 @@ TSVConnSslCurveGet(TSVConn sslp) } int -TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6463,7 +6475,7 @@ TSHttpTxnPushedRespHdrBytesGet(TSHttpTxn txnp) } int64_t -TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6474,7 +6486,7 @@ TSHttpTxnPushedRespBodyBytesGet(TSHttpTxn txnp) // Get a particular milestone hrtime'r. Note that this can return 0, which means it has not // been set yet. TSReturnCode -TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, ink_hrtime *time) +tsapi::c::TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, ink_hrtime *time) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr(time) == TS_SUCCESS); @@ -6492,7 +6504,7 @@ TSHttpTxnMilestoneGet(TSHttpTxn txnp, TSMilestonesType milestone, ink_hrtime *ti } TSReturnCode -TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time) +tsapi::c::TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6508,7 +6520,7 @@ TSHttpTxnCachedRespTimeGet(TSHttpTxn txnp, time_t *resp_time) } int -TSHttpTxnLookingUpTypeGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnLookingUpTypeGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6519,7 +6531,7 @@ TSHttpTxnLookingUpTypeGet(TSHttpTxn txnp) } int -TSHttpCurrentClientConnectionsGet() +tsapi::c::TSHttpCurrentClientConnectionsGet() { int64_t S; @@ -6528,7 +6540,7 @@ TSHttpCurrentClientConnectionsGet() } int -TSHttpCurrentActiveClientConnectionsGet() +tsapi::c::TSHttpCurrentActiveClientConnectionsGet() { int64_t S; @@ -6537,7 +6549,7 @@ TSHttpCurrentActiveClientConnectionsGet() } int -TSHttpCurrentIdleClientConnectionsGet() +tsapi::c::TSHttpCurrentIdleClientConnectionsGet() { int64_t total = 0; int64_t active = 0; @@ -6553,7 +6565,7 @@ TSHttpCurrentIdleClientConnectionsGet() } int -TSHttpCurrentCacheConnectionsGet() +tsapi::c::TSHttpCurrentCacheConnectionsGet() { int64_t S; @@ -6562,7 +6574,7 @@ TSHttpCurrentCacheConnectionsGet() } int -TSHttpCurrentServerConnectionsGet() +tsapi::c::TSHttpCurrentServerConnectionsGet() { int64_t S; @@ -6572,7 +6584,7 @@ TSHttpCurrentServerConnectionsGet() /* HTTP alternate selection */ TSReturnCode -TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS); @@ -6585,7 +6597,7 @@ TSHttpAltInfoClientReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS); @@ -6598,7 +6610,7 @@ TSHttpAltInfoCachedReqGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) } TSReturnCode -TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS); @@ -6611,7 +6623,7 @@ TSHttpAltInfoCachedRespGet(TSHttpAltInfo infop, TSMBuffer *bufp, TSMLoc *obj) } void -TSHttpAltInfoQualitySet(TSHttpAltInfo infop, float quality) +tsapi::c::TSHttpAltInfoQualitySet(TSHttpAltInfo infop, float quality) { sdk_assert(sdk_sanity_check_alt_info(infop) == TS_SUCCESS); @@ -6623,7 +6635,7 @@ extern HttpSessionAccept *plugin_http_accept; extern HttpSessionAccept *plugin_http_transparent_accept; const char * -TSHttpTxnPluginTagGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnPluginTagGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6631,8 +6643,8 @@ TSHttpTxnPluginTagGet(TSHttpTxn txnp) return sm->plugin_tag; } -TSHttpConnectOptions -TSHttpConnectOptionsGet(TSConnectType connect_type) +tsapi::c::TSHttpConnectOptions +tsapi::c::TSHttpConnectOptionsGet(TSConnectType connect_type) { sdk_assert(connect_type > TS_CONNECT_UNDEFINED); sdk_assert(connect_type < TS_CONNECT_LAST_ENTRY); @@ -6645,8 +6657,8 @@ TSHttpConnectOptionsGet(TSConnectType connect_type) .buffer_water_mark = TS_IOBUFFER_WATER_MARK_PLUGIN_VC_DEFAULT}; } -TSVConn -TSHttpConnectWithPluginId(sockaddr const *addr, const char *tag, int64_t id) +tsapi::c::TSVConn +tsapi::c::TSHttpConnectWithPluginId(sockaddr const *addr, const char *tag, int64_t id) { TSHttpConnectOptions options = TSHttpConnectOptionsGet(TS_CONNECT_PLUGIN); options.addr = addr; @@ -6656,8 +6668,8 @@ TSHttpConnectWithPluginId(sockaddr const *addr, const char *tag, int64_t id) return TSHttpConnectPlugin(&options); } -TSVConn -TSHttpConnectPlugin(TSHttpConnectOptions *options) +tsapi::c::TSVConn +tsapi::c::TSHttpConnectPlugin(TSHttpConnectOptions *options) { sdk_assert(options != nullptr); sdk_assert(options->connect_type == TS_CONNECT_PLUGIN); @@ -6697,14 +6709,14 @@ TSHttpConnectPlugin(TSHttpConnectOptions *options) return nullptr; } -TSVConn -TSHttpConnect(sockaddr const *addr) +tsapi::c::TSVConn +tsapi::c::TSHttpConnect(sockaddr const *addr) { return TSHttpConnectWithPluginId(addr, "plugin", 0); } -TSVConn -TSHttpConnectTransparent(sockaddr const *client_addr, sockaddr const *server_addr) +tsapi::c::TSVConn +tsapi::c::TSHttpConnectTransparent(sockaddr const *client_addr, sockaddr const *server_addr) { sdk_assert(ats_is_ip(client_addr)); sdk_assert(ats_is_ip(server_addr)); @@ -6740,7 +6752,7 @@ TSHttpConnectTransparent(sockaddr const *client_addr, sockaddr const *server_add /* Actions */ void -TSActionCancel(TSAction actionp) +tsapi::c::TSActionCancel(TSAction actionp) { Action *thisaction; INKContInternal *i; @@ -6768,15 +6780,15 @@ TSActionCancel(TSAction actionp) // Currently no error handling necessary, actionp can be anything. int -TSActionDone(TSAction actionp) +tsapi::c::TSActionDone(TSAction actionp) { return ((Action *)actionp == ACTION_RESULT_DONE) ? 1 : 0; } /* Connections */ -TSVConn -TSVConnCreate(TSEventFunc event_funcp, TSMutex mutexp) +tsapi::c::TSVConn +tsapi::c::TSVConnCreate(TSEventFunc event_funcp, TSMutex mutexp) { if (mutexp == nullptr) { mutexp = (TSMutex)new_ProxyMutex(); @@ -6810,8 +6822,8 @@ struct ActionSink : public Continuation { static ActionSink a; -TSVConn -TSVConnFdCreate(int fd) +tsapi::c::TSVConn +tsapi::c::TSVConnFdCreate(int fd) { UnixNetVConnection *vc; EThread *t = this_ethread(); @@ -6848,8 +6860,8 @@ TSVConnFdCreate(int fd) return reinterpret_cast(vc); } -TSVIO -TSVConnReadVIOGet(TSVConn connp) +tsapi::c::TSVIO +tsapi::c::TSVConnReadVIOGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6863,8 +6875,8 @@ TSVConnReadVIOGet(TSVConn connp) return nullptr; } -TSVIO -TSVConnWriteVIOGet(TSVConn connp) +tsapi::c::TSVIO +tsapi::c::TSVConnWriteVIOGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6879,7 +6891,7 @@ TSVConnWriteVIOGet(TSVConn connp) } int -TSVConnClosedGet(TSVConn connp) +tsapi::c::TSVConnClosedGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6890,8 +6902,8 @@ TSVConnClosedGet(TSVConn connp) return data; } -TSVIO -TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes) +tsapi::c::TSVIO +tsapi::c::TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -6904,8 +6916,8 @@ TSVConnRead(TSVConn connp, TSCont contp, TSIOBuffer bufp, int64_t nbytes) return reinterpret_cast(vc->do_io_read((INKContInternal *)contp, nbytes, (MIOBuffer *)bufp)); } -TSVIO -TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbytes) +tsapi::c::TSVIO +tsapi::c::TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbytes) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -6919,7 +6931,7 @@ TSVConnWrite(TSVConn connp, TSCont contp, TSIOBufferReader readerp, int64_t nbyt } void -TSVConnClose(TSVConn connp) +tsapi::c::TSVConnClose(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6928,7 +6940,7 @@ TSVConnClose(TSVConn connp) } void -TSVConnAbort(TSVConn connp, int error) +tsapi::c::TSVConnAbort(TSVConn connp, int error) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6937,7 +6949,7 @@ TSVConnAbort(TSVConn connp, int error) } void -TSVConnShutdown(TSVConn connp, int read, int write) +tsapi::c::TSVConnShutdown(TSVConn connp, int read, int write) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6953,7 +6965,7 @@ TSVConnShutdown(TSVConn connp, int read, int write) } int64_t -TSVConnCacheObjectSizeGet(TSVConn connp) +tsapi::c::TSVConnCacheObjectSizeGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6962,7 +6974,7 @@ TSVConnCacheObjectSizeGet(TSVConn connp) } void -TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop) +tsapi::c::TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6974,8 +6986,8 @@ TSVConnCacheHttpInfoSet(TSVConn connp, TSCacheHttpInfo infop) /* Transformations */ -TSVConn -TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp) +tsapi::c::TSVConn +tsapi::c::TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -6983,8 +6995,8 @@ TSTransformCreate(TSEventFunc event_funcp, TSHttpTxn txnp) reinterpret_cast(static_cast(reinterpret_cast(txnp))->getMutex())); } -TSVConn -TSTransformOutputVConnGet(TSVConn connp) +tsapi::c::TSVConn +tsapi::c::TSTransformOutputVConnGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -6996,7 +7008,7 @@ TSTransformOutputVConnGet(TSVConn connp) } void -TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp) +tsapi::c::TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp) { HttpSM *http_sm = (HttpSM *)txnp; @@ -7011,7 +7023,7 @@ TSHttpTxnServerIntercept(TSCont contp, TSHttpTxn txnp) } void -TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp) +tsapi::c::TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp) { HttpSM *http_sm = (HttpSM *)txnp; @@ -7025,8 +7037,8 @@ TSHttpTxnIntercept(TSCont contp, TSHttpTxn txnp) http_sm->plugin_tunnel = PluginVCCore::alloc((INKContInternal *)contp, buffer_index, buffer_water_mark); } -TSIOBufferSizeIndex -TSPluginVCIOBufferIndexGet(TSHttpTxn txnp) +tsapi::c::TSIOBufferSizeIndex +tsapi::c::TSPluginVCIOBufferIndexGet(TSHttpTxn txnp) { TSMgmtInt index; @@ -7038,8 +7050,8 @@ TSPluginVCIOBufferIndexGet(TSHttpTxn txnp) return TS_IOBUFFER_SIZE_INDEX_32K; } -TSIOBufferWaterMark -TSPluginVCIOBufferWaterMarkGet(TSHttpTxn txnp) +tsapi::c::TSIOBufferWaterMark +tsapi::c::TSPluginVCIOBufferWaterMarkGet(TSHttpTxn txnp) { TSMgmtInt water_mark; @@ -7057,7 +7069,7 @@ TSPluginVCIOBufferWaterMarkGet(TSHttpTxn txnp) // api. /* Net VConnections */ void -TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout) +tsapi::c::TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -7066,7 +7078,7 @@ TSVConnInactivityTimeoutSet(TSVConn connp, TSHRTime timeout) } void -TSVConnInactivityTimeoutCancel(TSVConn connp) +tsapi::c::TSVConnInactivityTimeoutCancel(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -7075,7 +7087,7 @@ TSVConnInactivityTimeoutCancel(TSVConn connp) } void -TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout) +tsapi::c::TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -7084,7 +7096,7 @@ TSVConnActiveTimeoutSet(TSVConn connp, TSHRTime timeout) } void -TSVConnActiveTimeoutCancel(TSVConn connp) +tsapi::c::TSVConnActiveTimeoutCancel(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); @@ -7093,7 +7105,7 @@ TSVConnActiveTimeoutCancel(TSVConn connp) } sockaddr const * -TSNetVConnLocalAddrGet(TSVConn connp) +tsapi::c::TSNetVConnLocalAddrGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); NetVConnection *vc = reinterpret_cast(connp); @@ -7101,15 +7113,15 @@ TSNetVConnLocalAddrGet(TSVConn connp) } sockaddr const * -TSNetVConnRemoteAddrGet(TSVConn connp) +tsapi::c::TSNetVConnRemoteAddrGet(TSVConn connp) { sdk_assert(sdk_sanity_check_iocore_structure(connp) == TS_SUCCESS); NetVConnection *vc = reinterpret_cast(connp); return vc->get_remote_addr(); } -TSAction -TSNetConnect(TSCont contp, sockaddr const *addr) +tsapi::c::TSAction +tsapi::c::TSNetConnect(TSCont contp, sockaddr const *addr) { sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); sdk_assert(ats_is_ip(addr)); @@ -7128,8 +7140,8 @@ TSNetConnect(TSCont contp, sockaddr const *addr) return reinterpret_cast(netProcessor.connect_re(reinterpret_cast(contp), addr, opt)); } -TSAction -TSNetConnectTransparent(TSCont contp, sockaddr const *client_addr, sockaddr const *server_addr) +tsapi::c::TSAction +tsapi::c::TSNetConnectTransparent(TSCont contp, sockaddr const *client_addr, sockaddr const *server_addr) { sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); sdk_assert(ats_is_ip(server_addr)); @@ -7145,8 +7157,8 @@ TSNetConnectTransparent(TSCont contp, sockaddr const *client_addr, sockaddr cons return reinterpret_cast(netProcessor.connect_re(reinterpret_cast(contp), server_addr, opt)); } -TSCont -TSNetInvokingContGet(TSVConn conn) +tsapi::c::TSCont +tsapi::c::TSNetInvokingContGet(TSVConn conn) { NetVConnection *vc = reinterpret_cast(conn); UnixNetVConnection *net_vc = dynamic_cast(vc); @@ -7158,8 +7170,8 @@ TSNetInvokingContGet(TSVConn conn) return ret; } -TSHttpTxn -TSNetInvokingTxnGet(TSVConn conn) +tsapi::c::TSHttpTxn +tsapi::c::TSNetInvokingTxnGet(TSVConn conn) { TSCont cont = TSNetInvokingContGet(conn); TSHttpTxn ret = nullptr; @@ -7173,8 +7185,8 @@ TSNetInvokingTxnGet(TSVConn conn) return ret; } -TSAction -TSNetAccept(TSCont contp, int port, int domain, int accept_threads) +tsapi::c::TSAction +tsapi::c::TSNetAccept(TSCont contp, int port, int domain, int accept_threads) { NetProcessor::AcceptOptions opt; @@ -7201,7 +7213,7 @@ TSNetAccept(TSCont contp, int port, int domain, int accept_threads) extern bool ssl_register_protocol(const char *, Continuation *); TSReturnCode -TSNetAcceptNamedProtocol(TSCont contp, const char *protocol) +tsapi::c::TSNetAcceptNamedProtocol(TSCont contp, const char *protocol) { sdk_assert(protocol != nullptr); sdk_assert(contp != nullptr); @@ -7221,7 +7233,7 @@ struct TSResolveInfo { HostDBRecord *record = nullptr; ///< Record for the FQDN. }; -int +static int TSHostLookupTrampoline(TSCont contp, TSEvent ev, void *data) { auto c = reinterpret_cast(contp); @@ -7239,8 +7251,8 @@ TSHostLookupTrampoline(TSCont contp, TSEvent ev, void *data) return TS_SUCCESS; }; -TSAction -TSHostLookup(TSCont contp, const char *hostname, size_t namelen) +tsapi::c::TSAction +tsapi::c::TSHostLookup(TSCont contp, const char *hostname, size_t namelen) { sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)hostname) == TS_SUCCESS); @@ -7260,7 +7272,7 @@ TSHostLookup(TSCont contp, const char *hostname, size_t namelen) } sockaddr const * -TSHostLookupResultAddrGet(TSHostLookupResult lookup_result) +tsapi::c::TSHostLookupResultAddrGet(TSHostLookupResult lookup_result) { sdk_assert(sdk_sanity_check_hostlookup_structure(lookup_result) == TS_SUCCESS); auto ri{reinterpret_cast(lookup_result)}; @@ -7274,7 +7286,7 @@ TSHostLookupResultAddrGet(TSHostLookupResult lookup_result) /* Only TSCacheReady exposed in SDK. No need of TSCacheDataTypeReady */ /* because SDK cache API supports only the data type: NONE */ TSReturnCode -TSCacheReady(int *is_ready) +tsapi::c::TSCacheReady(int *is_ready) { sdk_assert(sdk_sanity_check_null_ptr((void *)is_ready) == TS_SUCCESS); return TSCacheDataTypeReady(TS_CACHE_DATA_TYPE_NONE, is_ready); @@ -7282,7 +7294,7 @@ TSCacheReady(int *is_ready) /* Private API (used by Mixt) */ TSReturnCode -TSCacheDataTypeReady(TSCacheDataType type, int *is_ready) +tsapi::c::TSCacheDataTypeReady(TSCacheDataType type, int *is_ready) { sdk_assert(sdk_sanity_check_null_ptr((void *)is_ready) == TS_SUCCESS); @@ -7306,8 +7318,8 @@ TSCacheDataTypeReady(TSCacheDataType type, int *is_ready) } /* Cache VConnections */ -TSAction -TSCacheRead(TSCont contp, TSCacheKey key) +tsapi::c::TSAction +tsapi::c::TSCacheRead(TSCont contp, TSCacheKey key) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -7320,8 +7332,8 @@ TSCacheRead(TSCont contp, TSCacheKey key) return (TSAction)cacheProcessor.open_read(i, &info->cache_key, info->frag_type, info->hostname, info->len); } -TSAction -TSCacheWrite(TSCont contp, TSCacheKey key) +tsapi::c::TSAction +tsapi::c::TSCacheWrite(TSCont contp, TSCacheKey key) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -7335,8 +7347,8 @@ TSCacheWrite(TSCont contp, TSCacheKey key) info->len); } -TSAction -TSCacheRemove(TSCont contp, TSCacheKey key) +tsapi::c::TSAction +tsapi::c::TSCacheRemove(TSCont contp, TSCacheKey key) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_cachekey(key) == TS_SUCCESS); @@ -7349,8 +7361,8 @@ TSCacheRemove(TSCont contp, TSCacheKey key) return (TSAction)cacheProcessor.remove(i, &info->cache_key, info->frag_type, info->hostname, info->len); } -TSAction -TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second) +tsapi::c::TSAction +tsapi::c::TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); // NOTE: key can be NULl here, so don't check for it. @@ -7368,7 +7380,7 @@ TSCacheScan(TSCont contp, TSCacheKey key, int KB_per_second) /************************ REC Stats API **************************/ int -TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence persist, TSStatSync sync) +tsapi::c::TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence persist, TSStatSync sync) { int id = global_api_metrics.newMetric(the_name); @@ -7380,35 +7392,35 @@ TSStatCreate(const char *the_name, TSRecordDataType the_type, TSStatPersistence } void -TSStatIntIncrement(int id, TSMgmtInt amount) +tsapi::c::TSStatIntIncrement(int id, TSMgmtInt amount) { sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS); global_api_metrics[id].fetch_add(amount); } void -TSStatIntDecrement(int id, TSMgmtInt amount) +tsapi::c::TSStatIntDecrement(int id, TSMgmtInt amount) { sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS); global_api_metrics[id].fetch_sub(amount); } -TSMgmtInt -TSStatIntGet(int id) +tsapi::c::TSMgmtInt +tsapi::c::TSStatIntGet(int id) { sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS); return global_api_metrics[id].load(); } void -TSStatIntSet(int id, TSMgmtInt value) +tsapi::c::TSStatIntSet(int id, TSMgmtInt value) { sdk_assert(sdk_sanity_check_stat_id(id) == TS_SUCCESS); global_api_metrics[id].store(value); } TSReturnCode -TSStatFindName(const char *name, int *idp) +tsapi::c::TSStatFindName(const char *name, int *idp) { sdk_assert(sdk_sanity_check_null_ptr((void *)name) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)idp) == TS_SUCCESS); @@ -7426,13 +7438,13 @@ TSStatFindName(const char *name, int *idp) /************************** Tracing API ****************************/ // returns 1 or 0 to indicate whether TS is being run with a debug tag. int -TSIsDebugTagSet(const char *t) +tsapi::c::TSIsDebugTagSet(const char *t) { return diags()->on_for_TSDebug(t); } void -TSDebugSpecific(int debug_flag, const char *tag, const char *format_str, ...) +tsapi::c::TSDebugSpecific(int debug_flag, const char *tag, const char *format_str, ...) { if ((debug_flag && diags()->on_for_TSDebug()) || diags()->on_for_TSDebug(tag)) { va_list ap; @@ -7446,7 +7458,7 @@ TSDebugSpecific(int debug_flag, const char *tag, const char *format_str, ...) // Plugins would use TSDebug just as the TS internal uses Debug // e.g. TSDebug("plugin-cool", "Snoopy is a cool guy even after %d requests.", num_reqs); void -TSDebug(const char *tag, const char *format_str, ...) +tsapi::c::TSDebug(const char *tag, const char *format_str, ...) { if (diags()->on_for_TSDebug() && diags()->tag_activated(tag)) { va_list ap; @@ -7458,7 +7470,7 @@ TSDebug(const char *tag, const char *format_str, ...) } void -_TSDbg(const char *tag, const char *format_str, ...) +tsapi::c::_TSDbg(const char *tag, const char *format_str, ...) { va_list ap; @@ -7470,7 +7482,7 @@ _TSDbg(const char *tag, const char *format_str, ...) /************************** Logging API ****************************/ TSReturnCode -TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_object) +tsapi::c::TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_object) { sdk_assert(sdk_sanity_check_null_ptr((void *)filename) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)new_object) == TS_SUCCESS); @@ -7502,7 +7514,7 @@ TSTextLogObjectCreate(const char *filename, int mode, TSTextLogObject *new_objec } TSReturnCode -TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...) +tsapi::c::TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)format) == TS_SUCCESS); @@ -7531,7 +7543,7 @@ TSTextLogObjectWrite(TSTextLogObject the_object, const char *format, ...) } void -TSTextLogObjectFlush(TSTextLogObject the_object) +tsapi::c::TSTextLogObjectFlush(TSTextLogObject the_object) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7539,7 +7551,7 @@ TSTextLogObjectFlush(TSTextLogObject the_object) } TSReturnCode -TSTextLogObjectDestroy(TSTextLogObject the_object) +tsapi::c::TSTextLogObjectDestroy(TSTextLogObject the_object) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7551,7 +7563,7 @@ TSTextLogObjectDestroy(TSTextLogObject the_object) } void -TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header) +tsapi::c::TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7559,7 +7571,7 @@ TSTextLogObjectHeaderSet(TSTextLogObject the_object, const char *header) } TSReturnCode -TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled) +tsapi::c::TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7572,7 +7584,7 @@ TSTextLogObjectRollingEnabledSet(TSTextLogObject the_object, int rolling_enabled } void -TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_interval_sec) +tsapi::c::TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_interval_sec) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7580,7 +7592,7 @@ TSTextLogObjectRollingIntervalSecSet(TSTextLogObject the_object, int rolling_int } void -TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset_hr) +tsapi::c::TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset_hr) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7588,7 +7600,7 @@ TSTextLogObjectRollingOffsetHrSet(TSTextLogObject the_object, int rolling_offset } void -TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb) +tsapi::c::TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb) { sdk_assert(sdk_sanity_check_iocore_structure(the_object) == TS_SUCCESS); @@ -7596,7 +7608,7 @@ TSTextLogObjectRollingSizeMbSet(TSTextLogObject the_object, int rolling_size_mb) } TSReturnCode -TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp) +tsapi::c::TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp) { sdk_assert(sdk_sanity_check_null_ptr((void *)fdp) == TS_SUCCESS); @@ -7616,7 +7628,7 @@ TSHttpSsnClientFdGet(TSHttpSsn ssnp, int *fdp) return TS_SUCCESS; } TSReturnCode -TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp) +tsapi::c::TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)fdp) == TS_SUCCESS); @@ -7626,7 +7638,7 @@ TSHttpTxnClientFdGet(TSHttpTxn txnp, int *fdp) } TSReturnCode -TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp) +tsapi::c::TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)fdp) == TS_SUCCESS); @@ -7647,62 +7659,65 @@ TSHttpTxnServerFdGet(TSHttpTxn txnp, int *fdp) /* Matcher Utils */ char * -TSMatcherReadIntoBuffer(char *file_name, int *file_len) +tsapi::c::TSMatcherReadIntoBuffer(char *file_name, int *file_len) { sdk_assert(sdk_sanity_check_null_ptr((void *)file_name) == TS_SUCCESS); return readIntoBuffer(file_name, "TSMatcher", file_len); } char * -TSMatcherTokLine(char *buffer, char **last) +tsapi::c::TSMatcherTokLine(char *buffer, char **last) { sdk_assert(sdk_sanity_check_null_ptr((void *)buffer) == TS_SUCCESS); return tokLine(buffer, last); } char * -TSMatcherExtractIPRange(char *match_str, uint32_t *addr1, uint32_t *addr2) +tsapi::c::TSMatcherExtractIPRange(char *match_str, uint32_t *addr1, uint32_t *addr2) { sdk_assert(sdk_sanity_check_null_ptr((void *)match_str) == TS_SUCCESS); return (char *)ExtractIpRange(match_str, addr1, addr2); } + +#if 0 // Not used // Conflict in header due to overload (must be C compatible). char * -TSMatcherExtractIPRange(char *match_str, sockaddr *addr1, sockaddr *addr2) +tsapi::c::TSMatcherExtractIPRange(char *match_str, sockaddr *addr1, sockaddr *addr2) { sdk_assert(sdk_sanity_check_null_ptr((void *)match_str) == TS_SUCCESS); return (char *)ExtractIpRange(match_str, addr1, addr2); } +#endif -TSMatcherLine -TSMatcherLineCreate() +tsapi::c::TSMatcherLine +tsapi::c::TSMatcherLineCreate() { return reinterpret_cast(ats_malloc(sizeof(matcher_line))); } void -TSMatcherLineDestroy(TSMatcherLine ml) +tsapi::c::TSMatcherLineDestroy(TSMatcherLine ml) { sdk_assert(sdk_sanity_check_null_ptr((void *)ml) == TS_SUCCESS); ats_free(ml); } const char * -TSMatcherParseSrcIPConfigLine(char *line, TSMatcherLine ml) +tsapi::c::TSMatcherParseSrcIPConfigLine(char *line, TSMatcherLine ml) { sdk_assert(sdk_sanity_check_null_ptr((void *)line) == TS_SUCCESS); return parseConfigLine(line, (matcher_line *)ml, &ip_allow_src_tags); } char * -TSMatcherLineName(TSMatcherLine ml, int element) +tsapi::c::TSMatcherLineName(TSMatcherLine ml, int element) { sdk_assert(sdk_sanity_check_null_ptr((void *)ml) == TS_SUCCESS); return (((matcher_line *)ml)->line)[0][element]; } char * -TSMatcherLineValue(TSMatcherLine ml, int element) +tsapi::c::TSMatcherLineValue(TSMatcherLine ml, int element) { sdk_assert(sdk_sanity_check_null_ptr((void *)ml) == TS_SUCCESS); return (((matcher_line *)ml)->line)[1][element]; @@ -7712,14 +7727,14 @@ extern void load_config_file_callback(const char *parent, const char *remap_file /* Config file name setting */ TSReturnCode -TSMgmtConfigFileAdd(const char *parent, const char *fileName) +tsapi::c::TSMgmtConfigFileAdd(const char *parent, const char *fileName) { load_config_file_callback(parent, fileName); return TS_SUCCESS; } TSReturnCode -TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length) +tsapi::c::TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -7743,7 +7758,7 @@ TSCacheUrlSet(TSHttpTxn txnp, const char *url, int length) } void -TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey keyp) +tsapi::c::TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey keyp) { // TODO: Check input ? CacheHTTPInfo *info = (CacheHTTPInfo *)infop; @@ -7753,7 +7768,7 @@ TSCacheHttpInfoKeySet(TSCacheHttpInfo infop, TSCacheKey keyp) } void -TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size) +tsapi::c::TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size) { // TODO: Check input ? CacheHTTPInfo *info = (CacheHTTPInfo *)infop; @@ -7763,7 +7778,7 @@ TSCacheHttpInfoSizeSet(TSCacheHttpInfo infop, int64_t size) // this function should be called at TS_EVENT_HTTP_READ_RESPONSE_HDR void -TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len) +tsapi::c::TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)url) == TS_SUCCESS); @@ -7787,7 +7802,7 @@ TSHttpTxnRedirectUrlSet(TSHttpTxn txnp, const char *url, const int url_len) } const char * -TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr) +tsapi::c::TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -7798,7 +7813,7 @@ TSHttpTxnRedirectUrlGet(TSHttpTxn txnp, int *url_len_ptr) } int -TSHttpTxnRedirectRetries(TSHttpTxn txnp) +tsapi::c::TSHttpTxnRedirectRetries(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -7808,7 +7823,7 @@ TSHttpTxnRedirectRetries(TSHttpTxn txnp) } char * -TSFetchRespGet(TSHttpTxn txnp, int *length) +tsapi::c::TSFetchRespGet(TSHttpTxn txnp, int *length) { sdk_assert(sdk_sanity_check_null_ptr((void *)length) == TS_SUCCESS); FetchSM *fetch_sm = reinterpret_cast(txnp); @@ -7816,7 +7831,7 @@ TSFetchRespGet(TSHttpTxn txnp, int *length) } TSReturnCode -TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) +tsapi::c::TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) { sdk_assert(sdk_sanity_check_null_ptr((void *)bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)obj) == TS_SUCCESS); @@ -7836,7 +7851,7 @@ TSFetchPageRespGet(TSHttpTxn txnp, TSMBuffer *bufp, TSMLoc *obj) extern ClassAllocator FetchSMAllocator; void -TSFetchPages(TSFetchUrlParams_t *params) +tsapi::c::TSFetchPages(TSFetchUrlParams_t *params) { TSFetchUrlParams_t *myparams = params; @@ -7851,9 +7866,9 @@ TSFetchPages(TSFetchUrlParams_t *params) } } -TSFetchSM -TSFetchUrl(const char *headers, int request_len, sockaddr const *ip, TSCont contp, TSFetchWakeUpOptions callback_options, - TSFetchEvent events) +tsapi::c::TSFetchSM +tsapi::c::TSFetchUrl(const char *headers, int request_len, sockaddr const *ip, TSCont contp, TSFetchWakeUpOptions callback_options, + TSFetchEvent events) { if (callback_options != NO_CALLBACK) { sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); @@ -7868,14 +7883,15 @@ TSFetchUrl(const char *headers, int request_len, sockaddr const *ip, TSCont cont } void -TSFetchFlagSet(TSFetchSM fetch_sm, int flags) +tsapi::c::TSFetchFlagSet(TSFetchSM fetch_sm, int flags) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); (reinterpret_cast(fetch_sm))->set_fetch_flags(flags); } -TSFetchSM -TSFetchCreate(TSCont contp, const char *method, const char *url, const char *version, struct sockaddr const *client_addr, int flags) +tsapi::c::TSFetchSM +tsapi::c::TSFetchCreate(TSCont contp, const char *method, const char *url, const char *version, struct sockaddr const *client_addr, + int flags) { sdk_assert(sdk_sanity_check_continuation(contp) == TS_SUCCESS); sdk_assert(ats_is_ip(client_addr)); @@ -7888,7 +7904,7 @@ TSFetchCreate(TSCont contp, const char *method, const char *url, const char *ver } void -TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char *value, int value_len) +tsapi::c::TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char *value, int value_len) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7896,7 +7912,7 @@ TSFetchHeaderAdd(TSFetchSM fetch_sm, const char *name, int name_len, const char } void -TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len) +tsapi::c::TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7904,7 +7920,7 @@ TSFetchWriteData(TSFetchSM fetch_sm, const void *data, size_t len) } ssize_t -TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len) +tsapi::c::TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7912,7 +7928,7 @@ TSFetchReadData(TSFetchSM fetch_sm, void *buf, size_t len) } void -TSFetchLaunch(TSFetchSM fetch_sm) +tsapi::c::TSFetchLaunch(TSFetchSM fetch_sm) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7920,7 +7936,7 @@ TSFetchLaunch(TSFetchSM fetch_sm) } void -TSFetchDestroy(TSFetchSM fetch_sm) +tsapi::c::TSFetchDestroy(TSFetchSM fetch_sm) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7928,7 +7944,7 @@ TSFetchDestroy(TSFetchSM fetch_sm) } void -TSFetchUserDataSet(TSFetchSM fetch_sm, void *data) +tsapi::c::TSFetchUserDataSet(TSFetchSM fetch_sm, void *data) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7936,23 +7952,23 @@ TSFetchUserDataSet(TSFetchSM fetch_sm, void *data) } void * -TSFetchUserDataGet(TSFetchSM fetch_sm) +tsapi::c::TSFetchUserDataGet(TSFetchSM fetch_sm) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); return (reinterpret_cast(fetch_sm))->ext_get_user_data(); } -TSMBuffer -TSFetchRespHdrMBufGet(TSFetchSM fetch_sm) +tsapi::c::TSMBuffer +tsapi::c::TSFetchRespHdrMBufGet(TSFetchSM fetch_sm) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); return ((FetchSM *)fetch_sm)->resp_hdr_bufp(); } -TSMLoc -TSFetchRespHdrMLocGet(TSFetchSM fetch_sm) +tsapi::c::TSMLoc +tsapi::c::TSFetchRespHdrMLocGet(TSFetchSM fetch_sm) { sdk_assert(sdk_sanity_check_fetch_sm(fetch_sm) == TS_SUCCESS); @@ -7960,7 +7976,7 @@ TSFetchRespHdrMLocGet(TSFetchSM fetch_sm) } int -TSHttpSsnIsInternal(TSHttpSsn ssnp) +tsapi::c::TSHttpSsnIsInternal(TSHttpSsn ssnp) { ProxySession *cs = reinterpret_cast(ssnp); @@ -7977,14 +7993,14 @@ TSHttpSsnIsInternal(TSHttpSsn ssnp) } int -TSHttpTxnIsInternal(TSHttpTxn txnp) +tsapi::c::TSHttpTxnIsInternal(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); return TSHttpSsnIsInternal(TSHttpTxnSsnGet(txnp)); } TSReturnCode -TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len) +tsapi::c::TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -8026,7 +8042,7 @@ TSHttpTxnServerPush(TSHttpTxn txnp, const char *url, int url_len) } TSReturnCode -TSHttpTxnClientStreamIdGet(TSHttpTxn txnp, uint64_t *stream_id) +tsapi::c::TSHttpTxnClientStreamIdGet(TSHttpTxn txnp, uint64_t *stream_id) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(stream_id != nullptr); @@ -8041,7 +8057,7 @@ TSHttpTxnClientStreamIdGet(TSHttpTxn txnp, uint64_t *stream_id) } TSReturnCode -TSHttpTxnClientStreamPriorityGet(TSHttpTxn txnp, TSHttpPriority *priority) +tsapi::c::TSHttpTxnClientStreamPriorityGet(TSHttpTxn txnp, TSHttpPriority *priority) { static_assert(sizeof(TSHttpPriority) >= sizeof(TSHttp2Priority), "TSHttpPriorityType is incorrectly smaller than TSHttp2Priority."); @@ -8063,7 +8079,7 @@ TSHttpTxnClientStreamPriorityGet(TSHttpTxn txnp, TSHttpPriority *priority) } TSReturnCode -TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp) +tsapi::c::TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -8090,21 +8106,21 @@ TSAIORead(int fd, off_t offset, char *buf, size_t buffSize, TSCont contp) } char * -TSAIOBufGet(TSAIOCallback data) +tsapi::c::TSAIOBufGet(TSAIOCallback data) { AIOCallback *pAIO = (AIOCallback *)data; return (char *)pAIO->aiocb.aio_buf; } int -TSAIONBytesGet(TSAIOCallback data) +tsapi::c::TSAIONBytesGet(TSAIOCallback data) { AIOCallback *pAIO = (AIOCallback *)data; return (int)pAIO->aio_result; } TSReturnCode -TSAIOWrite(int fd, off_t offset, char *buf, const size_t bufSize, TSCont contp) +tsapi::c::TSAIOWrite(int fd, off_t offset, char *buf, const size_t bufSize, TSCont contp) { sdk_assert(sdk_sanity_check_iocore_structure(contp) == TS_SUCCESS); @@ -8129,7 +8145,7 @@ TSAIOWrite(int fd, off_t offset, char *buf, const size_t bufSize, TSCont contp) } TSReturnCode -TSAIOThreadNumSet(int thread_num) +tsapi::c::TSAIOThreadNumSet(int thread_num) { #if AIO_MODE == AIO_MODE_NATIVE || AIO_MODE == AIO_MODE_IO_URING (void)thread_num; @@ -8144,7 +8160,7 @@ TSAIOThreadNumSet(int thread_num) } void -TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata) +tsapi::c::TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata) { RecDumpRecords((RecT)rec_type, (RecDumpEntryCb)callback, edata); } @@ -8153,7 +8169,7 @@ TSRecordDump(int rec_type, TSRecordDumpCb callback, void *edata) this only really makes sense in TS_HTTP_READ_REQUEST_HDR_HOOK */ void -TSSkipRemappingSet(TSHttpTxn txnp, int flag) +tsapi::c::TSSkipRemappingSet(TSHttpTxn txnp, int flag) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -8638,7 +8654,7 @@ _conf_to_memberp(TSOverridableConfigKey conf, const OverridableHttpConfigParams /* APIs to manipulate the overridable configuration options. */ TSReturnCode -TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt value) +tsapi::c::TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt value) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -8659,7 +8675,7 @@ TSHttpTxnConfigIntSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt val } TSReturnCode -TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *value) +tsapi::c::TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *value) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)value) == TS_SUCCESS); @@ -8678,7 +8694,7 @@ TSHttpTxnConfigIntGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtInt *va } TSReturnCode -TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat value) +tsapi::c::TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat value) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -8699,7 +8715,7 @@ TSHttpTxnConfigFloatSet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat } TSReturnCode -TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat *value) +tsapi::c::TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat *value) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr(static_cast(value)) == TS_SUCCESS); @@ -8716,7 +8732,7 @@ TSHttpTxnConfigFloatGet(TSHttpTxn txnp, TSOverridableConfigKey conf, TSMgmtFloat } TSReturnCode -TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char *value, int length) +tsapi::c::TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char *value, int length) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -8834,7 +8850,7 @@ TSHttpTxnConfigStringSet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char } TSReturnCode -TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char **value, int *length) +tsapi::c::TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char **value, int *length) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void **)value) == TS_SUCCESS); @@ -8877,7 +8893,7 @@ TSHttpTxnConfigStringGet(TSHttpTxn txnp, TSOverridableConfigKey conf, const char } TSReturnCode -TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, TSRecordDataType *type) +tsapi::c::TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, TSRecordDataType *type) { sdk_assert(sdk_sanity_check_null_ptr(name) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr(conf) == TS_SUCCESS); @@ -8892,7 +8908,7 @@ TSHttpTxnConfigFind(const char *name, int length, TSOverridableConfigKey *conf, } TSReturnCode -TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session) +tsapi::c::TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session) { if (sdk_sanity_check_txn(txnp) != TS_SUCCESS) { return TS_ERROR; @@ -8906,8 +8922,9 @@ TSHttpTxnPrivateSessionSet(TSHttpTxn txnp, int private_session) // APIs to register new Mgmt (records) entries. TSReturnCode -TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString data_default, TSRecordUpdateType update_type, - TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type) +tsapi::c::TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString data_default, + TSRecordUpdateType update_type, TSRecordCheckType check_type, const char *check_regex, + TSRecordAccessType access_type) { if (check_regex == nullptr && check_type != TS_RECORDCHECK_NULL) { return TS_ERROR; @@ -8922,8 +8939,8 @@ TSMgmtStringCreate(TSRecordType rec_type, const char *name, const TSMgmtString d } TSReturnCode -TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, TSRecordUpdateType update_type, - TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type) +tsapi::c::TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, TSRecordUpdateType update_type, + TSRecordCheckType check_type, const char *check_regex, TSRecordAccessType access_type) { if (check_regex == nullptr && check_type != TS_RECORDCHECK_NULL) { return TS_ERROR; @@ -8938,7 +8955,7 @@ TSMgmtIntCreate(TSRecordType rec_type, const char *name, TSMgmtInt data_default, } TSReturnCode -TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close) +tsapi::c::TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close) { if (sdk_sanity_check_txn(txnp) != TS_SUCCESS) { return TS_ERROR; @@ -8960,8 +8977,8 @@ TSHttpTxnCloseAfterResponse(TSHttpTxn txnp, int should_close) } // Parse a port descriptor for the proxy.config.http.server_ports descriptor format. -TSPortDescriptor -TSPortDescriptorParse(const char *descriptor) +tsapi::c::TSPortDescriptor +tsapi::c::TSPortDescriptorParse(const char *descriptor) { HttpProxyPort *port = new HttpProxyPort(); @@ -8974,7 +8991,7 @@ TSPortDescriptorParse(const char *descriptor) } TSReturnCode -TSPortDescriptorAccept(TSPortDescriptor descp, TSCont contp) +tsapi::c::TSPortDescriptorAccept(TSPortDescriptor descp, TSCont contp) { Action *action = nullptr; HttpProxyPort *port = (HttpProxyPort *)descp; @@ -8990,7 +9007,7 @@ TSPortDescriptorAccept(TSPortDescriptor descp, TSCont contp) } TSReturnCode -TSPluginDescriptorAccept(TSCont contp) +tsapi::c::TSPluginDescriptorAccept(TSCont contp) { Action *action = nullptr; @@ -9005,7 +9022,7 @@ TSPluginDescriptorAccept(TSCont contp) } int -TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp) +tsapi::c::TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *s = (HttpSM *)txnp; @@ -9014,7 +9031,7 @@ TSHttpTxnBackgroundFillStarted(TSHttpTxn txnp) } int -TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response) +tsapi::c::TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -9040,7 +9057,7 @@ TSHttpTxnIsCacheable(TSHttpTxn txnp, TSMBuffer request, TSMBuffer response) } int -TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response) +tsapi::c::TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -9051,7 +9068,7 @@ TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response) sdk_assert(sdk_sanity_check_mbuffer(response) == TS_SUCCESS); resp = reinterpret_cast(response); } else { - // Use the transactions origin response if the user passed NULL + // Use the transactions origin response if the user passed null resp = &(sm->t_state.hdr_info.server_response); } @@ -9065,19 +9082,19 @@ TSHttpTxnGetMaxAge(TSHttpTxn txnp, TSMBuffer response) // Lookup various debug names for common HTTP types. const char * -TSHttpServerStateNameLookup(TSServerState state) +tsapi::c::TSHttpServerStateNameLookup(TSServerState state) { return HttpDebugNames::get_server_state_name(static_cast(state)); } const char * -TSHttpHookNameLookup(TSHttpHookID hook) +tsapi::c::TSHttpHookNameLookup(TSHttpHookID hook) { return HttpDebugNames::get_api_hook_name(static_cast(hook)); } const char * -TSHttpEventNameLookup(TSEvent event) +tsapi::c::TSHttpEventNameLookup(TSEvent event) { return HttpDebugNames::get_event_name(static_cast(event)); } @@ -9105,7 +9122,7 @@ class TSSslCallback : public Continuation /// SSL Hooks TSReturnCode -TSVConnTunnel(TSVConn sslp) +tsapi::c::TSVConnTunnel(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); SSLNetVConnection *ssl_vc = dynamic_cast(vc); @@ -9118,8 +9135,8 @@ TSVConnTunnel(TSVConn sslp) return zret; } -TSSslConnection -TSVConnSslConnectionGet(TSVConn sslp) +tsapi::c::TSSslConnection +tsapi::c::TSVConnSslConnectionGet(TSVConn sslp) { TSSslConnection ssl = nullptr; NetVConnection *vc = reinterpret_cast(sslp); @@ -9131,7 +9148,7 @@ TSVConnSslConnectionGet(TSVConn sslp) } const char * -TSVConnSslSniGet(TSVConn sslp, int *length) +tsapi::c::TSVConnSslSniGet(TSVConn sslp, int *length) { char const *server_name = nullptr; NetVConnection *vc = reinterpret_cast(sslp); @@ -9149,8 +9166,8 @@ TSVConnSslSniGet(TSVConn sslp, int *length) return server_name; } -tsapi TSSslVerifyCTX -TSVConnSslVerifyCTXGet(TSVConn sslp) +tsapi::c::TSSslVerifyCTX +tsapi::c::TSVConnSslVerifyCTXGet(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); SSLNetVConnection *ssl_vc = dynamic_cast(vc); @@ -9160,8 +9177,8 @@ TSVConnSslVerifyCTXGet(TSVConn sslp) return nullptr; } -tsapi TSSslContext -TSSslContextFindByName(const char *name) +tsapi::c::TSSslContext +tsapi::c::TSSslContextFindByName(const char *name) { if (nullptr == name || 0 == strlen(name)) { // an empty name is an invalid input @@ -9181,8 +9198,8 @@ TSSslContextFindByName(const char *name) } return ret; } -tsapi TSSslContext -TSSslContextFindByAddr(struct sockaddr const *addr) +tsapi::c::TSSslContext +tsapi::c::TSSslContextFindByAddr(struct sockaddr const *addr) { TSSslContext ret = nullptr; SSLCertLookup *lookup = SSLCertificateConfig::acquire(); @@ -9205,8 +9222,8 @@ TSSslContextFindByAddr(struct sockaddr const *addr) * This function sets the secret cache value for a given secret name. This allows * plugins to load cert/key PEM information on for use by the TLS core */ -tsapi TSReturnCode -TSSslSecretSet(const char *secret_name, int secret_name_length, const char *secret_data, int secret_data_len) +TSReturnCode +tsapi::c::TSSslSecretSet(const char *secret_name, int secret_name_length, const char *secret_data, int secret_data_len) { TSReturnCode retval = TS_SUCCESS; std::string const secret_name_str{secret_name, unsigned(secret_name_length)}; @@ -9227,8 +9244,8 @@ TSSslSecretSet(const char *secret_name, int secret_name_length, const char *secr return retval; } -tsapi TSReturnCode -TSSslSecretUpdate(const char *secret_name, int secret_name_length) +TSReturnCode +tsapi::c::TSSslSecretUpdate(const char *secret_name, int secret_name_length) { TSReturnCode retval = TS_SUCCESS; SSLConfigParams *params = SSLConfig::acquire(); @@ -9239,8 +9256,8 @@ TSSslSecretUpdate(const char *secret_name, int secret_name_length) return retval; } -tsapi char * -TSSslSecretGet(const char *secret_name, int secret_name_length, int *secret_data_length) +char * +tsapi::c::TSSslSecretGet(const char *secret_name, int secret_name_length, int *secret_data_length) { sdk_assert(secret_name != nullptr); sdk_assert(secret_data_length != nullptr); @@ -9277,8 +9294,8 @@ TSSslSecretGet(const char *secret_name, int secret_name_length, int *secret_data * @param result Const char pointer arrays to be filled with lookup keys. * @param actual Total number of lookup keys. */ -tsapi TSReturnCode -TSSslClientContextsNamesGet(int n, const char **result, int *actual) +TSReturnCode +tsapi::c::TSSslClientContextsNamesGet(int n, const char **result, int *actual) { sdk_assert(n == 0 || result != nullptr); int idx = 0, count = 0; @@ -9320,8 +9337,8 @@ TSSslClientContextsNamesGet(int n, const char **result, int *actual) * @param first_key Key string for the top level. * @param second_key Key string for the second level. */ -tsapi TSSslContext -TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths) +tsapi::c::TSSslContext +tsapi::c::TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths) { if (!ca_paths || !ck_paths || ca_paths[0] == '\0' || ck_paths[0] == '\0') { return nullptr; @@ -9344,8 +9361,8 @@ TSSslClientContextFindByName(const char *ca_paths, const char *ck_paths) return retval; } -tsapi TSSslContext -TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_file) +tsapi::c::TSSslContext +tsapi::c::TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_file) { TSSslContext ret = nullptr; SSLConfigParams *config = SSLConfig::acquire(); @@ -9363,14 +9380,14 @@ TSSslServerContextCreate(TSSslX509 cert, const char *certname, const char *rsp_f return ret; } -tsapi void -TSSslContextDestroy(TSSslContext ctx) +void +tsapi::c::TSSslContextDestroy(TSSslContext ctx) { SSLReleaseContext(reinterpret_cast(ctx)); } TSReturnCode -TSSslClientCertUpdate(const char *cert_path, const char *key_path) +tsapi::c::TSSslClientCertUpdate(const char *cert_path, const char *key_path) { if (nullptr == cert_path) { return TS_ERROR; @@ -9432,7 +9449,7 @@ TSSslClientCertUpdate(const char *cert_path, const char *key_path) } TSReturnCode -TSSslServerCertUpdate(const char *cert_path, const char *key_path) +tsapi::c::TSSslServerCertUpdate(const char *cert_path, const char *key_path) { if (nullptr == cert_path) { return TS_ERROR; @@ -9466,7 +9483,7 @@ TSSslServerCertUpdate(const char *cert_path, const char *key_path) ASN1_STRING *common_name_asn1 = X509_NAME_ENTRY_get_data(common_name); char *common_name_str = reinterpret_cast(const_cast(ASN1_STRING_get0_data(common_name_asn1))); if (ASN1_STRING_length(common_name_asn1) != static_cast(strlen(common_name_str))) { - // Embedded NULL char + // Embedded null char return TS_ERROR; } Debug("ssl.cert_update", "Updating from %s with common name %s", cert_path, common_name_str); @@ -9487,14 +9504,14 @@ TSSslServerCertUpdate(const char *cert_path, const char *key_path) return TS_ERROR; } -tsapi TSReturnCode -TSSslTicketKeyUpdate(char *ticketData, int ticketDataLen) +TSReturnCode +tsapi::c::TSSslTicketKeyUpdate(char *ticketData, int ticketDataLen) { return SSLTicketKeyConfig::reconfigure_data(ticketData, ticketDataLen) ? TS_SUCCESS : TS_ERROR; } TSReturnCode -TSVConnProtocolEnable(TSVConn connp, const char *protocol_name) +tsapi::c::TSVConnProtocolEnable(TSVConn connp, const char *protocol_name) { TSReturnCode retval = TS_ERROR; int protocol_idx = globalSessionProtocolNameRegistry.toIndexConst(std::string_view{protocol_name}); @@ -9507,7 +9524,7 @@ TSVConnProtocolEnable(TSVConn connp, const char *protocol_name) } TSReturnCode -TSVConnProtocolDisable(TSVConn connp, const char *protocol_name) +tsapi::c::TSVConnProtocolDisable(TSVConn connp, const char *protocol_name) { TSReturnCode retval = TS_ERROR; int protocol_idx = globalSessionProtocolNameRegistry.toIndexConst(std::string_view{protocol_name}); @@ -9519,16 +9536,16 @@ TSVConnProtocolDisable(TSVConn connp, const char *protocol_name) return retval; } -TSAcceptor -TSAcceptorGet(TSVConn sslp) +tsapi::c::TSAcceptor +tsapi::c::TSAcceptorGet(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); SSLNetVConnection *ssl_vc = dynamic_cast(vc); return ssl_vc ? reinterpret_cast(ssl_vc->accept_object) : nullptr; } -TSAcceptor -TSAcceptorGetbyID(int ID) +tsapi::c::TSAcceptor +tsapi::c::TSAcceptorGetbyID(int ID) { SCOPED_MUTEX_LOCK(lock, naVecMutex, this_ethread()); auto ret = naVec.at(ID); @@ -9537,42 +9554,42 @@ TSAcceptorGetbyID(int ID) } int -TSAcceptorIDGet(TSAcceptor acceptor) +tsapi::c::TSAcceptorIDGet(TSAcceptor acceptor) { NetAccept *na = reinterpret_cast(acceptor); return na ? na->id : -1; } int -TSAcceptorCount() +tsapi::c::TSAcceptorCount() { SCOPED_MUTEX_LOCK(lock, naVecMutex, this_ethread()); return naVec.size(); } -tsapi int -TSVConnIsSsl(TSVConn sslp) +int +tsapi::c::TSVConnIsSsl(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); SSLNetVConnection *ssl_vc = dynamic_cast(vc); return ssl_vc != nullptr; } -tsapi int -TSVConnProvidedSslCert(TSVConn sslp) +int +tsapi::c::TSVConnProvidedSslCert(TSVConn sslp) { NetVConnection *vc = reinterpret_cast(sslp); return vc->provided_cert(); } void -TSVConnReenable(TSVConn vconn) +tsapi::c::TSVConnReenable(TSVConn vconn) { TSVConnReenableEx(vconn, TS_EVENT_CONTINUE); } void -TSVConnReenableEx(TSVConn vconn, TSEvent event) +tsapi::c::TSVConnReenableEx(TSVConn vconn, TSEvent event) { NetVConnection *vc = reinterpret_cast(vconn); SSLNetVConnection *ssl_vc = dynamic_cast(vc); @@ -9593,8 +9610,8 @@ TSVConnReenableEx(TSVConn vconn, TSEvent event) extern SSLSessionCache *session_cache; // declared extern in P_SSLConfig.h -TSSslSession -TSSslSessionGet(const TSSslSessionID *session_id) +tsapi::c::TSSslSession +tsapi::c::TSSslSessionGet(const TSSslSessionID *session_id) { SSL_SESSION *session = nullptr; if (session_id && session_cache) { @@ -9604,7 +9621,7 @@ TSSslSessionGet(const TSSslSessionID *session_id) } int -TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_ptr) +tsapi::c::TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_ptr) { int true_len = 0; // Don't get if there is no session id or the cache is not yet set up @@ -9615,7 +9632,7 @@ TSSslSessionGetBuffer(const TSSslSessionID *session_id, char *buffer, int *len_p } TSReturnCode -TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, TSSslConnection ssl_conn) +tsapi::c::TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, TSSslConnection ssl_conn) { // Don't insert if there is no session id or the cache is not yet set up if (session_id && session_cache) { @@ -9636,7 +9653,7 @@ TSSslSessionInsert(const TSSslSessionID *session_id, TSSslSession add_session, T } TSReturnCode -TSSslSessionRemove(const TSSslSessionID *session_id) +tsapi::c::TSSslSessionRemove(const TSSslSessionID *session_id) { // Don't remove if there is no session id or the cache is not yet set up if (session_id && session_cache) { @@ -9649,22 +9666,22 @@ TSSslSessionRemove(const TSSslSessionID *session_id) } // APIs for managing and using UUIDs. -TSUuid -TSUuidCreate() +tsapi::c::TSUuid +tsapi::c::TSUuidCreate() { ATSUuid *uuid = new ATSUuid(); return (TSUuid)uuid; } void -TSUuidDestroy(TSUuid uuid) +tsapi::c::TSUuidDestroy(TSUuid uuid) { sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS); delete (ATSUuid *)uuid; } TSReturnCode -TSUuidCopy(TSUuid dest, const TSUuid src) +tsapi::c::TSUuidCopy(TSUuid dest, const TSUuid src) { sdk_assert(sdk_sanity_check_null_ptr((void *)dest) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)src) == TS_SUCCESS); @@ -9680,7 +9697,7 @@ TSUuidCopy(TSUuid dest, const TSUuid src) } TSReturnCode -TSUuidInitialize(TSUuid uuid, TSUuidVersion v) +tsapi::c::TSUuidInitialize(TSUuid uuid, TSUuidVersion v) { sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS); ATSUuid *u = (ATSUuid *)uuid; @@ -9689,15 +9706,15 @@ TSUuidInitialize(TSUuid uuid, TSUuidVersion v) return u->valid() ? TS_SUCCESS : TS_ERROR; } -TSUuid -TSProcessUuidGet() +tsapi::c::TSUuid +tsapi::c::TSProcessUuidGet() { Machine *machine = Machine::instance(); return (TSUuid)(&machine->uuid); } const char * -TSUuidStringGet(const TSUuid uuid) +tsapi::c::TSUuidStringGet(const TSUuid uuid) { sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS); ATSUuid *u = (ATSUuid *)(uuid); @@ -9710,7 +9727,7 @@ TSUuidStringGet(const TSUuid uuid) } TSReturnCode -TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str) +tsapi::c::TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str) { sdk_assert(sdk_sanity_check_null_ptr((void *)uuid_str) == TS_SUCCESS); @@ -9727,7 +9744,7 @@ TSClientRequestUuidGet(TSHttpTxn txnp, char *uuid_str) } TSReturnCode -TSUuidStringParse(TSUuid uuid, const char *str) +tsapi::c::TSUuidStringParse(TSUuid uuid, const char *str) { sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)str) == TS_SUCCESS); @@ -9740,8 +9757,8 @@ TSUuidStringParse(TSUuid uuid, const char *str) return TS_ERROR; } -TSUuidVersion -TSUuidVersionGet(TSUuid uuid) +tsapi::c::TSUuidVersion +tsapi::c::TSUuidVersionGet(TSUuid uuid) { sdk_assert(sdk_sanity_check_null_ptr((void *)uuid) == TS_SUCCESS); ATSUuid *u = (ATSUuid *)uuid; @@ -9751,7 +9768,7 @@ TSUuidVersionGet(TSUuid uuid) // Expose the HttpSM's sequence number (ID) uint64_t -TSHttpTxnIdGet(TSHttpTxn txnp) +tsapi::c::TSHttpTxnIdGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; @@ -9761,7 +9778,7 @@ TSHttpTxnIdGet(TSHttpTxn txnp) // Returns unique client session identifier int64_t -TSHttpSsnIdGet(TSHttpSsn ssnp) +tsapi::c::TSHttpSsnIdGet(TSHttpSsn ssnp) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); ProxySession const *cs = reinterpret_cast(ssnp); @@ -9770,7 +9787,7 @@ TSHttpSsnIdGet(TSHttpSsn ssnp) // Return information about the protocols used by the client TSReturnCode -TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual) +tsapi::c::TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(count == 0 || result != nullptr); @@ -9790,7 +9807,7 @@ TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int count, const char **result, } TSReturnCode -TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int count, const char **result, int *actual) +tsapi::c::TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int count, const char **result, int *actual) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); sdk_assert(count == 0 || result != nullptr); @@ -9811,7 +9828,7 @@ TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int count, const char **result, // Return information about the protocols used by the server TSReturnCode -TSHttpTxnServerProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual) +tsapi::c::TSHttpTxnServerProtocolStackGet(TSHttpTxn txnp, int count, const char **result, int *actual) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); sdk_assert(count == 0 || result != nullptr); @@ -9831,13 +9848,13 @@ TSHttpTxnServerProtocolStackGet(TSHttpTxn txnp, int count, const char **result, } const char * -TSNormalizedProtocolTag(const char *tag) +tsapi::c::TSNormalizedProtocolTag(const char *tag) { return RecNormalizeProtoTag(tag); } const char * -TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, const char *tag) +tsapi::c::TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, const char *tag) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = reinterpret_cast(txnp); @@ -9845,7 +9862,7 @@ TSHttpTxnClientProtocolStackContains(TSHttpTxn txnp, const char *tag) } const char * -TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, const char *tag) +tsapi::c::TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, const char *tag) { sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS); ProxySession *cs = reinterpret_cast(ssnp); @@ -9853,7 +9870,7 @@ TSHttpSsnClientProtocolStackContains(TSHttpSsn ssnp, const char *tag) } const char * -TSHttpTxnServerProtocolStackContains(TSHttpTxn txnp, const char *tag) +tsapi::c::TSHttpTxnServerProtocolStackContains(TSHttpTxn txnp, const char *tag) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = reinterpret_cast(txnp); @@ -9861,13 +9878,13 @@ TSHttpTxnServerProtocolStackContains(TSHttpTxn txnp, const char *tag) } const char * -TSRegisterProtocolTag(const char *tag) +tsapi::c::TSRegisterProtocolTag(const char *tag) { return nullptr; } TSReturnCode -TSHttpTxnRedoCacheLookup(TSHttpTxn txnp, const char *url, int length) +tsapi::c::TSHttpTxnRedoCacheLookup(TSHttpTxn txnp, const char *url, int length) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); @@ -9914,20 +9931,20 @@ remapUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp, URL *(UrlMappingContainer::*mfp)() } // end anonymous namespace -tsapi TSReturnCode -TSRemapFromUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp) +TSReturnCode +tsapi::c::TSRemapFromUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp) { return remapUrlGet(txnp, urlLocp, &UrlMappingContainer::getFromURL); } -tsapi TSReturnCode -TSRemapToUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp) +TSReturnCode +tsapi::c::TSRemapToUrlGet(TSHttpTxn txnp, TSMLoc *urlLocp) { return remapUrlGet(txnp, urlLocp, &UrlMappingContainer::getToURL); } -tsapi void * -TSRemapDLHandleGet(TSRemapPluginInfo plugin_info) +void * +tsapi::c::TSRemapDLHandleGet(TSRemapPluginInfo plugin_info) { sdk_assert(sdk_sanity_check_null_ptr(plugin_info)); RemapPluginInfo *info = reinterpret_cast(plugin_info); @@ -9936,13 +9953,13 @@ TSRemapDLHandleGet(TSRemapPluginInfo plugin_info) } TSReturnCode -TSHostnameIsSelf(const char *hostname, size_t hostname_len) +tsapi::c::TSHostnameIsSelf(const char *hostname, size_t hostname_len) { return Machine::instance()->is_self(std::string_view{hostname, hostname_len}) ? TS_SUCCESS : TS_ERROR; } TSReturnCode -TSHostStatusGet(const char *hostname, const size_t hostname_len, TSHostStatus *status, unsigned int *reason) +tsapi::c::TSHostStatusGet(const char *hostname, const size_t hostname_len, TSHostStatus *status, unsigned int *reason) { HostStatRec *hst = HostStatus::instance().getHostStatus(std::string_view(hostname, hostname_len)); if (hst == nullptr) { @@ -9958,8 +9975,8 @@ TSHostStatusGet(const char *hostname, const size_t hostname_len, TSHostStatus *s } void -TSHostStatusSet(const char *hostname, const size_t hostname_len, TSHostStatus status, const unsigned int down_time, - const unsigned int reason) +tsapi::c::TSHostStatusSet(const char *hostname, const size_t hostname_len, TSHostStatus status, const unsigned int down_time, + const unsigned int reason) { HostStatus::instance().setHostStatus(std::string_view(hostname, hostname_len), status, down_time, reason); } @@ -9970,8 +9987,8 @@ TSHostStatusSet(const char *hostname, const size_t hostname_len, TSHostStatus st // // The passed *action must not be null, and is copied and may be destroyed after this call returns. // Callers must maintain owernship of action.hostname, and its lifetime must exceed the transaction. -tsapi void -TSHttpTxnResponseActionSet(TSHttpTxn txnp, TSResponseAction *action) +void +tsapi::c::TSHttpTxnResponseActionSet(TSHttpTxn txnp, TSResponseAction *action) { HttpSM *sm = reinterpret_cast(txnp); HttpTransact::State *s = &(sm->t_state); @@ -9986,8 +10003,8 @@ TSHttpTxnResponseActionSet(TSHttpTxn txnp, TSResponseAction *action) // // The action members will always be zero, if no plugin has called TSHttpTxnResponseActionSet. // -tsapi void -TSHttpTxnResponseActionGet(TSHttpTxn txnp, TSResponseAction *action) +void +tsapi::c::TSHttpTxnResponseActionGet(TSHttpTxn txnp, TSResponseAction *action) { HttpSM *sm = reinterpret_cast(txnp); HttpTransact::State *s = &(sm->t_state); @@ -9998,16 +10015,16 @@ TSHttpTxnResponseActionGet(TSHttpTxn txnp, TSResponseAction *action) } } -tsapi TSIOBufferReader -TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp) +tsapi::c::TSIOBufferReader +tsapi::c::TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp) { sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS); HttpSM *sm = (HttpSM *)txnp; return (TSIOBufferReader)sm->get_postbuf_clone_reader(); } -tsapi TSDbgCtl const * -TSDbgCtlCreate(char const *tag) +tsapi::c::TSDbgCtl const * +tsapi::c::TSDbgCtlCreate(char const *tag) { sdk_assert(tag != nullptr); sdk_assert(*tag != '\0'); @@ -10015,8 +10032,8 @@ TSDbgCtlCreate(char const *tag) return DbgCtl::_new_reference(tag); } -tsapi void -TSDbgCtlDestroy(TSDbgCtl const *dbg_ctl) +void +tsapi::c::TSDbgCtlDestroy(TSDbgCtl const *dbg_ctl) { sdk_assert(dbg_ctl != nullptr); @@ -10031,8 +10048,8 @@ extern ts::Rv g_rpcHandlerResponseData; extern bool g_rpcHandlerProcessingCompleted; } // namespace rpc -tsapi TSRPCProviderHandle -TSRPCRegister(const char *provider_name, size_t provider_len, const char *yaml_version, size_t yamlcpp_lib_len) +tsapi::c::TSRPCProviderHandle +tsapi::c::TSRPCRegister(const char *provider_name, size_t provider_len, const char *yaml_version, size_t yamlcpp_lib_len) { sdk_assert(sdk_sanity_check_null_ptr(yaml_version) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr(provider_name) == TS_SUCCESS); @@ -10050,9 +10067,9 @@ TSRPCRegister(const char *provider_name, size_t provider_len, const char *yaml_v return (TSRPCProviderHandle)info; } -tsapi TSReturnCode -TSRPCRegisterMethodHandler(const char *name, size_t name_len, TSRPCMethodCb callback, TSRPCProviderHandle info, - const TSRPCHandlerOptions *opt) +TSReturnCode +tsapi::c::TSRPCRegisterMethodHandler(const char *name, size_t name_len, TSRPCMethodCb callback, TSRPCProviderHandle info, + const TSRPCHandlerOptions *opt) { sdk_assert(sdk_sanity_check_rpc_handler_options(opt) == TS_SUCCESS); @@ -10068,9 +10085,9 @@ TSRPCRegisterMethodHandler(const char *name, size_t name_len, TSRPCMethodCb call return TS_SUCCESS; } -tsapi TSReturnCode -TSRPCRegisterNotificationHandler(const char *name, size_t name_len, TSRPCNotificationCb callback, TSRPCProviderHandle info, - const TSRPCHandlerOptions *opt) +TSReturnCode +tsapi::c::TSRPCRegisterNotificationHandler(const char *name, size_t name_len, TSRPCNotificationCb callback, + TSRPCProviderHandle info, const TSRPCHandlerOptions *opt) { sdk_assert(sdk_sanity_check_rpc_handler_options(opt) == TS_SUCCESS); @@ -10082,8 +10099,8 @@ TSRPCRegisterNotificationHandler(const char *name, size_t name_len, TSRPCNotific return TS_SUCCESS; } -tsapi TSReturnCode -TSRPCHandlerDone(TSYaml resp) +TSReturnCode +tsapi::c::TSRPCHandlerDone(TSYaml resp) { Debug("rpc.api", ">> Handler seems to be done"); std::lock_guard lock(rpc::g_rpcHandlingMutex); @@ -10095,8 +10112,8 @@ TSRPCHandlerDone(TSYaml resp) return TS_SUCCESS; } -tsapi TSReturnCode -TSRPCHandlerError(int ec, const char *descr, size_t descr_len) +TSReturnCode +tsapi::c::TSRPCHandlerError(int ec, const char *descr, size_t descr_len) { Debug("rpc.api", ">> Handler seems to be done with an error"); std::lock_guard lock(rpc::g_rpcHandlingMutex); @@ -10108,7 +10125,7 @@ TSRPCHandlerError(int ec, const char *descr, size_t descr_len) } TSReturnCode -TSRecYAMLConfigParse(TSYaml node, TSYAMLRecNodeHandler handler, void *data) +tsapi::c::TSRecYAMLConfigParse(TSYaml node, TSYAMLRecNodeHandler handler, void *data) { swoc::Errata err; try { diff --git a/src/traffic_server/InkIOCoreAPI.cc b/src/traffic_server/InkIOCoreAPI.cc index f29cbadc35a..cd5ca92098e 100644 --- a/src/traffic_server/InkIOCoreAPI.cc +++ b/src/traffic_server/InkIOCoreAPI.cc @@ -44,7 +44,7 @@ #endif TSReturnCode -sdk_sanity_check_mutex(TSMutex mutex) +tsapi::c::sdk_sanity_check_mutex(TSMutex mutex) { if (mutex == nullptr) { return TS_ERROR; @@ -63,7 +63,7 @@ sdk_sanity_check_mutex(TSMutex mutex) } TSReturnCode -sdk_sanity_check_hostlookup_structure(TSHostLookupResult data) +tsapi::c::sdk_sanity_check_hostlookup_structure(TSHostLookupResult data) { if (data == nullptr) { return TS_ERROR; @@ -73,7 +73,7 @@ sdk_sanity_check_hostlookup_structure(TSHostLookupResult data) } TSReturnCode -sdk_sanity_check_iocore_structure(void *data) +tsapi::c::sdk_sanity_check_iocore_structure(void *data) { if (data == nullptr) { return TS_ERROR; @@ -83,8 +83,8 @@ sdk_sanity_check_iocore_structure(void *data) } // From InkAPI.cc -TSReturnCode sdk_sanity_check_continuation(TSCont cont); -TSReturnCode sdk_sanity_check_null_ptr(void const *ptr); +tsapi::c::TSReturnCode sdk_sanity_check_continuation(TSCont cont); +tsapi::c::TSReturnCode sdk_sanity_check_null_ptr(void const *ptr); //////////////////////////////////////////////////////////////////// // @@ -133,10 +133,10 @@ ink_thread_trampoline(void *data) } /* - * INKqa12653. Return TSThread or NULL if error + * INKqa12653. Return TSThread or null if error */ TSThread -TSThreadCreate(TSThreadFunc func, void *data) +tsapi::c::TSThreadCreate(TSThreadFunc func, void *data) { INKThreadInternal *thread; ink_thread tid = 0; @@ -164,7 +164,7 @@ TSThreadCreate(TSThreadFunc func, void *data) // needs to delete the thread, it must first wait for the thread to // complete. void -TSThreadWait(TSThread thread) +tsapi::c::TSThreadWait(TSThread thread) { sdk_assert(sdk_sanity_check_iocore_structure(thread) == TS_SUCCESS); INKThreadInternal *ithread = reinterpret_cast(thread); @@ -179,7 +179,7 @@ TSThreadWait(TSThread thread) } TSThread -TSThreadInit() +tsapi::c::TSThreadInit() { INKThreadInternal *thread; @@ -197,7 +197,7 @@ TSThreadInit() } void -TSThreadDestroy(TSThread thread) +tsapi::c::TSThreadDestroy(TSThread thread) { sdk_assert(sdk_sanity_check_iocore_structure(thread) == TS_SUCCESS); @@ -217,14 +217,14 @@ TSThreadDestroy(TSThread thread) } TSThread -TSThreadSelf(void) +tsapi::c::TSThreadSelf(void) { TSThread ithread = (TSThread)this_ethread(); return ithread; } TSEventThread -TSEventThreadSelf(void) +tsapi::c::TSEventThreadSelf(void) { return reinterpret_cast(this_event_thread()); } @@ -239,7 +239,7 @@ TSEventThreadSelf(void) // //////////////////////////////////////////////////////////////////// TSMutex -TSMutexCreate() +tsapi::c::TSMutexCreate() { ProxyMutex *mutexp = new_ProxyMutex(); @@ -250,7 +250,7 @@ TSMutexCreate() } void -TSMutexDestroy(TSMutex m) +tsapi::c::TSMutexDestroy(TSMutex m) { sdk_assert(sdk_sanity_check_mutex(m) == TS_SUCCESS); ProxyMutex *mutexp = reinterpret_cast(m); @@ -266,7 +266,7 @@ TSMutexDestroy(TSMutex m) of the mutex pointer, plugins may want more control of the creation and destroy of the mutex.*/ TSMutex -TSMutexCreateInternal() +tsapi::c::TSMutexCreateInternal() { ProxyMutex *new_mutex = new_ProxyMutex(); @@ -278,7 +278,7 @@ TSMutexCreateInternal() } int -TSMutexCheck(TSMutex mutex) +tsapi::c::TSMutexCheck(TSMutex mutex) { ProxyMutex *mutexp = (ProxyMutex *)mutex; @@ -292,7 +292,7 @@ TSMutexCheck(TSMutex mutex) } void -TSMutexLock(TSMutex mutexp) +tsapi::c::TSMutexLock(TSMutex mutexp) { sdk_assert(sdk_sanity_check_mutex(mutexp) == TS_SUCCESS); ProxyMutex *proxy_mutex = reinterpret_cast(mutexp); @@ -300,7 +300,7 @@ TSMutexLock(TSMutex mutexp) } TSReturnCode -TSMutexLockTry(TSMutex mutexp) +tsapi::c::TSMutexLockTry(TSMutex mutexp) { sdk_assert(sdk_sanity_check_mutex(mutexp) == TS_SUCCESS); ProxyMutex *proxy_mutex = reinterpret_cast(mutexp); @@ -308,7 +308,7 @@ TSMutexLockTry(TSMutex mutexp) } void -TSMutexUnlock(TSMutex mutexp) +tsapi::c::TSMutexUnlock(TSMutex mutexp) { sdk_assert(sdk_sanity_check_mutex(mutexp) == TS_SUCCESS); ProxyMutex *proxy_mutex(reinterpret_cast(mutexp)); @@ -318,7 +318,7 @@ TSMutexUnlock(TSMutex mutexp) /* VIOs */ void -TSVIOReenable(TSVIO viop) +tsapi::c::TSVIOReenable(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -327,7 +327,7 @@ TSVIOReenable(TSVIO viop) } TSIOBuffer -TSVIOBufferGet(TSVIO viop) +tsapi::c::TSVIOBufferGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -336,7 +336,7 @@ TSVIOBufferGet(TSVIO viop) } TSIOBufferReader -TSVIOReaderGet(TSVIO viop) +tsapi::c::TSVIOReaderGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -345,7 +345,7 @@ TSVIOReaderGet(TSVIO viop) } int64_t -TSVIONBytesGet(TSVIO viop) +tsapi::c::TSVIONBytesGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -354,7 +354,7 @@ TSVIONBytesGet(TSVIO viop) } void -TSVIONBytesSet(TSVIO viop, int64_t nbytes) +tsapi::c::TSVIONBytesSet(TSVIO viop, int64_t nbytes) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); sdk_assert(nbytes >= 0); @@ -364,7 +364,7 @@ TSVIONBytesSet(TSVIO viop, int64_t nbytes) } int64_t -TSVIONDoneGet(TSVIO viop) +tsapi::c::TSVIONDoneGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -373,7 +373,7 @@ TSVIONDoneGet(TSVIO viop) } void -TSVIONDoneSet(TSVIO viop, int64_t ndone) +tsapi::c::TSVIONDoneSet(TSVIO viop, int64_t ndone) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); sdk_assert(ndone >= 0); @@ -383,7 +383,7 @@ TSVIONDoneSet(TSVIO viop, int64_t ndone) } int64_t -TSVIONTodoGet(TSVIO viop) +tsapi::c::TSVIONTodoGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -392,7 +392,7 @@ TSVIONTodoGet(TSVIO viop) } TSCont -TSVIOContGet(TSVIO viop) +tsapi::c::TSVIOContGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -401,7 +401,7 @@ TSVIOContGet(TSVIO viop) } TSVConn -TSVIOVConnGet(TSVIO viop) +tsapi::c::TSVIOVConnGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -410,7 +410,7 @@ TSVIOVConnGet(TSVIO viop) } TSMutex -TSVIOMutexGet(TSVIO viop) +tsapi::c::TSVIOMutexGet(TSVIO viop) { sdk_assert(sdk_sanity_check_iocore_structure(viop) == TS_SUCCESS); @@ -561,7 +561,7 @@ INKUDPPacketGet(INKUDPacketQueue queuep) /* Buffers */ TSIOBuffer -TSIOBufferCreate() +tsapi::c::TSIOBufferCreate() { MIOBuffer *b = new_empty_MIOBuffer(BUFFER_SIZE_INDEX_32K); @@ -571,7 +571,7 @@ TSIOBufferCreate() } TSIOBuffer -TSIOBufferSizedCreate(TSIOBufferSizeIndex index) +tsapi::c::TSIOBufferSizedCreate(TSIOBufferSizeIndex index) { sdk_assert((index >= TS_IOBUFFER_SIZE_INDEX_128) && (index <= TS_IOBUFFER_SIZE_INDEX_32K)); @@ -583,14 +583,14 @@ TSIOBufferSizedCreate(TSIOBufferSizeIndex index) } void -TSIOBufferDestroy(TSIOBuffer bufp) +tsapi::c::TSIOBufferDestroy(TSIOBuffer bufp) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); free_MIOBuffer((MIOBuffer *)bufp); } TSIOBufferBlock -TSIOBufferStart(TSIOBuffer bufp) +tsapi::c::TSIOBufferStart(TSIOBuffer bufp) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); @@ -609,7 +609,7 @@ TSIOBufferStart(TSIOBuffer bufp) } int64_t -TSIOBufferCopy(TSIOBuffer bufp, TSIOBufferReader readerp, int64_t length, int64_t offset) +tsapi::c::TSIOBufferCopy(TSIOBuffer bufp, TSIOBufferReader readerp, int64_t length, int64_t offset) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); @@ -622,7 +622,7 @@ TSIOBufferCopy(TSIOBuffer bufp, TSIOBufferReader readerp, int64_t length, int64_ } int64_t -TSIOBufferWrite(TSIOBuffer bufp, const void *buf, int64_t length) +tsapi::c::TSIOBufferWrite(TSIOBuffer bufp, const void *buf, int64_t length) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_null_ptr((void *)buf) == TS_SUCCESS); @@ -633,7 +633,7 @@ TSIOBufferWrite(TSIOBuffer bufp, const void *buf, int64_t length) } int64_t -TSIOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length) +tsapi::c::TSIOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length) { auto r{reinterpret_cast(readerp)}; char *limit = r->memcpy(buf, length, 0); @@ -641,7 +641,7 @@ TSIOBufferReaderCopy(TSIOBufferReader readerp, void *buf, int64_t length) } void -TSIOBufferProduce(TSIOBuffer bufp, int64_t nbytes) +tsapi::c::TSIOBufferProduce(TSIOBuffer bufp, int64_t nbytes) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); sdk_assert(nbytes >= 0); @@ -652,7 +652,7 @@ TSIOBufferProduce(TSIOBuffer bufp, int64_t nbytes) // dev API, not exposed void -TSIOBufferBlockDestroy(TSIOBufferBlock blockp) +tsapi::c::TSIOBufferBlockDestroy(TSIOBufferBlock blockp) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); @@ -661,7 +661,7 @@ TSIOBufferBlockDestroy(TSIOBufferBlock blockp) } TSIOBufferBlock -TSIOBufferBlockNext(TSIOBufferBlock blockp) +tsapi::c::TSIOBufferBlockNext(TSIOBufferBlock blockp) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); @@ -671,7 +671,7 @@ TSIOBufferBlockNext(TSIOBufferBlock blockp) // dev API, not exposed int64_t -TSIOBufferBlockDataSizeGet(TSIOBufferBlock blockp) +tsapi::c::TSIOBufferBlockDataSizeGet(TSIOBufferBlock blockp) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); @@ -680,7 +680,7 @@ TSIOBufferBlockDataSizeGet(TSIOBufferBlock blockp) } const char * -TSIOBufferBlockReadStart(TSIOBufferBlock blockp, TSIOBufferReader readerp, int64_t *avail) +tsapi::c::TSIOBufferBlockReadStart(TSIOBufferBlock blockp, TSIOBufferReader readerp, int64_t *avail) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); @@ -708,7 +708,7 @@ TSIOBufferBlockReadStart(TSIOBufferBlock blockp, TSIOBufferReader readerp, int64 } int64_t -TSIOBufferBlockReadAvail(TSIOBufferBlock blockp, TSIOBufferReader readerp) +tsapi::c::TSIOBufferBlockReadAvail(TSIOBufferBlock blockp, TSIOBufferReader readerp) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); @@ -730,7 +730,7 @@ TSIOBufferBlockReadAvail(TSIOBufferBlock blockp, TSIOBufferReader readerp) } char * -TSIOBufferBlockWriteStart(TSIOBufferBlock blockp, int64_t *avail) +tsapi::c::TSIOBufferBlockWriteStart(TSIOBufferBlock blockp, int64_t *avail) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); @@ -743,7 +743,7 @@ TSIOBufferBlockWriteStart(TSIOBufferBlock blockp, int64_t *avail) } int64_t -TSIOBufferBlockWriteAvail(TSIOBufferBlock blockp) +tsapi::c::TSIOBufferBlockWriteAvail(TSIOBufferBlock blockp) { sdk_assert(sdk_sanity_check_iocore_structure(blockp) == TS_SUCCESS); @@ -752,7 +752,7 @@ TSIOBufferBlockWriteAvail(TSIOBufferBlock blockp) } int64_t -TSIOBufferWaterMarkGet(TSIOBuffer bufp) +tsapi::c::TSIOBufferWaterMarkGet(TSIOBuffer bufp) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); @@ -761,7 +761,7 @@ TSIOBufferWaterMarkGet(TSIOBuffer bufp) } void -TSIOBufferWaterMarkSet(TSIOBuffer bufp, int64_t water_mark) +tsapi::c::TSIOBufferWaterMarkSet(TSIOBuffer bufp, int64_t water_mark) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); sdk_assert(water_mark >= 0); @@ -771,7 +771,7 @@ TSIOBufferWaterMarkSet(TSIOBuffer bufp, int64_t water_mark) } TSIOBufferReader -TSIOBufferReaderAlloc(TSIOBuffer bufp) +tsapi::c::TSIOBufferReaderAlloc(TSIOBuffer bufp) { sdk_assert(sdk_sanity_check_iocore_structure(bufp) == TS_SUCCESS); @@ -784,7 +784,7 @@ TSIOBufferReaderAlloc(TSIOBuffer bufp) } TSIOBufferReader -TSIOBufferReaderClone(TSIOBufferReader readerp) +tsapi::c::TSIOBufferReaderClone(TSIOBufferReader readerp) { sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); @@ -793,7 +793,7 @@ TSIOBufferReaderClone(TSIOBufferReader readerp) } void -TSIOBufferReaderFree(TSIOBufferReader readerp) +tsapi::c::TSIOBufferReaderFree(TSIOBufferReader readerp) { sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); @@ -802,7 +802,7 @@ TSIOBufferReaderFree(TSIOBufferReader readerp) } TSIOBufferBlock -TSIOBufferReaderStart(TSIOBufferReader readerp) +tsapi::c::TSIOBufferReaderStart(TSIOBufferReader readerp) { sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); @@ -816,7 +816,7 @@ TSIOBufferReaderStart(TSIOBufferReader readerp) } void -TSIOBufferReaderConsume(TSIOBufferReader readerp, int64_t nbytes) +tsapi::c::TSIOBufferReaderConsume(TSIOBufferReader readerp, int64_t nbytes) { sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); sdk_assert(nbytes >= 0); @@ -826,7 +826,7 @@ TSIOBufferReaderConsume(TSIOBufferReader readerp, int64_t nbytes) } int64_t -TSIOBufferReaderAvail(TSIOBufferReader readerp) +tsapi::c::TSIOBufferReaderAvail(TSIOBufferReader readerp) { sdk_assert(sdk_sanity_check_iocore_structure(readerp) == TS_SUCCESS); diff --git a/src/tscore/Diags.cc b/src/tscore/Diags.cc index 53fc0d7b9de..1e9b7f825dc 100644 --- a/src/tscore/Diags.cc +++ b/src/tscore/Diags.cc @@ -46,9 +46,9 @@ #include "tscore/Regression.h" #include "tscore/Diags.h" -int diags_on_for_plugins = 0; -char ts_new_debug_on_flag_ = 0; -int DiagsConfigState::_enabled[2] = {0, 0}; +int tsapi::c::diags_on_for_plugins = 0; +bool tsapi::c::TSDbgCtlDetail::debug_on = false; +int DiagsConfigState::_enabled[2] = {0, 0}; using namespace swoc::literals; @@ -61,8 +61,8 @@ DiagsConfigState::enabled(DiagsTagType dtt, int new_value) _enabled[dtt] = new_value; if (DiagsTagType_Debug == dtt) { - diags_on_for_plugins = 1 == new_value; - ts_new_debug_on_flag_ = (1 & new_value) != 0; + diags_on_for_plugins = 1 == new_value; + TSDbgCtlDetail::debug_on = (1 & new_value) != 0; } } @@ -227,7 +227,7 @@ Diags::~Diags() // parentheses if its value is not nullptr. It takes a , // which is converted to a prefix string. // print_va takes an optional source location structure pointer , -// which can be nullptr. If is not NULL, the source code location +// which can be nullptr. If is not null, the source code location // is converted to a string, and printed between angle brackets. // Finally, it takes a printf format string , and a // va_list list of varargs.