You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by bc...@apache.org on 2019/01/22 23:26:12 UTC

[trafficserver] branch master updated: The cookie_remap plugin.

This is an automated email from the ASF dual-hosted git repository.

bcall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/trafficserver.git


The following commit(s) were added to refs/heads/master by this push:
     new 408bc6b  The cookie_remap plugin.
408bc6b is described below

commit 408bc6be7ba1470fc3a887a99c90adf861bef4ee
Author: Pushkar Pradhan <pp...@oath.com>
AuthorDate: Wed Jan 2 19:10:07 2019 -0800

    The cookie_remap plugin.
---
 doc/admin-guide/plugins/cookie_remap.en.rst        |  462 ++++++++
 plugins/Makefile.am                                |    1 +
 plugins/experimental/cookie_remap/Makefile.inc     |   39 +
 plugins/experimental/cookie_remap/README           |    9 +
 plugins/experimental/cookie_remap/cookie_remap.cc  | 1151 ++++++++++++++++++++
 plugins/experimental/cookie_remap/cookiejar.cc     |  255 +++++
 plugins/experimental/cookie_remap/cookiejar.h      |   62 ++
 plugins/experimental/cookie_remap/hash.c           |  110 ++
 plugins/experimental/cookie_remap/hash.h           |   54 +
 plugins/experimental/cookie_remap/strip.c          |  282 +++++
 plugins/experimental/cookie_remap/strip.h          |  146 +++
 .../cookie_remap/unit_tests/cookiejar/unit_test.cc |  250 +++++
 .../pluginTest/cookie_remap/bucketcookie.test.py   |  104 ++
 .../cookie_remap/collapseslashes.test.py           |   71 ++
 .../cookie_remap/configs/bucketconfig.txt          |    9 +
 .../cookie_remap/configs/collapseconfig.txt        |    6 +
 .../cookie_remap/configs/connectorconfig.txt       |   16 +
 .../cookie_remap/configs/existsconfig.txt          |    8 +
 .../cookie_remap/configs/matchconfig.txt           |    8 +
 .../cookie_remap/configs/matchuriconfig.txt        |   17 +
 .../cookie_remap/configs/matrixconfig.txt          |   24 +
 .../cookie_remap/configs/notexistsconfig.txt       |    8 +
 .../cookie_remap/configs/regexconfig.txt           |    9 +
 .../cookie_remap/configs/statusconfig.txt          |   17 +
 .../pluginTest/cookie_remap/configs/subcookie.txt  |   17 +
 .../cookie_remap/configs/substituteconfig.txt      |   21 +
 .../pluginTest/cookie_remap/connector.test.py      |  104 ++
 .../pluginTest/cookie_remap/existscookie.test.py   |  104 ++
 .../cookie_remap/gold/collapseslashes.gold         |    3 +
 .../cookie_remap/gold/doesntexistcookie.gold       |    3 +
 .../pluginTest/cookie_remap/gold/existscookie.gold |    3 +
 .../pluginTest/cookie_remap/gold/matchcookie.gold  |    3 +
 .../pluginTest/cookie_remap/gold/matchcookie2.gold |    3 +
 .../cookie_remap/gold/matchelsestatus.gold         |    3 +
 .../pluginTest/cookie_remap/gold/matchstatus.gold  |    3 +
 .../pluginTest/cookie_remap/gold/matrix.gold       |   15 +
 .../cookie_remap/gold/regexdoesntmatch.gold        |    3 +
 .../pluginTest/cookie_remap/gold/regexmatches.gold |    3 +
 .../pluginTest/cookie_remap/gold/substitute.gold   |    9 +
 .../cookie_remap/gold/wontmatchcookie.gold         |    3 +
 .../cookie_remap/gold/wontmatchcookie2.gold        |    3 +
 .../pluginTest/cookie_remap/matchcookie.test.py    |  104 ++
 .../pluginTest/cookie_remap/matchuri.test.py       |  103 ++
 .../pluginTest/cookie_remap/matrixparams.test.py   |  148 +++
 .../cookie_remap/notexistscookie.test.py           |  103 ++
 .../pluginTest/cookie_remap/regexcookie.test.py    |  104 ++
 .../pluginTest/cookie_remap/setstatus.test.py      |   79 ++
 .../pluginTest/cookie_remap/subcookie.test.py      |  100 ++
 .../pluginTest/cookie_remap/substitute.test.py     |  116 ++
 49 files changed, 4278 insertions(+)

diff --git a/doc/admin-guide/plugins/cookie_remap.en.rst b/doc/admin-guide/plugins/cookie_remap.en.rst
new file mode 100644
index 0000000..f79074b
--- /dev/null
+++ b/doc/admin-guide/plugins/cookie_remap.en.rst
@@ -0,0 +1,462 @@
+.. 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.defs
+
+.. _admin-plugins-cookie_remap:
+
+============================================================
+Cookie Based Routing Inside TrafficServer Using cookie_remap
+============================================================
+
+----
+
+
+* `Cookie Based Routing Inside TrafficServer Using cookie_remap <#cookie-based-routing-inside-trafficserver-using-cookie_remap>`_
+
+  * `Features <#features>`_
+  * `Limitations <#limitations>`_
+  * `Setup <#setup>`_
+  * `Operations <#operations>`_
+
+    * `Comments <#comments>`_
+    * `cookie: X|X.Y <#cookie-xxy>`_
+    * `operation: exists|not exists|string|regex|bucket <#operation-existsnot-existsstringregexbucket>`_
+    * `match: str <#match-str>`_
+    * `regex: str <#regex-str>`_
+    * `bucket|hash: X/Y <#buckethash-xy>`_
+    * `sendto|url: url <#sendtourl-url>`_
+    * `status: HTTP status-code <#status-http-status-code>`_
+    * `else: url [optional] <#else-url-optional>`_
+    * `connector: and <#connector-and>`_
+
+  * `Reserved path expressions <#reserved-path-expressions>`_
+
+    * `$cr_request_url <#cr_request_url-v-15>`_
+    * `$cr_urlencode() <#cr_urlencode-v-15>`_
+    * `$path <#path>`_
+    * `$unmatched_path <#unmatched_path>`_
+
+  * `An example configuration file <#an-example-configuration-file>`_
+  * `Debugging things <#debugging-things>`_
+
+    * `Initial output <#initial-output>`_
+
+This remap plugin makes decisions about where to send your request based on properties present (or absent) within the HTTP Cookie header.  It can also make decisions based on your uri (url path + query.)
+
+Features
+--------
+
+----
+
+
+* Also supports sub-level cookies
+
+  * K indicates top-level cookie "K"
+  * K.l indicates top-level cookie "K", subfield "l"
+
+* Cookie exists / Cookie doesn't exist
+* Cookie or uri matches string
+* Cookie or uri matches regex (with match replacement in the sendto like `http://foo.com/$1/$2 <http://foo.com/$1/$2>`_\ )
+* Cookie falls into a hash/bucket range
+* Can url encode dynamic data
+
+Limitations
+-----------
+
+----
+
+
+* Does not support `plugin chaining <http://trafficserver.apache.org/docs/v2/admin/files.htm#remap.config>`_.
+
+Setup
+-----
+
+----
+
+The plugin is specified in remap.config using a syntax similar to:
+
+
+.. raw:: html
+
+   <pre>
+   map http://foo.com http://bar.com @plugin=/usr/bin/trafficserver/libexec64/cookie_remap.so @pparam=/home/trafficserver/conf/cookie_remap/cookie_remap.txt
+   </pre>
+
+
+Operations
+----------
+
+----
+
+All operations are specified in a YAML configuration file you pass as @pparam on the plugin configuration line. YAML is very simple syntax. See the example configuration files below.
+
+Each operation results in a sendto action. That means that, if matched, cookie_remap forwards the request to the given ``sendto`` url. It can be proxied or redirected. An ``else`` sendto can be specified, in which case a failure to match will forward the request also. Once a sendto is invoked:
+
+
+* cookie_remap will not process any more "operations" from the configuration
+* the default destination specified in the remap.config file will not be used; it will be replaced by the ``sendto``
+
+Each ``operation`` can have multiple "sub-operations", connected with an conjunction operator.  Currently, only the ``and`` operator is supported. So, you can say, "if cookie exists, ``and`` uri is ``x``\ , then redirect."
+
+Comments
+^^^^^^^^
+
+----
+
+Comments are allowed in the configuration file if they begin with '#'
+
+cookie: X|X.Y
+^^^^^^^^^^^^^
+
+----
+
+This sub-operation is testing against the X cookie or X.Y cookie where X.Y denotes the X cookie, sub cookie Y
+e.g
+
+
+.. raw:: html
+
+   <pre>
+   A=ACOOKIE;B=data&f=fsub&z=zsub;
+   A will operate on ACOOKIE
+   B will operate on data&f=fsub&z=zsub
+   B.f will operate on fsub
+   </pre>
+
+
+operation: exists|not exists|string|regex|bucket
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+----
+
+This keyword actually denotes a "suboperation" - it can be specified multiple times, connected with ``and``\ , and send the user to a given destination.
+
+
+* exists: Test for the existence of a cookie
+* not exists: Test for the non-existence of a cookie
+* string: string match
+* regex: regex matching with $1 - $9 replaced in ``sendto``
+* bucket: Hash the cookie and check if it falls in a bucket
+
+The ``cookie`` operator must be specified in the YAML file just before the suboperation that will apply to the cookie.
+
+The ``string``, ``regex`` and ``bucket`` operate on the specified cookie, or if no cookie is specified, they will operate on the uri of the request.
+
+match: str
+^^^^^^^^^^
+
+----
+
+Match the cookie data to str.  If no cookie is specified, match to the request uri.
+
+regex: str
+^^^^^^^^^^
+
+----
+
+Sets the regex to str. Matching is enabled with $1-$9 (replaced in sendto).  Note that only the final regex match in an operation will be used to populate the substitutions $1-$9.  If no cookie is specified, match to the request uri.
+
+bucket|hash: X/Y
+^^^^^^^^^^^^^^^^
+
+----
+
+Hashes (bucketizes) the data in Y buckets. If you fall into the first X of them, this suboperation passes. If no cookie is specified, match to the request uri.
+
+
+.. raw:: html
+
+   <pre>
+   bucket: 1/100
+   will effectively bucketize 1% of your users
+   </pre>
+
+
+sendto|url: url
+^^^^^^^^^^^^^^^
+
+----
+
+if the sub-operation(s) all match, send to url
+
+status: HTTP status-code
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+----
+
+if the sub-operation(s) all match, set the status code (e.g. set it to 302). In the case of a redirect, the sendto URL becomes the redirect URL.
+
+else: url [optional]
+^^^^^^^^^^^^^^^^^^^^
+
+----
+
+If one of the sub-operations fails, send to url. This is optional. If there is no 'else', we will continue to process operations until either one succeeds, there is an else in one of the operations or we fall through to the default mapping from remap.config
+
+connector: and
+^^^^^^^^^^^^^^
+
+----
+
+'and' is the only supported connector
+
+Reserved path expressions
+-------------------------
+
+----
+
+The following expressions can be used in either the sendto **or** ``else`` URLs, and will be expanded.
+
+$cr_request_url
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+----
+
+Replaced with the full original url.
+
+Therefore, a rule like:
+
+
+.. raw:: html
+
+   <pre>
+   op:
+     cookie: K
+     operation: exists
+     sendto: http://foo.com/?.done=$cr_request_url
+   </pre>
+
+
+and a request that matches, e.g.
+
+
+.. raw:: html
+
+   <pre>
+   http://bar.com/hello?fruit=bananas
+   </pre>
+
+
+will become
+
+
+.. raw:: html
+
+   <pre>
+   http://foo.com/?.done=http://bar.com/hello?fruit=bananas
+   </pre>
+
+
+$cr_urlencode()
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+----
+
+Replaced with a urlencoded version of its argument.  The url argument is aggressively encoded such that all non-alphanumeric characters are converted to % hex notation.  The simple algorithm could probably be refined in the future to be less aggressive (encode fewer characters.)
+
+Therefore, a rule like:
+
+
+.. raw:: html
+
+   <pre>
+   op:
+     cookie: B
+     operation: exists
+     sendto: http://foo.com/?.done=$cr_urlencode($cr_request_url)
+   </pre>
+
+
+and a request that matches, e.g.
+
+
+.. raw:: html
+
+   <pre>
+   http://bar.com/hello?fruit=bananas
+   </pre>
+
+
+will become
+
+
+.. raw:: html
+
+   <pre>
+   http://foo.com/?.done=http%3A%2F%2Fbar%2Ecom@2Fhello%3Ffruit%3Dbananas
+   </pre>
+
+
+$path
+^^^^^
+
+----
+
+$path can be used to replace in either the sendto **or** else URLs the original request path. Therefore a rule like:
+
+
+.. raw:: html
+
+   <pre>
+   op:
+     cookie: K
+     operation: exists
+     sendto: http://foo.com/$path/x/y/z
+   </pre>
+
+
+and a request like `http://finance.yahoo.com/photos/what/ever/ <http://foo.com/photos/what/ever/>`_ that matches the rule
+
+
+.. raw:: html
+
+   <pre>
+   map http://finance.yahoo.com/photos/ http://newfinance.yahoo.com/1k.html @plugin=cookie_remap.so @pparam=foo.txt
+   </pre>
+
+
+will become `http://foo.com/photos/what/ever/x/y/z <http://foo.com/photos/what/ever/x/y/z>`_
+
+$unmatched_path
+^^^^^^^^^^^^^^^
+
+----
+
+$unmatched_path can be used to gather the URL arguments **beyond** what was matched by the remap rule. Therefore a rule like:
+
+
+.. raw:: html
+
+   <pre>
+   op:
+     cookie: K
+     operation: exists
+     sendto: http://foo.com/$unmatched_path/x/y/z
+   </pre>
+
+
+and a request like `http://finance.yahoo.com/photos/what/ever/ <http://foo.com/photos/what/ever/>`_ that matches the rule
+
+
+.. raw:: html
+
+   <pre>
+   map http://finance.yahoo.com/photos/ http://newfinance.yahoo.com/1k.html @plugin=cookie_remap.so @pparam=foo.txt
+   </pre>
+
+
+will become `http://foo.com/what/ever/matches/x/y/z <http://foo.com/what/ever/matches/x/y/z>`_
+
+An example configuration file
+-----------------------------
+
+----
+
+
+
+* first match "wins" (top down)
+
+
+.. raw:: html
+
+   <pre>
+   #comments
+   #are allowed
+   op:
+     cookie: K
+     operation: exists
+     url: http://www.yahoo.com
+
+   op:
+     cookie: K
+     operation: exists
+     connector: and
+     cookie: K.l
+     operation: not exists
+     sendto: http://www.yahoo.com
+
+   op:
+     cookie: Y
+     operation: bucket
+     bucket: 1/1000
+     connector: and
+     cookie: Y.l
+     operation: regex
+     regex: (.*)
+     connector: and
+     cookie: Y.n
+     operation: string
+     match: foobar
+     sendto: http://cnn.com/$1
+     else: http://yahoo.com
+   </pre>
+
+
+Debugging things
+----------------
+
+----
+
+The easiest way to debug problems with this plugin is to run in the following manner:
+
+
+.. raw:: html
+
+   <pre>
+   bin/traffic_server -T cookie_remap
+   </pre>
+
+
+which will produce output on startup, and for each request. Be aware that this mode of running trafficserver is **extremely** inefficient and should only be used for debugging.
+
+Initial output
+^^^^^^^^^^^^^^
+
+----
+
+Initially, you will notice output describing each operation and how trafficserver interpreted the information from your configuration file:
+
+
+.. raw:: html
+
+   <pre>
+   [Jul  8 13:08:34.183] Server {3187168} DIAG: (cookie_remap) loading cookie remap configuration file from /homes/ebalsa/dev/yts_mods/cookie_remap/example_config.txt
+   [Jul  8 13:08:34.199] Server {3187168} DIAG: (cookie_remap) ++++operation++++
+   [Jul  8 13:08:34.199] Server {3187168} DIAG: (cookie_remap) sending to: http://finance.yahoo.com/2k.html
+   [Jul  8 13:08:34.199] Server {3187168} DIAG: (cookie_remap) if these operations match:
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)     +++subop+++
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)         cookie: B
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)         operation: bucket
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)         bucket: 1/100
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)         taking: 1
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)         out of: 100
+   [Jul  8 13:08:34.200] Server {3187168} DIAG: (cookie_remap)     +++subop+++
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap)         cookie: Y.l
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap)         operation: exists
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap) ++++operation++++
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap) sending to: http://X.existed.com
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap) if these operations match:
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap)     +++subop+++
+   [Jul  8 13:08:34.201] Server {3187168} DIAG: (cookie_remap)         cookie: PH.l
+   [Jul  8 13:08:34.202] Server {3187168} DIAG: (cookie_remap)         operation: exists
+   [Jul  8 13:08:34.202] Server {3187168} DIAG: (cookie_remap) # of ops: 2
+   </pre>
+
+
+each operation is enumerated and is more-or-less human readable from the top-down.  From now on, each request has information spit out to the console with debugging information on how the cookie_remap is treating this request.
+
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index 09e814a..9eee0dd 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -58,6 +58,7 @@ include experimental/buffer_upload/Makefile.inc
 include experimental/cache_range_requests/Makefile.inc
 include experimental/certifier/Makefile.inc
 include experimental/collapsed_forwarding/Makefile.inc
+include experimental/cookie_remap/Makefile.inc
 include experimental/custom_redirect/Makefile.inc
 include experimental/fq_pacing/Makefile.inc
 include experimental/geoip_acl/Makefile.inc
diff --git a/plugins/experimental/cookie_remap/Makefile.inc b/plugins/experimental/cookie_remap/Makefile.inc
new file mode 100644
index 0000000..5b44c4f
--- /dev/null
+++ b/plugins/experimental/cookie_remap/Makefile.inc
@@ -0,0 +1,39 @@
+#  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.
+
+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/strip.c \
+	experimental/cookie_remap/cookiejar.cc
+
+experimental_cookie_remap_cookie_remap_la_LDFLAGS = \
+	$(AM_LDFLAGS)
+
+AM_CPPFLAGS += @YAMLCPP_INCLUDES@
+
+check_PROGRAMS +=  \
+	cookie_remap/test_cookiejar
+
+cookie_remap_test_cookiejar_CPPFLAGS = $(AM_CPPFLAGS) -Iexperimental/cookie_remap -I$(abs_top_srcdir)/tests/include
+cookie_remap_test_cookiejar_SOURCES = \
+    experimental/cookie_remap/unit_tests/cookiejar/unit_test.cc \
+    experimental/cookie_remap/strip.c \
+    experimental/cookie_remap/cookiejar.cc
+
+# vim: ft=make ts=8 sw=8 et:
diff --git a/plugins/experimental/cookie_remap/README b/plugins/experimental/cookie_remap/README
new file mode 100644
index 0000000..d9064f3
--- /dev/null
+++ b/plugins/experimental/cookie_remap/README
@@ -0,0 +1,9 @@
+============================================================
+Cookie Based Routing Inside TrafficServer Using cookie_remap
+============================================================
+
+----
+
+
+For details please read the official documentation in the Admin Guide section.
+
diff --git a/plugins/experimental/cookie_remap/cookie_remap.cc b/plugins/experimental/cookie_remap/cookie_remap.cc
new file mode 100644
index 0000000..b567188
--- /dev/null
+++ b/plugins/experimental/cookie_remap/cookie_remap.cc
@@ -0,0 +1,1151 @@
+/*
+  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.
+*/
+////////////////////////////////////////////////////////////////////////////////
+// cookie_remap: ATS plugin to do (simple) cookie based remap rules
+// To use this plugin, configure a remap.config rule like
+//   map http://foo.com http://bar.com @plugin=.../libexec/cookie_remap.so
+//   @pparam=maps.reg
+
+#include "cookiejar.h"
+#include <ts/ts.h>
+
+#include <pcre.h>
+#include <ts/remap.h>
+#include <yaml-cpp/yaml.h>
+
+#include <algorithm>
+#include <list>
+#include <map>
+#include <set>
+#include <string.h>
+#include <string>
+#include <unistd.h>
+#include <vector>
+#include "hash.h"
+
+using namespace std;
+
+// for bucketizing
+
+#define MY_NAME "cookie_remap"
+const int OVECCOUNT = 30; // We support $1 - $9 only, and this needs to be 3x that
+
+#if TS_VERSION_MAJOR > 7
+#define SETHTTPSTATUS(TXN, STATUS) TSHttpTxnStatusSet((TXN), STATUS)
+#else
+#define SETHTTPSTATUS(TXN, STATUS) TSHttpTxnSetHttpRetStatus((TXN), STATUS)
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// Helpers for memory management (to make sure pcre uses the TS APIs).
+//
+inline void *
+ink_malloc(size_t s)
+{
+  return TSmalloc(s);
+}
+
+inline void
+ink_free(void *s)
+{
+  return TSfree(s);
+}
+///////////////////////////////////////////////////////////////////////////////
+// Class holding one request URL's component, to simplify the code and
+// length calculations (we need all of them).
+//
+struct UrlComponents {
+  UrlComponents() {}
+
+  ~UrlComponents()
+  {
+    if (url != nullptr)
+      TSfree((void *)url);
+  }
+
+  void
+  populate(TSRemapRequestInfo *rri)
+  {
+    scheme    = TSUrlSchemeGet(rri->requestBufp, rri->requestUrl, &scheme_len);
+    host      = TSUrlHostGet(rri->requestBufp, rri->requestUrl, &host_len);
+    tspath    = TSUrlPathGet(rri->requestBufp, rri->requestUrl, &tspath_len);
+    query     = TSUrlHttpQueryGet(rri->requestBufp, rri->requestUrl, &query_len);
+    matrix    = TSUrlHttpParamsGet(rri->requestBufp, rri->requestUrl, &matrix_len);
+    port      = TSUrlPortGet(rri->requestBufp, rri->requestUrl);
+    url       = TSUrlStringGet(rri->requestBufp, rri->requestUrl, &url_len);
+    from_path = TSUrlPathGet(rri->requestBufp, rri->mapFromUrl, &from_path_len);
+
+    // based on RFC2396, matrix params are part of path segments so
+    // we will just
+    // append them to the path
+    path.assign(tspath, tspath_len);
+    if (matrix_len) {
+      path += ';';
+      path.append(matrix, matrix_len);
+    }
+  }
+
+  const char *scheme = nullptr;
+  const char *host   = nullptr;
+  const char *tspath = nullptr;
+  std::string path{};
+  const char *query     = nullptr;
+  const char *matrix    = nullptr;
+  const char *url       = nullptr;
+  const char *from_path = nullptr;
+  int port              = 0;
+
+  int scheme_len    = 0;
+  int host_len      = 0;
+  int tspath_len    = 0;
+  int query_len     = 0;
+  int matrix_len    = 0;
+  int url_len       = 0;
+  int from_path_len = 0;
+};
+
+void
+setup_memory_allocation()
+{
+  pcre_malloc = &ink_malloc;
+  pcre_free   = &ink_free;
+}
+
+enum operation_type { UNKNOWN = -1, EXISTS = 1, NOTEXISTS, REGEXP, STRING, BUCKET };
+
+enum target_type {
+  COOKIE = 1,
+  URI, // URI = PATH + QUERY
+  UNKNOWN_TARGET
+};
+
+/***************************************************************************************
+                                                                Decimal to Hex
+converter
+
+This is a template function which returns a char* array filled with hex digits
+when
+passed to it a number(can work as a decimal to hex conversion)and will work for
+signed
+and unsigned: char, short, and integer(long) type parameters passed to it.
+
+Shortcomings:It won't work for decimal numbers because of presence of
+bitshifting in its algorithm.
+
+Arguments:
+  * _num is the number to convert to hex
+  * hdigits two-byte character array, will be populated with the hex number
+
+***************************************************************************************/
+
+template <class type> // template usage to allow multiple types of parameters
+void
+dec_to_hex(type _num, char *hdigits)
+{
+  const char *hlookup = "0123456789ABCDEF"; // lookup table stores the hex digits into their
+  // corresponding index.
+
+  if (_num < 0)
+    _num *= -1; // and make _num positive to clear(zero) the sign bit
+
+  char mask = 0x000f; // mask will clear(zero) out all the bits except lowest 4
+  // which represent a single hex digit
+
+  hdigits[1] = hlookup[mask & _num];
+  hdigits[0] = hlookup[mask & (_num >> 4)];
+
+  return;
+}
+
+void
+urlencode(std::string &str)
+{
+  size_t pos = 0;
+  std::string replacement;
+  for (; pos < str.length(); pos++) {
+    if (!isalnum(str[pos])) {
+      char dec[2];
+      dec_to_hex(str[pos], dec);
+      std::string replacement = "%" + std::string(dec, 2);
+      str.replace(pos, 1, replacement);
+    }
+  }
+}
+
+//----------------------------------------------------------------------------
+class subop
+{
+public:
+  subop()
+    : cookie(""),
+      operation(""),
+      op_type(UNKNOWN),
+      target(UNKNOWN_TARGET),
+      str_match(""),
+      regex(nullptr),
+      regex_extra(nullptr),
+      regex_ccount(0),
+      bucket(""),
+      how_many(0),
+      out_of(0)
+  {
+    TSDebug(MY_NAME, "subop constructor called");
+  }
+
+  ~subop()
+  {
+    TSDebug(MY_NAME, "subop destructor called");
+    if (regex)
+      pcre_free(regex);
+
+    if (regex_extra)
+      pcre_free(regex_extra);
+  }
+
+  bool
+  empty() const
+  {
+    return (cookie == "" && operation == "" && op_type == UNKNOWN);
+  }
+
+  void
+  setCookieName(const std::string &s)
+  {
+    cookie = s;
+  }
+
+  const std::string &
+  getCookieName() const
+  {
+    return cookie;
+  }
+
+  const std::string &
+  getOperation() const
+  {
+    return operation;
+  }
+
+  operation_type
+  getOpType() const
+  {
+    return op_type;
+  }
+
+  target_type
+  getTargetType() const
+  {
+    return target;
+  }
+
+  void
+  setOperation(const std::string &s)
+  {
+    operation = s;
+
+    if (operation == "string") {
+      op_type = STRING;
+    }
+    if (operation == "regex") {
+      op_type = REGEXP;
+    }
+    if (operation == "exists") {
+      op_type = EXISTS;
+    }
+    if (operation == "not exists") {
+      op_type = NOTEXISTS;
+    }
+    if (operation == "bucket") {
+      op_type = BUCKET;
+    }
+  }
+
+  void
+  setTarget(const std::string &s)
+  {
+    if (s == "uri")
+      target = URI;
+    else
+      target = COOKIE;
+  }
+
+  void
+  setStringMatch(const std::string &s)
+  {
+    op_type   = STRING;
+    str_match = s;
+  }
+
+  const std::string &
+  getStringMatch() const
+  {
+    return str_match;
+  }
+
+  void
+  setBucket(const std::string &s)
+  {
+    int start_pos = s.find("/");
+
+    op_type  = BUCKET;
+    bucket   = s;
+    how_many = atoi(bucket.substr(0, start_pos).c_str());
+    out_of   = atoi(bucket.substr(start_pos + 1).c_str());
+  }
+
+  int
+  bucketGetTaking() const
+  {
+    return how_many;
+  }
+
+  int
+  bucketOutOf() const
+  {
+    return out_of;
+  }
+
+  bool
+  setRegexMatch(const std::string &s)
+  {
+    const char *error_comp  = nullptr;
+    const char *error_study = nullptr;
+    int erroffset;
+
+    op_type      = REGEXP;
+    regex_string = s;
+    regex        = pcre_compile(regex_string.c_str(), 0, &error_comp, &erroffset, nullptr);
+
+    if (regex == nullptr) {
+      return false;
+    }
+    regex_extra = pcre_study(regex, 0, &error_study);
+    if ((regex_extra == nullptr) && (error_study != 0)) {
+      return false;
+    }
+
+    if (pcre_fullinfo(regex, regex_extra, PCRE_INFO_CAPTURECOUNT, &regex_ccount) != 0)
+      return false;
+
+    return true;
+  }
+
+  const std::string &
+  getRegexString() const
+  {
+    return regex_string;
+  }
+
+  int
+  getRegexCcount() const
+  {
+    return regex_ccount;
+  }
+
+  int
+  regexMatch(const char *str, int len, int ovector[]) const
+  {
+    return pcre_exec(regex,       // the compiled pattern
+                     regex_extra, // Extra data from study (maybe)
+                     str,         // the subject std::string
+                     len,         // the length of the subject
+                     0,           // start at offset 0 in the subject
+                     0,           // default options
+                     ovector,     // output vector for substring information
+                     OVECCOUNT);  // number of elements in the output vector
+  };
+
+  void
+  printSubOp() const
+  {
+    TSDebug(MY_NAME, "\t+++subop+++");
+    TSDebug(MY_NAME, "\t\tcookie: %s", cookie.c_str());
+    TSDebug(MY_NAME, "\t\toperation: %s", operation.c_str());
+    if (str_match.size() > 0) {
+      TSDebug(MY_NAME, "\t\tmatching: %s", str_match.c_str());
+    }
+    if (regex) {
+      TSDebug(MY_NAME, "\t\tregex: %s", regex_string.c_str());
+    }
+    if (bucket.size() > 0) {
+      TSDebug(MY_NAME, "\t\tbucket: %s", bucket.c_str());
+      TSDebug(MY_NAME, "\t\ttaking: %d", how_many);
+      TSDebug(MY_NAME, "\t\tout of: %d", out_of);
+    }
+  }
+
+private:
+  std::string cookie;
+  std::string operation;
+  enum operation_type op_type;
+  enum target_type target;
+
+  std::string str_match;
+
+  pcre *regex;
+  pcre_extra *regex_extra;
+  std::string regex_string;
+  int regex_ccount;
+
+  std::string bucket;
+  unsigned int how_many;
+  unsigned int out_of;
+};
+
+typedef std::vector<const subop *> SubOpQueue;
+
+//----------------------------------------------------------------------------
+class op
+{
+public:
+  op() { TSDebug(MY_NAME, "op constructor called"); }
+
+  ~op()
+  {
+    TSDebug(MY_NAME, "op destructor called");
+    for (SubOpQueue::iterator it = subops.begin(); it != subops.end(); ++it) {
+      delete *it;
+    }
+  }
+
+  void
+  addSubOp(const subop *s)
+  {
+    subops.push_back(s);
+  }
+
+  void
+  setSendTo(const std::string &s)
+  {
+    sendto = s;
+  }
+
+  const std::string &
+  getSendTo() const
+  {
+    return sendto;
+  }
+
+  void
+  setElseSendTo(const std::string &s)
+  {
+    else_sendto = s;
+  }
+
+  void
+  setStatus(const std::string &s)
+  {
+    if (else_sendto.size() > 0)
+      else_status = static_cast<TSHttpStatus>(atoi(s.c_str()));
+    else
+      status = static_cast<TSHttpStatus>(atoi(s.c_str()));
+  }
+
+  void
+  setElseStatus(const std::string &s)
+  {
+    else_status = static_cast<TSHttpStatus>(atoi(s.c_str()));
+  }
+
+  void
+  printOp() const
+  {
+    TSDebug(MY_NAME, "++++operation++++");
+    TSDebug(MY_NAME, "sending to: %s", sendto.c_str());
+    TSDebug(MY_NAME, "if these operations match: ");
+
+    for (SubOpQueue::const_iterator it = subops.begin(); it != subops.end(); ++it) {
+      (*it)->printSubOp();
+    }
+    if (else_sendto.size() > 0)
+      TSDebug(MY_NAME, "else: %s", else_sendto.c_str());
+  }
+
+  bool
+  process(CookieJar &jar, std::string &dest, TSHttpStatus &retstat, TSRemapRequestInfo *rri) const
+  {
+    if (sendto == "") {
+      return false; // guessing every operation must have a
+                    // sendto url???
+    }
+
+    int retval        = 1;
+    bool cookie_found = false;
+    std::string c;
+    std::string cookie_data;
+    std::string object_name; // name of the thing being processed,
+                             // cookie, or
+                             // request url
+
+    TSDebug(MY_NAME, "starting to process a new operation");
+
+    for (SubOpQueue::const_iterator it = subops.begin(); it != subops.end(); ++it) {
+      // subop* s = *it;
+      int subop_type     = (*it)->getOpType();
+      target_type target = (*it)->getTargetType();
+
+      c = (*it)->getCookieName();
+      if (c.length()) {
+        TSDebug(MY_NAME, "processing cookie: %s", c.c_str());
+
+        size_t period_pos = c.find_first_of(".");
+
+        if (period_pos == std::string::npos) { // not a sublevel
+                                               // cookie name
+          TSDebug(MY_NAME, "processing non-sublevel cookie");
+
+          cookie_found = jar.get_full(c, cookie_data);
+          TSDebug(MY_NAME, "full cookie: %s", cookie_data.c_str());
+          object_name = c;
+        } else { // is in the format FOO.BAR
+          std::string cookie_main   = c.substr(0, period_pos);
+          std::string cookie_subkey = c.substr(period_pos + 1);
+
+          TSDebug(MY_NAME, "processing sublevel cookie");
+          TSDebug(MY_NAME, "c key: %s", cookie_main.c_str());
+          TSDebug(MY_NAME, "c subkey: %s", cookie_subkey.c_str());
+
+          cookie_found = jar.get_part(cookie_main, cookie_subkey, cookie_data);
+          object_name  = cookie_main + " . " + cookie_subkey;
+        }
+        // invariant:  cookie name is in object_name and
+        // cookie data (if any) is
+        // in cookie_data
+
+        if (cookie_found == false) { // cookie name or sub-key not found
+                                     // inside cookies
+          if (subop_type == NOTEXISTS) {
+            TSDebug(MY_NAME,
+                    "cookie %s was not "
+                    "found (and we wanted "
+                    "that)",
+                    object_name.c_str());
+            continue; // we can short
+                      // circuit more
+                      // testing
+          }
+          TSDebug(MY_NAME, "cookie %s was not found", object_name.c_str());
+          retval &= 0;
+          break;
+        } else {
+          // cookie exists
+          if (subop_type == NOTEXISTS) { // we found the cookie
+                                         // but are asking
+            // for non existence
+            TSDebug(MY_NAME,
+                    "cookie %s was found, "
+                    "but operation "
+                    "requires "
+                    "non-existence",
+                    object_name.c_str());
+            retval &= 0;
+            break;
+          }
+
+          if (subop_type == EXISTS) {
+            TSDebug(MY_NAME, "cookie %s was found", object_name.c_str()); // got what
+                                                                          // we were
+                                                                          // looking
+                                                                          // for
+            continue;                                                     // we can short
+                                                                          // circuit more
+                                                                          // testing
+          }
+        } // handled EXISTS / NOTEXISTS subops
+
+        TSDebug(MY_NAME, "processing cookie data: \"%s\"", cookie_data.c_str());
+      } else
+        target = URI;
+
+      // INVARIANT: we now have the data from the cookie (if
+      // any) inside
+      // cookie_data and we are here because we need
+      // to continue processing this suboperation in some way
+
+      if (!rri) { // too dangerous to continue without the
+                  // rri; hopefully that
+        // never happens
+        TSDebug(MY_NAME, "request info structure is "
+                         "empty; can't continue "
+                         "processing this subop");
+        retval &= 0;
+        break;
+      }
+
+      // If the user has specified a cookie in his
+      // suboperation, use the cookie
+      // data for matching;
+      //  otherwise, use the request uri (path + query)
+      std::string request_uri; // only set the value if we
+                               // need it; we might
+      // match the cookie data instead
+      const std::string &string_to_match(target == URI ? request_uri : cookie_data);
+      if (target == URI) {
+        UrlComponents req_url;
+        req_url.populate(rri);
+
+        TSDebug(MY_NAME, "process req_url.path = %s", req_url.path.c_str());
+        request_uri = req_url.path;
+        if (request_uri.length() && request_uri[0] != '/')
+          request_uri.insert(0, 1, '/');
+        if (req_url.query_len > 0) {
+          request_uri += '?';
+          request_uri += std::string(req_url.query, req_url.query_len);
+        }
+        object_name = "request uri";
+      }
+
+      // invariant:  we've decided at this point what string
+      // we'll match, if we
+      // do matching
+
+      // OPERATION::string matching
+      if (subop_type == STRING) {
+        if (string_to_match == (*it)->getStringMatch()) {
+          TSDebug(MY_NAME, "string match succeeded");
+          continue;
+        } else {
+          TSDebug(MY_NAME, "string match failed");
+          retval &= 0;
+          break;
+        }
+      }
+
+      // OPERATION::regex matching
+      if (subop_type == REGEXP) {
+        int ovector[OVECCOUNT];
+        int ret = (*it)->regexMatch(string_to_match.c_str(), string_to_match.length(), ovector);
+
+        if (ret >= 0) {
+          std::string::size_type pos  = sendto.find('$');
+          std::string::size_type ppos = 0;
+
+          dest.erase();                    // we only reset dest if
+                                           // there is a successful
+                                           // regex
+                                           // match
+          dest.reserve(sendto.size() * 2); // Wild guess at this
+                                           // time ... is
+          // sucks we can't precalculate this
+          // like regex_remap.
+
+          TSDebug(MY_NAME, "found %d matches", ret);
+          TSDebug(MY_NAME,
+                  "successful regex "
+                  "match of: %s with %s "
+                  "rewriting string: %s",
+                  string_to_match.c_str(), (*it)->getRegexString().c_str(), sendto.c_str());
+
+          // replace the $(1-9) in the sendto url
+          // as necessary
+          const size_t LAST_IDX_TO_SEARCH(sendto.length() - 2); // otherwise the below loop can
+                                                                // access "sendto" out of range
+          while (pos <= LAST_IDX_TO_SEARCH) {
+            if (isdigit(sendto[pos + 1])) {
+              int ix = sendto[pos + 1] - '0';
+
+              if (ix <= (*it)->getRegexCcount()) { // Just skip an illegal regex group
+                dest += sendto.substr(ppos, pos - ppos);
+                dest += string_to_match.substr(ovector[ix * 2], ovector[ix * 2 + 1] - ovector[ix * 2]);
+                ppos = pos + 2;
+              } else {
+                TSDebug(MY_NAME,
+                        "bad "
+                        "rewriting "
+                        "string, "
+                        "for group "
+                        "%d: %s",
+                        ix, sendto.c_str());
+              }
+            }
+            pos = sendto.find('$', pos + 1);
+          }
+          dest += sendto.substr(ppos);
+          continue; // next subop, please
+        } else {
+          TSDebug(MY_NAME,
+                  "could not match "
+                  "regular expression "
+                  "%s to %s",
+                  (*it)->getRegexString().c_str(), string_to_match.c_str());
+          retval &= 0;
+          break;
+        }
+      }
+
+      // OPERATION::bucket ranges
+      if (subop_type == BUCKET) {
+        unsigned int taking = (*it)->bucketGetTaking();
+        unsigned int out_of = (*it)->bucketOutOf();
+
+        uint32_t hash;
+
+        if (taking == 0 || out_of == 0) {
+          TSDebug(MY_NAME,
+                  "taking %d out of %d "
+                  "makes no sense?!",
+                  taking, out_of);
+          retval &= 0;
+          break;
+        }
+
+        hash = hash_fnv32_buckets(cookie_data.c_str(), cookie_data.size(), out_of);
+        TSDebug(MY_NAME,
+                "we hashed this to bucket: %u "
+                "taking: %u out of: %u",
+                hash, taking, out_of);
+
+        if (hash < taking) {
+          TSDebug(MY_NAME, "we hashed in the range, yay!");
+          continue; // we hashed in the range
+        } else {
+          TSDebug(MY_NAME, "we didnt hash in the "
+                           "range requested, so "
+                           "sad");
+          retval &= 0;
+          break;
+        }
+      }
+    }
+
+    if (retval == 1) {
+      if (dest.size() == 0) // Unless already set by one of
+                            // the operators (e.g. regex)
+        dest = sendto;
+      if (status > 0) {
+        retstat = status;
+      }
+      return true;
+    } else if (else_sendto.size() > 0 && retval == 0) {
+      dest = else_sendto;
+      if (else_status > 0) {
+        retstat = else_status;
+      }
+      return true;
+    } else {
+      dest = "";
+      return false;
+    }
+  }
+
+private:
+  SubOpQueue subops{};
+  std::string sendto{""};
+  std::string else_sendto{""};
+  TSHttpStatus status      = TS_HTTP_STATUS_NONE;
+  TSHttpStatus else_status = TS_HTTP_STATUS_NONE;
+};
+
+typedef std::pair<std::string, std::string> StringPair;
+typedef std::vector<StringPair> OpMap;
+
+//----------------------------------------------------------------------------
+static bool
+build_op(op &o, OpMap const &q)
+{
+  StringPair m;
+
+  subop *sub = new subop();
+
+  // loop through the array of key->value pairs
+  for (auto const &pr : q) {
+    std::string const &key = pr.first;
+    std::string const &val = pr.second;
+
+    if (key == "cookie") {
+      if (!sub->empty()) {
+        TSDebug(MY_NAME, "ERROR: you need to define a connector");
+        goto error;
+      }
+      sub->setCookieName(val);
+    }
+
+    if (key == "sendto" || key == "url") {
+      o.setSendTo(val);
+    }
+
+    if (key == "else") {
+      o.setElseSendTo(val);
+    }
+
+    if (key == "status") {
+      o.setStatus(val);
+    }
+
+    if (key == "operation") {
+      sub->setOperation(val);
+    }
+
+    if (key == "target") {
+      sub->setTarget(val);
+    }
+
+    if (key == "match") {
+      sub->setStringMatch(val);
+    }
+
+    if (key == "regex") {
+      bool ret = sub->setRegexMatch(val);
+
+      if (!ret) {
+        goto error;
+      }
+    }
+
+    if (key == "bucket" || key == "hash") {
+      sub->setBucket(val);
+    }
+
+    if (key == "connector") {
+      o.addSubOp(sub);
+      sub = new subop();
+    }
+  }
+
+  o.addSubOp(sub);
+  return true;
+
+error:
+  TSDebug(MY_NAME, "error building operation");
+  return false;
+}
+
+typedef std::vector<const op *> OpsQueue;
+
+//----------------------------------------------------------------------------
+// init
+TSReturnCode
+TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size)
+{
+  setup_memory_allocation();
+
+  return TS_SUCCESS;
+}
+
+//----------------------------------------------------------------------------
+// initialization of structures from config parameters
+TSReturnCode
+TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size)
+{
+  if (argc != 3) {
+    TSError("arguments not equal to 3: %d", argc);
+    TSDebug(MY_NAME, "arguments not equal to 3: %d", argc);
+    return TS_ERROR;
+  }
+
+  std::string filename(argv[2]);
+  try {
+    YAML::Node config = YAML::LoadFile(filename);
+
+    std::unique_ptr<OpsQueue> ops(new OpsQueue);
+    OpMap op_data;
+
+    for (YAML::const_iterator it = config.begin(); it != config.end(); ++it) {
+      const string &name         = it->first.as<std::string>();
+      YAML::NodeType::value type = it->second.Type();
+
+      if (name != "op" || type != YAML::NodeType::Map) {
+        const string reason = "Top level nodes must be named op and be of type map";
+        TSError("Invalid YAML Configuration format for cookie_remap: %s, reason: %s", filename.c_str(), reason.c_str());
+        return TS_ERROR;
+      }
+
+      for (YAML::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) {
+        const YAML::Node &first  = it2->first;
+        const YAML::Node &second = it2->second;
+
+        if (second.Type() != YAML::NodeType::Scalar) {
+          const string reason = "All op nodes must be of type scalar";
+          TSError("Invalid YAML Configuration format for cookie_remap: %s, reason: %s", filename.c_str(), reason.c_str());
+          return TS_ERROR;
+        }
+
+        const string &key   = first.as<std::string>();
+        const string &value = second.as<std::string>();
+        op_data.emplace_back(key, value);
+      }
+
+      if (op_data.size()) {
+        op *o = new op();
+        if (!build_op(*o, op_data)) {
+          delete o;
+
+          TSError("building operation, check configuration file: %s", filename.c_str());
+          return TS_ERROR;
+        } else {
+          ops->push_back(o);
+        }
+        o->printOp();
+        op_data.clear();
+      }
+    }
+
+    TSDebug(MY_NAME, "# of ops: %d", (int)ops->size());
+    *ih = static_cast<void *>(ops.release());
+  } catch (const YAML::Exception &e) {
+    TSError("YAML::Exception %s when parsing YAML config file %s for cookie_remap", e.what(), filename.c_str());
+    return TS_ERROR;
+  }
+
+  return TS_SUCCESS;
+}
+
+//----------------------------------------------------------------------------
+// called whenever we need to perform substiturions on a string; used to replace
+// things like
+//  $url, $unmatched_path, $cr_req_url, and $cr_url_encode
+// returns 0 if no substitutions, 1 otw.
+int
+cr_substitutions(std::string &obj, TSRemapRequestInfo *rri)
+{
+  int retval = 0;
+
+  size_t pos      = obj.find('$');
+  size_t tmp_pos  = 0;
+  size_t last_pos = pos;
+
+  UrlComponents req_url;
+  req_url.populate(rri);
+  TSDebug(MY_NAME, "x req_url.path: %s %zu", req_url.path.c_str(), req_url.path.length());
+  TSDebug(MY_NAME, "x req_url.url: %s %d", std::string(req_url.url, req_url.url_len).c_str(), req_url.url_len);
+
+  while (pos < obj.length()) {
+    if (pos + 1 >= obj.length())
+      break; // trailing ?
+
+    switch (obj[pos + 1]) {
+    case 'p':
+      if (obj.substr(pos + 1, 4) == "path") {
+        obj.replace(pos, 5, req_url.path);
+        pos += req_url.path.length();
+      }
+      break;
+    case 'u':
+      if (obj.substr(pos + 1, 14) == "unmatched_path") {
+        // we found $unmatched_path inside the sendto
+        // url
+        std::string unmatched_path(req_url.path);
+        TSDebug(MY_NAME, "unmatched_path: %s", unmatched_path.c_str());
+        TSDebug(MY_NAME, "from_path: %s", req_url.from_path);
+
+        tmp_pos = unmatched_path.find(req_url.from_path, 0, req_url.from_path_len); // from patch
+        if (tmp_pos != std::string::npos) {
+          unmatched_path.erase(tmp_pos, req_url.from_path_len);
+        }
+        TSDebug(MY_NAME, "unmatched_path: %s", unmatched_path.c_str());
+        TSDebug(MY_NAME, "obj: %s", obj.c_str());
+        obj.replace(pos, 15, unmatched_path);
+        TSDebug(MY_NAME, "obj: %s", obj.c_str());
+        pos += unmatched_path.length();
+      }
+      break;
+    case 'c':
+      if (obj.substr(pos + 1, 3) == "cr_")
+        switch (obj[pos + 4]) {
+        case 'r':
+          if (obj.substr(pos + 4, 7) == "req_url") {
+            // we found $cr_req_url inside
+            // the sendto url
+            std::string request_url;
+            if (req_url.url && req_url.url_len > 0) {
+              request_url = std::string(req_url.url, req_url.url_len);
+            }
+            TSDebug(MY_NAME, "req_url.url: %s %d", std::string(req_url.url, req_url.url_len).c_str(), req_url.url_len);
+            obj.replace(pos, 11, request_url);
+            pos += request_url.length();
+          }
+          break;
+        case 'u':
+          // note that this allows for variables
+          // nested in the function, but not
+          // for functions nested in the function
+          if (obj.substr(pos + 4, 10) == "urlencode(" && (tmp_pos = obj.find(')', pos + 14)) != std::string::npos) {
+            std::string str = obj.substr(pos + 14, tmp_pos - pos - 14); // the string to
+                                                                        // encode
+            cr_substitutions(str, rri);                                 // expand any
+                                                                        // variables as
+                                                                        // necessary
+                                                                        // before
+                                                                        // encoding
+            urlencode(str);
+            obj.replace(pos, tmp_pos - pos + 1, str); // +1 for the
+                                                      // closing
+                                                      // parens
+            pos += str.length();
+          }
+          break;
+        }
+      break;
+    }
+    if (last_pos == pos)
+      pos++; // don't search the same place again and again
+    last_pos = pos;
+    pos      = obj.find('$', pos);
+  }
+
+  return retval;
+}
+
+//----------------------------------------------------------------------------
+// called on each request
+// returns 0 on error or failure to match rules, 1 on a match
+TSRemapStatus
+TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri)
+{
+  OpsQueue *ops       = (OpsQueue *)ih;
+  TSHttpStatus status = TS_HTTP_STATUS_NONE;
+
+  UrlComponents req_url;
+  req_url.populate(rri);
+
+  if (ops == (OpsQueue *)nullptr) {
+    TSError("serious error with encountered while attempting to "
+            "cookie_remap");
+    TSDebug(MY_NAME, "serious error with encountered while attempting to remap");
+    return TSREMAP_NO_REMAP;
+  }
+
+  // get any query params..we will append that to the answer (possibly)
+  std::string client_req_query_params;
+  if (req_url.query_len) {
+    client_req_query_params = "?";
+    client_req_query_params += std::string(req_url.query, req_url.query_len);
+  }
+  TSDebug(MY_NAME, "Query Parameters: %s", client_req_query_params.c_str());
+
+  std::string rewrite_to;
+  char cookie_str[] = "Cookie";
+  TSMLoc field      = TSMimeHdrFieldFind(rri->requestBufp, rri->requestHdrp, cookie_str, sizeof(cookie_str) - 1);
+
+  // cookie header doesn't exist
+  if (field == nullptr) {
+    TSDebug(MY_NAME, "no cookie header");
+    // return TSREMAP_NO_REMAP;
+  }
+
+  const char *cookie = nullptr;
+  int cookie_len     = 0;
+  if (field != nullptr) {
+    cookie = TSMimeHdrFieldValueStringGet(rri->requestBufp, rri->requestHdrp, field, -1, &cookie_len);
+  }
+  std::string temp_cookie(cookie, cookie_len);
+  CookieJar jar;
+  jar.create(temp_cookie);
+
+  for (OpsQueue::iterator it = ops->begin(); it != ops->end(); ++it) {
+    TSDebug(MY_NAME, ">>> processing new operation");
+    if ((*it)->process(jar, rewrite_to, status, rri)) {
+      cr_substitutions(rewrite_to, rri);
+
+      size_t pos = 7;                             // 7 because we want to ignore the // in
+                                                  // http:// :)
+      size_t tmp_pos = rewrite_to.find('?', pos); // we don't want to alter the query string
+      do {
+        pos = rewrite_to.find("//", pos);
+        if (pos < tmp_pos)
+          rewrite_to.erase(pos, 1); // remove one '/'
+      } while (pos <= rewrite_to.length() && pos < tmp_pos);
+
+      // Add Query Parameters if not already present
+      if (!client_req_query_params.empty() && rewrite_to.find("?") == std::string::npos) {
+        rewrite_to.append(client_req_query_params);
+      }
+
+      TSDebug(MY_NAME, "rewriting to: %s", rewrite_to.c_str());
+
+      // Maybe set the return status
+      if (status > TS_HTTP_STATUS_NONE) {
+        TSDebug(MY_NAME, "Setting return status to %d", status);
+        SETHTTPSTATUS(txnp, status);
+        if ((status == TS_HTTP_STATUS_MOVED_PERMANENTLY) || (status == TS_HTTP_STATUS_MOVED_TEMPORARILY)) {
+          if (rewrite_to.size() > 8192) {
+            TSError("Redirect in target "
+                    "URL too long");
+            SETHTTPSTATUS(txnp, TS_HTTP_STATUS_REQUEST_URI_TOO_LONG);
+          } else {
+            const char *start = rewrite_to.c_str();
+            int dest_len      = rewrite_to.size();
+
+            if (TS_PARSE_ERROR == TSUrlParse(rri->requestBufp, rri->requestUrl, &start, start + dest_len)) {
+              SETHTTPSTATUS(txnp, TS_HTTP_STATUS_INTERNAL_SERVER_ERROR);
+              TSError("can't parse "
+                      "substituted "
+                      "URL string");
+            } else {
+              rri->redirect = 1;
+            }
+          }
+        }
+        if (field != nullptr) {
+          TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
+        }
+        if (rri->redirect) {
+          return TSREMAP_DID_REMAP;
+        } else {
+          return TSREMAP_NO_REMAP;
+        }
+      }
+
+      const char *start = rewrite_to.c_str();
+
+      // set the new url
+      if (TSUrlParse(rri->requestBufp, rri->requestUrl, &start, start + rewrite_to.length()) == TS_PARSE_ERROR) {
+        SETHTTPSTATUS(txnp, TS_HTTP_STATUS_INTERNAL_SERVER_ERROR);
+        TSError("can't parse substituted URL string");
+        goto error;
+      } else {
+        if (field != nullptr) {
+          TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
+        }
+        return TSREMAP_DID_REMAP;
+      }
+
+    // Cleanup
+    error:
+      if (field != nullptr) {
+        TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
+      }
+      return TSREMAP_NO_REMAP;
+    }
+  }
+
+  TSDebug(MY_NAME, "could not execute ANY of the cookie remap operations... "
+                   "falling back to default in remap.config");
+
+  if (field != nullptr) {
+    TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field);
+  }
+  return TSREMAP_NO_REMAP;
+}
+
+//----------------------------------------------------------------------------
+// unload
+void
+TSRemapDeleteInstance(void *ih)
+{
+  OpsQueue *ops = (OpsQueue *)ih;
+
+  TSDebug(MY_NAME, "deleting loaded operations");
+  for (OpsQueue::iterator it = ops->begin(); it != ops->end(); ++it) {
+    delete *it;
+  }
+
+  delete ops;
+
+  return;
+}
diff --git a/plugins/experimental/cookie_remap/cookiejar.cc b/plugins/experimental/cookie_remap/cookiejar.cc
new file mode 100644
index 0000000..be46e2c
--- /dev/null
+++ b/plugins/experimental/cookie_remap/cookiejar.cc
@@ -0,0 +1,255 @@
+/*
+  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 "cookiejar.h"
+#include "strip.h"
+#include <string.h>
+
+/* allowed cookie-name definition from RFC
+ * cookie-name       = token
+ * token             = <token, defined in [RFC2616], Section 2.2>
+ * token             = 1*<any CHAR except CTLs or separators>
+ * separators        = "(" | ")" | "<" | ">" | "@"
+ *                   | "," | ";" | ":" | "\" | <">
+ *                   | "/" | "[" | "]" | "?" | "="
+ *                   | "{" | "}" | SP | HT
+ * CTL               = <any US-ASCII control character
+ *                     (octets 0 - 31) and DEL (127)>
+ * SP                = <US-ASCII SP, space (32)>
+ * HT                = <US-ASCII HT, horizontal-tab (9)>
+ */
+
+static const int rfc_cookie_name_table[256] = {
+  /* 0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F            */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00-0F */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10-1F */
+  0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, /* 20-2F */
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 30-3F */
+  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40-4F */
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, /* 50-5F */
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60-6F */
+  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, /* 70-7F */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90-9F */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0-AF */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0-CF */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0-DF */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0-EF */
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0  /* F0-FF */
+};
+
+bool
+CookieJar::create(const string &strCookie)
+{
+  if (strCookie.empty()) {
+    return false;
+  }
+
+  if (parse(strCookie, "; ", true, true) != 0) {
+    return false;
+  }
+
+  return true;
+}
+
+int
+CookieJar::parse(const string &arg, const char *sepstr, bool val_check, bool mainElement)
+{
+  char *arg_copy;
+  char *cp;
+  char *key;
+
+  if ((arg_copy = strdup(arg.c_str())) == nullptr)
+    return -1;
+
+  cp           = arg_copy;
+  char empty[] = "";
+  for (key = strsep(&cp, sepstr); key != nullptr; key = strsep(&cp, sepstr)) {
+    int val_len;
+    char *val   = strchr(key, '=');
+    char *addme = nullptr;
+
+    if (val) {
+      /* split key and value */
+      *val++  = '\0';
+      val_len = strlen(val);
+      if (val_len > 0) {
+        /* if we have DQUOTES around our value then drop them */
+
+        if (val_len > 1 && val[0] == '"' && val[val_len - 1] == '"') {
+          val[val_len - 1] = '\0';
+          addme            = val + 1;
+
+          /* update the value length accordingly */
+
+          val_len -= 2;
+        } else {
+          addme = val; /* We have got a valid value eg: "YL=a" */
+        }
+
+        /* verify that the value is valid according to our configured
+         * opton and possibly strip out invalid characters. */
+
+        if (val_check && verify_value(addme, val_len) != 0)
+          continue;
+      } else {
+        // Empty cookie case eg: "L="
+        addme = empty;
+      }
+    } else /* If val is nullptr, then no need to add this kv pair to hashtable, skip this key */
+    {
+      continue;
+    }
+
+    /* we are going to verify the key name for our top level
+     * cookie names only so we'll use the val_check variables
+     * to know what we're processing */
+
+    if (val_check && verify_name(key) != 0)
+      continue;
+
+    if (mainElement)
+      addElement(key, addme);
+    else
+      addSubElement(key, addme);
+  }
+
+  free(arg_copy);
+  return 0;
+}
+
+void
+CookieJar::addElement(const char *key, const char *val)
+{
+  /* The insert method avoids duplicates */
+  CookieVal cval;
+  cval.m_val = val;
+  m_jar.insert(std::make_pair(key, cval));
+}
+
+void
+CookieJar::addSubElement(const char *key, const char *val)
+{
+  /* The insert method avoids duplicates */
+  m_currentVal->m_subelements.insert(std::make_pair(key, val));
+}
+
+int
+CookieJar::verify_value(char *val, int val_len)
+{
+  char *buf;
+  char *data_ptr      = nullptr;
+  char data_buf[1024] = {
+    0,
+  };
+  int buf_len;
+
+  if (val_len > static_cast<int>(sizeof(data_buf) - 1)) {
+    buf_len = val_len + 1;
+    if ((data_ptr = static_cast<char *>(malloc(buf_len))) == nullptr)
+      return -1;
+
+    buf = data_ptr;
+  } else {
+    buf     = data_buf;
+    buf_len = sizeof(data_buf);
+  }
+
+  if (get_stripped(val, val_len, buf, &buf_len, 0) != STRIP_RESULT_OK) {
+    if (data_ptr)
+      free(data_ptr);
+    return -1;
+  }
+
+  /* returned buf_len includes the null terminator
+   * so we need to verify that somehow we didn't end up
+   * with a bigger buffer than what we started with */
+
+  if (buf_len > val_len + 1) {
+    if (data_ptr)
+      free(data_ptr);
+    return -1;
+  }
+
+  memcpy(val, buf, buf_len);
+  if (data_ptr)
+    free(data_ptr);
+
+  return 0;
+}
+
+int
+CookieJar::verify_name(char *name)
+{
+  char *p;
+
+  for (p = name; *p; p++) {
+    /* if we get any invalid characters then return failure
+     * in order to skip this cookie completely */
+
+    if (rfc_cookie_name_table[(int)*p] == 0)
+      return -1;
+  }
+
+  return 0;
+}
+
+bool
+CookieJar::get_full(const string &cookie_name, string &val)
+{
+  if (m_jar.find(cookie_name) != m_jar.end()) {
+    val = m_jar[cookie_name].m_val;
+    return true;
+  }
+  return false;
+}
+
+bool
+CookieJar::get_part(const string &cookie_name, const string &part_name, string &val)
+{
+  if (m_jar.empty())
+    return false;
+
+  if (m_jar.find(cookie_name) == m_jar.end()) {
+    /* full cookie not found */
+    return false;
+  }
+
+  CookieVal &fe = m_jar[cookie_name];
+  /* check if we need to do lazy evaluation */
+  if (fe.parts_inited == false) {
+    /* since we already validated the value for the full cookie
+     * there is no need to validate the components again so
+     * we'll be passing 0/false for the val_check argument */
+
+    m_currentVal = &fe;
+    if (parse(fe.m_val, "&", false, false) != 0)
+      return false;
+
+    fe.parts_inited = true;
+    m_currentVal    = nullptr;
+  }
+
+  if (fe.m_subelements.find(part_name) == fe.m_subelements.end()) {
+    return false; /* not found */
+  }
+
+  val = fe.m_subelements[part_name];
+  return true;
+}
diff --git a/plugins/experimental/cookie_remap/cookiejar.h b/plugins/experimental/cookie_remap/cookiejar.h
new file mode 100644
index 0000000..65d1c9b
--- /dev/null
+++ b/plugins/experimental/cookie_remap/cookiejar.h
@@ -0,0 +1,62 @@
+/*
+  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.
+*/
+
+#ifndef CKREMAP_COOKIEJAR_H_
+#define CKREMAP_COOKIEJAR_H_
+
+#include <string>
+#include <unordered_map>
+
+using std::string;
+using std::unordered_map;
+
+class CookieJar
+{
+public:
+  CookieJar(){};
+  ~CookieJar(){};
+
+  bool create(const string &strCookie);
+
+  CookieJar(const CookieJar &) = delete;
+  CookieJar &operator=(const CookieJar &) = delete;
+
+  bool get_full(const string &cookie_name, string &val);
+  bool get_part(const string &cookie_name, const string &part_name, string &val);
+
+private:
+  int verify_name(char *name);
+  int verify_value(char *val, int val_len);
+  int parse(const string &arg, const char *sepstr, bool val_check, bool mainElement);
+
+  void addElement(const char *key, const char *val);
+  void addSubElement(const char *key, const char *val);
+
+  class CookieVal
+  {
+  public:
+    unordered_map<string, string> m_subelements;
+    string m_val;
+    bool parts_inited = 0;
+  };
+  CookieVal *m_currentVal = nullptr;
+
+  unordered_map<string, CookieVal> m_jar;
+};
+
+#endif // CKREMAP_COOKIEJAR_H_
diff --git a/plugins/experimental/cookie_remap/hash.c b/plugins/experimental/cookie_remap/hash.c
new file mode 100644
index 0000000..a1bdbb5
--- /dev/null
+++ b/plugins/experimental/cookie_remap/hash.c
@@ -0,0 +1,110 @@
+/*
+  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 "hash.h"
+#include <string.h>
+#include <ctype.h>
+
+////////////////////////////////////////////////////////////////////////////////
+//        Implementation of the Fowler–Noll–Vo hash function                  //
+//        More Details at: http://www.isthe.com/chongo/tech/comp/fnv/         //
+////////////////////////////////////////////////////////////////////////////////
+
+/*
+ * 32/64 bit magic FNV primes
+ * The main secret of the algorithm is in these prime numbers
+ * and their special relation to 2^32 (or 2^64) [a word]
+ * and 2^8 [a byte].
+ */
+#define FNV_32_PRIME ((uint32_t)0x01000193UL)
+#define FNV_64_PRIME ((uint64_t)0x100000001b3ULL)
+
+/*
+ * The init value is quite arbitrary, but these seem to perform
+ * well on both web2 and sequential integers represented as strings.
+ */
+#define FNV1_32_INIT ((uint32_t)33554467UL)
+#define FNV1_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
+
+#define MAX_UINT32 (~((uint32_t)0))
+#define MAX_UINT64 (~((uint64_t)0))
+
+#define MASK(x) (((uint32_t)1 << (x)) - 1)
+
+static uint32_t
+fnv32_nbits(const char *buf, int len, int nbits)
+{
+  uint32_t hash;
+  hash = hash_fnv32_buf(buf, len);
+
+  if (nbits <= 16) {
+    hash = ((hash >> nbits) ^ hash) & MASK(nbits);
+  } else {
+    hash = (hash >> nbits) ^ (hash & MASK(nbits));
+  }
+
+  return hash;
+}
+
+uint32_t
+hash_fnv32_buckets(const char *buf, size_t len, uint32_t num_buckets)
+{
+  uint32_t hash;
+  uint32_t retry;
+  int first_bit;
+
+  if (num_buckets < 1) {
+    return 0;
+  }
+
+  first_bit = ffs(num_buckets);
+
+  if (num_buckets >> first_bit == 0) { /* Power of two */
+    /* Yay we can xor fold */
+    hash = fnv32_nbits(buf, len, first_bit - 1);
+    return hash;
+  }
+
+  /* Can't xor fold so use the retry method */
+
+  hash = hash_fnv32_buf(buf, len);
+
+  /* This code ensures there is no bias against larger values */
+  retry = (MAX_UINT32 / num_buckets) * num_buckets;
+  while (hash >= retry) {
+    hash = (hash * FNV_32_PRIME) + FNV1_32_INIT;
+  }
+
+  hash %= num_buckets;
+  return hash;
+}
+
+/* 32-bit version */
+uint32_t
+hash_fnv32_buf(const char *buf, size_t len)
+{
+  uint32_t val; /* initial hash value */
+
+  for (val = FNV1_32_INIT; len > 0; --len) {
+    val *= FNV_32_PRIME;
+    val ^= (uint32_t)(*buf);
+    ++buf;
+  }
+
+  return val;
+}
diff --git a/plugins/experimental/cookie_remap/hash.h b/plugins/experimental/cookie_remap/hash.h
new file mode 100644
index 0000000..daeffc2
--- /dev/null
+++ b/plugins/experimental/cookie_remap/hash.h
@@ -0,0 +1,54 @@
+/*
+  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.
+*/
+
+#ifndef _CKREMAP_HASH_H_
+#define _CKREMAP_HASH_H_
+
+#include <stddef.h>
+#include <sys/types.h>
+#include <inttypes.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * 32-bit Fowler / Noll / Vo (FNV) Hash.
+ *
+ * see http://www.isthe.com/chongo/tech/comp/fnv/index.html
+ */
+uint32_t hash_fnv32_buf(const char *buf, size_t len);
+
+/**
+ * Computes an fnv32 hash whose value is less than num_buckets
+ *
+ * This functions computes an fnv32 between zero and num_buckets - 1.
+ * It computes an fnv32 hash and collapses that hash into a smaller
+ * range using techniques which avoid the bias in a simple mod
+ * operation.
+ *
+ * This function has the best performance (speed and hash distribution)
+ * 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
+
+#endif /* _CKREMAP_HASH_H_ */
diff --git a/plugins/experimental/cookie_remap/strip.c b/plugins/experimental/cookie_remap/strip.c
new file mode 100644
index 0000000..d596573
--- /dev/null
+++ b/plugins/experimental/cookie_remap/strip.c
@@ -0,0 +1,282 @@
+/*
+  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 <stdio.h>
+#include <string.h>
+#include <sys/types.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <ctype.h>
+#include <assert.h>
+#include <inttypes.h>
+
+#include "strip.h"
+
+static int copy_whitespace(const char **r, const char *in_end, char **w, const char *out_end);
+
+static int strip_whitespace(const char **r, const char **in_end);
+
+/* Determine if there is room to store len bytes starting at p for an
+ * object that ends at maxp.  This is not as simple as a less-than
+ * comparison, because our code may increment p well beyond the end of
+ * the object it originally pointed to (in complete violation of what
+ * ANSI C says is legitimate).  The result is that p may wrap around.
+ * This has been  observed with using stack buffers as arguments
+ * from 32 bit programs running on 64-bit RHEL.
+ */
+#define ROOM(p, len, maxp) (((maxp) - ((p) + (len))) >= 0)
+
+/* write c into *p if there's room, always incrementing *p.  This
+ * implementation uses a do-loop to avoid several syntactic issues
+ * when this macro is expanded in the context of if-then-else constructs.
+ * It is expected that the compiler will optimize away the "while (0)"
+ */
+#define WRITE_C_IF_ROOM(p, maxp, c) \
+  do {                              \
+    if (ROOM(*(p), 1, (maxp)))      \
+      **(p) = (c);                  \
+    (*(p))++;                       \
+  } while (0)
+
+/* write s into *p if there's room, always adding slen to *p . This
+ * implementation uses a do-loop to avoid several syntactic issues
+ * when this macro is expanded in the context of if-then-else constructs.
+ * It is expected that the compiler will optimize away the "while 0"
+ */
+#define WRITE_STR_IF_ROOM(p, maxp, s, slen) \
+  do {                                      \
+    if (ROOM(*(p), (slen), (maxp)))         \
+      memcpy(*(p), (s), (slen));            \
+    *(p) += (slen);                         \
+  } while (0)
+
+/* Write count spaces into *p if there's room, always adding count to *p.
+ * The count argument is set to zero at the end of execution. This
+ * implementation uses a do-loop to avoid several syntactic issues when
+ * this macro is expanded in the context of if-then-else constructs.
+ * It is expected that the compiler will optimize away the "while 0"
+ */
+#define WRITE_SPACES_IF_ROOM(p, maxp, slen) \
+  do {                                      \
+    if (ROOM(*(p), (slen), (maxp)))         \
+      memset(*(p), ' ', (slen));            \
+    *(p) += (slen);                         \
+    (slen) = 0;                             \
+  } while (0)
+
+/*
+ * File-scope data
+ */
+
+static const unsigned int allowed_flags = (STRIP_FLAG_LEAVE_WHITESP | STRIP_FLAG_STRIP_LOW | STRIP_FLAG_STRIP_HIGH |
+                                           STRIP_FLAG_UNSAFE_QUOTES | STRIP_FLAG_UNSAFE_SLASHES | STRIP_FLAG_UNSAFE_SPACES);
+
+static int
+stripped_core(const char *r, const char *in_end, char **w, const char *out_end, unsigned int flags)
+{
+  int leading        = 1;    /* haven't yet written a non-space */
+  int in_js_entity   = 0;    /* are we inside a javascript entity? */
+  char in_quote_char = '\0'; /* in quoted region? which kind: '\'' or '"' */
+  int space          = 0;    /* number of spaces pending */
+  int stripped       = 0;    /* have we stripped since last output? */
+  int in_tag         = 0;    /* are we inside a tag? */
+
+  /* parse the string, stripping risky characters/sequences */
+  for (/* already established */; r < in_end; r++) {
+    unsigned char c = *r;
+    if (in_tag) {
+      switch (c) {
+      case '>':
+        if (!in_quote_char) {
+          in_tag = 0;
+        }
+        break;
+
+      case '"':
+      case '\'':
+        if (!in_quote_char) {
+          in_quote_char = c;
+        } else if (in_quote_char == c) {
+          in_quote_char = '\0';
+        }
+        break;
+
+      default:
+        break; /* eat everything between < and > */
+      }
+    } else if (in_js_entity) {
+      switch (c) {
+      case '}':
+        if (!in_quote_char) {
+          in_js_entity = 0;
+          if (r + 1 < in_end && *(r + 1) == ';') {
+            r++;
+          }
+        }
+        break;
+
+      case '"':
+      case '\'':
+        if (!in_quote_char) {
+          in_quote_char = c;
+        } else if (in_quote_char == c) {
+          in_quote_char = '\0';
+        }
+        break;
+
+      default:
+        break; /* eat everything between < and > */
+      }
+    } else {
+      if (c == '<') {
+        in_tag   = 1;
+        stripped = 1;
+      } else if (c == '&' && r + 1 < in_end && *(r + 1) == '{') {
+        in_js_entity = 1;
+        stripped     = 1;
+        r++;
+      } else if ((c < 0x07 && (flags & STRIP_FLAG_STRIP_LOW)) || (c >= 0x80 && (flags & STRIP_FLAG_STRIP_HIGH)) ||
+                 (c == '"' && !(flags & STRIP_FLAG_UNSAFE_QUOTES)) || (c == '\'' && !(flags & STRIP_FLAG_UNSAFE_QUOTES)) ||
+                 (c == '\\' && !(flags & STRIP_FLAG_UNSAFE_SLASHES)) || c == '>') {
+        stripped = 1;
+      } else if (c == ' ') {
+        space++; /* don't collapse existing spaces */
+      } else {
+        /* we're ready to write an output character */
+        if (leading) {
+          leading  = 0; /* first non-whitespace character */
+          stripped = 0;
+          if (!(flags & STRIP_FLAG_LEAVE_WHITESP)) {
+            space = 0;
+          }
+        }
+
+        /* flush pending spaces */
+        if (!space && stripped && !(flags & STRIP_FLAG_UNSAFE_SPACES)) {
+          space = 1; /* replace stripped sequence with space */
+        }
+        stripped = 0; /* reset until next stripped sequence */
+        WRITE_SPACES_IF_ROOM(w, out_end, space);
+
+        /* Process as single character. */
+        WRITE_C_IF_ROOM(w, out_end, c);
+      }
+    }
+  }
+
+  /* Restore trailing whitespace if asked */
+  if (flags & STRIP_FLAG_LEAVE_WHITESP)
+    WRITE_SPACES_IF_ROOM(w, out_end, space);
+
+  return STRIP_RESULT_OK;
+}
+
+int
+get_stripped(const char *in, ssize_t in_len, char *out, int *out_len, unsigned int flags)
+{
+  int retval = STRIP_RESULT_OK;
+  const char *r, *in_end; /* where we read from, read limit */
+  char *w, *out_end;      /* where we write to, write limit */
+
+  /* validate params */
+  if (in == NULL || in_len < 0 || out_len == NULL || *out_len < 0 || (out == NULL && *out_len > 0) || (flags & (~allowed_flags))) {
+    if (out != NULL && out_len != NULL && *out_len > 0) {
+      *out     = '\0';
+      *out_len = 1;
+    }
+    return STRIP_RESULT_BAD_PARAM;
+  }
+
+  /* make room for null terminator in output and remove if present in in */
+  (*out_len) -= out ? 1 : 0; /* make space for '\0' unless NULL out */
+  if (in_len > 0 && in[in_len - 1] == '\0') {
+    in_len--; /* don't count null terminator in input */
+  }
+
+  /* establish our read and write limits */
+  r       = in;
+  w       = out;
+  in_end  = in + in_len;
+  out_end = out + *out_len;
+
+  /* strip leading and trailing whitespace, unless asked not to */
+  if (!(flags & STRIP_FLAG_LEAVE_WHITESP)) {
+    strip_whitespace(&r, &in_end);
+  } else {
+    copy_whitespace(&r, in_end, &w, out_end);
+  }
+
+  /* handle empty input case (null terminated or not) */
+  if ((!(flags & STRIP_FLAG_LEAVE_WHITESP) && r >= in_end) || ((flags & STRIP_FLAG_LEAVE_WHITESP) && in_len == 0)) {
+    WRITE_C_IF_ROOM(&w, out_end, '\0'); /* make out empty string */
+    *out_len = 1;
+    return STRIP_RESULT_EMPTY_IN; /* input is empty string */
+  }
+
+  /* call the core function that does actual checking and stripping */
+  retval = stripped_core(r, in_end, &w, out_end, flags);
+
+  /* null terminate */
+  out_end += out_end ? 1 : 0;         /* undo decrement at start */
+  WRITE_C_IF_ROOM(&w, out_end, '\0'); /* try to term at end of output */
+
+  /* report the required/used length */
+  *out_len = w - out;
+
+  /* see if we ran out of space, but were otherwise ok */
+  if (w > out_end && retval == STRIP_RESULT_OK) {
+    retval = STRIP_RESULT_OUTLEN_SMALL;
+  }
+
+  if (retval != STRIP_RESULT_OK) {
+    /* return the empty string on all errors */
+    WRITE_C_IF_ROOM(&out, out_end, '\0'); /* make out the empty string */
+    if (retval != STRIP_RESULT_OUTLEN_SMALL) {
+      *out_len = 1; /* even if retried, we won't use more than 1 byte */
+    }
+  }
+
+  return retval;
+}
+
+/*
+ * Copy sequence of whitespace from r to w
+ */
+static int
+copy_whitespace(const char **r, const char *in_end, char **w, const char *out_end)
+{
+  char c;
+  while (*r < in_end && (c = **r) && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
+    WRITE_C_IF_ROOM(w, out_end, c);
+    (*r)++;
+  }
+  return 0;
+}
+
+static int
+strip_whitespace(const char **r, const char **in_end)
+{
+  char c;
+  while (*r < *in_end && (c = **r) && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
+    (*r)++;
+  }
+  while (*in_end > *r && (c = *((*in_end) - 1)) && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
+    (*in_end)--;
+  }
+  return 0;
+}
diff --git a/plugins/experimental/cookie_remap/strip.h b/plugins/experimental/cookie_remap/strip.h
new file mode 100644
index 0000000..cf76f67
--- /dev/null
+++ b/plugins/experimental/cookie_remap/strip.h
@@ -0,0 +1,146 @@
+/*
+  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.
+*/
+
+#ifndef CKREMAP_IV_H
+#define CKREMAP_IV_H
+
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* return codes */
+#define STRIP_RESULT_OK 0            /**< success */
+#define STRIP_RESULT_BAD_PARAM -1    /**< one or more invalid arguments */
+#define STRIP_RESULT_OUTLEN_SMALL -2 /**< output buffer not large enough */
+#define STRIP_RESULT_EMPTY_IN -3     /**< in consists solely of whitespace */
+
+/* defined flags */
+#define STRIP_FLAG_NONE 0x0            /**< no flags */
+#define STRIP_FLAG_STRIP_LOW 0x1       /**< stripped, html: strip low */
+#define STRIP_FLAG_STRIP_HIGH 0x2      /**< stripped, html: strip high */
+#define STRIP_FLAG_LEAVE_WHITESP 0x4   /**< all: avoid trimming spaces */
+#define STRIP_FLAG_UNSAFE_QUOTES 0x8   /**< html: dont encode quotes */
+#define STRIP_FLAG_UNSAFE_SLASHES 0x10 /**< all: dont encode backslashes */
+#define STRIP_FLAG_UNSAFE_SPACES 0x20  /**< html: stipped tag isnt space */
+
+/** Output the input after stripping all characters that are
+ *  unsafe in an HTML context.
+ *
+ * This function performs the following treatment:
+ *
+ *   - strips from a '<' to the next unquoted '>'
+ *
+ *   - strips "&{" to the next unquoted '}' or "};"
+ *
+ *   - strips the character '>'
+ *
+ *   - strips the following characters: '\'', '"', unless the flag
+ *     STRIP_FLAG_UNSAFE_QUOTES is present.
+ *
+ *   - strips the character '\\' unless the flag STRIP_FLAG_UNSAFE_SLASHES
+ *     is present.
+ *
+ *   - leaves a single space character in place of each
+ *     sequence of stripped characters if no other space
+ *     preceeded the stripped sequence (e.g., "a <b>b" becomes
+ *     "a b", but "a<b>b" becomes "a b")
+ *
+ * @param[in]     in        character array (string)
+ * @param[in]     in_len    number of bytes in character array
+ * @param[in,out] out       (in)storage for the resulting character array,
+ *                          (out)contains the null terminated result
+ * @param[in,out] out_len   (in)number of available bytes in out parameter,
+ *                          (out)number of bytes used or required in out
+ *                          (including NUL)
+ * @param[in]     flags     zero or more function-specific flags:
+ *                - STRIP_FLAG_LEAVE_WHITESP  - Leave whitespace in place.
+ *                - STRIP_FLAG_STRIP_LOW      - Strip all values <= 0x07.
+ *                - STRIP_FLAG_STRIP_HIGH     - Strip all values >= 0x80.
+ *                - 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
+ *
+ * @return
+ *    IV_RESULT_OK(0) on success.  Non-zero on failure.
+ *    See the complete list above.
+ *
+ * @verbatim
+ * EXAMPLES
+ *
+ *     Input                                 Output
+ *     -----------------------------         -----------------------------
+ *     <b>Bob & Mary</b>                     Bob & Mary
+ *     "a phrase"                            a phrase
+ *     Alice and Bob's house                 Alice and Bob s house
+ * @endverbatim
+ *
+ *
+ * DESIGN NOTES
+ *
+ *     The function assumes ISO-8859-1 encoding.
+ *
+ *   - the caller is responsible for managing memory; the code
+ *     does not allocate memory
+ *
+ *   - The function requires the input length to be specified
+ *     and place the required and/or used length in the
+ *     out_len parameter; this allows them to be efficiently
+ *     used in environments that store something other than
+ *     null terminated strings and also allows you to never
+ *     call a function more than once (if the output buffer is
+ *     too small on the first call, the value of out_len tells
+ *     you how long the buffer needs to be)
+ *
+ *   - all length parameters specify the length of the
+ *     corresponding string in bytes, not characters
+ *
+ *   - 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)
+ *
+ *   - no context is retained between calls
+ *
+ *     NOTES
+ *
+ *       - leading and trailing whitespace is stripped by default;
+ *         pass STRIP_FLAG_LEAVE_WHITESP to leave leading and
+ *         trailing whitespace in place
+ *
+ *       - when called with out_len less than the required
+ *         length, IV_RESULT_OUTLEN_SMALL is returned with the
+ *         required length in out_len and out set to the empty
+ *         string
+ *
+ *       - can be called with out_len == 0 and out == NULL to
+ *         compute sufficient storage size, which is returned
+ *         in out_len
+ *
+ *       - when called with out_len == 0, the output is not
+ *         NUL-terminated
+ */
+int get_stripped(const char *in, ssize_t in_len, char *out, int *out_len, unsigned int flags);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CKREMAP_IV_H */
diff --git a/plugins/experimental/cookie_remap/unit_tests/cookiejar/unit_test.cc b/plugins/experimental/cookie_remap/unit_tests/cookiejar/unit_test.cc
new file mode 100644
index 0000000..cacf857
--- /dev/null
+++ b/plugins/experimental/cookie_remap/unit_tests/cookiejar/unit_test.cc
@@ -0,0 +1,250 @@
+/*
+  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.
+*/
+
+#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
+#include <iostream>
+#include <string>
+#include <assert.h>
+#include "catch.hpp"
+#include "cookiejar.h"
+
+using std::cout;
+using std::endl;
+using std::string;
+
+TEST_CASE("Basic test with ; separated cookies", "[CookieJar]")
+{
+  std::cerr << "Verify individual cookie crumbs (semicolon separated)" << std::endl;
+  CookieJar oreo;
+  bool rc = oreo.create("fp=1;fn=2;sp=3;tl=4");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("fp", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "1");
+
+  rc = oreo.get_full("fn", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "2");
+
+  rc = oreo.get_full("sp", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "3");
+
+  rc = oreo.get_full("tl", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "4");
+
+  rc = oreo.get_full("doesnotexist", val);
+  REQUIRE(rc == false);
+}
+
+TEST_CASE("Basic test with space separated cookies", "[CookieJar]")
+{
+  std::cerr << "Verify individual cookie crumbs (space separated)" << std::endl;
+  CookieJar oreo;
+  bool rc = oreo.create("fp=1 fn=2    sp=3          tl=4");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("fp", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "1");
+
+  rc = oreo.get_full("fn", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "2");
+
+  rc = oreo.get_full("sp", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "3");
+
+  rc = oreo.get_full("tl", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "4");
+
+  rc = oreo.get_full("doesnotexist", val);
+  REQUIRE(rc == false);
+}
+
+TEST_CASE("Basic test with mixed delimiters", "[CookieJar]")
+{
+  std::cerr << "Verify individual cookie crumbs (mixed delimiters)" << std::endl;
+  CookieJar oreo;
+  bool rc = oreo.create("fp=1;fn=2 ;  sp=3 ;;     ; tl=4");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("fp", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "1");
+
+  rc = oreo.get_full("fn", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "2");
+
+  rc = oreo.get_full("sp", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "3");
+
+  rc = oreo.get_full("tl", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "4");
+
+  rc = oreo.get_full("doesnotexist", val);
+  REQUIRE(rc == false);
+}
+
+TEST_CASE("Test with some empty values", "[CookieJar]")
+{
+  std::cerr << "Verify empty values" << std::endl;
+  CookieJar oreo;
+  bool rc = oreo.create("lastname=whatever;firstname=;age=100;salary=;dept=engineering");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("lastname", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "whatever");
+
+  rc = oreo.get_full("firstname", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "");
+
+  rc = oreo.get_full("age", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "100");
+
+  rc = oreo.get_full("salary", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "");
+
+  rc = oreo.get_full("dept", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "engineering");
+}
+
+TEST_CASE("Verify double quotes around values are stripped", "[CookieJar]")
+{
+  std::cerr << "Verify double quotes around values are stripped" << std::endl;
+  CookieJar oreo;
+  bool rc = oreo.create("lang=c;vcs=\"git\"");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("vcs", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "git");
+}
+
+TEST_CASE("Discard invalid cookie names", "[CookieJar]")
+{
+  std::cerr << "Discard invalid cookie names" << std::endl;
+
+  // [] cannot be used in cookie names
+  CookieJar oreo;
+  bool rc = oreo.create("t=2;x=3;[invalid]=4;valid=5");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("t", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "2");
+
+  rc = oreo.get_full("x", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "3");
+
+  rc = oreo.get_full("valid", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "5");
+
+  rc = oreo.get_full("[invalid]", val);
+  REQUIRE(rc == false);
+}
+
+TEST_CASE("Handle null values", "[CookieJar]")
+{
+  std::cerr << "Handle null values" << std::endl;
+  CookieJar oreo;
+
+  // perl's value will be ""
+  // ancient will not be found because there is no = following it
+  // = will not be found because there is no = following it
+  // python will be "modern"
+  bool rc = oreo.create("perl=  ancient  =;python=modern");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("perl", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "");
+
+  rc = oreo.get_full("ancient", val);
+  REQUIRE(rc == false);
+
+  rc = oreo.get_full("=", val);
+  REQUIRE(rc == false);
+
+  rc = oreo.get_full("python", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "modern");
+}
+
+TEST_CASE("Verify subcookies are parsed", "[CookieJar]")
+{
+  std::cerr << "Verify subcookies are parsed" << std::endl;
+  CookieJar oreo;
+
+  bool rc = oreo.create("team1=spiderman=1&ironman=2&batman=3;team2=thor=1&wonderwoman=2&antman=3;superhero3=spiderman");
+  REQUIRE(rc == true);
+
+  string val;
+  rc = oreo.get_full("team1", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "spiderman=1&ironman=2&batman=3");
+
+  rc = oreo.get_full("superhero3", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "spiderman");
+
+  rc = oreo.get_part("team1", "spiderman", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "1");
+
+  rc = oreo.get_part("team1", "ironman", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "2");
+
+  rc = oreo.get_part("team1", "batman", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "3");
+
+  rc = oreo.get_part("team2", "thor", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "1");
+
+  rc = oreo.get_part("team2", "wonderwoman", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "2");
+
+  rc = oreo.get_part("team2", "antman", val);
+  REQUIRE(rc == true);
+  REQUIRE(val == "3");
+}
diff --git a/tests/gold_tests/pluginTest/cookie_remap/bucketcookie.test.py b/tests/gold_tests/pluginTest/cookie_remap/bucketcookie.test.py
new file mode 100644
index 0000000..4e1863a
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/bucketcookie.test.py
@@ -0,0 +1,104 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: cookie in bucket or not"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiematches HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookiedoesntmatch HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/bucketconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/bucketconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/bucketconfig.txt'
+)
+
+# Cookie value in bucket
+tr = Test.AddTestRun("cookie value in bucket")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=333"
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/matchcookie.gold"
+
+# cookie value not in bucket
+tr = Test.AddTestRun("cooke value not in bucket")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=etc" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/wontmatchcookie.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/collapseslashes.test.py b/tests/gold_tests/pluginTest/cookie_remap/collapseslashes.test.py
new file mode 100644
index 0000000..4819899
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/collapseslashes.test.py
@@ -0,0 +1,71 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: plugin collapses consecutive slashes"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# We only run a server to capture ATS outbound requests
+# and verify it collapsed the double //
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/collapseconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/collapseconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/collapseconfig.txt'
+)
+
+tr = Test.AddTestRun("collapse consecutive forward slashes")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/collapseslashes.gold"
+
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/bucketconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/bucketconfig.txt
new file mode 100644
index 0000000..2af72d0
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/bucketconfig.txt
@@ -0,0 +1,9 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  operation: bucket
+  bucket: 30/100
+  sendto: http://127.0.0.10:$PORT/cookiematches
+  else: http://127.0.0.11:$ALTPORT/cookiedoesntmatch
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/collapseconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/collapseconfig.txt
new file mode 100644
index 0000000..11693a0
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/collapseconfig.txt
@@ -0,0 +1,6 @@
+# This is a test configuration
+
+# Do a regex against the request url
+op:
+  regex: magic
+  sendto: http://127.0.0.10:$PORT/i/////////like/cheetos?.done=http://finance.yahoo.com
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/connectorconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/connectorconfig.txt
new file mode 100644
index 0000000..a35a1a6
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/connectorconfig.txt
@@ -0,0 +1,16 @@
+# This is a test configuration
+
+# First 2 ops do a comparison against the cookie and the 3rd
+# one does against the url
+op:
+  cookie: fpbeta
+  operation: string
+  match: abcd
+  connector: and
+  cookie: icecream
+  operation: exists
+  connector: and
+  operation: regex
+  regex: magic
+  sendto: http://127.0.0.10:$PORT/cookiematches
+  else: http://127.0.0.11:$ALTPORT/cookiedoesntmatch
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/existsconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/existsconfig.txt
new file mode 100644
index 0000000..8b3189a
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/existsconfig.txt
@@ -0,0 +1,8 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  operation: exists
+  sendto: http://127.0.0.10:$PORT/cookieexists
+  else: http://127.0.0.11:$ALTPORT/cookiedoesntexist
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/matchconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/matchconfig.txt
new file mode 100644
index 0000000..a7b850a
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/matchconfig.txt
@@ -0,0 +1,8 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  match: magic
+  sendto: http://127.0.0.10:$PORT/cookiematches
+  else: http://127.0.0.11:$ALTPORT/cookiedoesntmatch
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/matchuriconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/matchuriconfig.txt
new file mode 100644
index 0000000..3272826
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/matchuriconfig.txt
@@ -0,0 +1,17 @@
+# This is a test configuration
+
+# Do a regex against the request url
+op:
+  match: dkfdkfkdfkdfkdfkdfk
+  sendto: http://nothere.com
+op:
+  match: eioreioreioreioeio
+  sendto: http://nothereeither.com
+op:
+  match: mmmdm,cmvmcnxcxncn
+  sendto: http://nothereaswell.com
+op:
+  operation: regex
+  regex: thisispartofthepath
+  sendto: http://127.0.0.10:$PORT/cookiematches
+  else: http://127.0.0.11:$ALTPORT/cookiedoesntmatch
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/matrixconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/matrixconfig.txt
new file mode 100644
index 0000000..263c957
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/matrixconfig.txt
@@ -0,0 +1,24 @@
+# This is a test configuration
+
+# Do a regex against the url
+
+op:
+  operation: regex
+  regex: eleventh
+  sendto: http://127.0.0.10:$PORT/$path/eleventh;matrix=2?query=true
+
+op:
+  operation: regex
+  regex: tenth
+  sendto: http://127.0.0.10:$PORT/$path/tenth;matrix=2
+
+op:
+  operation: regex
+  regex: ninth
+  sendto: http://127.0.0.10:$PORT/$path/ninth?query=true
+
+op:
+  operation: regex
+  regex: eighth
+  sendto: http://127.0.0.10:$PORT/$path/eighth
+
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/notexistsconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/notexistsconfig.txt
new file mode 100644
index 0000000..72a2c19
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/notexistsconfig.txt
@@ -0,0 +1,8 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  operation: not exists
+  sendto: http://127.0.0.10:$PORT/cookiedoesntexist
+  else: http://127.0.0.11:$ALTPORT/cookieexists
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/regexconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/regexconfig.txt
new file mode 100644
index 0000000..04e7fdd
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/regexconfig.txt
@@ -0,0 +1,9 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  operation: regex
+  regex: ilove-(\w+)-(\w+)-(\w+)
+  sendto: http://127.0.0.10:$PORT/regexmatches?cookies=$1-$2-$3
+  else: http://127.0.0.11:$ALTPORT/regexdoesntmatch
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/statusconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/statusconfig.txt
new file mode 100644
index 0000000..6d66e8d
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/statusconfig.txt
@@ -0,0 +1,17 @@
+# This is a test configuration
+# When status is set, ATS doesn't follow the sendto or else
+# It just returns a canned response
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  match: magic
+  sendto: http://shouldnevergohere.com
+  status: 205
+op:
+  cookie: abracadabra
+  match: magic
+  sendto: http://shouldnevergohere.com
+  else: http://shouldnotgohereaswell.com
+  # When a else is present, status is associated with it
+  status: 400
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/subcookie.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/subcookie.txt
new file mode 100644
index 0000000..f34be18
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/subcookie.txt
@@ -0,0 +1,17 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta.a
+  operation: string
+  match: 1
+  connector: and
+  cookie: fpbeta.b
+  operation: string
+  match: 2
+  connector: and
+  cookie: fpbeta.c
+  operation: string
+  match: 3
+  sendto: http://127.0.0.10:$PORT/cookiematches
+  else: http://127.0.0.11:$ALTPORT/cookiedoesntmatch
diff --git a/tests/gold_tests/pluginTest/cookie_remap/configs/substituteconfig.txt b/tests/gold_tests/pluginTest/cookie_remap/configs/substituteconfig.txt
new file mode 100644
index 0000000..120adc3
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/configs/substituteconfig.txt
@@ -0,0 +1,21 @@
+# This is a test configuration
+
+# Do a regex against the cookie
+op:
+  cookie: fpbeta
+  operation: exists
+  sendto: http://127.0.0.10:$PORT/photos/search?query=$path
+op:
+  cookie: oxalpha
+  operation: exists
+  sendto: http://127.0.0.10:$PORT/photos/search?query=$unmatched_path
+op:
+  cookie: acgamma
+  operation: exists
+  sendto: http://127.0.0.10:$PORT/photos/search/cr_substitutions?query=$cr_urlencode($cr_req_url)
+# Regex against url and path is substituted in outgoing path
+op:
+  operation: regex
+  regex: foobar
+  sendto: http://127.0.0.10:$PORT/photos/search/$path
+
diff --git a/tests/gold_tests/pluginTest/cookie_remap/connector.test.py b/tests/gold_tests/pluginTest/cookie_remap/connector.test.py
new file mode 100644
index 0000000..378b880
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/connector.test.py
@@ -0,0 +1,104 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: test connector"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiematches HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookiedoesntmatch HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/connectorconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/connectorconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/connectorconfig.txt'
+)
+
+# Positive test case that remaps because all connected operations pass
+tr = Test.AddTestRun("cookie value matches")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=abcd icecream=donteat" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/matchcookie.gold"
+
+# Negative test case that doesn't remap because not all subops pass
+tr = Test.AddTestRun("cookie value doesn't match")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=somethingelse" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/wontmatchcookie.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/existscookie.test.py b/tests/gold_tests/pluginTest/cookie_remap/existscookie.test.py
new file mode 100644
index 0000000..6f07b02
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/existscookie.test.py
@@ -0,0 +1,104 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: cookie exists"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookieexists HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookiedoesntexist HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/existsconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/existsconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/existsconfig.txt'
+)
+
+# Positive test case that remaps because cookie exists
+tr = Test.AddTestRun("cookie fpbeta exists")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=fdkfkdfkdfkdkdfkdfk" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/existscookie.gold"
+
+# Negative test case that doesn't remap because cookie doesn't exist
+tr = Test.AddTestRun("cooke fpbeta doesnt exist")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: breadcrumb=etc" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/doesntexistcookie.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/collapseslashes.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/collapseslashes.gold
new file mode 100644
index 0000000..68802f1
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/collapseslashes.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /i/like/cheetos?.done=http://finance.yahoo.com HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/doesntexistcookie.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/doesntexistcookie.gold
new file mode 100644
index 0000000..d137bee
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/doesntexistcookie.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /cookiedoesntexist HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/existscookie.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/existscookie.gold
new file mode 100644
index 0000000..9bae354
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/existscookie.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /cookieexists HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/matchcookie.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/matchcookie.gold
new file mode 100644
index 0000000..fe1811d
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/matchcookie.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /cookiematches HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/matchcookie2.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/matchcookie2.gold
new file mode 100644
index 0000000..969256d
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/matchcookie2.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /cookiematches?a=1&b=2&c=3 HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/matchelsestatus.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/matchelsestatus.gold
new file mode 100644
index 0000000..5c4de12
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/matchelsestatus.gold
@@ -0,0 +1,3 @@
+``
+HTTP/1.1 400 Bad Request
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/matchstatus.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/matchstatus.gold
new file mode 100644
index 0000000..c396c13
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/matchstatus.gold
@@ -0,0 +1,3 @@
+``
+HTTP/1.1 205 Reset Content
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/matrix.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/matrix.gold
new file mode 100644
index 0000000..dfc2735
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/matrix.gold
@@ -0,0 +1,15 @@
+``
+Request=GET /eighth/magic;matrix=1/eighth HTTP/1.1 lookup_key={PATH}
+``
+``
+Request=GET /eighth/magic;matrix=1/eighth?hello=10 HTTP/1.1 lookup_key={PATH}
+``
+``
+Request=GET /tenth/magic/tenth;matrix=2 HTTP/1.1 lookup_key={PATH}
+``
+``
+Request=GET /tenth/magic/tenth;matrix=2?query=10 HTTP/1.1 lookup_key={PATH}
+``
+``
+Request=GET /eleventh/magic;matrix=4/eleventh;matrix=2?query=true HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/regexdoesntmatch.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/regexdoesntmatch.gold
new file mode 100644
index 0000000..206e19b
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/regexdoesntmatch.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /regexdoesntmatch HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/regexmatches.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/regexmatches.gold
new file mode 100644
index 0000000..5f484fd
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/regexmatches.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /regexmatches?cookies=oreos-chipsahoy-icecream HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/substitute.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/substitute.gold
new file mode 100644
index 0000000..b490d41
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/substitute.gold
@@ -0,0 +1,9 @@
+``
+Request=GET /photos/search?query=magic HTTP/1.1 lookup_key={PATH}
+``
+``
+Request=GET /photos/search?query=/theunmatchedpath HTTP/1.1 lookup_key={PATH}
+``
+``
+equest=GET /photos/search/magic/foobar HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/wontmatchcookie.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/wontmatchcookie.gold
new file mode 100644
index 0000000..29bb5e5
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/wontmatchcookie.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /cookiedoesntmatch HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/gold/wontmatchcookie2.gold b/tests/gold_tests/pluginTest/cookie_remap/gold/wontmatchcookie2.gold
new file mode 100644
index 0000000..6d5dbb1
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/gold/wontmatchcookie2.gold
@@ -0,0 +1,3 @@
+``
+Request=GET /cookiedoesntmatch?a=1&b=2&c=3 HTTP/1.1 lookup_key={PATH}
+``
diff --git a/tests/gold_tests/pluginTest/cookie_remap/matchcookie.test.py b/tests/gold_tests/pluginTest/cookie_remap/matchcookie.test.py
new file mode 100644
index 0000000..bafb0ef
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/matchcookie.test.py
@@ -0,0 +1,104 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: match cookie"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiematches?a=1&b=2&c=3 HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookiedoesntmatch?a=1&b=2&c=3 HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/matchconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/matchconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/matchconfig.txt'
+)
+
+# Positive test case that remaps because cookie matches
+tr = Test.AddTestRun("cookie value matches")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/magic?a=1&b=2&c=3" \
+-H"Cookie: fpbeta=magic" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/matchcookie2.gold"
+
+# Negative test case that doesn't remap because cookie doesn't match
+tr = Test.AddTestRun("cookie regex doesn't match")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/magic?a=1&b=2&c=3" \
+-H"Cookie: fpbeta=magit" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/wontmatchcookie2.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/matchuri.test.py b/tests/gold_tests/pluginTest/cookie_remap/matchuri.test.py
new file mode 100644
index 0000000..706f353
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/matchuri.test.py
@@ -0,0 +1,103 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: match cookie"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiematches HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookiedoesntmatch HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/matchuriconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/matchuriconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/matchuriconfig.txt'
+)
+
+# Positive test case, URI matches rule
+tr = Test.AddTestRun("URI value matches")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic/thisispartofthepath" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/matchcookie.gold"
+
+# Negative test case that doesn't remap because URI doesn't match
+tr = Test.AddTestRun("URI value doesn't match")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=etc" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/wontmatchcookie.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/matrixparams.test.py b/tests/gold_tests/pluginTest/cookie_remap/matrixparams.test.py
new file mode 100644
index 0000000..9b3c7f3
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/matrixparams.test.py
@@ -0,0 +1,148 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: Tests when matrix parameters are present"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# We just need a server to capture ATS outgoing requests
+# so that we can verify the remap rules
+# That's why I am not adding any canned request/response
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/matrixconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/matrixconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/eighth http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/matrixconfig.txt'
+)
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/ninth http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/matrixconfig.txt'
+)
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/tenth http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/matrixconfig.txt'
+)
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/eleventh http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/matrixconfig.txt'
+)
+
+tr = Test.AddTestRun("path is substituted")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/eighth/magic;matrix=1" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("path is substituted when matrix \
+                      and query is present")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/eighth/magic;matrix=1?hello=10" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("Another $path substitution passing matrix \
+                       and query and replacing query")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/ninth/magic;matrix=5?hello=16" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("$path substitution in sendto and \
+                      inserting matrix parameters in remap")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/tenth/magic" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("inserting matrix params in remap and \
+                      passing along query string")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/tenth/magic?query=10" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("Another test to verify matrix and query \
+                      params are passed along")
+tr.Processes.Default.Command = '''
+curl \
+--proxy 127.0.0.1:{0} \
+"http://www.example.com/eleventh/magic;matrix=4?query=12" \
+-H "Proxy-Connection: keep-alive" \
+-H "Proxy-Connection: keep-alive" \
+--verbose \
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+server.Streams.All = "gold/matrix.gold"
+
diff --git a/tests/gold_tests/pluginTest/cookie_remap/notexistscookie.test.py b/tests/gold_tests/pluginTest/cookie_remap/notexistscookie.test.py
new file mode 100644
index 0000000..6028ec8
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/notexistscookie.test.py
@@ -0,0 +1,103 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: cookie not exists"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiedoesntexist HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookieexists HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/notexistsconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/notexistsconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/notexistsconfig.txt'
+)
+
+# Positive test case that remaps because cookie doesn't exist
+tr = Test.AddTestRun("cookie fpbeta doesn't exist")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/doesntexistcookie.gold"
+
+# Negative test case that doesn't remap because cookie exists
+tr = Test.AddTestRun("cooke fpbeta exists")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=etc" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/existscookie.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/regexcookie.test.py b/tests/gold_tests/pluginTest/cookie_remap/regexcookie.test.py
new file mode 100644
index 0000000..3e2c817
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/regexcookie.test.py
@@ -0,0 +1,104 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: cookie regex match and substition"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /regexmatches HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /regexdoesntmatch HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/regexconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/regexconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/regexconfig.txt'
+)
+
+# Positive test case that remaps because cookie regex matches
+tr = Test.AddTestRun("cookie regex matches")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=ilove-oreos-chipsahoy-icecream"
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/regexmatches.gold"
+
+# Negative test case that doesn't remap because cookie regex doesn't match
+tr = Test.AddTestRun("cookie regex doesn't match")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=etc" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/regexdoesntmatch.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/setstatus.test.py b/tests/gold_tests/pluginTest/cookie_remap/setstatus.test.py
new file mode 100644
index 0000000..34c0b34
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/setstatus.test.py
@@ -0,0 +1,79 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: set HTTP status of the response"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/statusconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/statusconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/statusconfig.txt'
+)
+
+# Plugin sets the HTTP status because first rule matches
+tr = Test.AddTestRun("Sets the status to 205")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=magic" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+tr.Streams.All = "gold/matchstatus.gold"
+
+# Plugin sets the HTTP status because the else rule matches (i.e. no match)
+tr = Test.AddTestRun("Sets the else status to 400")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H "Proxy-Connection: keep-alive" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+tr.Streams.All = "gold/matchelsestatus.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/subcookie.test.py b/tests/gold_tests/pluginTest/cookie_remap/subcookie.test.py
new file mode 100644
index 0000000..0716689
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/subcookie.test.py
@@ -0,0 +1,100 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: test connector"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+# First server is run during first test and
+# second server is run during second test
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiematches HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+server2 = Test.MakeOriginServer("server2", ip='127.0.0.11')
+request_header2 = {"headers": "GET /cookiedoesntmatch HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server2.addResponse("sessionfile.log", request_header2, response_header2)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/subcookie.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+config1 = config1.replace("$ALTPORT", str(server2.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/subcookie.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/subcookie.txt'
+)
+
+# Positive test case that remaps because all connected operations pass
+tr = Test.AddTestRun("cookie value matches")
+# Unlike in other places I am using a single line string because the & seems to
+# be interpreted by the autest framework or the shell (tried escaping with \)
+tr.Processes.Default.Command = 'curl --proxy 127.0.0.1:{0} "http://www.example.com/magic" -H"Cookie: fpbeta=a=1&b=2&c=3" -H "Proxy-Connection: keep-alive" --verbose '.format(ts.Variables.port)
+#tr.Processes.Default.Command = '''
+#curl 
+#--proxy 127.0.0.1:{0} 
+#"http://www.example.com/magic" 
+#-H\"Cookie: fpbeta=a=1&b=2&c=3\" 
+#-H "Proxy-Connection: keep-alive" 
+#--verbose
+#'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+
+server.Streams.All = "gold/matchcookie.gold"
+
+# Negative test case that doesn't remap because not all subops pass
+tr = Test.AddTestRun("cookie value doesn't match")
+tr.Processes.Default.Command = 'curl --proxy 127.0.0.1:{0} "http://www.example.com/magic" -H"Cookie: fpbeta=a=1&b=2&c=4" -H "Proxy-Connection: keep-alive" --verbose '.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.StartBefore(server2, ready=When.PortOpen(server2.Variables.Port))
+tr.StillRunningAfter = ts
+
+server2.Streams.All = "gold/wontmatchcookie.gold"
diff --git a/tests/gold_tests/pluginTest/cookie_remap/substitute.test.py b/tests/gold_tests/pluginTest/cookie_remap/substitute.test.py
new file mode 100644
index 0000000..9cfb01d
--- /dev/null
+++ b/tests/gold_tests/pluginTest/cookie_remap/substitute.test.py
@@ -0,0 +1,116 @@
+'''
+'''
+#  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.
+
+import os
+Test.Summary = '''
+
+'''
+# need Curl
+Test.SkipUnless(
+    Condition.HasProgram("curl", "Curl need to be installed on system for this test to work")
+)
+Test.ContinueOnFail = True
+Test.testName = "cookie_remap: Substitute variables"
+
+# Define default ATS
+ts = Test.MakeATSProcess("ts")
+
+server = Test.MakeOriginServer("server", ip='127.0.0.10')
+
+request_header = {"headers": "GET /cookiematches HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+# expected response from the origin server
+response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+
+# add response to the server dictionary
+server.addResponse("sessionfile.log", request_header, response_header)
+
+# Setup the remap configuration
+config_path = os.path.join(Test.TestDirectory, "configs/substituteconfig.txt")
+with open(config_path, 'r') as config_file:
+    config1 = config_file.read()
+
+ts.Disk.records_config.update({
+    'proxy.config.diags.debug.enabled': 1,
+    'proxy.config.diags.debug.tags': 'cookie_remap.*|http.*|dns.*',
+})
+
+config1 = config1.replace("$PORT", str(server.Variables.Port))
+
+ts.Disk.File(ts.Variables.CONFIGDIR +"/substituteconfig.txt", exists=False, id="config1")
+ts.Disk.config1.WriteOn(config1)
+
+ts.Disk.remap_config.AddLine(
+    'map http://www.example.com/magic http://shouldnothit.com @plugin=cookie_remap.so @pparam=config/substituteconfig.txt'
+)
+
+tr = Test.AddTestRun("Substitute $path in the dest query")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: fpbeta=abcd" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+# time delay as proxy.config.http.wait_for_cache could be broken
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(Test.Processes.ts)
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("Substitute $unmatched_path in the dest query")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic/theunmatchedpath" 
+-H"Cookie: oxalpha=3333" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("Substitute $cr_req_url using $cr_urlencode")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic" 
+-H"Cookie: acgamma=dfndfdfd" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+tr = Test.AddTestRun("Substitute $path as is in outgoing path")
+tr.Processes.Default.Command = '''
+curl 
+--proxy 127.0.0.1:{0} 
+"http://www.example.com/magic/foobar" 
+-H "Proxy-Connection: keep-alive" 
+--verbose
+'''.format(ts.Variables.port)
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+server.Streams.All = "gold/substitute.gold"
+